blob_id
stringlengths 40
40
| __id__
int64 225
39,780B
| directory_id
stringlengths 40
40
| path
stringlengths 6
313
| content_id
stringlengths 40
40
| detected_licenses
list | license_type
stringclasses 2
values | repo_name
stringlengths 6
132
| repo_url
stringlengths 25
151
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
70
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 7.28k
689M
⌀ | star_events_count
int64 0
131k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 23
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
40.4M
⌀ | gha_stargazers_count
int32 0
112k
⌀ | gha_forks_count
int32 0
39.4k
⌀ | gha_open_issues_count
int32 0
11k
⌀ | gha_language
stringlengths 1
21
⌀ | gha_archived
bool 2
classes | gha_disabled
bool 1
class | content
stringlengths 7
4.37M
| src_encoding
stringlengths 3
16
| language
stringclasses 1
value | length_bytes
int64 7
4.37M
| extension
stringclasses 24
values | filename
stringlengths 4
174
| language_id
stringclasses 1
value | entities
list | contaminating_dataset
stringclasses 0
values | malware_signatures
list | redacted_content
stringlengths 7
4.37M
| redacted_length_bytes
int64 7
4.37M
| alphanum_fraction
float32 0.25
0.94
| alpha_fraction
float32 0.25
0.94
| num_lines
int32 1
84k
| avg_line_length
float32 0.76
99.9
| std_line_length
float32 0
220
| max_line_length
int32 5
998
| is_vendor
bool 2
classes | is_generated
bool 1
class | max_hex_length
int32 0
319
| hex_fraction
float32 0
0.38
| max_unicode_length
int32 0
408
| unicode_fraction
float32 0
0.36
| max_base64_length
int32 0
506
| base64_fraction
float32 0
0.5
| avg_csv_sep_count
float32 0
4
| is_autogen_header
bool 1
class | is_empty_html
bool 1
class | shard
stringclasses 16
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9ab70972855dd1928b6cb9ad31a2b9c734057ffe
| 12,996,571,089,899 |
939bbac2c0b303e133d2b042d82623bb66ad702f
|
/src/main/java/project/pnia/data/enums/BusinessSectorType.java
|
05acb7a94066a8473c82752442a289a4a421ed04
|
[] |
no_license
|
AndreMAbreu/pnia
|
https://github.com/AndreMAbreu/pnia
|
f92823ab54a40a69c10a7bca86ae9aa2223df3ea
|
d21c72dd6685c2207f01baf8624b32e8b3147591
|
refs/heads/main
| 2023-06-02T08:15:12.090000 | 2021-06-29T11:09:05 | 2021-06-29T11:09:05 | 381,334,898 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package project.pnia.data.enums;
import com.fasterxml.jackson.annotation.JsonValue;
public enum BusinessSectorType {
TECHNOLOGY("Technology"),
BANKING("Banking"),
CLOTHING("Clothing");
private final String name;
BusinessSectorType(String name) {
this.name = name;
}
@JsonValue
public String getName() {
return name;
}
}
|
UTF-8
|
Java
| 378 |
java
|
BusinessSectorType.java
|
Java
|
[] | null |
[] |
package project.pnia.data.enums;
import com.fasterxml.jackson.annotation.JsonValue;
public enum BusinessSectorType {
TECHNOLOGY("Technology"),
BANKING("Banking"),
CLOTHING("Clothing");
private final String name;
BusinessSectorType(String name) {
this.name = name;
}
@JsonValue
public String getName() {
return name;
}
}
| 378 | 0.65873 | 0.65873 | 21 | 17 | 15.206515 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.380952 | false | false |
5
|
0d38d3c4bc6cc250220ec094f341a2747480103c
| 16,252,156,260,036 |
fc2d4d5a28c76e21315abf570dadbc4ed77e8dd6
|
/api-push-notificaction-project/api-push-notificaction-dao/src/main/java/com/notiificaciones/push/dao/mysql/UsuarioMapper.java
|
5b27531599532c361c8d39a459de412e208a77a9
|
[] |
no_license
|
asanchez1610/web_push_one_signal
|
https://github.com/asanchez1610/web_push_one_signal
|
e798a5591d34ad0ae6f12a4f24ce4fe548cf0dbc
|
cba054762e6a99254bdbedcb408e0a3c6dc45a47
|
refs/heads/master
| 2020-03-20T22:00:24.086000 | 2018-06-20T17:54:38 | 2018-06-20T17:54:38 | 137,773,965 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.notiificaciones.push.dao.mysql;
import com.notiificaciones.push.domain.mysql.Usuario;
import com.notiificaciones.push.domain.mysql.UsuarioCriteria;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface UsuarioMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table usuario
*
* @mbg.generated Sun Sep 17 00:14:12 COT 2017
*/
long countByExample(UsuarioCriteria example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table usuario
*
* @mbg.generated Sun Sep 17 00:14:12 COT 2017
*/
int deleteByExample(UsuarioCriteria example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table usuario
*
* @mbg.generated Sun Sep 17 00:14:12 COT 2017
*/
int deleteByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table usuario
*
* @mbg.generated Sun Sep 17 00:14:12 COT 2017
*/
int insert(Usuario record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table usuario
*
* @mbg.generated Sun Sep 17 00:14:12 COT 2017
*/
int insertSelective(Usuario record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table usuario
*
* @mbg.generated Sun Sep 17 00:14:12 COT 2017
*/
List<Usuario> selectByExample(UsuarioCriteria example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table usuario
*
* @mbg.generated Sun Sep 17 00:14:12 COT 2017
*/
Usuario selectByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table usuario
*
* @mbg.generated Sun Sep 17 00:14:12 COT 2017
*/
int updateByExampleSelective(@Param("record") Usuario record, @Param("example") UsuarioCriteria example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table usuario
*
* @mbg.generated Sun Sep 17 00:14:12 COT 2017
*/
int updateByExample(@Param("record") Usuario record, @Param("example") UsuarioCriteria example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table usuario
*
* @mbg.generated Sun Sep 17 00:14:12 COT 2017
*/
int updateByPrimaryKeySelective(Usuario record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table usuario
*
* @mbg.generated Sun Sep 17 00:14:12 COT 2017
*/
int updateByPrimaryKey(Usuario record);
}
|
UTF-8
|
Java
| 2,988 |
java
|
UsuarioMapper.java
|
Java
|
[] | null |
[] |
package com.notiificaciones.push.dao.mysql;
import com.notiificaciones.push.domain.mysql.Usuario;
import com.notiificaciones.push.domain.mysql.UsuarioCriteria;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface UsuarioMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table usuario
*
* @mbg.generated Sun Sep 17 00:14:12 COT 2017
*/
long countByExample(UsuarioCriteria example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table usuario
*
* @mbg.generated Sun Sep 17 00:14:12 COT 2017
*/
int deleteByExample(UsuarioCriteria example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table usuario
*
* @mbg.generated Sun Sep 17 00:14:12 COT 2017
*/
int deleteByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table usuario
*
* @mbg.generated Sun Sep 17 00:14:12 COT 2017
*/
int insert(Usuario record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table usuario
*
* @mbg.generated Sun Sep 17 00:14:12 COT 2017
*/
int insertSelective(Usuario record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table usuario
*
* @mbg.generated Sun Sep 17 00:14:12 COT 2017
*/
List<Usuario> selectByExample(UsuarioCriteria example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table usuario
*
* @mbg.generated Sun Sep 17 00:14:12 COT 2017
*/
Usuario selectByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table usuario
*
* @mbg.generated Sun Sep 17 00:14:12 COT 2017
*/
int updateByExampleSelective(@Param("record") Usuario record, @Param("example") UsuarioCriteria example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table usuario
*
* @mbg.generated Sun Sep 17 00:14:12 COT 2017
*/
int updateByExample(@Param("record") Usuario record, @Param("example") UsuarioCriteria example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table usuario
*
* @mbg.generated Sun Sep 17 00:14:12 COT 2017
*/
int updateByPrimaryKeySelective(Usuario record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table usuario
*
* @mbg.generated Sun Sep 17 00:14:12 COT 2017
*/
int updateByPrimaryKey(Usuario record);
}
| 2,988 | 0.67336 | 0.629183 | 96 | 30.135416 | 26.191053 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.1875 | false | false |
5
|
3a8fdaa219d0e2b8d548c2e11369c5efeaa0d4c4
| 755,914,271,189 |
cee2ba3ef42c7c28afb24ab2eaed8ea2f859293e
|
/src/main/java/com/game30/javagl/textures/GLTextureFactory.java
|
533522baeb90f2ae0d960bf4332e3ea7b6d7d8f3
|
[] |
no_license
|
game-30/javagl
|
https://github.com/game-30/javagl
|
e8689efe87ec2bc9300886bfcca26afaace09870
|
68c5cc4ce2fdd8271e22c6a8591d718b26059682
|
refs/heads/master
| 2020-05-30T17:48:40.427000 | 2015-11-07T15:30:11 | 2015-11-07T15:30:11 | 18,864,326 | 0 | 0 | null | false | 2014-07-03T20:09:05 | 2014-04-17T02:44:20 | 2014-07-03T19:05:53 | 2014-07-03T20:09:05 | 1,056 | 0 | 0 | 2 |
Java
| null | null |
package com.game30.javagl.textures;
import java.nio.ByteBuffer;
import org.lwjgl.BufferUtils;
/**
* @author Brian Norman
* @version 1.0.0-SNAPSHOT
* @since 1.0.0
*/
public interface GLTextureFactory {
static GLTextureFactory createDefault() {
return GLTextureBase::new;
}
GLTexture create(GLTextureTarget target, GLTextureFormat format, int width, int height, ByteBuffer data);
default GLTexture create(GLTextureTarget target, GLTextureFormat format, int square, ByteBuffer data) {
return create(target, format, square, square, data);
}
default GLTexture create(GLTextureTarget target, GLTextureFormat format, int width, int height, byte[] data) {
final ByteBuffer buffer = BufferUtils.createByteBuffer(data.length);
buffer.put(data);
buffer.flip();
return create(target, format, width, height, buffer);
}
default GLTexture create(GLTextureTarget target, GLTextureFormat format, int square, byte[] data) {
return create(target, format, square, square, data);
}
}
|
UTF-8
|
Java
| 1,068 |
java
|
GLTextureFactory.java
|
Java
|
[
{
"context": "er;\n\nimport org.lwjgl.BufferUtils;\n\n/**\n * @author Brian Norman\n * @version 1.0.0-SNAPSHOT\n * @since 1.0.0\n */\npu",
"end": 124,
"score": 0.9998027086257935,
"start": 112,
"tag": "NAME",
"value": "Brian Norman"
}
] | null |
[] |
package com.game30.javagl.textures;
import java.nio.ByteBuffer;
import org.lwjgl.BufferUtils;
/**
* @author <NAME>
* @version 1.0.0-SNAPSHOT
* @since 1.0.0
*/
public interface GLTextureFactory {
static GLTextureFactory createDefault() {
return GLTextureBase::new;
}
GLTexture create(GLTextureTarget target, GLTextureFormat format, int width, int height, ByteBuffer data);
default GLTexture create(GLTextureTarget target, GLTextureFormat format, int square, ByteBuffer data) {
return create(target, format, square, square, data);
}
default GLTexture create(GLTextureTarget target, GLTextureFormat format, int width, int height, byte[] data) {
final ByteBuffer buffer = BufferUtils.createByteBuffer(data.length);
buffer.put(data);
buffer.flip();
return create(target, format, width, height, buffer);
}
default GLTexture create(GLTextureTarget target, GLTextureFormat format, int square, byte[] data) {
return create(target, format, square, square, data);
}
}
| 1,062 | 0.707865 | 0.700375 | 35 | 29.514286 | 35.052101 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.057143 | false | false |
5
|
328b2ffb88f2130a078156701ca94bdeafeec44d
| 755,914,271,047 |
428807bd28553603170deed70223e8d0a130d074
|
/app/src/main/java/com/fivelove/adapter/FriendsAdapter.java
|
d8ea9a59024d603cca000af4953b7e3981a22d37
|
[] |
no_license
|
Dta-KO/fFive_love2
|
https://github.com/Dta-KO/fFive_love2
|
54ec3da232eaef6e7ad0a3a32f9d1513c2b13188
|
07b457f5596383a7463f48dbc545994394506621
|
refs/heads/master
| 2022-11-26T21:39:30.504000 | 2020-07-26T08:27:22 | 2020-07-26T08:27:22 | 281,708,562 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.fivelove.adapter;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;
import com.fivelove.R;
import com.fivelove.databinding.UserItemBinding;
import com.fivelove.db.model.User;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Nguyen Kim Khanh on 6/8/2020.
*/
public class FriendsAdapter extends RecyclerView.Adapter<FriendsAdapter.UserViewHolder> {
private List<User> users = new ArrayList<>();
public void setUsers(List<User> users) {
this.users = users;
notifyDataSetChanged();
}
public FriendsAdapter() {
}
@NonNull
@Override
public UserViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
UserItemBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.user_item, parent, false);
return new UserViewHolder(binding);
}
@Override
public void onBindViewHolder(@NonNull UserViewHolder holder, int position) {
holder.binding.setUser(users.get(position));
holder.binding.executePendingBindings();
}
@Override
public int getItemCount() {
return users.size();
}
static class UserViewHolder extends RecyclerView.ViewHolder {
UserItemBinding binding;
public UserViewHolder(@NonNull UserItemBinding binding) {
super(binding.getRoot());
this.binding = binding;
}
}
}
|
UTF-8
|
Java
| 1,583 |
java
|
FriendsAdapter.java
|
Java
|
[
{
"context": "rayList;\nimport java.util.List;\n\n/**\n * Created by Nguyen Kim Khanh on 6/8/2020.\n */\npublic class FriendsAdapter exte",
"end": 425,
"score": 0.999821126461029,
"start": 409,
"tag": "NAME",
"value": "Nguyen Kim Khanh"
}
] | null |
[] |
package com.fivelove.adapter;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;
import com.fivelove.R;
import com.fivelove.databinding.UserItemBinding;
import com.fivelove.db.model.User;
import java.util.ArrayList;
import java.util.List;
/**
* Created by <NAME> on 6/8/2020.
*/
public class FriendsAdapter extends RecyclerView.Adapter<FriendsAdapter.UserViewHolder> {
private List<User> users = new ArrayList<>();
public void setUsers(List<User> users) {
this.users = users;
notifyDataSetChanged();
}
public FriendsAdapter() {
}
@NonNull
@Override
public UserViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
UserItemBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.user_item, parent, false);
return new UserViewHolder(binding);
}
@Override
public void onBindViewHolder(@NonNull UserViewHolder holder, int position) {
holder.binding.setUser(users.get(position));
holder.binding.executePendingBindings();
}
@Override
public int getItemCount() {
return users.size();
}
static class UserViewHolder extends RecyclerView.ViewHolder {
UserItemBinding binding;
public UserViewHolder(@NonNull UserItemBinding binding) {
super(binding.getRoot());
this.binding = binding;
}
}
}
| 1,573 | 0.709413 | 0.705622 | 60 | 25.366667 | 27.53178 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.45 | false | false |
5
|
cdf698302de76c2cf0fd1d41987bc85d99ab752f
| 15,444,702,415,892 |
45d485c7b931d2a2e98b17af4dd68919d7777178
|
/backend/src/test/java/com/training/schedule/ScheduleApplicationTests.java
|
98f6658b4406fcddab26eda71af2c7cd4eaf9af6
|
[] |
no_license
|
caueprado/training
|
https://github.com/caueprado/training
|
e61d2a09c64bc4b89e45f557c506106e9558d321
|
2ba303852b0ec9a8da4d278ee28c8932cde1b4a3
|
refs/heads/master
| 2023-02-27T06:04:54.774000 | 2021-02-04T04:04:44 | 2021-02-04T04:04:44 | 332,936,094 | 0 | 0 | null | false | 2021-02-03T02:48:13 | 2021-01-26T01:33:14 | 2021-02-03T01:40:31 | 2021-02-03T02:48:13 | 231 | 0 | 0 | 0 |
Java
| false | false |
package com.training.schedule;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ScheduleApplicationTests {
}
|
UTF-8
|
Java
| 147 |
java
|
ScheduleApplicationTests.java
|
Java
|
[] | null |
[] |
package com.training.schedule;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ScheduleApplicationTests {
}
| 147 | 0.829932 | 0.829932 | 9 | 15.333333 | 20.094223 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.222222 | false | false |
5
|
e0774b82ac75aef3c36a1f59f9327c798f90f311
| 19,267,223,296,539 |
4bf4c72638414c22ef9722fc115d23525baf6569
|
/java/Crypto.java
|
6af7b063149a3cc0346f26b315dd5d730f914964
|
[] |
no_license
|
defuse/eotp
|
https://github.com/defuse/eotp
|
413f99f007df5b9c7c4fda9d823f28418b985eff
|
203350e7588e271f801e9fc599481b42b4e86ca7
|
refs/heads/master
| 2021-06-07T15:13:32.830000 | 2019-01-16T00:40:35 | 2019-01-16T00:40:35 | 10,529,913 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.io.ByteArrayOutputStream;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public abstract class Crypto {
public static final String CIPHER_NAME = "AES";
public static final String CIPHER_INSTANCE = "AES/CBC/PKCS5Padding";
public static final String RNG = "SHA1PRNG";
public static final String MD = "SHA-1";
public static final String MAC = "HmacSHA1";
public static final String HEX_CHARS = "0123456789abcdef";
public static final char[] HEX_BYTES = HEX_CHARS.toCharArray();
public static final String MODHEX_CHARS = "cbdefghijklnrtuv";
public static final char[] MODHEX_BYTES = MODHEX_CHARS.toCharArray();
public boolean compare(byte[] first, byte[] second) {
return java.util.Arrays.equals(first, second);
}
public byte[] concat(byte[] first, byte[] second) {
byte[] result = java.util.Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}
public byte[] dec(byte[] data, byte[] keyData, byte[] ivData) throws NoSuchAlgorithmException, NoSuchPaddingException {
try {
Cipher cipher = Cipher.getInstance(CIPHER_INSTANCE);
final IvParameterSpec iv = new IvParameterSpec(ivData);
SecretKey key = new SecretKeySpec(keyData, CIPHER_NAME);
cipher.init(Cipher.DECRYPT_MODE, key, iv);
return cipher.doFinal(data);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public byte[] dehex(String data) {
byte[] res = new byte[data.length() / 2];
for (int i = 0; i < res.length; i++) {
res[i] = (byte) Integer.parseInt(data.substring(2*i, 2*i+2), 16);
}
return res;
}
public byte[] derive(byte[] input, byte[] salt, Integer count, Integer iterations) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance(MD);
byte[] keyMaterial = new byte[md.getDigestLength() * iterations];
byte[] data00 = concat(input, salt);
byte[] result = null;
byte[] hashtarget = new byte[md.getDigestLength() + data00.length];
for (int j = 0; j < iterations; j++) {
if (j == 0) {
result = data00;
} else {
hashtarget = concat(result, data00);
result = hashtarget;
}
for(int i = 0; i < count; i++)
result = md.digest(result);
System.arraycopy(result, 0, keyMaterial, j * md.getDigestLength(), result.length);
}
return keyMaterial;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
public byte[] enc(byte[] data, byte[]keyData, byte[] ivData) throws NoSuchAlgorithmException, NoSuchPaddingException {
try {
Cipher cipher = Cipher.getInstance(CIPHER_INSTANCE);
final IvParameterSpec iv = new IvParameterSpec(ivData);
SecretKey key = new SecretKeySpec(keyData, CIPHER_NAME);
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
return cipher.doFinal(data);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String hex(byte data[]) {
char[] res = new char[2 * data.length];
for (int i = 0; i < data.length; ++i)
{
res[2 * i] = HEX_BYTES[(data[i] & 0xF0) >>> 4];
res[2 * i + 1] = HEX_BYTES[data[i] & 0x0F];
}
return new String(res).toUpperCase();
}
public void inc(byte[] counter) {
for (int i = counter.length - 1; i >= 0; i--) {
++counter[i];
if (counter[i] != 0) break; //Check whether we need to loop again to carry the one.
}
}
public byte[] mac(byte[] key, byte[] data) throws NoSuchAlgorithmException, InvalidKeyException {
Mac mac = Mac.getInstance(MAC);
mac.init(new SecretKeySpec(key, "RAW"));
return mac.doFinal(data);
}
public byte[] md(byte[] data) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance(MD);
return md.digest(data);
}
public byte[] modehex(String data) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len = data.length();
boolean toggle = false;
int keep = 0;
for (int i = 0; i < len; i++) {
char ch = data.charAt(i);
int n = MODHEX_CHARS.indexOf(Character.toLowerCase(ch));
if (n == -1) {
throw new
IllegalArgumentException(data + " is not properly encoded");
}
toggle = !toggle;
if (toggle) {
keep = n;
} else {
baos.write((keep << 4) | n);
}
}
return baos.toByteArray();
}
public String modhex(byte[] data) {
StringBuffer result = new StringBuffer();
for (int i = 0; i < data.length; i++) {
result.append(MODHEX_BYTES[(data[i] >> 4) & 0xf]);
result.append(MODHEX_BYTES[data[i] & 0xf]);
}
return result.toString();
}
public void rng(byte[] bytes) throws NoSuchAlgorithmException {
SecureRandom sr = SecureRandom.getInstance(RNG);
sr.nextBytes(bytes);
}
}
|
UTF-8
|
Java
| 5,201 |
java
|
Crypto.java
|
Java
|
[] | null |
[] |
import java.io.ByteArrayOutputStream;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public abstract class Crypto {
public static final String CIPHER_NAME = "AES";
public static final String CIPHER_INSTANCE = "AES/CBC/PKCS5Padding";
public static final String RNG = "SHA1PRNG";
public static final String MD = "SHA-1";
public static final String MAC = "HmacSHA1";
public static final String HEX_CHARS = "0123456789abcdef";
public static final char[] HEX_BYTES = HEX_CHARS.toCharArray();
public static final String MODHEX_CHARS = "cbdefghijklnrtuv";
public static final char[] MODHEX_BYTES = MODHEX_CHARS.toCharArray();
public boolean compare(byte[] first, byte[] second) {
return java.util.Arrays.equals(first, second);
}
public byte[] concat(byte[] first, byte[] second) {
byte[] result = java.util.Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}
public byte[] dec(byte[] data, byte[] keyData, byte[] ivData) throws NoSuchAlgorithmException, NoSuchPaddingException {
try {
Cipher cipher = Cipher.getInstance(CIPHER_INSTANCE);
final IvParameterSpec iv = new IvParameterSpec(ivData);
SecretKey key = new SecretKeySpec(keyData, CIPHER_NAME);
cipher.init(Cipher.DECRYPT_MODE, key, iv);
return cipher.doFinal(data);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public byte[] dehex(String data) {
byte[] res = new byte[data.length() / 2];
for (int i = 0; i < res.length; i++) {
res[i] = (byte) Integer.parseInt(data.substring(2*i, 2*i+2), 16);
}
return res;
}
public byte[] derive(byte[] input, byte[] salt, Integer count, Integer iterations) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance(MD);
byte[] keyMaterial = new byte[md.getDigestLength() * iterations];
byte[] data00 = concat(input, salt);
byte[] result = null;
byte[] hashtarget = new byte[md.getDigestLength() + data00.length];
for (int j = 0; j < iterations; j++) {
if (j == 0) {
result = data00;
} else {
hashtarget = concat(result, data00);
result = hashtarget;
}
for(int i = 0; i < count; i++)
result = md.digest(result);
System.arraycopy(result, 0, keyMaterial, j * md.getDigestLength(), result.length);
}
return keyMaterial;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
public byte[] enc(byte[] data, byte[]keyData, byte[] ivData) throws NoSuchAlgorithmException, NoSuchPaddingException {
try {
Cipher cipher = Cipher.getInstance(CIPHER_INSTANCE);
final IvParameterSpec iv = new IvParameterSpec(ivData);
SecretKey key = new SecretKeySpec(keyData, CIPHER_NAME);
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
return cipher.doFinal(data);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String hex(byte data[]) {
char[] res = new char[2 * data.length];
for (int i = 0; i < data.length; ++i)
{
res[2 * i] = HEX_BYTES[(data[i] & 0xF0) >>> 4];
res[2 * i + 1] = HEX_BYTES[data[i] & 0x0F];
}
return new String(res).toUpperCase();
}
public void inc(byte[] counter) {
for (int i = counter.length - 1; i >= 0; i--) {
++counter[i];
if (counter[i] != 0) break; //Check whether we need to loop again to carry the one.
}
}
public byte[] mac(byte[] key, byte[] data) throws NoSuchAlgorithmException, InvalidKeyException {
Mac mac = Mac.getInstance(MAC);
mac.init(new SecretKeySpec(key, "RAW"));
return mac.doFinal(data);
}
public byte[] md(byte[] data) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance(MD);
return md.digest(data);
}
public byte[] modehex(String data) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len = data.length();
boolean toggle = false;
int keep = 0;
for (int i = 0; i < len; i++) {
char ch = data.charAt(i);
int n = MODHEX_CHARS.indexOf(Character.toLowerCase(ch));
if (n == -1) {
throw new
IllegalArgumentException(data + " is not properly encoded");
}
toggle = !toggle;
if (toggle) {
keep = n;
} else {
baos.write((keep << 4) | n);
}
}
return baos.toByteArray();
}
public String modhex(byte[] data) {
StringBuffer result = new StringBuffer();
for (int i = 0; i < data.length; i++) {
result.append(MODHEX_BYTES[(data[i] >> 4) & 0xf]);
result.append(MODHEX_BYTES[data[i] & 0xf]);
}
return result.toString();
}
public void rng(byte[] bytes) throws NoSuchAlgorithmException {
SecureRandom sr = SecureRandom.getInstance(RNG);
sr.nextBytes(bytes);
}
}
| 5,201 | 0.649298 | 0.638723 | 171 | 28.403509 | 25.63933 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.508772 | false | false |
5
|
d02e43204f61e223141f771969efcc4c392a12f2
| 18,408,229,846,563 |
a5b7ac8e27803d8411170496bdcbb80201f5644c
|
/service/src/main/java/com/simple/bz/controller/PermissionController.java
|
38243c753311b51ec09a92eba203fa24579c0595
|
[
"Apache-2.0"
] |
permissive
|
windwithlife/SimpleAccount
|
https://github.com/windwithlife/SimpleAccount
|
8bfc3679609b63a6a342e0019b13039cd9d2e29c
|
44bd21b8885311bad9ddad643ca6eb940175da16
|
refs/heads/master
| 2023-08-11T15:02:00.084000 | 2021-09-16T03:58:25 | 2021-09-16T03:58:25 | 381,307,254 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.simple.bz.controller;
import com.simple.bz.dto.*;
import com.simple.bz.service.PermissionService;
import com.simple.bz.service.RoleService;
import com.simple.common.api.BaseResponse;
import com.simple.common.api.GenericResponse;
import com.simple.common.api.SimpleRequest;
import com.simple.common.api.SimpleResponse;
import com.simple.common.controller.BaseController;
import com.simple.common.props.AppProps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@AllArgsConstructor
@RestController
@RequestMapping("/permission")
@Api(tags = "权限相关的SOA集合")
public class PermissionController extends BaseController {
private final PermissionService service;
private final AppProps appProps;
@ApiOperation(value="库里所有帐户权限(用于测试)")
@PostMapping(path = "/queryAll")
public SimpleResponse<PermissionsDto> queryAll (){
List<PermissionDto> permissions = service.queryAll();
SimpleResponse<PermissionsDto> result = new SimpleResponse<PermissionsDto>();
return result.success(PermissionsDto.builder().permissions(permissions).build());
}
@GetMapping(path = "/testAuthorize")
public BaseResponse testAuth (@RequestParam("param") String param){
return GenericResponse.buildSuccess("okok response ==>" + param);
}
@ApiOperation(value="根据ID获取权限信息",notes = "")
@PostMapping(path = "/findById")
public SimpleResponse<PermissionDto> findById (@RequestBody SimpleRequest<IDRequest> request){
Long id = request.getParams().getId();
System.out.println("applicationId:" + id);
PermissionDto dto = service.findById(id);
SimpleResponse<PermissionDto> result = new SimpleResponse<PermissionDto>();
return result.success(dto);
}
@ApiOperation(value="新增权限",notes = "")
@PostMapping(path = "/addPermission")
public SimpleResponse<PermissionDto> addNewPermission (@RequestBody SimpleRequest<PermissionNewDto> request){
PermissionNewDto dto = request.getParams();
PermissionDto data = service.save(dto);
SimpleResponse<PermissionDto> result = new SimpleResponse<PermissionDto>();
return result.success(data);
}
@ApiOperation(value="修改权限信息",notes = "")
@PostMapping(path = "/update")
public SimpleResponse<PermissionDto> updateSave(@RequestBody SimpleRequest<PermissionDto> req) {
PermissionDto dto = req.getParams();
System.out.println(dto.toString());
service.update(dto);
SimpleResponse<PermissionDto> result = new SimpleResponse<PermissionDto>();
return result.success(dto);
}
@ApiOperation(value="删除权限",notes = "")
@ResponseBody
@RequestMapping(value = "/removeById", method = RequestMethod.POST)
public SimpleResponse<IDResponse> removeById(@RequestBody SimpleRequest<IDRequest> req) {
service.remove(req.getParams().getId());
SimpleResponse<IDResponse> result = new SimpleResponse<IDResponse>();
return result.success(IDResponse.builder().id(req.getParams().getId()).build());
}
@ApiOperation(value="批量删除角色",notes = "")
@ResponseBody
@RequestMapping(value = "/removeBatch", method = RequestMethod.POST)
public SimpleResponse<IDResponse> removeBatch(@RequestBody SimpleRequest<BatchIDRequest> req) {
System.out.println(req.getParams().getIds().toString());
SimpleResponse<IDResponse> result = new SimpleResponse<IDResponse>();
service.removeBatch(req.getParams().getIds());
return result.success(IDResponse.builder().id(0L).build());
}
}
|
UTF-8
|
Java
| 3,798 |
java
|
PermissionController.java
|
Java
|
[] | null |
[] |
package com.simple.bz.controller;
import com.simple.bz.dto.*;
import com.simple.bz.service.PermissionService;
import com.simple.bz.service.RoleService;
import com.simple.common.api.BaseResponse;
import com.simple.common.api.GenericResponse;
import com.simple.common.api.SimpleRequest;
import com.simple.common.api.SimpleResponse;
import com.simple.common.controller.BaseController;
import com.simple.common.props.AppProps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@AllArgsConstructor
@RestController
@RequestMapping("/permission")
@Api(tags = "权限相关的SOA集合")
public class PermissionController extends BaseController {
private final PermissionService service;
private final AppProps appProps;
@ApiOperation(value="库里所有帐户权限(用于测试)")
@PostMapping(path = "/queryAll")
public SimpleResponse<PermissionsDto> queryAll (){
List<PermissionDto> permissions = service.queryAll();
SimpleResponse<PermissionsDto> result = new SimpleResponse<PermissionsDto>();
return result.success(PermissionsDto.builder().permissions(permissions).build());
}
@GetMapping(path = "/testAuthorize")
public BaseResponse testAuth (@RequestParam("param") String param){
return GenericResponse.buildSuccess("okok response ==>" + param);
}
@ApiOperation(value="根据ID获取权限信息",notes = "")
@PostMapping(path = "/findById")
public SimpleResponse<PermissionDto> findById (@RequestBody SimpleRequest<IDRequest> request){
Long id = request.getParams().getId();
System.out.println("applicationId:" + id);
PermissionDto dto = service.findById(id);
SimpleResponse<PermissionDto> result = new SimpleResponse<PermissionDto>();
return result.success(dto);
}
@ApiOperation(value="新增权限",notes = "")
@PostMapping(path = "/addPermission")
public SimpleResponse<PermissionDto> addNewPermission (@RequestBody SimpleRequest<PermissionNewDto> request){
PermissionNewDto dto = request.getParams();
PermissionDto data = service.save(dto);
SimpleResponse<PermissionDto> result = new SimpleResponse<PermissionDto>();
return result.success(data);
}
@ApiOperation(value="修改权限信息",notes = "")
@PostMapping(path = "/update")
public SimpleResponse<PermissionDto> updateSave(@RequestBody SimpleRequest<PermissionDto> req) {
PermissionDto dto = req.getParams();
System.out.println(dto.toString());
service.update(dto);
SimpleResponse<PermissionDto> result = new SimpleResponse<PermissionDto>();
return result.success(dto);
}
@ApiOperation(value="删除权限",notes = "")
@ResponseBody
@RequestMapping(value = "/removeById", method = RequestMethod.POST)
public SimpleResponse<IDResponse> removeById(@RequestBody SimpleRequest<IDRequest> req) {
service.remove(req.getParams().getId());
SimpleResponse<IDResponse> result = new SimpleResponse<IDResponse>();
return result.success(IDResponse.builder().id(req.getParams().getId()).build());
}
@ApiOperation(value="批量删除角色",notes = "")
@ResponseBody
@RequestMapping(value = "/removeBatch", method = RequestMethod.POST)
public SimpleResponse<IDResponse> removeBatch(@RequestBody SimpleRequest<BatchIDRequest> req) {
System.out.println(req.getParams().getIds().toString());
SimpleResponse<IDResponse> result = new SimpleResponse<IDResponse>();
service.removeBatch(req.getParams().getIds());
return result.success(IDResponse.builder().id(0L).build());
}
}
| 3,798 | 0.720692 | 0.720421 | 95 | 37.968422 | 29.540499 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.515789 | false | false |
5
|
3a4461f8ce28a00aff7733143374f0ff552e037c
| 23,063,974,414,202 |
0ae9bf4fa5702860934db483b86f0636d015a171
|
/src/gsb/getcatchup/catchup/EveryoneListAdapter.java
|
4c17299987907bc784bb190abc8eadbe6d12939e
|
[] |
no_license
|
aaustin/CatchUp
|
https://github.com/aaustin/CatchUp
|
fd4fe0d7239cba5ce104dac33b75cdec5761748f
|
739df72c2e3635a3d606fe6ea1f483dabdff74b0
|
refs/heads/master
| 2020-12-24T14:27:03.681000 | 2013-03-25T17:21:24 | 2013-03-25T17:21:24 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package gsb.getcatchup.catchup;
import java.util.ArrayList;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class EveryoneListAdapter extends ArrayAdapter<Contact> {
private final Activity context;
private final ArrayList<Contact> contacts;
private final SubscriptionScheduler subSched;
FragmentJuggler FJ;
EveryoneFragment everyoneFrag;
PortraitDownloader pDownloader;
public EveryoneListAdapter(Activity context, ArrayList<Contact> contacts, FragmentJuggler FJ, EveryoneFragment everyoneFrag) {
super(context, R.layout.everyone_row, contacts);
//Log.i(DatabaseHelper.class.getName(),"loaded list adapter with " + contacts.size() + " contacts");
this.subSched = new SubscriptionScheduler(context);
this.contacts = contacts;
this.context = context;
this.FJ = FJ;
this.everyoneFrag = everyoneFrag;
pDownloader = new PortraitDownloader(context, contacts);
}
@Override
public boolean isEnabled(int position) {
return false;
}
@Override
public View getView(int position, View convertView, ViewGroup parent){
View rowView;
if (convertView == null) {
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.everyone_row, null, true);
} else {
rowView = convertView;
//return rowView;
}
//Log.i(DatabaseHelper.class.getName(),"showing groupPosition " + groupPosition);
TextView firstname = (TextView) rowView.findViewById(R.id.txtRowFirstname);
TextView lastname = (TextView) rowView.findViewById(R.id.txtRowLastname);
ImageView portrait = (ImageView) rowView.findViewById(R.id.imgPortrait);
final Button cmdSmallSub = (Button) rowView.findViewById(R.id.cmdSmallerSub);
final Button cmdLargerSub = (Button) rowView.findViewById(R.id.cmdLargerSub);
final Button cmdArrow = (Button) rowView.findViewById(R.id.cmdArrow);
final Contact curr = contacts.get(position);
cmdSmallSub.setFocusable(false);
cmdLargerSub.setFocusable(false);
set_click_responses(position, curr, cmdSmallSub, null, cmdLargerSub, null);
cmdArrow.setFocusable(false);
cmdArrow.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
FJ.index = curr.index;
FJ.remove = false;
FJ.switch_fragments("expand");
}
});
firstname.setText(curr.firstname);
lastname.setText(curr.lastname);
if (curr.portrait == null) {
portrait.setImageResource(R.drawable.blank_portrait);
pDownloader.get_image(position);
} else {
Bitmap bm = BitmapFactory.decodeByteArray(curr.portrait, 0, curr.portrait.length);
portrait.setImageBitmap(bm);
}
rowView.setOnClickListener(null);
rowView.setOnLongClickListener(null);
return rowView;
}
private void set_click_responses(final int position, final Contact current, final Button smallest, final Button smaller, final Button larger, final Button largest) {
//Log.i(DatabaseHelper.class.getName(),"setting up clicks for index " + current.index + ", " + current.firstname + " " + current.lastname);
if (smallest != null) {
smallest.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int index = position;
//Log.i(DatabaseHelper.class.getName(),"contact ref " + current.index);
Contact curr = contacts.get(index);
//Log.i(DatabaseHelper.class.getName(),"setting index 0 for index: " + curr.index + ", " + curr.firstname + " " + curr.lastname);
if (curr.subindex > 0)
subSched.unschedule_contact(curr);
subSched.schedule_contact(curr, 0, true);
contacts.remove(index);
Toast.makeText(context, "Contact added!", Toast.LENGTH_LONG).show();
notifyDataSetChanged();
}
});
}
if (smaller != null) {
smaller.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int index = position;
//Log.i(DatabaseHelper.class.getName(),"contact ref " + current.index);
Contact curr = contacts.get(index);
//Log.i(DatabaseHelper.class.getName(),"setting index 1 for " + curr.firstname + " " + curr.lastname);
if (curr.subindex > 0)
subSched.unschedule_contact(curr);
subSched.schedule_contact(curr, 1, true);
contacts.remove(index);
Toast.makeText(context, "Contact added!", Toast.LENGTH_LONG).show();
notifyDataSetChanged();
}
});
}
if (larger != null) {
larger.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int index = position;
//Log.i(DatabaseHelper.class.getName(),"contact ref " + current.index);
Contact curr = contacts.get(index);
//Log.i(DatabaseHelper.class.getName(),"setting index 2 for " + curr.firstname + " " + curr.lastname);
if (curr.subindex > 0)
subSched.unschedule_contact(curr);
subSched.schedule_contact(curr, 2, true);
contacts.remove(index);
Toast.makeText(context, "Contact added!", Toast.LENGTH_LONG).show();
notifyDataSetChanged();
}
});
}
if (largest != null) {
largest.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int index = position;
//Log.i(DatabaseHelper.class.getName(),"contact ref " + current.index);
Contact curr = contacts.get(index);
//Log.i(DatabaseHelper.class.getName(),"setting index 3 for " + curr.firstname + " " + curr.lastname);
if (curr.subindex > 0)
subSched.unschedule_contact(curr);
subSched.schedule_contact(curr, 3, true);
contacts.remove(index);
Toast.makeText(context, "Contact added!", Toast.LENGTH_LONG).show();
notifyDataSetChanged();
}
});
}
}
public boolean hasStableIds() {
return true;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
|
UTF-8
|
Java
| 6,406 |
java
|
EveryoneListAdapter.java
|
Java
|
[] | null |
[] |
package gsb.getcatchup.catchup;
import java.util.ArrayList;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class EveryoneListAdapter extends ArrayAdapter<Contact> {
private final Activity context;
private final ArrayList<Contact> contacts;
private final SubscriptionScheduler subSched;
FragmentJuggler FJ;
EveryoneFragment everyoneFrag;
PortraitDownloader pDownloader;
public EveryoneListAdapter(Activity context, ArrayList<Contact> contacts, FragmentJuggler FJ, EveryoneFragment everyoneFrag) {
super(context, R.layout.everyone_row, contacts);
//Log.i(DatabaseHelper.class.getName(),"loaded list adapter with " + contacts.size() + " contacts");
this.subSched = new SubscriptionScheduler(context);
this.contacts = contacts;
this.context = context;
this.FJ = FJ;
this.everyoneFrag = everyoneFrag;
pDownloader = new PortraitDownloader(context, contacts);
}
@Override
public boolean isEnabled(int position) {
return false;
}
@Override
public View getView(int position, View convertView, ViewGroup parent){
View rowView;
if (convertView == null) {
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.everyone_row, null, true);
} else {
rowView = convertView;
//return rowView;
}
//Log.i(DatabaseHelper.class.getName(),"showing groupPosition " + groupPosition);
TextView firstname = (TextView) rowView.findViewById(R.id.txtRowFirstname);
TextView lastname = (TextView) rowView.findViewById(R.id.txtRowLastname);
ImageView portrait = (ImageView) rowView.findViewById(R.id.imgPortrait);
final Button cmdSmallSub = (Button) rowView.findViewById(R.id.cmdSmallerSub);
final Button cmdLargerSub = (Button) rowView.findViewById(R.id.cmdLargerSub);
final Button cmdArrow = (Button) rowView.findViewById(R.id.cmdArrow);
final Contact curr = contacts.get(position);
cmdSmallSub.setFocusable(false);
cmdLargerSub.setFocusable(false);
set_click_responses(position, curr, cmdSmallSub, null, cmdLargerSub, null);
cmdArrow.setFocusable(false);
cmdArrow.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
FJ.index = curr.index;
FJ.remove = false;
FJ.switch_fragments("expand");
}
});
firstname.setText(curr.firstname);
lastname.setText(curr.lastname);
if (curr.portrait == null) {
portrait.setImageResource(R.drawable.blank_portrait);
pDownloader.get_image(position);
} else {
Bitmap bm = BitmapFactory.decodeByteArray(curr.portrait, 0, curr.portrait.length);
portrait.setImageBitmap(bm);
}
rowView.setOnClickListener(null);
rowView.setOnLongClickListener(null);
return rowView;
}
private void set_click_responses(final int position, final Contact current, final Button smallest, final Button smaller, final Button larger, final Button largest) {
//Log.i(DatabaseHelper.class.getName(),"setting up clicks for index " + current.index + ", " + current.firstname + " " + current.lastname);
if (smallest != null) {
smallest.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int index = position;
//Log.i(DatabaseHelper.class.getName(),"contact ref " + current.index);
Contact curr = contacts.get(index);
//Log.i(DatabaseHelper.class.getName(),"setting index 0 for index: " + curr.index + ", " + curr.firstname + " " + curr.lastname);
if (curr.subindex > 0)
subSched.unschedule_contact(curr);
subSched.schedule_contact(curr, 0, true);
contacts.remove(index);
Toast.makeText(context, "Contact added!", Toast.LENGTH_LONG).show();
notifyDataSetChanged();
}
});
}
if (smaller != null) {
smaller.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int index = position;
//Log.i(DatabaseHelper.class.getName(),"contact ref " + current.index);
Contact curr = contacts.get(index);
//Log.i(DatabaseHelper.class.getName(),"setting index 1 for " + curr.firstname + " " + curr.lastname);
if (curr.subindex > 0)
subSched.unschedule_contact(curr);
subSched.schedule_contact(curr, 1, true);
contacts.remove(index);
Toast.makeText(context, "Contact added!", Toast.LENGTH_LONG).show();
notifyDataSetChanged();
}
});
}
if (larger != null) {
larger.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int index = position;
//Log.i(DatabaseHelper.class.getName(),"contact ref " + current.index);
Contact curr = contacts.get(index);
//Log.i(DatabaseHelper.class.getName(),"setting index 2 for " + curr.firstname + " " + curr.lastname);
if (curr.subindex > 0)
subSched.unschedule_contact(curr);
subSched.schedule_contact(curr, 2, true);
contacts.remove(index);
Toast.makeText(context, "Contact added!", Toast.LENGTH_LONG).show();
notifyDataSetChanged();
}
});
}
if (largest != null) {
largest.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int index = position;
//Log.i(DatabaseHelper.class.getName(),"contact ref " + current.index);
Contact curr = contacts.get(index);
//Log.i(DatabaseHelper.class.getName(),"setting index 3 for " + curr.firstname + " " + curr.lastname);
if (curr.subindex > 0)
subSched.unschedule_contact(curr);
subSched.schedule_contact(curr, 3, true);
contacts.remove(index);
Toast.makeText(context, "Contact added!", Toast.LENGTH_LONG).show();
notifyDataSetChanged();
}
});
}
}
public boolean hasStableIds() {
return true;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
| 6,406 | 0.67187 | 0.669841 | 182 | 34.197803 | 30.750046 | 166 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.225275 | false | false |
5
|
13873e8f039dc416306373c8c68e240cde24ce87
| 22,273,700,466,831 |
99334425079e64f6511d59e2d4a50b3c89145ab9
|
/src/GUI/Xbrick.java
|
596a88e40763a7152457f3aed0dc190f4ffa5dda
|
[] |
no_license
|
romayalon/OOP_ass4
|
https://github.com/romayalon/OOP_ass4
|
7e8773e4cbea1969e4b859ceee67d04343366f0d
|
b81a4f50b205dc098ceaa001665d88d9df64f4e9
|
refs/heads/master
| 2020-04-07T22:06:02.460000 | 2018-11-22T22:16:12 | 2018-11-22T22:16:12 | 158,754,597 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package GUI;
import java.io.IOException;
import javax.swing.ImageIcon;
public class Xbrick extends Brick {
public Xbrick(int x, int y, Board board){
super(x,y,board);
try{ // Adding the Xbrick photo
ImageIcon Xbrick = new ImageIcon(new java.io.File( "." ).getCanonicalPath()+"\\Resources\\Brick5.jpg");
image = Xbrick.getImage();
i_width = image.getWidth(null);
i_heigth = image.getHeight(null);
}catch(IOException e){
System.out.println("file Not Found");
}
}
public void visit(FireBall fireBall){
if(!isDestroyed())
board.XCollision(this);
}
public void visit(WoodBall woodBall){
if(!isDestroyed())
board.XCollision(this);
}
public void visit(WaterBall waterBall){
if(!isDestroyed())
board.XCollision(this);
}
public void visit(ElectricBall electricBall){
if(!isDestroyed())
board.XCollision(this);
}
}
|
UTF-8
|
Java
| 937 |
java
|
Xbrick.java
|
Java
|
[] | null |
[] |
package GUI;
import java.io.IOException;
import javax.swing.ImageIcon;
public class Xbrick extends Brick {
public Xbrick(int x, int y, Board board){
super(x,y,board);
try{ // Adding the Xbrick photo
ImageIcon Xbrick = new ImageIcon(new java.io.File( "." ).getCanonicalPath()+"\\Resources\\Brick5.jpg");
image = Xbrick.getImage();
i_width = image.getWidth(null);
i_heigth = image.getHeight(null);
}catch(IOException e){
System.out.println("file Not Found");
}
}
public void visit(FireBall fireBall){
if(!isDestroyed())
board.XCollision(this);
}
public void visit(WoodBall woodBall){
if(!isDestroyed())
board.XCollision(this);
}
public void visit(WaterBall waterBall){
if(!isDestroyed())
board.XCollision(this);
}
public void visit(ElectricBall electricBall){
if(!isDestroyed())
board.XCollision(this);
}
}
| 937 | 0.640342 | 0.639274 | 37 | 23.324324 | 20.862555 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2 | false | false |
5
|
3ed1591eb5d33019748fdba170a61fb5d34d1231
| 16,320,875,728,466 |
ff90aedaff2b3adab50e68b2f3eef3a74f3f2b0d
|
/src/com/android/volley/cache/plus/ImageRequest.java
|
378a4bbc4cf18a6c1e86f0135331909124aa626a
|
[] |
no_license
|
rrabit42/Malware_Project_EWHA
|
https://github.com/rrabit42/Malware_Project_EWHA
|
cf81ab0d6cdc64cf0fb722e9427f7307da3689ab
|
3865c1c393a9873915ec07389afb799573d5d135
|
refs/heads/master
| 2020-11-24T06:42:17.435000 | 2019-12-16T20:48:04 | 2019-12-16T20:48:04 | 228,010,763 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.android.volley.cache.plus;
import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.media.ThumbnailUtils;
import android.os.Build;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.error.ParseError;
import com.android.volley.misc.ImageUtils;
import com.android.volley.misc.Utils;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.ui.RecyclingBitmapDrawable;
import java.io.File;
import java.io.FileNotFoundException;
public class ImageRequest extends Request<BitmapDrawable> {
private static final float IMAGE_BACKOFF_MULT = 2.0F;
private static final int IMAGE_MAX_RETRIES = 2;
private static final int IMAGE_TIMEOUT_MS = 1000;
private static final boolean PREFER_QUALITY_OVER_SPEED = false;
private static final Object sDecodeLock = new Object();
private final BitmapFactory.Options defaultOptions;
private ContentResolver mContentResolver;
private final Bitmap.Config mDecodeConfig;
private final Response.Listener<BitmapDrawable> mListener;
private final int mMaxHeight;
private final int mMaxWidth;
private Resources mResources;
public ImageRequest(String paramString, Resources paramResources, ContentResolver paramContentResolver, Response.Listener<BitmapDrawable> paramListener, int paramInt1, int paramInt2, Bitmap.Config paramConfig, Response.ErrorListener paramErrorListener) {
super(0, paramString, paramErrorListener);
setRetryPolicy(new DefaultRetryPolicy(1000, 2, 2.0F));
this.mResources = paramResources;
this.mContentResolver = paramContentResolver;
this.mListener = paramListener;
this.mDecodeConfig = paramConfig;
this.mMaxWidth = paramInt1;
this.mMaxHeight = paramInt2;
this.defaultOptions = getDefaultOptions();
}
private static void copyOptions(BitmapFactory.Options paramOptions1, BitmapFactory.Options paramOptions2) {
if (Build.VERSION.SDK_INT >= 11) {
copyOptionsHoneycomb(paramOptions1, paramOptions2);
return;
}
if (Build.VERSION.SDK_INT >= 10) {
copyOptionsGingerbreadMr1(paramOptions1, paramOptions2);
return;
}
copyOptionsFroyo(paramOptions1, paramOptions2);
}
private static void copyOptionsFroyo(BitmapFactory.Options paramOptions1, BitmapFactory.Options paramOptions2) {
paramOptions2.inDensity = paramOptions1.inDensity;
paramOptions2.inDither = paramOptions1.inDither;
paramOptions2.inInputShareable = paramOptions1.inInputShareable;
paramOptions2.inPreferredConfig = paramOptions1.inPreferredConfig;
paramOptions2.inPurgeable = paramOptions1.inPurgeable;
paramOptions2.inSampleSize = paramOptions1.inSampleSize;
paramOptions2.inScaled = paramOptions1.inScaled;
paramOptions2.inScreenDensity = paramOptions1.inScreenDensity;
paramOptions2.inTargetDensity = paramOptions1.inTargetDensity;
}
@TargetApi(10)
private static void copyOptionsGingerbreadMr1(BitmapFactory.Options paramOptions1, BitmapFactory.Options paramOptions2) {
copyOptionsFroyo(paramOptions1, paramOptions2);
paramOptions2.inPreferQualityOverSpeed = paramOptions1.inPreferQualityOverSpeed;
}
@TargetApi(11)
private static void copyOptionsHoneycomb(BitmapFactory.Options paramOptions1, BitmapFactory.Options paramOptions2) {
copyOptionsGingerbreadMr1(paramOptions1, paramOptions2);
paramOptions2.inMutable = paramOptions1.inMutable;
}
private Response<BitmapDrawable> doContentParse() { // Byte code:
// 0: aload_0
// 1: getfield mContentResolver : Landroid/content/ContentResolver;
// 4: ifnonnull -> 20
// 7: new com/android/volley/error/ParseError
// 10: dup
// 11: ldc 'Content Resolver instance is null'
// 13: invokespecial <init> : (Ljava/lang/String;)V
// 16: invokestatic error : (Lcom/android/volley/error/VolleyError;)Lcom/android/volley/Response;
// 19: areturn
// 20: aload_0
// 21: invokevirtual getUrl : ()Ljava/lang/String;
// 24: invokestatic parse : (Ljava/lang/String;)Landroid/net/Uri;
// 27: astore #6
// 29: new android/graphics/BitmapFactory$Options
// 32: dup
// 33: invokespecial <init> : ()V
// 36: astore #5
// 38: aload #5
// 40: iconst_1
// 41: putfield inInputShareable : Z
// 44: aload #5
// 46: iconst_1
// 47: putfield inPurgeable : Z
// 50: aload #5
// 52: aload_0
// 53: getfield mDecodeConfig : Landroid/graphics/Bitmap$Config;
// 56: putfield inPreferredConfig : Landroid/graphics/Bitmap$Config;
// 59: aload_0
// 60: getfield mMaxWidth : I
// 63: ifne -> 95
// 66: aload_0
// 67: getfield mMaxHeight : I
// 70: ifne -> 95
// 73: aload_0
// 74: getfield mContentResolver : Landroid/content/ContentResolver;
// 77: aload #6
// 79: aload #5
// 81: invokestatic decodeStream : (Landroid/content/ContentResolver;Landroid/net/Uri;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;
// 84: astore #5
// 86: aload_0
// 87: ldc 'read-full-size-image-from-resource'
// 89: invokevirtual addMarker : (Ljava/lang/String;)V
// 92: goto -> 264
// 95: aload #5
// 97: iconst_1
// 98: putfield inJustDecodeBounds : Z
// 101: aload_0
// 102: getfield mContentResolver : Landroid/content/ContentResolver;
// 105: aload #6
// 107: aload #5
// 109: invokestatic decodeStream : (Landroid/content/ContentResolver;Landroid/net/Uri;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;
// 112: pop
// 113: aload #5
// 115: getfield outWidth : I
// 118: istore_1
// 119: aload #5
// 121: getfield outHeight : I
// 124: istore_2
// 125: aload_0
// 126: getfield mMaxWidth : I
// 129: aload_0
// 130: getfield mMaxHeight : I
// 133: iload_1
// 134: iload_2
// 135: invokestatic getResizedDimension : (IIII)I
// 138: istore_3
// 139: aload_0
// 140: getfield mMaxHeight : I
// 143: aload_0
// 144: getfield mMaxWidth : I
// 147: iload_2
// 148: iload_1
// 149: invokestatic getResizedDimension : (IIII)I
// 152: istore #4
// 154: aload #5
// 156: iconst_0
// 157: putfield inJustDecodeBounds : Z
// 160: aload #5
// 162: iload_1
// 163: iload_2
// 164: iload_3
// 165: iload #4
// 167: invokestatic findBestSampleSize : (IIII)I
// 170: putfield inSampleSize : I
// 173: aload_0
// 174: getfield mContentResolver : Landroid/content/ContentResolver;
// 177: aload #6
// 179: aload #5
// 181: invokestatic decodeStream : (Landroid/content/ContentResolver;Landroid/net/Uri;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;
// 184: astore #6
// 186: aload_0
// 187: ldc 'read-from-resource-scaled-times-%d'
// 189: iconst_1
// 190: anewarray java/lang/Object
// 193: dup
// 194: iconst_0
// 195: aload #5
// 197: getfield inSampleSize : I
// 200: invokestatic valueOf : (I)Ljava/lang/Integer;
// 203: aastore
// 204: invokestatic format : (Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;
// 207: invokevirtual addMarker : (Ljava/lang/String;)V
// 210: aload #6
// 212: astore #5
// 214: aload #6
// 216: ifnull -> 264
// 219: aload #6
// 221: invokevirtual getWidth : ()I
// 224: iload_3
// 225: if_icmpgt -> 242
// 228: aload #6
// 230: astore #5
// 232: aload #6
// 234: invokevirtual getHeight : ()I
// 237: iload #4
// 239: if_icmple -> 264
// 242: aload #6
// 244: iload_3
// 245: iload #4
// 247: iconst_1
// 248: invokestatic createScaledBitmap : (Landroid/graphics/Bitmap;IIZ)Landroid/graphics/Bitmap;
// 251: astore #5
// 253: aload #6
// 255: invokevirtual recycle : ()V
// 258: aload_0
// 259: ldc 'scaling-read-from-resource-bitmap'
// 261: invokevirtual addMarker : (Ljava/lang/String;)V
// 264: aload #5
// 266: ifnonnull -> 280
// 269: new com/android/volley/error/ParseError
// 272: dup
// 273: invokespecial <init> : ()V
// 276: invokestatic error : (Lcom/android/volley/error/VolleyError;)Lcom/android/volley/Response;
// 279: areturn
// 280: invokestatic hasHoneycomb : ()Z
// 283: ifeq -> 304
// 286: new android/graphics/drawable/BitmapDrawable
// 289: dup
// 290: aload_0
// 291: getfield mResources : Landroid/content/res/Resources;
// 294: aload #5
// 296: invokespecial <init> : (Landroid/content/res/Resources;Landroid/graphics/Bitmap;)V
// 299: astore #6
// 301: goto -> 319
// 304: new com/android/volley/ui/RecyclingBitmapDrawable
// 307: dup
// 308: aload_0
// 309: getfield mResources : Landroid/content/res/Resources;
// 312: aload #5
// 314: invokespecial <init> : (Landroid/content/res/Resources;Landroid/graphics/Bitmap;)V
// 317: astore #6
// 319: aload #6
// 321: aload #5
// 323: invokestatic parseBitmapCacheHeaders : (Landroid/graphics/Bitmap;)Lcom/android/volley/Cache$Entry;
// 326: invokestatic success : (Ljava/lang/Object;Lcom/android/volley/Cache$Entry;)Lcom/android/volley/Response;
// 329: areturn }
private Response<BitmapDrawable> doFileParse() {
String str = getUrl();
Bitmap bitmap = new File(str.substring(7, str.length()));
if (!bitmap.exists() || !bitmap.isFile())
return Response.error(new ParseError(new FileNotFoundException(String.format("File not found: %s", new Object[] { bitmap.getAbsolutePath() }))));
RecyclingBitmapDrawable recyclingBitmapDrawable = new BitmapFactory.Options();
recyclingBitmapDrawable.inInputShareable = true;
recyclingBitmapDrawable.inPurgeable = true;
recyclingBitmapDrawable.inPreferredConfig = this.mDecodeConfig;
if (this.mMaxWidth == 0 && this.mMaxHeight == 0) {
bitmap = BitmapFactory.decodeFile(bitmap.getAbsolutePath(), recyclingBitmapDrawable);
addMarker("read-full-size-image-from-file");
} else {
recyclingBitmapDrawable.inJustDecodeBounds = true;
BitmapFactory.decodeFile(bitmap.getAbsolutePath(), recyclingBitmapDrawable);
int i = recyclingBitmapDrawable.outWidth;
int j = recyclingBitmapDrawable.outHeight;
int k = getResizedDimension(this.mMaxWidth, this.mMaxHeight, i, j);
int m = getResizedDimension(this.mMaxHeight, this.mMaxWidth, j, i);
recyclingBitmapDrawable.inJustDecodeBounds = false;
recyclingBitmapDrawable.inSampleSize = ImageUtils.findBestSampleSize(i, j, k, m);
bitmap = BitmapFactory.decodeFile(bitmap.getAbsolutePath(), recyclingBitmapDrawable);
addMarker(String.format("read-from-file-scaled-times-%d", new Object[] { Integer.valueOf(recyclingBitmapDrawable.inSampleSize) }));
if (bitmap != null && (bitmap.getWidth() > k || bitmap.getHeight() > m)) {
Bitmap bitmap1 = Bitmap.createScaledBitmap(bitmap, k, m, true);
bitmap.recycle();
addMarker("scaling-read-from-file-bitmap");
bitmap = bitmap1;
}
}
if (bitmap == null)
return Response.error(new ParseError());
if (Utils.hasHoneycomb()) {
BitmapDrawable bitmapDrawable = new BitmapDrawable(this.mResources, bitmap);
} else {
recyclingBitmapDrawable = new RecyclingBitmapDrawable(this.mResources, bitmap);
}
return Response.success(recyclingBitmapDrawable, HttpHeaderParser.parseBitmapCacheHeaders(bitmap));
}
@TargetApi(10)
private Response<BitmapDrawable> doParse(NetworkResponse paramNetworkResponse) { // Byte code:
// 0: aload_1
// 1: getfield data : [B
// 4: astore #6
// 6: new android/graphics/BitmapFactory$Options
// 9: dup
// 10: invokespecial <init> : ()V
// 13: astore #7
// 15: aload #7
// 17: iconst_1
// 18: putfield inInputShareable : Z
// 21: aload #7
// 23: iconst_1
// 24: putfield inPurgeable : Z
// 27: aload #7
// 29: aload_0
// 30: getfield mDecodeConfig : Landroid/graphics/Bitmap$Config;
// 33: putfield inPreferredConfig : Landroid/graphics/Bitmap$Config;
// 36: aload_0
// 37: getfield mMaxWidth : I
// 40: ifne -> 66
// 43: aload_0
// 44: getfield mMaxHeight : I
// 47: ifne -> 66
// 50: aload #6
// 52: iconst_0
// 53: aload #6
// 55: arraylength
// 56: aload #7
// 58: invokestatic decodeByteArray : ([BIILandroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;
// 61: astore #6
// 63: goto -> 221
// 66: aload #7
// 68: iconst_1
// 69: putfield inJustDecodeBounds : Z
// 72: aload #6
// 74: iconst_0
// 75: aload #6
// 77: arraylength
// 78: aload #7
// 80: invokestatic decodeByteArray : ([BIILandroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;
// 83: pop
// 84: aload #7
// 86: getfield outWidth : I
// 89: istore_2
// 90: aload #7
// 92: getfield outHeight : I
// 95: istore_3
// 96: aload_0
// 97: getfield mMaxWidth : I
// 100: aload_0
// 101: getfield mMaxHeight : I
// 104: iload_2
// 105: iload_3
// 106: invokestatic getResizedDimension : (IIII)I
// 109: istore #4
// 111: aload_0
// 112: getfield mMaxHeight : I
// 115: aload_0
// 116: getfield mMaxWidth : I
// 119: iload_3
// 120: iload_2
// 121: invokestatic getResizedDimension : (IIII)I
// 124: istore #5
// 126: aload #7
// 128: iconst_0
// 129: putfield inJustDecodeBounds : Z
// 132: invokestatic hasGingerbreadMR1 : ()Z
// 135: ifeq -> 144
// 138: aload #7
// 140: iconst_0
// 141: putfield inPreferQualityOverSpeed : Z
// 144: aload #7
// 146: iload_2
// 147: iload_3
// 148: iload #4
// 150: iload #5
// 152: invokestatic findBestSampleSize : (IIII)I
// 155: putfield inSampleSize : I
// 158: aload #6
// 160: iconst_0
// 161: aload #6
// 163: arraylength
// 164: aload #7
// 166: invokestatic decodeByteArray : ([BIILandroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;
// 169: astore #7
// 171: aload #7
// 173: astore #6
// 175: aload #7
// 177: ifnull -> 221
// 180: aload #7
// 182: invokevirtual getWidth : ()I
// 185: iload #4
// 187: if_icmpgt -> 204
// 190: aload #7
// 192: astore #6
// 194: aload #7
// 196: invokevirtual getHeight : ()I
// 199: iload #5
// 201: if_icmple -> 221
// 204: aload #7
// 206: iload #4
// 208: iload #5
// 210: iconst_1
// 211: invokestatic createScaledBitmap : (Landroid/graphics/Bitmap;IIZ)Landroid/graphics/Bitmap;
// 214: astore #6
// 216: aload #7
// 218: invokevirtual recycle : ()V
// 221: aload #6
// 223: ifnonnull -> 238
// 226: new com/android/volley/error/ParseError
// 229: dup
// 230: aload_1
// 231: invokespecial <init> : (Lcom/android/volley/NetworkResponse;)V
// 234: invokestatic error : (Lcom/android/volley/error/VolleyError;)Lcom/android/volley/Response;
// 237: areturn
// 238: invokestatic hasHoneycomb : ()Z
// 241: ifeq -> 262
// 244: new android/graphics/drawable/BitmapDrawable
// 247: dup
// 248: aload_0
// 249: getfield mResources : Landroid/content/res/Resources;
// 252: aload #6
// 254: invokespecial <init> : (Landroid/content/res/Resources;Landroid/graphics/Bitmap;)V
// 257: astore #6
// 259: goto -> 277
// 262: new com/android/volley/ui/RecyclingBitmapDrawable
// 265: dup
// 266: aload_0
// 267: getfield mResources : Landroid/content/res/Resources;
// 270: aload #6
// 272: invokespecial <init> : (Landroid/content/res/Resources;Landroid/graphics/Bitmap;)V
// 275: astore #6
// 277: aload #6
// 279: aload_1
// 280: invokestatic parseCacheHeaders : (Lcom/android/volley/NetworkResponse;)Lcom/android/volley/Cache$Entry;
// 283: invokestatic success : (Ljava/lang/Object;Lcom/android/volley/Cache$Entry;)Lcom/android/volley/Response;
// 286: areturn }
private Response<BitmapDrawable> doResourceParse() { // Byte code:
// 0: aload_0
// 1: getfield mResources : Landroid/content/res/Resources;
// 4: ifnonnull -> 18
// 7: new com/android/volley/error/ParseError
// 10: dup
// 11: invokespecial <init> : ()V
// 14: invokestatic error : (Lcom/android/volley/error/VolleyError;)Lcom/android/volley/Response;
// 17: areturn
// 18: aload_0
// 19: invokevirtual getUrl : ()Ljava/lang/String;
// 22: invokestatic parse : (Ljava/lang/String;)Landroid/net/Uri;
// 25: invokevirtual getLastPathSegment : ()Ljava/lang/String;
// 28: invokestatic valueOf : (Ljava/lang/String;)Ljava/lang/Integer;
// 31: invokevirtual intValue : ()I
// 34: istore_1
// 35: new android/graphics/BitmapFactory$Options
// 38: dup
// 39: invokespecial <init> : ()V
// 42: astore #6
// 44: aload #6
// 46: iconst_1
// 47: putfield inInputShareable : Z
// 50: aload #6
// 52: iconst_1
// 53: putfield inPurgeable : Z
// 56: aload #6
// 58: aload_0
// 59: getfield mDecodeConfig : Landroid/graphics/Bitmap$Config;
// 62: putfield inPreferredConfig : Landroid/graphics/Bitmap$Config;
// 65: aload_0
// 66: getfield mMaxWidth : I
// 69: ifne -> 100
// 72: aload_0
// 73: getfield mMaxHeight : I
// 76: ifne -> 100
// 79: aload_0
// 80: getfield mResources : Landroid/content/res/Resources;
// 83: iload_1
// 84: aload #6
// 86: invokestatic decodeResource : (Landroid/content/res/Resources;ILandroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;
// 89: astore #6
// 91: aload_0
// 92: ldc 'read-full-size-image-from-resource'
// 94: invokevirtual addMarker : (Ljava/lang/String;)V
// 97: goto -> 271
// 100: aload #6
// 102: iconst_1
// 103: putfield inJustDecodeBounds : Z
// 106: aload_0
// 107: getfield mResources : Landroid/content/res/Resources;
// 110: iload_1
// 111: aload #6
// 113: invokestatic decodeResource : (Landroid/content/res/Resources;ILandroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;
// 116: pop
// 117: aload #6
// 119: getfield outWidth : I
// 122: istore_2
// 123: aload #6
// 125: getfield outHeight : I
// 128: istore_3
// 129: aload_0
// 130: getfield mMaxWidth : I
// 133: aload_0
// 134: getfield mMaxHeight : I
// 137: iload_2
// 138: iload_3
// 139: invokestatic getResizedDimension : (IIII)I
// 142: istore #4
// 144: aload_0
// 145: getfield mMaxHeight : I
// 148: aload_0
// 149: getfield mMaxWidth : I
// 152: iload_3
// 153: iload_2
// 154: invokestatic getResizedDimension : (IIII)I
// 157: istore #5
// 159: aload #6
// 161: iconst_0
// 162: putfield inJustDecodeBounds : Z
// 165: aload #6
// 167: iload_2
// 168: iload_3
// 169: iload #4
// 171: iload #5
// 173: invokestatic findBestSampleSize : (IIII)I
// 176: putfield inSampleSize : I
// 179: aload_0
// 180: getfield mResources : Landroid/content/res/Resources;
// 183: iload_1
// 184: aload #6
// 186: invokestatic decodeResource : (Landroid/content/res/Resources;ILandroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;
// 189: astore #7
// 191: aload_0
// 192: ldc 'read-from-resource-scaled-times-%d'
// 194: iconst_1
// 195: anewarray java/lang/Object
// 198: dup
// 199: iconst_0
// 200: aload #6
// 202: getfield inSampleSize : I
// 205: invokestatic valueOf : (I)Ljava/lang/Integer;
// 208: aastore
// 209: invokestatic format : (Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;
// 212: invokevirtual addMarker : (Ljava/lang/String;)V
// 215: aload #7
// 217: astore #6
// 219: aload #7
// 221: ifnull -> 271
// 224: aload #7
// 226: invokevirtual getWidth : ()I
// 229: iload #4
// 231: if_icmpgt -> 248
// 234: aload #7
// 236: astore #6
// 238: aload #7
// 240: invokevirtual getHeight : ()I
// 243: iload #5
// 245: if_icmple -> 271
// 248: aload #7
// 250: iload #4
// 252: iload #5
// 254: iconst_1
// 255: invokestatic createScaledBitmap : (Landroid/graphics/Bitmap;IIZ)Landroid/graphics/Bitmap;
// 258: astore #6
// 260: aload #7
// 262: invokevirtual recycle : ()V
// 265: aload_0
// 266: ldc 'scaling-read-from-resource-bitmap'
// 268: invokevirtual addMarker : (Ljava/lang/String;)V
// 271: aload #6
// 273: ifnonnull -> 287
// 276: new com/android/volley/error/ParseError
// 279: dup
// 280: invokespecial <init> : ()V
// 283: invokestatic error : (Lcom/android/volley/error/VolleyError;)Lcom/android/volley/Response;
// 286: areturn
// 287: invokestatic hasHoneycomb : ()Z
// 290: ifeq -> 311
// 293: new android/graphics/drawable/BitmapDrawable
// 296: dup
// 297: aload_0
// 298: getfield mResources : Landroid/content/res/Resources;
// 301: aload #6
// 303: invokespecial <init> : (Landroid/content/res/Resources;Landroid/graphics/Bitmap;)V
// 306: astore #7
// 308: goto -> 326
// 311: new com/android/volley/ui/RecyclingBitmapDrawable
// 314: dup
// 315: aload_0
// 316: getfield mResources : Landroid/content/res/Resources;
// 319: aload #6
// 321: invokespecial <init> : (Landroid/content/res/Resources;Landroid/graphics/Bitmap;)V
// 324: astore #7
// 326: aload #7
// 328: aload #6
// 330: invokestatic parseBitmapCacheHeaders : (Landroid/graphics/Bitmap;)Lcom/android/volley/Cache$Entry;
// 333: invokestatic success : (Ljava/lang/Object;Lcom/android/volley/Cache$Entry;)Lcom/android/volley/Response;
// 336: areturn }
private Response<BitmapDrawable> doVideoFileParse() {
String str = getUrl();
Bitmap bitmap = new File(str.substring(8, str.length()));
if (!bitmap.exists() || !bitmap.isFile())
return Response.error(new ParseError(new FileNotFoundException(String.format("File not found: %s", new Object[] { bitmap.getAbsolutePath() }))));
RecyclingBitmapDrawable recyclingBitmapDrawable = new BitmapFactory.Options();
recyclingBitmapDrawable.inInputShareable = true;
recyclingBitmapDrawable.inPurgeable = true;
recyclingBitmapDrawable.inPreferredConfig = this.mDecodeConfig;
if (this.mMaxWidth == 0 && this.mMaxHeight == 0) {
bitmap = getVideoFrame(bitmap.getAbsolutePath());
addMarker("read-full-size-image-from-file");
} else {
recyclingBitmapDrawable.inJustDecodeBounds = true;
int i = recyclingBitmapDrawable.outWidth;
int j = recyclingBitmapDrawable.outHeight;
int k = getResizedDimension(this.mMaxWidth, this.mMaxHeight, i, j);
int m = getResizedDimension(this.mMaxHeight, this.mMaxWidth, j, i);
recyclingBitmapDrawable.inJustDecodeBounds = false;
recyclingBitmapDrawable.inSampleSize = ImageUtils.findBestSampleSize(i, j, k, m);
bitmap = getVideoFrame(bitmap.getAbsolutePath());
addMarker(String.format("read-from-file-scaled-times-%d", new Object[] { Integer.valueOf(recyclingBitmapDrawable.inSampleSize) }));
if (bitmap != null && (bitmap.getWidth() > k || bitmap.getHeight() > m)) {
Bitmap bitmap1 = Bitmap.createScaledBitmap(bitmap, k, m, true);
bitmap.recycle();
addMarker("scaling-read-from-file-bitmap");
bitmap = bitmap1;
}
}
if (bitmap == null)
return Response.error(new ParseError());
if (Utils.hasHoneycomb()) {
BitmapDrawable bitmapDrawable = new BitmapDrawable(this.mResources, bitmap);
} else {
recyclingBitmapDrawable = new RecyclingBitmapDrawable(this.mResources, bitmap);
}
return Response.success(recyclingBitmapDrawable, HttpHeaderParser.parseBitmapCacheHeaders(bitmap));
}
@TargetApi(11)
public static BitmapFactory.Options getDefaultOptions() {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inDither = false;
options.inScaled = false;
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inSampleSize = 1;
if (Utils.hasHoneycomb())
options.inMutable = true;
return options;
}
private BitmapFactory.Options getOptions() {
BitmapFactory.Options options = new BitmapFactory.Options();
copyOptions(this.defaultOptions, options);
return options;
}
private static int getResizedDimension(int paramInt1, int paramInt2, int paramInt3, int paramInt4) {
if (paramInt1 == 0 && paramInt2 == 0)
return paramInt3;
if (paramInt1 == 0) {
double d4 = paramInt2;
double d5 = paramInt4;
Double.isNaN(d4);
Double.isNaN(d5);
d4 /= d5;
d5 = paramInt3;
Double.isNaN(d5);
return (int)(d5 * d4);
}
if (paramInt2 == 0)
return paramInt1;
double d1 = paramInt4;
double d2 = paramInt3;
Double.isNaN(d1);
Double.isNaN(d2);
d1 /= d2;
d2 = paramInt1;
Double.isNaN(d2);
double d3 = paramInt2;
if (d2 * d1 > d3) {
Double.isNaN(d3);
paramInt1 = (int)(d3 / d1);
}
return paramInt1;
}
private Bitmap getVideoFrame(String paramString) { return ThumbnailUtils.createVideoThumbnail(paramString, 1); }
protected void deliverResponse(BitmapDrawable paramBitmapDrawable) { this.mListener.onResponse(paramBitmapDrawable); }
public Request.Priority getPriority() { return Request.Priority.LOW; }
protected Response<BitmapDrawable> parseNetworkResponse(NetworkResponse paramNetworkResponse) {
synchronized (sDecodeLock) {
if (getUrl().startsWith("video"))
return doVideoFileParse();
if (getUrl().startsWith("file"))
return doFileParse();
if (getUrl().startsWith("android.resource"))
return doResourceParse();
if (getUrl().startsWith("content"))
return doContentParse();
return doParse(paramNetworkResponse);
}
}
}
|
UTF-8
|
Java
| 27,354 |
java
|
ImageRequest.java
|
Java
|
[] | null |
[] |
package com.android.volley.cache.plus;
import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.media.ThumbnailUtils;
import android.os.Build;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.error.ParseError;
import com.android.volley.misc.ImageUtils;
import com.android.volley.misc.Utils;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.ui.RecyclingBitmapDrawable;
import java.io.File;
import java.io.FileNotFoundException;
public class ImageRequest extends Request<BitmapDrawable> {
private static final float IMAGE_BACKOFF_MULT = 2.0F;
private static final int IMAGE_MAX_RETRIES = 2;
private static final int IMAGE_TIMEOUT_MS = 1000;
private static final boolean PREFER_QUALITY_OVER_SPEED = false;
private static final Object sDecodeLock = new Object();
private final BitmapFactory.Options defaultOptions;
private ContentResolver mContentResolver;
private final Bitmap.Config mDecodeConfig;
private final Response.Listener<BitmapDrawable> mListener;
private final int mMaxHeight;
private final int mMaxWidth;
private Resources mResources;
public ImageRequest(String paramString, Resources paramResources, ContentResolver paramContentResolver, Response.Listener<BitmapDrawable> paramListener, int paramInt1, int paramInt2, Bitmap.Config paramConfig, Response.ErrorListener paramErrorListener) {
super(0, paramString, paramErrorListener);
setRetryPolicy(new DefaultRetryPolicy(1000, 2, 2.0F));
this.mResources = paramResources;
this.mContentResolver = paramContentResolver;
this.mListener = paramListener;
this.mDecodeConfig = paramConfig;
this.mMaxWidth = paramInt1;
this.mMaxHeight = paramInt2;
this.defaultOptions = getDefaultOptions();
}
private static void copyOptions(BitmapFactory.Options paramOptions1, BitmapFactory.Options paramOptions2) {
if (Build.VERSION.SDK_INT >= 11) {
copyOptionsHoneycomb(paramOptions1, paramOptions2);
return;
}
if (Build.VERSION.SDK_INT >= 10) {
copyOptionsGingerbreadMr1(paramOptions1, paramOptions2);
return;
}
copyOptionsFroyo(paramOptions1, paramOptions2);
}
private static void copyOptionsFroyo(BitmapFactory.Options paramOptions1, BitmapFactory.Options paramOptions2) {
paramOptions2.inDensity = paramOptions1.inDensity;
paramOptions2.inDither = paramOptions1.inDither;
paramOptions2.inInputShareable = paramOptions1.inInputShareable;
paramOptions2.inPreferredConfig = paramOptions1.inPreferredConfig;
paramOptions2.inPurgeable = paramOptions1.inPurgeable;
paramOptions2.inSampleSize = paramOptions1.inSampleSize;
paramOptions2.inScaled = paramOptions1.inScaled;
paramOptions2.inScreenDensity = paramOptions1.inScreenDensity;
paramOptions2.inTargetDensity = paramOptions1.inTargetDensity;
}
@TargetApi(10)
private static void copyOptionsGingerbreadMr1(BitmapFactory.Options paramOptions1, BitmapFactory.Options paramOptions2) {
copyOptionsFroyo(paramOptions1, paramOptions2);
paramOptions2.inPreferQualityOverSpeed = paramOptions1.inPreferQualityOverSpeed;
}
@TargetApi(11)
private static void copyOptionsHoneycomb(BitmapFactory.Options paramOptions1, BitmapFactory.Options paramOptions2) {
copyOptionsGingerbreadMr1(paramOptions1, paramOptions2);
paramOptions2.inMutable = paramOptions1.inMutable;
}
private Response<BitmapDrawable> doContentParse() { // Byte code:
// 0: aload_0
// 1: getfield mContentResolver : Landroid/content/ContentResolver;
// 4: ifnonnull -> 20
// 7: new com/android/volley/error/ParseError
// 10: dup
// 11: ldc 'Content Resolver instance is null'
// 13: invokespecial <init> : (Ljava/lang/String;)V
// 16: invokestatic error : (Lcom/android/volley/error/VolleyError;)Lcom/android/volley/Response;
// 19: areturn
// 20: aload_0
// 21: invokevirtual getUrl : ()Ljava/lang/String;
// 24: invokestatic parse : (Ljava/lang/String;)Landroid/net/Uri;
// 27: astore #6
// 29: new android/graphics/BitmapFactory$Options
// 32: dup
// 33: invokespecial <init> : ()V
// 36: astore #5
// 38: aload #5
// 40: iconst_1
// 41: putfield inInputShareable : Z
// 44: aload #5
// 46: iconst_1
// 47: putfield inPurgeable : Z
// 50: aload #5
// 52: aload_0
// 53: getfield mDecodeConfig : Landroid/graphics/Bitmap$Config;
// 56: putfield inPreferredConfig : Landroid/graphics/Bitmap$Config;
// 59: aload_0
// 60: getfield mMaxWidth : I
// 63: ifne -> 95
// 66: aload_0
// 67: getfield mMaxHeight : I
// 70: ifne -> 95
// 73: aload_0
// 74: getfield mContentResolver : Landroid/content/ContentResolver;
// 77: aload #6
// 79: aload #5
// 81: invokestatic decodeStream : (Landroid/content/ContentResolver;Landroid/net/Uri;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;
// 84: astore #5
// 86: aload_0
// 87: ldc 'read-full-size-image-from-resource'
// 89: invokevirtual addMarker : (Ljava/lang/String;)V
// 92: goto -> 264
// 95: aload #5
// 97: iconst_1
// 98: putfield inJustDecodeBounds : Z
// 101: aload_0
// 102: getfield mContentResolver : Landroid/content/ContentResolver;
// 105: aload #6
// 107: aload #5
// 109: invokestatic decodeStream : (Landroid/content/ContentResolver;Landroid/net/Uri;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;
// 112: pop
// 113: aload #5
// 115: getfield outWidth : I
// 118: istore_1
// 119: aload #5
// 121: getfield outHeight : I
// 124: istore_2
// 125: aload_0
// 126: getfield mMaxWidth : I
// 129: aload_0
// 130: getfield mMaxHeight : I
// 133: iload_1
// 134: iload_2
// 135: invokestatic getResizedDimension : (IIII)I
// 138: istore_3
// 139: aload_0
// 140: getfield mMaxHeight : I
// 143: aload_0
// 144: getfield mMaxWidth : I
// 147: iload_2
// 148: iload_1
// 149: invokestatic getResizedDimension : (IIII)I
// 152: istore #4
// 154: aload #5
// 156: iconst_0
// 157: putfield inJustDecodeBounds : Z
// 160: aload #5
// 162: iload_1
// 163: iload_2
// 164: iload_3
// 165: iload #4
// 167: invokestatic findBestSampleSize : (IIII)I
// 170: putfield inSampleSize : I
// 173: aload_0
// 174: getfield mContentResolver : Landroid/content/ContentResolver;
// 177: aload #6
// 179: aload #5
// 181: invokestatic decodeStream : (Landroid/content/ContentResolver;Landroid/net/Uri;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;
// 184: astore #6
// 186: aload_0
// 187: ldc 'read-from-resource-scaled-times-%d'
// 189: iconst_1
// 190: anewarray java/lang/Object
// 193: dup
// 194: iconst_0
// 195: aload #5
// 197: getfield inSampleSize : I
// 200: invokestatic valueOf : (I)Ljava/lang/Integer;
// 203: aastore
// 204: invokestatic format : (Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;
// 207: invokevirtual addMarker : (Ljava/lang/String;)V
// 210: aload #6
// 212: astore #5
// 214: aload #6
// 216: ifnull -> 264
// 219: aload #6
// 221: invokevirtual getWidth : ()I
// 224: iload_3
// 225: if_icmpgt -> 242
// 228: aload #6
// 230: astore #5
// 232: aload #6
// 234: invokevirtual getHeight : ()I
// 237: iload #4
// 239: if_icmple -> 264
// 242: aload #6
// 244: iload_3
// 245: iload #4
// 247: iconst_1
// 248: invokestatic createScaledBitmap : (Landroid/graphics/Bitmap;IIZ)Landroid/graphics/Bitmap;
// 251: astore #5
// 253: aload #6
// 255: invokevirtual recycle : ()V
// 258: aload_0
// 259: ldc 'scaling-read-from-resource-bitmap'
// 261: invokevirtual addMarker : (Ljava/lang/String;)V
// 264: aload #5
// 266: ifnonnull -> 280
// 269: new com/android/volley/error/ParseError
// 272: dup
// 273: invokespecial <init> : ()V
// 276: invokestatic error : (Lcom/android/volley/error/VolleyError;)Lcom/android/volley/Response;
// 279: areturn
// 280: invokestatic hasHoneycomb : ()Z
// 283: ifeq -> 304
// 286: new android/graphics/drawable/BitmapDrawable
// 289: dup
// 290: aload_0
// 291: getfield mResources : Landroid/content/res/Resources;
// 294: aload #5
// 296: invokespecial <init> : (Landroid/content/res/Resources;Landroid/graphics/Bitmap;)V
// 299: astore #6
// 301: goto -> 319
// 304: new com/android/volley/ui/RecyclingBitmapDrawable
// 307: dup
// 308: aload_0
// 309: getfield mResources : Landroid/content/res/Resources;
// 312: aload #5
// 314: invokespecial <init> : (Landroid/content/res/Resources;Landroid/graphics/Bitmap;)V
// 317: astore #6
// 319: aload #6
// 321: aload #5
// 323: invokestatic parseBitmapCacheHeaders : (Landroid/graphics/Bitmap;)Lcom/android/volley/Cache$Entry;
// 326: invokestatic success : (Ljava/lang/Object;Lcom/android/volley/Cache$Entry;)Lcom/android/volley/Response;
// 329: areturn }
private Response<BitmapDrawable> doFileParse() {
String str = getUrl();
Bitmap bitmap = new File(str.substring(7, str.length()));
if (!bitmap.exists() || !bitmap.isFile())
return Response.error(new ParseError(new FileNotFoundException(String.format("File not found: %s", new Object[] { bitmap.getAbsolutePath() }))));
RecyclingBitmapDrawable recyclingBitmapDrawable = new BitmapFactory.Options();
recyclingBitmapDrawable.inInputShareable = true;
recyclingBitmapDrawable.inPurgeable = true;
recyclingBitmapDrawable.inPreferredConfig = this.mDecodeConfig;
if (this.mMaxWidth == 0 && this.mMaxHeight == 0) {
bitmap = BitmapFactory.decodeFile(bitmap.getAbsolutePath(), recyclingBitmapDrawable);
addMarker("read-full-size-image-from-file");
} else {
recyclingBitmapDrawable.inJustDecodeBounds = true;
BitmapFactory.decodeFile(bitmap.getAbsolutePath(), recyclingBitmapDrawable);
int i = recyclingBitmapDrawable.outWidth;
int j = recyclingBitmapDrawable.outHeight;
int k = getResizedDimension(this.mMaxWidth, this.mMaxHeight, i, j);
int m = getResizedDimension(this.mMaxHeight, this.mMaxWidth, j, i);
recyclingBitmapDrawable.inJustDecodeBounds = false;
recyclingBitmapDrawable.inSampleSize = ImageUtils.findBestSampleSize(i, j, k, m);
bitmap = BitmapFactory.decodeFile(bitmap.getAbsolutePath(), recyclingBitmapDrawable);
addMarker(String.format("read-from-file-scaled-times-%d", new Object[] { Integer.valueOf(recyclingBitmapDrawable.inSampleSize) }));
if (bitmap != null && (bitmap.getWidth() > k || bitmap.getHeight() > m)) {
Bitmap bitmap1 = Bitmap.createScaledBitmap(bitmap, k, m, true);
bitmap.recycle();
addMarker("scaling-read-from-file-bitmap");
bitmap = bitmap1;
}
}
if (bitmap == null)
return Response.error(new ParseError());
if (Utils.hasHoneycomb()) {
BitmapDrawable bitmapDrawable = new BitmapDrawable(this.mResources, bitmap);
} else {
recyclingBitmapDrawable = new RecyclingBitmapDrawable(this.mResources, bitmap);
}
return Response.success(recyclingBitmapDrawable, HttpHeaderParser.parseBitmapCacheHeaders(bitmap));
}
@TargetApi(10)
private Response<BitmapDrawable> doParse(NetworkResponse paramNetworkResponse) { // Byte code:
// 0: aload_1
// 1: getfield data : [B
// 4: astore #6
// 6: new android/graphics/BitmapFactory$Options
// 9: dup
// 10: invokespecial <init> : ()V
// 13: astore #7
// 15: aload #7
// 17: iconst_1
// 18: putfield inInputShareable : Z
// 21: aload #7
// 23: iconst_1
// 24: putfield inPurgeable : Z
// 27: aload #7
// 29: aload_0
// 30: getfield mDecodeConfig : Landroid/graphics/Bitmap$Config;
// 33: putfield inPreferredConfig : Landroid/graphics/Bitmap$Config;
// 36: aload_0
// 37: getfield mMaxWidth : I
// 40: ifne -> 66
// 43: aload_0
// 44: getfield mMaxHeight : I
// 47: ifne -> 66
// 50: aload #6
// 52: iconst_0
// 53: aload #6
// 55: arraylength
// 56: aload #7
// 58: invokestatic decodeByteArray : ([BIILandroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;
// 61: astore #6
// 63: goto -> 221
// 66: aload #7
// 68: iconst_1
// 69: putfield inJustDecodeBounds : Z
// 72: aload #6
// 74: iconst_0
// 75: aload #6
// 77: arraylength
// 78: aload #7
// 80: invokestatic decodeByteArray : ([BIILandroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;
// 83: pop
// 84: aload #7
// 86: getfield outWidth : I
// 89: istore_2
// 90: aload #7
// 92: getfield outHeight : I
// 95: istore_3
// 96: aload_0
// 97: getfield mMaxWidth : I
// 100: aload_0
// 101: getfield mMaxHeight : I
// 104: iload_2
// 105: iload_3
// 106: invokestatic getResizedDimension : (IIII)I
// 109: istore #4
// 111: aload_0
// 112: getfield mMaxHeight : I
// 115: aload_0
// 116: getfield mMaxWidth : I
// 119: iload_3
// 120: iload_2
// 121: invokestatic getResizedDimension : (IIII)I
// 124: istore #5
// 126: aload #7
// 128: iconst_0
// 129: putfield inJustDecodeBounds : Z
// 132: invokestatic hasGingerbreadMR1 : ()Z
// 135: ifeq -> 144
// 138: aload #7
// 140: iconst_0
// 141: putfield inPreferQualityOverSpeed : Z
// 144: aload #7
// 146: iload_2
// 147: iload_3
// 148: iload #4
// 150: iload #5
// 152: invokestatic findBestSampleSize : (IIII)I
// 155: putfield inSampleSize : I
// 158: aload #6
// 160: iconst_0
// 161: aload #6
// 163: arraylength
// 164: aload #7
// 166: invokestatic decodeByteArray : ([BIILandroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;
// 169: astore #7
// 171: aload #7
// 173: astore #6
// 175: aload #7
// 177: ifnull -> 221
// 180: aload #7
// 182: invokevirtual getWidth : ()I
// 185: iload #4
// 187: if_icmpgt -> 204
// 190: aload #7
// 192: astore #6
// 194: aload #7
// 196: invokevirtual getHeight : ()I
// 199: iload #5
// 201: if_icmple -> 221
// 204: aload #7
// 206: iload #4
// 208: iload #5
// 210: iconst_1
// 211: invokestatic createScaledBitmap : (Landroid/graphics/Bitmap;IIZ)Landroid/graphics/Bitmap;
// 214: astore #6
// 216: aload #7
// 218: invokevirtual recycle : ()V
// 221: aload #6
// 223: ifnonnull -> 238
// 226: new com/android/volley/error/ParseError
// 229: dup
// 230: aload_1
// 231: invokespecial <init> : (Lcom/android/volley/NetworkResponse;)V
// 234: invokestatic error : (Lcom/android/volley/error/VolleyError;)Lcom/android/volley/Response;
// 237: areturn
// 238: invokestatic hasHoneycomb : ()Z
// 241: ifeq -> 262
// 244: new android/graphics/drawable/BitmapDrawable
// 247: dup
// 248: aload_0
// 249: getfield mResources : Landroid/content/res/Resources;
// 252: aload #6
// 254: invokespecial <init> : (Landroid/content/res/Resources;Landroid/graphics/Bitmap;)V
// 257: astore #6
// 259: goto -> 277
// 262: new com/android/volley/ui/RecyclingBitmapDrawable
// 265: dup
// 266: aload_0
// 267: getfield mResources : Landroid/content/res/Resources;
// 270: aload #6
// 272: invokespecial <init> : (Landroid/content/res/Resources;Landroid/graphics/Bitmap;)V
// 275: astore #6
// 277: aload #6
// 279: aload_1
// 280: invokestatic parseCacheHeaders : (Lcom/android/volley/NetworkResponse;)Lcom/android/volley/Cache$Entry;
// 283: invokestatic success : (Ljava/lang/Object;Lcom/android/volley/Cache$Entry;)Lcom/android/volley/Response;
// 286: areturn }
private Response<BitmapDrawable> doResourceParse() { // Byte code:
// 0: aload_0
// 1: getfield mResources : Landroid/content/res/Resources;
// 4: ifnonnull -> 18
// 7: new com/android/volley/error/ParseError
// 10: dup
// 11: invokespecial <init> : ()V
// 14: invokestatic error : (Lcom/android/volley/error/VolleyError;)Lcom/android/volley/Response;
// 17: areturn
// 18: aload_0
// 19: invokevirtual getUrl : ()Ljava/lang/String;
// 22: invokestatic parse : (Ljava/lang/String;)Landroid/net/Uri;
// 25: invokevirtual getLastPathSegment : ()Ljava/lang/String;
// 28: invokestatic valueOf : (Ljava/lang/String;)Ljava/lang/Integer;
// 31: invokevirtual intValue : ()I
// 34: istore_1
// 35: new android/graphics/BitmapFactory$Options
// 38: dup
// 39: invokespecial <init> : ()V
// 42: astore #6
// 44: aload #6
// 46: iconst_1
// 47: putfield inInputShareable : Z
// 50: aload #6
// 52: iconst_1
// 53: putfield inPurgeable : Z
// 56: aload #6
// 58: aload_0
// 59: getfield mDecodeConfig : Landroid/graphics/Bitmap$Config;
// 62: putfield inPreferredConfig : Landroid/graphics/Bitmap$Config;
// 65: aload_0
// 66: getfield mMaxWidth : I
// 69: ifne -> 100
// 72: aload_0
// 73: getfield mMaxHeight : I
// 76: ifne -> 100
// 79: aload_0
// 80: getfield mResources : Landroid/content/res/Resources;
// 83: iload_1
// 84: aload #6
// 86: invokestatic decodeResource : (Landroid/content/res/Resources;ILandroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;
// 89: astore #6
// 91: aload_0
// 92: ldc 'read-full-size-image-from-resource'
// 94: invokevirtual addMarker : (Ljava/lang/String;)V
// 97: goto -> 271
// 100: aload #6
// 102: iconst_1
// 103: putfield inJustDecodeBounds : Z
// 106: aload_0
// 107: getfield mResources : Landroid/content/res/Resources;
// 110: iload_1
// 111: aload #6
// 113: invokestatic decodeResource : (Landroid/content/res/Resources;ILandroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;
// 116: pop
// 117: aload #6
// 119: getfield outWidth : I
// 122: istore_2
// 123: aload #6
// 125: getfield outHeight : I
// 128: istore_3
// 129: aload_0
// 130: getfield mMaxWidth : I
// 133: aload_0
// 134: getfield mMaxHeight : I
// 137: iload_2
// 138: iload_3
// 139: invokestatic getResizedDimension : (IIII)I
// 142: istore #4
// 144: aload_0
// 145: getfield mMaxHeight : I
// 148: aload_0
// 149: getfield mMaxWidth : I
// 152: iload_3
// 153: iload_2
// 154: invokestatic getResizedDimension : (IIII)I
// 157: istore #5
// 159: aload #6
// 161: iconst_0
// 162: putfield inJustDecodeBounds : Z
// 165: aload #6
// 167: iload_2
// 168: iload_3
// 169: iload #4
// 171: iload #5
// 173: invokestatic findBestSampleSize : (IIII)I
// 176: putfield inSampleSize : I
// 179: aload_0
// 180: getfield mResources : Landroid/content/res/Resources;
// 183: iload_1
// 184: aload #6
// 186: invokestatic decodeResource : (Landroid/content/res/Resources;ILandroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;
// 189: astore #7
// 191: aload_0
// 192: ldc 'read-from-resource-scaled-times-%d'
// 194: iconst_1
// 195: anewarray java/lang/Object
// 198: dup
// 199: iconst_0
// 200: aload #6
// 202: getfield inSampleSize : I
// 205: invokestatic valueOf : (I)Ljava/lang/Integer;
// 208: aastore
// 209: invokestatic format : (Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;
// 212: invokevirtual addMarker : (Ljava/lang/String;)V
// 215: aload #7
// 217: astore #6
// 219: aload #7
// 221: ifnull -> 271
// 224: aload #7
// 226: invokevirtual getWidth : ()I
// 229: iload #4
// 231: if_icmpgt -> 248
// 234: aload #7
// 236: astore #6
// 238: aload #7
// 240: invokevirtual getHeight : ()I
// 243: iload #5
// 245: if_icmple -> 271
// 248: aload #7
// 250: iload #4
// 252: iload #5
// 254: iconst_1
// 255: invokestatic createScaledBitmap : (Landroid/graphics/Bitmap;IIZ)Landroid/graphics/Bitmap;
// 258: astore #6
// 260: aload #7
// 262: invokevirtual recycle : ()V
// 265: aload_0
// 266: ldc 'scaling-read-from-resource-bitmap'
// 268: invokevirtual addMarker : (Ljava/lang/String;)V
// 271: aload #6
// 273: ifnonnull -> 287
// 276: new com/android/volley/error/ParseError
// 279: dup
// 280: invokespecial <init> : ()V
// 283: invokestatic error : (Lcom/android/volley/error/VolleyError;)Lcom/android/volley/Response;
// 286: areturn
// 287: invokestatic hasHoneycomb : ()Z
// 290: ifeq -> 311
// 293: new android/graphics/drawable/BitmapDrawable
// 296: dup
// 297: aload_0
// 298: getfield mResources : Landroid/content/res/Resources;
// 301: aload #6
// 303: invokespecial <init> : (Landroid/content/res/Resources;Landroid/graphics/Bitmap;)V
// 306: astore #7
// 308: goto -> 326
// 311: new com/android/volley/ui/RecyclingBitmapDrawable
// 314: dup
// 315: aload_0
// 316: getfield mResources : Landroid/content/res/Resources;
// 319: aload #6
// 321: invokespecial <init> : (Landroid/content/res/Resources;Landroid/graphics/Bitmap;)V
// 324: astore #7
// 326: aload #7
// 328: aload #6
// 330: invokestatic parseBitmapCacheHeaders : (Landroid/graphics/Bitmap;)Lcom/android/volley/Cache$Entry;
// 333: invokestatic success : (Ljava/lang/Object;Lcom/android/volley/Cache$Entry;)Lcom/android/volley/Response;
// 336: areturn }
private Response<BitmapDrawable> doVideoFileParse() {
String str = getUrl();
Bitmap bitmap = new File(str.substring(8, str.length()));
if (!bitmap.exists() || !bitmap.isFile())
return Response.error(new ParseError(new FileNotFoundException(String.format("File not found: %s", new Object[] { bitmap.getAbsolutePath() }))));
RecyclingBitmapDrawable recyclingBitmapDrawable = new BitmapFactory.Options();
recyclingBitmapDrawable.inInputShareable = true;
recyclingBitmapDrawable.inPurgeable = true;
recyclingBitmapDrawable.inPreferredConfig = this.mDecodeConfig;
if (this.mMaxWidth == 0 && this.mMaxHeight == 0) {
bitmap = getVideoFrame(bitmap.getAbsolutePath());
addMarker("read-full-size-image-from-file");
} else {
recyclingBitmapDrawable.inJustDecodeBounds = true;
int i = recyclingBitmapDrawable.outWidth;
int j = recyclingBitmapDrawable.outHeight;
int k = getResizedDimension(this.mMaxWidth, this.mMaxHeight, i, j);
int m = getResizedDimension(this.mMaxHeight, this.mMaxWidth, j, i);
recyclingBitmapDrawable.inJustDecodeBounds = false;
recyclingBitmapDrawable.inSampleSize = ImageUtils.findBestSampleSize(i, j, k, m);
bitmap = getVideoFrame(bitmap.getAbsolutePath());
addMarker(String.format("read-from-file-scaled-times-%d", new Object[] { Integer.valueOf(recyclingBitmapDrawable.inSampleSize) }));
if (bitmap != null && (bitmap.getWidth() > k || bitmap.getHeight() > m)) {
Bitmap bitmap1 = Bitmap.createScaledBitmap(bitmap, k, m, true);
bitmap.recycle();
addMarker("scaling-read-from-file-bitmap");
bitmap = bitmap1;
}
}
if (bitmap == null)
return Response.error(new ParseError());
if (Utils.hasHoneycomb()) {
BitmapDrawable bitmapDrawable = new BitmapDrawable(this.mResources, bitmap);
} else {
recyclingBitmapDrawable = new RecyclingBitmapDrawable(this.mResources, bitmap);
}
return Response.success(recyclingBitmapDrawable, HttpHeaderParser.parseBitmapCacheHeaders(bitmap));
}
@TargetApi(11)
public static BitmapFactory.Options getDefaultOptions() {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inDither = false;
options.inScaled = false;
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inSampleSize = 1;
if (Utils.hasHoneycomb())
options.inMutable = true;
return options;
}
private BitmapFactory.Options getOptions() {
BitmapFactory.Options options = new BitmapFactory.Options();
copyOptions(this.defaultOptions, options);
return options;
}
private static int getResizedDimension(int paramInt1, int paramInt2, int paramInt3, int paramInt4) {
if (paramInt1 == 0 && paramInt2 == 0)
return paramInt3;
if (paramInt1 == 0) {
double d4 = paramInt2;
double d5 = paramInt4;
Double.isNaN(d4);
Double.isNaN(d5);
d4 /= d5;
d5 = paramInt3;
Double.isNaN(d5);
return (int)(d5 * d4);
}
if (paramInt2 == 0)
return paramInt1;
double d1 = paramInt4;
double d2 = paramInt3;
Double.isNaN(d1);
Double.isNaN(d2);
d1 /= d2;
d2 = paramInt1;
Double.isNaN(d2);
double d3 = paramInt2;
if (d2 * d1 > d3) {
Double.isNaN(d3);
paramInt1 = (int)(d3 / d1);
}
return paramInt1;
}
private Bitmap getVideoFrame(String paramString) { return ThumbnailUtils.createVideoThumbnail(paramString, 1); }
protected void deliverResponse(BitmapDrawable paramBitmapDrawable) { this.mListener.onResponse(paramBitmapDrawable); }
public Request.Priority getPriority() { return Request.Priority.LOW; }
protected Response<BitmapDrawable> parseNetworkResponse(NetworkResponse paramNetworkResponse) {
synchronized (sDecodeLock) {
if (getUrl().startsWith("video"))
return doVideoFileParse();
if (getUrl().startsWith("file"))
return doFileParse();
if (getUrl().startsWith("android.resource"))
return doResourceParse();
if (getUrl().startsWith("content"))
return doContentParse();
return doParse(paramNetworkResponse);
}
}
}
| 27,354 | 0.634459 | 0.574176 | 700 | 38.077145 | 29.321028 | 256 | true | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.482857 | false | false |
5
|
ce5df2416f4218c469ada983591f45f059cd26d4
| 29,411,936,095,151 |
3d86455324f9af14c650a60ffc38c44660610308
|
/MyServer/src/WebService/relatedSubjectsServlet.java
|
db694c6ccfad9f501e4772bd335a7c876ff61283
|
[
"MIT"
] |
permissive
|
HongliYu/EmotionHelper
|
https://github.com/HongliYu/EmotionHelper
|
7fcc6cf319bbf494f02cb3cadef1ea348644adfb
|
0eaaa9c833d579ef3a1abbb679ebcc9c1542c114
|
refs/heads/master
| 2016-03-25T16:53:27.653000 | 2014-07-21T06:03:02 | 2014-07-21T06:03:02 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package WebService;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.User;
import org.json.JSONException;
import org.json.JSONObject;
import database.ConnData;
@WebServlet(name = "relatedSubjectsServlet", urlPatterns = "/relatedSubjects")
public class relatedSubjectsServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -5501607943309735828L;
public void service(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
request.setCharacterEncoding("utf-8");
response.setContentType("text/json;charset=utf-8");
String status = "";
User user = new User();
user.setPhone(request.getParameter("phone"));
user.setPsw(request.getParameter("psw"));
User searchUser = new User();
searchUser.setPhone(request.getParameter("searchPhone"));
ConnData userData = new ConnData();
if(User.checkLogin(user)){
ArrayList<String> subejctIDs = userData.searchRelatedSubjectsID(searchUser.getUserID());
ArrayList<String> titles = new ArrayList<String>();
for(int i = 0 ;i<subejctIDs.size();i++){
userData.briefSearch("title", "subjects", "id", subejctIDs.get(i));
titles.add(userData.briefSearch("title", "subjects", "id", subejctIDs.get(i)));
}
try {
status = "0";
JSONObject member = new JSONObject();
member.put("status", status);
if(titles!=null){
for(int i = 0;i< titles.size();i++){
member.put("title"+i,titles.get(i));
}
}
response.getWriter().print(member.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
try {
status = "1";
JSONObject member = new JSONObject();
member.put("status", status);
response.getWriter().print(member.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
|
UTF-8
|
Java
| 2,171 |
java
|
relatedSubjectsServlet.java
|
Java
|
[] | null |
[] |
package WebService;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.User;
import org.json.JSONException;
import org.json.JSONObject;
import database.ConnData;
@WebServlet(name = "relatedSubjectsServlet", urlPatterns = "/relatedSubjects")
public class relatedSubjectsServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -5501607943309735828L;
public void service(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
request.setCharacterEncoding("utf-8");
response.setContentType("text/json;charset=utf-8");
String status = "";
User user = new User();
user.setPhone(request.getParameter("phone"));
user.setPsw(request.getParameter("psw"));
User searchUser = new User();
searchUser.setPhone(request.getParameter("searchPhone"));
ConnData userData = new ConnData();
if(User.checkLogin(user)){
ArrayList<String> subejctIDs = userData.searchRelatedSubjectsID(searchUser.getUserID());
ArrayList<String> titles = new ArrayList<String>();
for(int i = 0 ;i<subejctIDs.size();i++){
userData.briefSearch("title", "subjects", "id", subejctIDs.get(i));
titles.add(userData.briefSearch("title", "subjects", "id", subejctIDs.get(i)));
}
try {
status = "0";
JSONObject member = new JSONObject();
member.put("status", status);
if(titles!=null){
for(int i = 0;i< titles.size();i++){
member.put("title"+i,titles.get(i));
}
}
response.getWriter().print(member.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
try {
status = "1";
JSONObject member = new JSONObject();
member.put("status", status);
response.getWriter().print(member.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
| 2,171 | 0.695993 | 0.684477 | 74 | 28.337837 | 24.69997 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.108108 | false | false |
5
|
f79b4450537c5d98a8c3892930a8b778c1288596
| 21,148,418,988,297 |
1efbd79d386d50a3880df912f8bbd5056ff154a7
|
/src/main/MainClass.java
|
51a37e884978fbadcbde15625efe0dc1c6f6f366
|
[] |
no_license
|
georgiananila/management_banca
|
https://github.com/georgiananila/management_banca
|
acf29540cd828b4b0d783f23025a6444aceb1012
|
f999b534015f24bab16514cb235b2e86fa39ce58
|
refs/heads/main
| 2023-06-05T12:18:25.581000 | 2021-06-25T08:08:33 | 2021-06-25T08:08:33 | 380,168,261 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package main;
import clase.*;
import interfete.IBanca;
import interfete.TipCredit;
import interfete.TipDobanda;
import interfete.TipPersoana;
public class MainClass {
public static void main(String[] args){
IBanca bcr= new Banca("Banca Comerciala Romana","Strada Stefan cel Mare nr. 20A",(float)4.85,(float)3.91);
Banca brd= new Banca("Banca Romana de Dezvoltare","Strada Mihai Bravu",(float)4.82,(float)3.87);
System.out.println("Aici s-a apelat istoricul: ");
bcr.preluareIstoricCrediteDinBD();
System.out.println("S-A INCHEIEAT PRELUAREA DIN BAZA DE DATE! ");
System.out.println( "=====================================================================================================================================================");
Persoana p1=new Persoana("Nila","Georgiana",22, TipPersoana.PFA,true,"BCR","Analist Tehnic Junior",7800);
Persoana p2=new Persoana("Manole","Sabina",49, TipPersoana.PFA,true,"Spitalul Boli Infectiose Stefanesti","Bucatar",3000);
Persoana p3=new Persoana("Paraschiv","Mihaela",65, TipPersoana.ORG,false,null,null,2500);
Persoana p4=new Persoana("Petrache","Mihai",30, TipPersoana.PFA,true,"Com Divers Auto RO s.a","Paznic",1800);
Persoana p5=new Persoana("Pop","Ionel",35, TipPersoana.PJ,true,"Harman","Dezvoltator",9000);
Credit c1=new CreditPrimaCasa(43431,2,(float)2.87, TipDobanda.DOBANDA_FIXA);
Credit c2=new CreditGaudeamus(654676,6,(float)3.8, TipDobanda.DOBANDA_VARIABILA);
Credit c3=new CreditImobiliarIpotecar(4347631,15,(float)1.98, TipDobanda.DOBANDA_VARIABILA);
Credit c4=new CreditIpotecar(4432244,20,(float)2.00, TipDobanda.DOBANDA_FIXA);
Credit c5=new CreditNevoiPersonale(1131131,25,(float)4.19, TipDobanda.DOBANDA_FIXA);
//metode din clasa Credit
System.out.println("Plata in avans s-a putut/nu s-a putut efectua: "+c1.plataAnticipata(5000));
System.out.println("Plata in avans s-a putut/nu s-a putut efectua: "+c2.plataAnticipata(500));
System.out.println("Plata in avans s-a putut/nu s-a putut efectua: "+c3.plataAnticipata(2000));
System.out.println("Plata in avans s-a putut/nu s-a putut efectua: "+c4.plataAnticipata(3300));
System.out.println("Plata in avans s-a putut/nu s-a putut efectua: "+c5.plataAnticipata(3500));
System.out.println("Calculare rata: "+c2.calculareRataPerLuna());
System.out.println("Calculare rata: "+c1.calculareRataPerLuna());
System.out.println("Calculare rata: "+c3.calculareRataPerLuna());
System.out.println("Calculare rata: "+c4.calculareRataPerLuna());
System.out.println("Calculare rata: "+c5.calculareRataPerLuna());
System.out.println( "=====================================================================================================================================================");
//Acordarea de credite prin populare Map de lista credite acordate din banci
Credit acordat=bcr.acordareCredit(80000,10,p2, TipCredit.CREDIT_IPOTECAR_IMOBILIAR);
if(acordat!=null){
System.out.println("Creditul a fost acordat cu succes!");
}else{
System.out.println("Creditul nu a fost acordat din cauza unor probleme!");
}
Credit acordat1=bcr.acordareCredit(638312,15,p1, TipCredit.CREDIT_PRIMA_CASA);
if(acordat1!=null){
System.out.println("Creditul a fost acordat cu succes!");
}else{
System.out.println("Creditul nu a fost acordat din cauza unor probleme!");
}
Credit acordat2=bcr.acordareCredit(6482374,25,p3, TipCredit.CREDIT_NEVOI_PERSONALE);
if(acordat2!=null){
System.out.println("Creditul a fost acordat cu succes!");
}else{
System.out.println("Creditul nu a fost acordat din cauza unor probleme!");
}
Credit acordat4=brd.acordareCredit(42342343,30,p4, TipCredit.CREDIT_GAUDEAMUS);
if(acordat4!=null){
System.out.println("Creditul a fost acordat cu succes!");
}else{
System.out.println("Creditul nu a fost acordat din cauza unor probleme!");
}
Credit acordat5=brd.acordareCredit(3231111,10,p5, TipCredit.CREDIT_IPOTECAR);
if(acordat5!=null){
System.out.println("Creditul a fost acordat cu succes!");
}else{
System.out.println("Creditul nu a fost acordat din cauza unor probleme!");
}
Credit acordat6=bcr.acordareCredit(80000,p2, TipCredit.CREDIT_IPOTECAR_IMOBILIAR);
if(acordat!=null){
System.out.println("Creditul a fost acordat cu succes!");
}else{
System.out.println("Creditul nu a fost acordat din cauza unor probleme!");
}
//Metode definite in clasa Credit
System.out.println( "=====================================================================================================================================================");
//Metode definite in clasa Banca
System.out.println( brd.toString());
System.out.println("Se va afisa cursulDolar initial: " +brd.getCursValutarDolar());
brd.modificaCursDolar((float)1.00);
System.out.println("Se va afisa cursulDolar modificat(in scadere): " +brd.getCursValutarDolar());
System.out.println( brd.toString());
}
}
|
UTF-8
|
Java
| 5,420 |
java
|
MainClass.java
|
Java
|
[
{
"context": "){\n IBanca bcr= new Banca(\"Banca Comerciala Romana\",\"Strada Stefan cel Mare nr. 20A\",(float)4.85,",
"end": 265,
"score": 0.5930718183517456,
"start": 262,
"tag": "NAME",
"value": "Rom"
},
{
"context": "float)3.91);\n Banca brd= new Banca(\"Banca Romana de Dezvoltare\",\"Strada Mihai Bravu\",(float)4.8",
"end": 368,
"score": 0.5068932175636292,
"start": 366,
"tag": "NAME",
"value": "om"
},
{
"context": ";\n Banca brd= new Banca(\"Banca Romana de Dezvoltare\",\"Strada Mihai Bravu\",(float)4.82,(float)3.87)",
"end": 382,
"score": 0.5964086651802063,
"start": 377,
"tag": "NAME",
"value": "zvolt"
},
{
"context": "===========\");\n\n Persoana p1=new Persoana(\"Nila\",\"Georgiana\",22, TipPersoana.PFA,true,\"BCR\",\"Anal",
"end": 832,
"score": 0.9998301863670349,
"start": 828,
"tag": "NAME",
"value": "Nila"
},
{
"context": "====\");\n\n Persoana p1=new Persoana(\"Nila\",\"Georgiana\",22, TipPersoana.PFA,true,\"BCR\",\"Analist Tehnic J",
"end": 844,
"score": 0.9997385144233704,
"start": 835,
"tag": "NAME",
"value": "Georgiana"
},
{
"context": " Junior\",7800);\n Persoana p2=new Persoana(\"Manole\",\"Sabina\",49, TipPersoana.PFA,true,\"Spitalul Boli",
"end": 948,
"score": 0.9998064041137695,
"start": 942,
"tag": "NAME",
"value": "Manole"
},
{
"context": "7800);\n Persoana p2=new Persoana(\"Manole\",\"Sabina\",49, TipPersoana.PFA,true,\"Spitalul Boli Infectio",
"end": 957,
"score": 0.9997360110282898,
"start": 951,
"tag": "NAME",
"value": "Sabina"
},
{
"context": "a.PFA,true,\"Spitalul Boli Infectiose Stefanesti\",\"Bucatar\",3000);\n Persoana p3=new Persoana(\"Parasch",
"end": 1030,
"score": 0.9751001000404358,
"start": 1023,
"tag": "NAME",
"value": "Bucatar"
},
{
"context": "Bucatar\",3000);\n Persoana p3=new Persoana(\"Paraschiv\",\"Mihaela\",65, TipPersoana.ORG,false,null,null,25",
"end": 1082,
"score": 0.9984560012817383,
"start": 1073,
"tag": "NAME",
"value": "Paraschiv"
},
{
"context": "0);\n Persoana p3=new Persoana(\"Paraschiv\",\"Mihaela\",65, TipPersoana.ORG,false,null,null,2500);\n ",
"end": 1092,
"score": 0.9996889233589172,
"start": 1085,
"tag": "NAME",
"value": "Mihaela"
},
{
"context": "ull,null,2500);\n Persoana p4=new Persoana(\"Petrache\",\"Mihai\",30, TipPersoana.PFA,true,\"Com Divers Aut",
"end": 1179,
"score": 0.9997928738594055,
"start": 1171,
"tag": "NAME",
"value": "Petrache"
},
{
"context": "00);\n Persoana p4=new Persoana(\"Petrache\",\"Mihai\",30, TipPersoana.PFA,true,\"Com Divers Auto RO s.a",
"end": 1187,
"score": 0.9996325373649597,
"start": 1182,
"tag": "NAME",
"value": "Mihai"
},
{
"context": "0, TipPersoana.PFA,true,\"Com Divers Auto RO s.a\",\"Paznic\",1800);\n Persoana p5=new Persoana(\"Pop\",\"I",
"end": 1246,
"score": 0.9865196347236633,
"start": 1240,
"tag": "NAME",
"value": "Paznic"
},
{
"context": "\"Paznic\",1800);\n Persoana p5=new Persoana(\"Pop\",\"Ionel\",35, TipPersoana.PJ,true,\"Harman\",\"Dezvol",
"end": 1292,
"score": 0.9967853426933289,
"start": 1289,
"tag": "NAME",
"value": "Pop"
},
{
"context": "c\",1800);\n Persoana p5=new Persoana(\"Pop\",\"Ionel\",35, TipPersoana.PJ,true,\"Harman\",\"Dezvoltator\",9",
"end": 1300,
"score": 0.999701738357544,
"start": 1295,
"tag": "NAME",
"value": "Ionel"
},
{
"context": "w Persoana(\"Pop\",\"Ionel\",35, TipPersoana.PJ,true,\"Harman\",\"Dezvoltator\",9000);\n\n Credit c1=new Cred",
"end": 1333,
"score": 0.999718427658081,
"start": 1327,
"tag": "NAME",
"value": "Harman"
},
{
"context": "a(\"Pop\",\"Ionel\",35, TipPersoana.PJ,true,\"Harman\",\"Dezvoltator\",9000);\n\n Credit c1=new CreditPrimaCasa(43",
"end": 1347,
"score": 0.9988592267036438,
"start": 1336,
"tag": "NAME",
"value": "Dezvoltator"
}
] | null |
[] |
package main;
import clase.*;
import interfete.IBanca;
import interfete.TipCredit;
import interfete.TipDobanda;
import interfete.TipPersoana;
public class MainClass {
public static void main(String[] args){
IBanca bcr= new Banca("Banca Comerciala Romana","Strada Stefan cel Mare nr. 20A",(float)4.85,(float)3.91);
Banca brd= new Banca("Banca Romana de Dezvoltare","Strada Mihai Bravu",(float)4.82,(float)3.87);
System.out.println("Aici s-a apelat istoricul: ");
bcr.preluareIstoricCrediteDinBD();
System.out.println("S-A INCHEIEAT PRELUAREA DIN BAZA DE DATE! ");
System.out.println( "=====================================================================================================================================================");
Persoana p1=new Persoana("Nila","Georgiana",22, TipPersoana.PFA,true,"BCR","Analist Tehnic Junior",7800);
Persoana p2=new Persoana("Manole","Sabina",49, TipPersoana.PFA,true,"Spitalul Boli Infectiose Stefanesti","Bucatar",3000);
Persoana p3=new Persoana("Paraschiv","Mihaela",65, TipPersoana.ORG,false,null,null,2500);
Persoana p4=new Persoana("Petrache","Mihai",30, TipPersoana.PFA,true,"Com Divers Auto RO s.a","Paznic",1800);
Persoana p5=new Persoana("Pop","Ionel",35, TipPersoana.PJ,true,"Harman","Dezvoltator",9000);
Credit c1=new CreditPrimaCasa(43431,2,(float)2.87, TipDobanda.DOBANDA_FIXA);
Credit c2=new CreditGaudeamus(654676,6,(float)3.8, TipDobanda.DOBANDA_VARIABILA);
Credit c3=new CreditImobiliarIpotecar(4347631,15,(float)1.98, TipDobanda.DOBANDA_VARIABILA);
Credit c4=new CreditIpotecar(4432244,20,(float)2.00, TipDobanda.DOBANDA_FIXA);
Credit c5=new CreditNevoiPersonale(1131131,25,(float)4.19, TipDobanda.DOBANDA_FIXA);
//metode din clasa Credit
System.out.println("Plata in avans s-a putut/nu s-a putut efectua: "+c1.plataAnticipata(5000));
System.out.println("Plata in avans s-a putut/nu s-a putut efectua: "+c2.plataAnticipata(500));
System.out.println("Plata in avans s-a putut/nu s-a putut efectua: "+c3.plataAnticipata(2000));
System.out.println("Plata in avans s-a putut/nu s-a putut efectua: "+c4.plataAnticipata(3300));
System.out.println("Plata in avans s-a putut/nu s-a putut efectua: "+c5.plataAnticipata(3500));
System.out.println("Calculare rata: "+c2.calculareRataPerLuna());
System.out.println("Calculare rata: "+c1.calculareRataPerLuna());
System.out.println("Calculare rata: "+c3.calculareRataPerLuna());
System.out.println("Calculare rata: "+c4.calculareRataPerLuna());
System.out.println("Calculare rata: "+c5.calculareRataPerLuna());
System.out.println( "=====================================================================================================================================================");
//Acordarea de credite prin populare Map de lista credite acordate din banci
Credit acordat=bcr.acordareCredit(80000,10,p2, TipCredit.CREDIT_IPOTECAR_IMOBILIAR);
if(acordat!=null){
System.out.println("Creditul a fost acordat cu succes!");
}else{
System.out.println("Creditul nu a fost acordat din cauza unor probleme!");
}
Credit acordat1=bcr.acordareCredit(638312,15,p1, TipCredit.CREDIT_PRIMA_CASA);
if(acordat1!=null){
System.out.println("Creditul a fost acordat cu succes!");
}else{
System.out.println("Creditul nu a fost acordat din cauza unor probleme!");
}
Credit acordat2=bcr.acordareCredit(6482374,25,p3, TipCredit.CREDIT_NEVOI_PERSONALE);
if(acordat2!=null){
System.out.println("Creditul a fost acordat cu succes!");
}else{
System.out.println("Creditul nu a fost acordat din cauza unor probleme!");
}
Credit acordat4=brd.acordareCredit(42342343,30,p4, TipCredit.CREDIT_GAUDEAMUS);
if(acordat4!=null){
System.out.println("Creditul a fost acordat cu succes!");
}else{
System.out.println("Creditul nu a fost acordat din cauza unor probleme!");
}
Credit acordat5=brd.acordareCredit(3231111,10,p5, TipCredit.CREDIT_IPOTECAR);
if(acordat5!=null){
System.out.println("Creditul a fost acordat cu succes!");
}else{
System.out.println("Creditul nu a fost acordat din cauza unor probleme!");
}
Credit acordat6=bcr.acordareCredit(80000,p2, TipCredit.CREDIT_IPOTECAR_IMOBILIAR);
if(acordat!=null){
System.out.println("Creditul a fost acordat cu succes!");
}else{
System.out.println("Creditul nu a fost acordat din cauza unor probleme!");
}
//Metode definite in clasa Credit
System.out.println( "=====================================================================================================================================================");
//Metode definite in clasa Banca
System.out.println( brd.toString());
System.out.println("Se va afisa cursulDolar initial: " +brd.getCursValutarDolar());
brd.modificaCursDolar((float)1.00);
System.out.println("Se va afisa cursulDolar modificat(in scadere): " +brd.getCursValutarDolar());
System.out.println( brd.toString());
}
}
| 5,420 | 0.611255 | 0.573801 | 105 | 50.619049 | 45.242077 | 181 | false | false | 0 | 0 | 0 | 0 | 149 | 0.082472 | 1.238095 | false | false |
5
|
83a2a541364d05c1e60dd00597e5df289baafbb6
| 5,600,637,377,522 |
187f253296c50c5d29ebdc71da7adced16b483d3
|
/src/project/MyVisitor.java
|
e8bdfbf1b674ef61fd16ee8254b8f4fcc67b90d4
|
[] |
no_license
|
gar13177/Scanner
|
https://github.com/gar13177/Scanner
|
abde8501cd418b2d6917f70962d0aa7a88760ea7
|
ef4d721cae61c13fa10b21c19a0ca9407db51898
|
refs/heads/master
| 2021-01-21T14:01:20.949000 | 2016-06-02T16:36:22 | 2016-06-02T16:36:22 | 50,368,500 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package project;
import grammar.ANTLR.decafBaseVisitor;
import java.util.ArrayList;
import java.util.Stack;
import grammar.ANTLR.decafParser.*;
import static java.lang.Integer.parseInt;
import java.util.LinkedHashSet;
import org.antlr.v4.runtime.tree.ParseTree;
/*
* 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.
*/
/**
*
* @author Kevin
*/
public class MyVisitor extends decafBaseVisitor<Object> {
private LinkedHashSet<String> _types;//tipos predefinidos
private Stack<Scope> _scopes;//ambiente global
private Stack<Exception> _errors;//errores
private Method _methodRevision;
private IntermediateCodeBuilder _interCode = new IntermediateCodeBuilder();
public void initAll(){
_types = new LinkedHashSet();
_scopes = new Stack();
_scopes.push(new Scope());
_errors = new Stack();
setInterCode(new IntermediateCodeBuilder());
}
public Object visitProgram(ProgramContext ctx){
initAll();
//'class' ID '{' (declaration)* '}'
for (DeclarationContext child: ctx.declaration()){
Object obj = visit(child);//visitamos hijo
if (obj == null){
int line = child.getStart().getLine();
int column = child.getStart().getCharPositionInLine();
_errors.add(new Exception("Error en declaration @line: "+line+" @column: "+column));
}
}
if (_errors.empty()){
//System.out.println(getInterCode());
Method mt = _scopes.peek().hasMethodDef("main");
if (mt == null){
_errors.add(new Exception("main no definido"));
}
if (!mt.getMetType().equals("void")){
_errors.add(new Exception("main no definido como void"));
}
if (mt.getParams().size()>0){
_errors.add(new Exception("main espera parametros, no deberia"));
}
getInterCode().buildStringValue();
getInterCode().buildReturnValues();
getInterCode().finishBuilding();
return null;
}
//else: crear codigo intermedio
return null;
}
public Object visitDeclaration(DeclarationContext ctx){
if (ctx.methodDeclaration() != null){
Object obj = visitChildren(ctx);//
if (obj == null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error en methodDeclaration @line: "+line+" @column: "+column));
return null;
}
return "void";
}
if (ctx.structDeclaration() != null){
Object obj = visitChildren(ctx);
if (obj == null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error en structDeclaration @line: "+line+" @column: "+column));
return null;
}
Object[] structDec = (Object[]) obj;
//Object[] objR = {"struct", sd.getSize(), sd};
StructDef sd = _scopes.peek().hasStructDef(((StructDef) structDec[2]).getStructID());
if (sd != null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error struct '"+sd.getStructID()+"' previamente definido @line: "+line+" @column: "+column));
return null;
}
_scopes.peek().getStructures().add((StructDef) structDec[2]);//agregamos structure
return "void";
}
if (ctx.varDeclaration() != null){
Object obj = visitChildren(ctx);
if (obj == null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error en varDeclaration @line: "+line+" @column: "+column));
return null;
}
Variable varDec = (Variable) obj;
Variable var = _scopes.peek().hasVariableDef(varDec.getVarId());
if (var != null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable definida anteriormente '"+varDec.getVarId()+"' @line: "+line+" @column: "+column));
return null;
}
_scopes.peek().getVars().add(varDec);//agregamos variable
return "void";
}
return null;
}
public Object visitVarDeclaration(VarDeclarationContext ctx){
Object obj1 = visit(ctx.varType());
if (obj1 == null){
int line = ctx.varType().getStart().getLine();
int column = ctx.varType().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en varType @line: "+line+" @column: "+column));
return null;
}
Variable var;
Object[] varType = (Object[]) obj1;//casteamos obj1 como array
if (((String)varType[0]).equals("struct")){
var = new StructVar(ctx.ID().getText(),(StructDef) varType[2]);//si es struct, se crea un struct
}else{
var = new Variable(ctx.ID().getText(), (String)varType[0], (int)varType[1]);//si es variable, se crea variable
}
var.updateTotalSize();
if (ctx.getChildCount()<=3)
return var;
//de lo contrario
int length = Integer.parseInt(ctx.NUM().getText());//parseamos length
var.setArray(true);//lo identificamos como array
var.setArraySize(length);//iniciamos su tamanio
var.updateTotalSize();//
return var;//retornamos variable
}
public Object visitVarType(VarTypeContext ctx){
if (ctx.getChild(0).getText().equals("int")){
Object[] obj = {"int", 4};
return obj;
}
if (ctx.getChild(0).getText().equals("char")){
Object[] obj = {"char", 4};
return obj;
}
if (ctx.getChild(0).getText().equals("boolean")){
Object[] obj = {"boolean", 4};
return obj;
}
if (ctx.getChild(0).getText().equals("struct")){
String id = ctx.ID().getText();
StructDef sd = _scopes.peek().hasStructDef(id);
if (sd == null){
sd = _scopes.get(0).hasStructDef(id);
if (sd == null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error tipo struct '"+id+"' no definido @line: "+line+" @column: "+column));
return null;
}
}
Object[] obj = {"struct", sd.getSize(),sd};//retornamos struct, tamanio y struct referencia
return obj;
}
//visita structDeclaration
Object obj = visitChildren(ctx);
if (obj == null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error en structDeclaration @line: "+line+" @column: "+column));
return null;
}
Object[] structDec = (Object[]) obj;
//Object[] objR = {"struct", sd.getSize(), sd};
StructDef sd = _scopes.peek().hasStructDef(((StructDef) structDec[2]).getStructID());
if (sd != null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error struct '"+sd.getStructID()+"' previamente definido @line: "+line+" @column: "+column));
return null;
}
_scopes.peek().getStructures().add((StructDef) structDec[2]);//agregamos structure
return structDec;
}
public Object visitStructDeclaration(StructDeclarationContext ctx){
StructDef sd = _scopes.peek().hasStructDef(ctx.ID().getText());//buscamos
if (sd != null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error tipo struct '"+ctx.ID().getText()+"' ya definido @line: "+line+" @column: "+column));
return null;
}
sd = new StructDef(ctx.ID().getText());
boolean errores = false;
for (VarDeclarationContext vd: ctx.varDeclaration()){
if (vd.varType().structDeclaration() != null){
int line = vd.getStart().getLine();
int column = vd.getStart().getCharPositionInLine();
_errors.add(new Exception("Error no se puede declarar tipo struct en struct @line: "+line+" @column: "+column));
errores = true;
}else{
Object obj = visit(vd);//visitamos
if (obj == null){
int line = vd.getStart().getLine();
int column = vd.getStart().getCharPositionInLine();
_errors.add(new Exception("Error declaracion de variable @line: "+line+" @column: "+column));
errores = true;
}else{
Variable var = (Variable)obj;//casteamos el objeto a variable
Variable v2 = sd.hasVariable(var.getVarId());//identificamos si ya la tiene
if (v2 != null){
int line = vd.getStart().getLine();
int column = vd.getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable '"+v2.getVarId()+"' previamente definida @line: "+line+" @column: "+column));
errores = true;
}else{
sd.add(var);//agregamos la variable si no tiene errores y no existe previamente
}
}
}
}
if (errores){
return null;
}
sd.updateSize();
Object[] objR = {"struct", sd.getSize(), sd};//creamos el objeto de retorno
return objR;
}
public Object visitMethodDeclaration(MethodDeclarationContext ctx){
String type = ctx.methodType().getText();
String id = ctx.ID().toString();
getInterCode().newMethod(id);
LinkedHashSet<Variable> parameters = new LinkedHashSet();
boolean errores = false;
for (ParameterContext pr: ctx.parameter()){
Object obj = visit(pr);
if (obj == null){
int line = pr.getStart().getLine();
int column = pr.getStart().getCharPositionInLine();
_errors.add(new Exception("Error en parameter @line: "+line+" @column: "+column));
errores = true;
}else{
Variable var = (Variable) obj;//variable de retorno
int contador= 0;
for (Variable param: parameters){
if (param.getVarId().equals(var.getVarId())){
int line = pr.getStart().getLine();
int column = pr.getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable definida anteriormente '"+param.getVarId()+"' @line: "+line+" @column: "+column));
errores = true;
contador++;
}
}
if (contador==0){
parameters.add(var);
}
}
}
Method mt = new Method(id,type);
mt.setParams(parameters);//agregamos parametros
mt.setParamsAsVars();//agregamos los parametros como variables locales
int tamanio_de_parametro = mt.getVarsSize();
getInterCode().setParam_size(tamanio_de_parametro);
LinkedHashSet<Method> tempMethods = new LinkedHashSet();
tempMethods.addAll(_scopes.peek().getMethods());//guardamos los metodos pervios
_scopes.peek().getMethods().add(mt);//agregamos el metodo por si hay recursion
_scopes.push(new Scope());
_scopes.peek().setVars(mt.getVars());//generamos el nuevo scope con las variables ya definidas
_scopes.peek().getMethods().add(mt);//agregamos metodo a nuevo scope para evaluacion de tipo
//
Object obj = visit(ctx.block());//visitamos block
Scope nscope = _scopes.pop();
if (obj == null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error en declaracion de metodo '"+mt.getMetID()+"' @line: "+line+" @column: "+column));
_scopes.peek().setMethods(tempMethods);//regresamos a los metodos previos
errores = true;
}
Method mtn = new Method();
for (Method m: nscope.getMethods()){
mtn = m;
}
if (!mtn.isReturn() && !mtn.getMetType().equals("void") ){//si no tiene retorno y no es void
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error en declaracion de metodo '"+mt.getMetID()+"' sin retorno @line: "+line+" @column: "+column));
_scopes.peek().setMethods(tempMethods);//regresamos a los metodos previos
errores = true;
}
if (!mtn.getMetType().equals("void")){//si no es void, se crea variable de retorno
getInterCode().setNewReturn();
}
//asignamos las cosas nuevas al metodo
mt.setReturn(true);
mt.setVars(nscope.getVars());
mt.setStructures(nscope.getStructures());
if (errores) return null;
getInterCode().buildMethod();
return "void";
}
public Object visitBlock (BlockContext ctx){
LinkedHashSet<Variable> _vars = new LinkedHashSet();//variables definidas en este scope
LinkedHashSet<Method> _methods = new LinkedHashSet();//metodos definidos en este scope
LinkedHashSet<StructDef> _structures = new LinkedHashSet();//estructuras definidas
_vars.addAll(_scopes.peek().getVars());
_methods.addAll(_scopes.peek().getMethods());
_structures.addAll(_scopes.peek().getStructures());
boolean errores = false;
for (int i = 1; i < ctx.getChildCount()-1; i++){
ParseTree child = ctx.getChild(i);
if (child instanceof VarDeclarationContext){
VarDeclarationContext vdc = (VarDeclarationContext) child;
Object obj = visit(vdc);//visitamos varDeclaration
if (obj == null){
int line = vdc.getStart().getLine();
int column = vdc.getStart().getCharPositionInLine();
_errors.add(new Exception("Error en parameter @line: "+line+" @column: "+column));
errores = true;
}else{
Variable varDec = (Variable) obj;
Variable var = _scopes.peek().hasVariableDef(varDec.getVarId());
if (var != null){
int line = vdc.getStart().getLine();
int column = vdc.getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable definida anteriormente '"+varDec.getVarId()+"' @line: "+line+" @column: "+column));
errores = true;
}else{
_scopes.peek().getVars().add(varDec);//agregamos variable
}
}
}else if (child instanceof StatementContext){
StatementContext st = (StatementContext) child;
Object obj = visit(st);//visitamos statement
if (obj == null){
int line = st.getStart().getLine();
int column = st.getStart().getCharPositionInLine();
_errors.add(new Exception("Error en statement @line: "+line+" @column: "+column));
errores = true;
}else{
Object[] type_code = (Object[])obj;
String type = (String) type_code[0];//guarda el tipo del statement
String code = (String) type_code[1];//guarda el codigo intermedio del statement
}
}
}
/*
for (VarDeclarationContext vdc: ctx.varDeclaration()){//para cada definicion de variable
Object obj = visit(vdc);//visitamos varDeclaration
if (obj == null){
int line = vdc.getStart().getLine();
int column = vdc.getStart().getCharPositionInLine();
_errors.add(new Exception("Error en parameter @line: "+line+" @column: "+column));
errores = true;
}else{
Variable varDec = (Variable) obj;
Variable var = _scopes.peek().hasVariableDef(varDec.getVarId());
if (var != null){
int line = vdc.getStart().getLine();
int column = vdc.getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable definida anteriormente '"+varDec.getVarId()+"' @line: "+line+" @column: "+column));
errores = true;
}else{
_scopes.peek().getVars().add(varDec);//agregamos variable
}
}
}
for (StatementContext st: ctx.statement()){
Object obj = visit(st);//visitamos statement
if (obj == null){
int line = st.getStart().getLine();
int column = st.getStart().getCharPositionInLine();
_errors.add(new Exception("Error en statement @line: "+line+" @column: "+column));
errores = true;
}else{
Object[] type_code = (Object[])obj;
String type = (String) type_code[0];//guarda el tipo del statement
String code = (String) type_code[1];//guarda el codigo intermedio del statement
}
}
*/
_scopes.peek().setMethods(_methods);
_scopes.peek().setStructures(_structures);
_scopes.peek().setVars(_vars);
if (errores) return null;
Object[] returnO = {"void",""};
return returnO;
}
public Object visitStatementIf (StatementIfContext ctx){
Object obj = visit(ctx.expression());//visitamos expression
if (obj == null){
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en expression @line: "+line+" @column: "+column));
return null;
}
Object[] type_code = (Object[])obj;
String type = (String) type_code[0];//guarda el tipo del statement
String code = (String) type_code[1];//guarda el codigo intermedio del statement
if (!type.equals("boolean")){
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en expression no booleana @line: "+line+" @column: "+column));
return null;
}
getInterCode().newIf();
int i = 0;
for (BlockContext bc: ctx.block()){
Object objB = visit(bc);//visitamos bloque
if (objB == null){
int line = bc.getStart().getLine();
int column = bc.getStart().getCharPositionInLine();
_errors.add(new Exception("Error en bloque if @line: "+line+" @column: "+column));
return null;
}
Object[] type_codeB = (Object[])objB;
String typeB = (String) type_code[0];//guarda el tipo del statement
String codeB = (String) type_code[1];//guarda el codigo intermedio del statement
if (i==0) getInterCode().newElse();
i++;
}
getInterCode().endIf();
Object[] returnO = {"void",""};
return returnO ;
}
public Object visitStatementWhile (StatementWhileContext ctx){
getInterCode().newWhile();
Object obj = visit(ctx.expression());//visitamos expression
if (obj == null){
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en expression @line: "+line+" @column: "+column));
return null;
}
getInterCode().meanWhile();
Object[] type_code = (Object[])obj;
String type = (String) type_code[0];//guarda el tipo del statement
String code = (String) type_code[1];//guarda el codigo intermedio del statement
if (!type.equals("boolean")){
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en expression no booleana @line: "+line+" @column: "+column));
return null;
}
Object objB = visit(ctx.block());//visitamos bloque
if (objB == null){
int line = ctx.block().getStart().getLine();
int column = ctx.block().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en bloque while @line: "+line+" @column: "+column));
return null;
}
Object[] type_codeB = (Object[])objB;
String typeB = (String) type_code[0];//guarda el tipo del statement
String codeB = (String) type_code[1];//guarda el codigo intermedio del statement
getInterCode().endWhile();
Object[] returnO = {"void",""};
return returnO;
}
public Object visitStatementReturn (StatementReturnContext ctx){
if (ctx.expression() == null){
//como se que solo puede haber un metodo en este momento
for (Method mt: _scopes.peek().getMethods()){
String methodType = mt.getMetType();
if (!methodType.equals("void")){
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en tipo de metodo: '"+methodType+"' no es tipo expression: 'void' @line: "+line+" @column: "+column));
return null;
}else{
mt.setReturn(true);
getInterCode().buildReturnVoid();
Object[] returnO = {"void",""};
return returnO;
}
}
}
Object obj = visit(ctx.expression());//visitamos expression
if (obj == null){
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en expression @line: "+line+" @column: "+column));
return null;
}
Object[] type_code = (Object[])obj;
String type = (String) type_code[0];//guarda el tipo del statement
String code = (String) type_code[1];//guarda el codigo intermedio del statement
for (Method mt: _scopes.peek().getMethods()){
String methodType = mt.getMetType();
if (!methodType.equals(type)){
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en tipo de metodo: '"+methodType+"' no es tipo expression: '"+type+"' @line: "+line+" @column: "+column));
return null;
}else{
mt.setReturn(true);
getInterCode().buildReturn();
Object[] returnO = {"void",""};
return returnO;
}
}
Object[] returnO = {"void",""};
return returnO;
}
public Object visitStatementAsign (StatementAsignContext ctx){
getInterCode().setNeeds_value(false);
Object objL = visit(ctx.location());
if (objL == null){
int line = ctx.location().getStart().getLine();
int column = ctx.location().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en location @line: "+line+" @column: "+column));
return null;
}
Object[] type_codeL = (Object[])objL;
String typeL = (String) type_codeL[0];//guarda el tipo del statement
String codeL = (String) type_codeL[1];//guarda el codigo intermedio del statement
//location
getInterCode().pushTempActual();
getInterCode().setNeeds_value(true);
Object objE = visit(ctx.expression());
if (objE == null){
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en expression @line: "+line+" @column: "+column));
return null;
}
Object[] type_codeE = (Object[])objE;
String typeE = (String) type_codeE[0];//guarda el tipo del statement
String codeE = (String) type_codeE[1];//guarda el codigo intermedio del statement
if (!typeL.equals(typeE)){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error tipo location: '"+typeL+"' no concuerda tipo expression: '"+typeE+"' @line: "+line+" @column: "+column));
return null;
}
//tenemos expression
getInterCode().setLastAsLeft();
getInterCode().popTempActual();
getInterCode().setLastAsEq();
getInterCode().buildEqual();
Object[] returnO = {"void",""};
return returnO;
}
public Object visitStatementExp (StatementExpContext ctx){
getInterCode().setNeeds_value(true);
return visit(ctx.expression());//retornamos valor de expression
}
public Object visitStatementPrint(StatementPrintContext ctx){
String value = ctx.STRING().getText();
System.out.println(value);
_interCode.addNewString(value);
boolean param = false;
if (ctx.expression() != null){
getInterCode().setNeeds_value(true);
Object obj = visit(ctx.expression());
if (obj == null){
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en expression @line: "+line+" @column: "+column));
return null;
}
getInterCode().setLastAsLeft();
param = true;
}
getInterCode().setNewPrint(param);
Object[] returnO = {"void",""};
return returnO;
}
public Object visitLocationID(LocationIDContext ctx){
Variable var = _scopes.peek().hasVariableDef(ctx.ID().getText());
int offset =0;
boolean global = false;
if (var == null){
var = _scopes.get(0).hasVariableDef(ctx.ID().getText());
if (var == null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable '"+ctx.ID().getText()+"' no definida @line: "+line+" @column: "+column));
return null;
}
offset = _scopes.get(0).offsetOfVar(ctx.ID().getText());
getInterCode().setIntLiteral(""+offset);
getInterCode().setGlobalPointer();
}else{
offset = _scopes.peek().offsetOfVar(ctx.ID().getText());//extraigo offset desde inicio
//getInterCode().setIntLiteral(""+offset);
getInterCode().setOffset(offset);//regresar
getInterCode().setLocalPointer();
}
String type = var.getVarType();//'tipo'
if (type.equals("struct")){
type+= ((StructVar) var).getStructID().getStructID();
}
if (var.isArray()) type += "array";
Object[] returnO = {type,""};
return returnO;
}
public Object visitLocationExp(LocationExpContext ctx){
Variable var = _scopes.peek().hasVariableDef(ctx.ID().getText());
int offset =0;
boolean global = false;
if (var == null){
var = _scopes.get(0).hasVariableDef(ctx.ID().getText());
if (var == null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable '"+ctx.ID().getText()+"' no definida @line: "+line+" @column: "+column));
return null;
}
offset = _scopes.get(0).offsetOfVar(ctx.ID().getText());
global = true;
}else{
offset = _scopes.peek().offsetOfVar(ctx.ID().getText());//extraigo offset desde inicio
}
if (!var.isArray()){
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable '"+ctx.ID().getText()+"' no definida como array @line: "+line+" @column: "+column));
return null;
}
//quiere decir que si es array, y se esta llamando expression
Object obj = visit(ctx.expression());//visitamos expression
if (obj == null){//error en expression
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en expression @line: "+line+" @column: "+column));
return null;
}
//si no existe error
Object[] type_codeE = (Object[])obj;
String typeE = (String) type_codeE[0];//guarda el tipo del expression
String codeE = (String) type_codeE[1];//guarda el codigo intermedio del expression
//expression ya tiene el valor del indice
if (!typeE.equals("int")){
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en expression no de tipo int @line: "+line+" @column: "+column));
return null;
}
getInterCode().setLastAsLeft();//tenemos las posiciones en la izquierda gracias a expression
//_interCode.setIntLiteral(""+offset);
Variable var1 = new Variable();
if (var.getVarType().equals("struct")){
var1 = new StructVar(ctx.ID().getText(),((StructVar)var).getStructID());
}else{
var1 = new Variable(var.getVarId(),var.getVarType(), var.getSize());
}
getInterCode().setIntLiteral(var1.getTotalSize()+"");//tomamos el tamanio de dicha variable
getInterCode().setLastAsRight();
getInterCode().buildOperation("*");//multiplicamos para llegar al offset
getInterCode().setLastAsLeft();
getInterCode().setIntLiteral(""+offset);
getInterCode().setLastAsRight();
getInterCode().buildOperation("+");
if (global){
getInterCode().setGlobalPointer();
}else{
getInterCode().setLocalPointer();
}
String type = var1.getVarType();//'tipo'
if (type.equals("struct")){
type+= ((StructVar) var1).getStructID().getStructID();
}
if (var1.isArray()) type += "array";
Object[] returnO = {type,""};
return returnO;
}
public Object visitLocationIDlocation(LocationIDlocationContext ctx){
Variable var = _scopes.peek().hasVariableDef(ctx.ID().getText());
int offset =0;
boolean global = false;
if (var == null){
var = _scopes.get(0).hasVariableDef(ctx.ID().getText());
if (var == null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable '"+ctx.ID().getText()+"' no definida @line: "+line+" @column: "+column));
return null;
}
offset = _scopes.get(0).offsetOfVar(ctx.ID().getText());
global = true;
}else{
offset = _scopes.peek().offsetOfVar(ctx.ID().getText());//extraigo offset desde inicio
}
String type = var.getVarType();//'tipo'
if (!type.equals("struct")){//no es struct y se llama a location
int line = ctx.location().getStart().getLine();
int column = ctx.location().getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable no definida como 'struct' @line: "+line+" @column: "+column));
return null;
}
if (var.isArray()){
int line = ctx.location().getStart().getLine();
int column = ctx.location().getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable tipo array no tiene location definido @line: "+line+" @column: "+column));
return null;
}
Object obj = visitLocationContinuos(ctx.location(), (StructVar)var);
//retorna el valor del offset
getInterCode().setLastAsLeft();
getInterCode().setIntLiteral(""+offset);
getInterCode().setLastAsRight();
getInterCode().buildOperation("+");
if (global){
getInterCode().setGlobalPointer();
}else{
getInterCode().setLocalPointer();
}
return obj;
}
public Object visitLocationExplocation (LocationExplocationContext ctx){
Variable var = _scopes.peek().hasVariableDef(ctx.ID().getText());
int offset =0;
boolean global = false;
if (var == null){
var = _scopes.get(0).hasVariableDef(ctx.ID().getText());
if (var == null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable '"+ctx.ID().getText()+"' no definida @line: "+line+" @column: "+column));
return null;
}
offset = _scopes.get(0).offsetOfVar(ctx.ID().getText());
global = true;
}else{
offset = _scopes.peek().offsetOfVar(ctx.ID().getText());//extraigo offset desde inicio
}
if (!var.isArray()){//si no es array
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable tipo array no tiene location definido @line: "+line+" @column: "+column));
return null;
}
Object obj = visit(ctx.expression());//visitamos expression
if (obj == null){//error en expression
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en expression @line: "+line+" @column: "+column));
return null;
}
//si no existe error
Object[] type_codeE = (Object[])obj;
String typeE = (String) type_codeE[0];//guarda el tipo del expression
String codeE = (String) type_codeE[1];//guarda el codigo intermedio del expression
if (!typeE.equals("int")){
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en expression no de tipo int @line: "+line+" @column: "+column));
return null;
}
//si todo esta bien, expression tiene el offset en el ultimo
getInterCode().setLastAsLeft();//tomamos el tamanio y lo ponemos de izquierdo
String type = var.getVarType();//'tipo'
if (!type.equals("struct")){//no es struct y se llama a location
int line = ctx.location().getStart().getLine();
int column = ctx.location().getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable no definida como 'struct' @line: "+line+" @column: "+column));
return null;
}
int objLength = 0;
StructVar nvar = new StructVar(var.getVarId(),((StructVar)var).getStructID());
objLength = nvar.getTotalSize();//tomamos todo el tamanio de esa onda
type+= ((StructVar) var).getStructID().getStructID();
getInterCode().setIntLiteral(""+objLength);//tomamos el tamanio de cada objeto
getInterCode().setLastAsRight();
getInterCode().buildOperation("*");//multiplicamos ambas partes
getInterCode().setLastAsLeft();//tomamos el resultado y lo colocamos a la izquierda
getInterCode().setIntLiteral(""+offset);//agregamos el offset de esta variable
getInterCode().setLastAsRight();
getInterCode().buildOperation("+");
getInterCode().pushTempActual();
Object obj1 = visitLocationContinuos(ctx.location(),nvar);
getInterCode().setLastAsLeft();//colocamos el offset a la izquierda
getInterCode().popTempActual();
getInterCode().setLastAsRight();
getInterCode().buildOperation("+");
if (global){
getInterCode().setGlobalPointer();
}else{
getInterCode().setLocalPointer();
}
return obj1;
}
public Object visitLocationIDContext(LocationIDContext ctx, StructVar varCheck){
Variable var = varCheck.getStructID().hasVariable(ctx.ID().getText());
if (var == null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable '"+ctx.ID().getText()+"' no definida @line: "+line+" @column: "+column));
return null;
}
int offset = varCheck.getStructID().offsetOfVar(ctx.ID().getText());
getInterCode().setIntLiteral(""+offset);
String type = var.getVarType();//'tipo'
if (type.equals("struct")){
type+= ((StructVar) var).getStructID().getStructID();
}
if (var.isArray()) type += "array";
Object[] returnO = {type,""};
return returnO;
}
public Object visitLocationIDlocation(LocationIDlocationContext ctx, StructVar varCheck){
Variable var = varCheck.getStructID().hasVariable(ctx.ID().getText());
if (var == null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable '"+ctx.ID().getText()+"' no definida @line: "+line+" @column: "+column));
return null;
}
String type = var.getVarType();//'tipo'
if (!type.equals("struct")){//no es struct y se llama a location
int line = ctx.location().getStart().getLine();
int column = ctx.location().getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable no definida como 'struct' @line: "+line+" @column: "+column));
return null;
}
if (var.isArray()){
int line = ctx.location().getStart().getLine();
int column = ctx.location().getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable tipo array no tiene location definido @line: "+line+" @column: "+column));
return null;
}
Object obj = visitLocationContinuos(ctx.location(), (StructVar)var);
//retorna el valor del offset
getInterCode().setLastAsLeft();
int offset = varCheck.getStructID().offsetOfVar(ctx.ID().getText());
getInterCode().setIntLiteral(""+offset);
getInterCode().setLastAsRight();
getInterCode().buildOperation("+");
return obj;
}
public Object visitLocationExpContext(LocationExpContext ctx, StructVar varCheck){
Variable var = varCheck.getStructID().hasVariable(ctx.ID().getText());
if (var == null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable '"+ctx.ID().getText()+"' no definida @line: "+line+" @column: "+column));
return null;
}
int offset = varCheck.getStructID().offsetOfVar(ctx.ID().getText());
if (!var.isArray()){//si no es array
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable tipo array no tiene location definido @line: "+line+" @column: "+column));
return null;
}
Object obj = visit(ctx.expression());//visitamos expression
if (obj == null){//error en expression
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en expression @line: "+line+" @column: "+column));
return null;
}
//si no existe error
Object[] type_codeE = (Object[])obj;
String typeE = (String) type_codeE[0];//guarda el tipo del expression
String codeE = (String) type_codeE[1];//guarda el codigo intermedio del expression
if (!typeE.equals("int")){
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en expression no de tipo int @line: "+line+" @column: "+column));
return null;
}
//si todo esta bien, expression tiene el offset en el ultimo
getInterCode().setLastAsLeft();//tomamos el tamanio y lo ponemos de izquierdo
String type = var.getVarType();//'tipo'
int objLength = 0;
if (type.equals("struct")){//si lo que guarda es un array de struct
StructVar nvar = new StructVar(var.getVarId(),((StructVar)var).getStructID());
objLength = nvar.getTotalSize();//tomamos todo el tamanio de esa onda
type+= ((StructVar) var).getStructID().getStructID();
if (nvar.isArray()) type += "array";
}else{
Variable nvar = new Variable(var.getVarId(),var.getVarType(), var.getSize());
objLength = nvar.getTotalSize();
if (nvar.isArray()) type += "array";
}
getInterCode().setIntLiteral(""+objLength);//tomamos el tamanio de cada objeto
getInterCode().buildOperation("*");//multiplicamos ambas partes
getInterCode().setLastAsLeft();//tomamos el resultado y lo colocamos a la izquierda
getInterCode().setIntLiteral(""+offset);//agregamos el offset de esta variable
getInterCode().setLastAsRight();
getInterCode().buildOperation("+");
Object[] returnO = {type,""};
return returnO;
}
public Object visitLocationExplocationContext(LocationExplocationContext ctx, StructVar varCheck){
Variable var = varCheck.getStructID().hasVariable(ctx.ID().getText());
if (var == null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable '"+ctx.ID().getText()+"' no definida @line: "+line+" @column: "+column));
return null;
}
int offset = varCheck.getStructID().offsetOfVar(ctx.ID().getText());
if (!var.isArray()){//si no es array
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable tipo array no tiene location definido @line: "+line+" @column: "+column));
return null;
}
Object obj = visit(ctx.expression());//visitamos expression
if (obj == null){//error en expression
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en expression @line: "+line+" @column: "+column));
return null;
}
//si no existe error
Object[] type_codeE = (Object[])obj;
String typeE = (String) type_codeE[0];//guarda el tipo del expression
String codeE = (String) type_codeE[1];//guarda el codigo intermedio del expression
if (!typeE.equals("int")){
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en expression no de tipo int @line: "+line+" @column: "+column));
return null;
}
//si todo esta bien, expression tiene el offset en el ultimo
getInterCode().setLastAsLeft();//tomamos el tamanio y lo ponemos de izquierdo
String type = var.getVarType();//'tipo'
if (!type.equals("struct")){//no es struct y se llama a location
int line = ctx.location().getStart().getLine();
int column = ctx.location().getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable no definida como 'struct' @line: "+line+" @column: "+column));
return null;
}
int objLength = 0;
StructVar nvar = new StructVar(var.getVarId(),((StructVar)var).getStructID());
objLength = nvar.getTotalSize();//tomamos todo el tamanio de esa onda
type+= ((StructVar) var).getStructID().getStructID();
getInterCode().setIntLiteral(""+objLength);//tomamos el tamanio de cada objeto
getInterCode().setLastAsRight();
getInterCode().buildOperation("*");//multiplicamos ambas partes
getInterCode().setLastAsLeft();//tomamos el resultado y lo colocamos a la izquierda
getInterCode().setIntLiteral(""+offset);//agregamos el offset de esta variable
getInterCode().setLastAsRight();
getInterCode().buildOperation("+");
getInterCode().pushTempActual();
Object obj1 = visitLocationContinuos(ctx.location(),nvar);
getInterCode().setLastAsLeft();//colocamos el offset a la izquierda
getInterCode().popTempActual();
getInterCode().setLastAsRight();
getInterCode().buildOperation("+");
return obj1;
}
public Object visitLocationContinuos(LocationContext ctx, StructVar varCheck){
if (ctx instanceof LocationIDContext){
return visitLocationIDContext((LocationIDContext) ctx, varCheck);
}
if (ctx instanceof LocationIDlocationContext){
return visitLocationIDlocation((LocationIDlocationContext) ctx, varCheck);
}
if (ctx instanceof LocationExpContext){
return visitLocationExpContext((LocationExpContext) ctx, varCheck);
}
if (ctx instanceof LocationExplocationContext ){
return visitLocationExplocationContext((LocationExplocationContext) ctx, varCheck);
}
return null;
}
public Object visitMethodCall (MethodCallContext ctx){
String id = ctx.ID().getText();//nombre
Method mt = _scopes.get(0).hasMethodDef(id);
if (mt == null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error metodo '"+id+"' no definido @line: "+line+" @column: "+column));
return null;
}
ArrayList<String> params = new ArrayList();
for (ArgContext arg: ctx.arg()){
Object obj = visit(arg);
if (obj == null){
int line = arg.getStart().getLine();
int column = arg.getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de parametro @line: "+line+" @column: "+column));
return null;
}
Object[] type_code = (Object[])obj;
String type = (String) type_code[0];//guarda el tipo del expression
String code = (String) type_code[1];//guarda el codigo intermedio del expression
params.add(type);
getInterCode().pushParam();
}
if (params.size() != mt.getParams().size()){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de parametros, se esperan "+mt.getParams().size()+"' parametros @line: "+line+" @column: "+column));
return null;
}
int i = 0;
for (Variable v: mt.getParams()){
String typeParam = params.get(i);
String typeVar = v.getVarType();
if (typeVar.equals("struct")){
typeVar += ((StructVar)v).getStructID().getStructID();
}
if (v.isArray()) typeVar += "array";
if (!typeParam.equals(typeVar)){//si no son iguales
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de parametros, se esperaba "+typeVar+"', se obtuvo '"+typeParam+"' @line: "+line+" @column: "+column));
return null;
}
i++;
}
getInterCode().callMethod(id);
Object[] returnO = {mt.getMetType(),""};
return returnO;
}
public Object visitCondOp (CondOpContext ctx){
if (ctx.getChildCount()<=1) return visitChildren(ctx);//retornamos mulOrDiv
Object obj1 = visit(ctx.condOp());
if (obj1 == null){
int line = ctx.condOp().getStart().getLine();
int column = ctx.condOp().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de condOp @line: "+line+" @column: "+column));
return null;
}
getInterCode().pushTempActual();//guardamos el actual
//getInterCode().setLastAsLeft();
Object obj2 = visit(ctx.assignOp());
if (obj2 == null){
int line = ctx.assignOp().getStart().getLine();
int column = ctx.assignOp().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de assignOp @line: "+line+" @column: "+column));
return null;
}
getInterCode().setLastAsRight();
getInterCode().popTempActual();
getInterCode().setLastAsLeft();
Object[] type_code1 = (Object[])obj1;
String type1 = (String) type_code1[0];//guarda el tipo del expression
String code1 = (String) type_code1[1];//guarda el codigo intermedio del expression
Object[] type_code2 = (Object[])obj2;
String type2 = (String) type_code2[0];//guarda el tipo del expression
String code2 = (String) type_code2[1];//guarda el codigo intermedio del expression
if (!type1.equals("boolean")){
int line = ctx.condOp().getStart().getLine();
int column = ctx.condOp().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de condOp no es de tipo boolean @line: "+line+" @column: "+column));
return null;
}
if (!type2.equals("boolean")){
int line = ctx.assignOp().getStart().getLine();
int column = ctx.assignOp().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de assignOp no es de tipo boolean @line: "+line+" @column: "+column));
return null;
}
getInterCode().buildOperation(ctx.getChild(1).getText());
Object[] returnO = {"boolean",""};
return returnO;
}
public Object visitAssignOp (AssignOpContext ctx){
if (ctx.getChildCount() <=1) return visitChildren(ctx);
Object obj1 = visit(ctx.assignOp());
if (obj1 == null){
int line = ctx.assignOp().getStart().getLine();
int column = ctx.assignOp().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de assignOp @line: "+line+" @column: "+column));
return null;
}
getInterCode().pushTempActual();//metemos el actual a la pila
//getInterCode().setLastAsLeft();
Object obj2 = visit(ctx.pow2());
if (obj2 == null){
int line = ctx.pow2().getStart().getLine();
int column = ctx.pow2().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de pow2 @line: "+line+" @column: "+column));
return null;
}
getInterCode().setLastAsRight();//ponemos el ultimo de lado derecho
getInterCode().popTempActual();//sacamos el del lado izquierdo
getInterCode().setLastAsLeft();//lo ponemos como lado izquierdo
Object[] type_code1 = (Object[])obj1;
String typeE1 = (String) type_code1[0];//guarda el tipo del expression
String code1 = (String) type_code1[1];//guarda el codigo intermedio del expression
Object[] type_code2 = (Object[])obj2;
String typeE2 = (String) type_code2[0];//guarda el tipo del expression
String code2 = (String) type_code2[1];//guarda el codigo intermedio del expression
String op = (String)visit(ctx.op());//op
if (!typeE2.equals(typeE1)){
int line = ctx.op().getStart().getLine();
int column = ctx.op().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en tipo: '"+typeE1+"' no comparable con tipo: '"+typeE2+"' @line: "+line+" @column: "+column));
return null;
}
//'<' | '>' | '<=' | '>='
//'==' | '!='
//'&&' | '||'
switch (op){
case "<":
if (!typeE1.equals("int")){
int line = ctx.op().getStart().getLine();
int column = ctx.op().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en tipo: '"+typeE1+"' no comparable '<' @line: "+line+" @column: "+column));
return null;
}
break;
case ">":
if (!typeE1.equals("int")){
int line = ctx.op().getStart().getLine();
int column = ctx.op().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en tipo: '"+typeE1+"' no comparable '>' @line: "+line+" @column: "+column));
return null;
}
break;
case "<=":
if (!typeE1.equals("int")){
int line = ctx.op().getStart().getLine();
int column = ctx.op().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en tipo: '"+typeE1+"' no comparable '<=' @line: "+line+" @column: "+column));
return null;
}
break;
case ">=":
if (!typeE1.equals("int")){
int line = ctx.op().getStart().getLine();
int column = ctx.op().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en tipo: '"+typeE1+"' no comparable '>=' @line: "+line+" @column: "+column));
return null;
}
break;
case "==":
break;
case "!=":
break;
}
getInterCode().buildOperation(op);
Object[] returnO = {"boolean",""};
return returnO;
}
public Object visitUnaryMinus2 (UnaryMinus2Context ctx){
if (ctx.unaryMinus2() != null){
Object obj = visit(ctx.unaryMinus2());
if (obj == null){
int line = ctx.unaryMinus2().getStart().getLine();
int column = ctx.unaryMinus2().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de unaryMinus2 @line: "+line+" @column: "+column));
return null;
}
getInterCode().toNot();
return obj;
}
return visitChildren(ctx);
}
public Object visitAtom2 (Atom2Context ctx){
if (ctx.condOp() != null) return visit(ctx.condOp());
return visitChildren(ctx);
}
public Object visitPlusOrMinus (PlusOrMinusContext ctx){
if (ctx.getChildCount()<=1) return visitChildren(ctx);//retornamos mulOrDiv
Object obj1 = visit(ctx.plusOrMinus());
if (obj1 == null){
int line = ctx.plusOrMinus().getStart().getLine();
int column = ctx.plusOrMinus().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de plusOrMinus @line: "+line+" @column: "+column));
return null;
}
getInterCode().pushTempActual();
//getInterCode().setLastAsLeft();
Object obj2 = visit(ctx.multOrDiv());
if (obj2 == null){
int line = ctx.multOrDiv().getStart().getLine();
int column = ctx.multOrDiv().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de multOrDiv @line: "+line+" @column: "+column));
return null;
}
getInterCode().setLastAsRight();
getInterCode().popTempActual();
getInterCode().setLastAsLeft();
Object[] type_code1 = (Object[])obj1;
String type1 = (String) type_code1[0];//guarda el tipo del expression
String code1 = (String) type_code1[1];//guarda el codigo intermedio del expression
Object[] type_code2 = (Object[])obj2;
String type2 = (String) type_code2[0];//guarda el tipo del expression
String code2 = (String) type_code2[1];//guarda el codigo intermedio del expression
if (!type1.equals("int")){
int line = ctx.plusOrMinus().getStart().getLine();
int column = ctx.plusOrMinus().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de plusOrMinus no es de tipo int @line: "+line+" @column: "+column));
return null;
}
if (!type2.equals("int")){
int line = ctx.multOrDiv().getStart().getLine();
int column = ctx.multOrDiv().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de multOrDiv no es tipo int @line: "+line+" @column: "+column));
return null;
}
getInterCode().buildOperation(ctx.getChild(1).getText());
Object[] returnO = {"int",""};
return returnO;
}
public Object visitMultOrDiv (MultOrDivContext ctx){
if (ctx.getChildCount() <=1) return visitChildren(ctx);
Object obj1 = visit(ctx.multOrDiv());
if (obj1 == null){
int line = ctx.multOrDiv().getStart().getLine();
int column = ctx.multOrDiv().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de multOrDiv @line: "+line+" @column: "+column));
return null;
}
getInterCode().pushTempActual();
//getInterCode().setLastAsLeft();
Object obj2 = visit(ctx.pow());
if (obj2 == null){
int line = ctx.pow().getStart().getLine();
int column = ctx.pow().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de pow @line: "+line+" @column: "+column));
return null;
}
getInterCode().setLastAsRight();
getInterCode().popTempActual();
getInterCode().setLastAsLeft();
Object[] type_code1 = (Object[])obj1;
String type1 = (String) type_code1[0];//guarda el tipo del expression
String code1 = (String) type_code1[1];//guarda el codigo intermedio del expression
Object[] type_code2 = (Object[])obj2;
String type2 = (String) type_code2[0];//guarda el tipo del expression
String code2 = (String) type_code2[1];//guarda el codigo intermedio del expression
if (!type1.equals("int")){
int line = ctx.multOrDiv().getStart().getLine();
int column = ctx.multOrDiv().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de multOrDiv no es de tipo int @line: "+line+" @column: "+column));
return null;
}
if (!type2.equals("int")){
int line = ctx.pow().getStart().getLine();
int column = ctx.pow().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de multOrDiv no es tipo int @line: "+line+" @column: "+column));
return null;
}
getInterCode().buildOperation(ctx.getChild(1).getText());
Object[] returnO = {"int",""};
return returnO;
}
public Object visitOp (OpContext ctx){
return ctx.getText();
}
public Object visitUnaryMinus (UnaryMinusContext ctx){
if (ctx.unaryMinus() != null){
Object obj = visit(ctx.unaryMinus());
if (obj == null){
int line = ctx.unaryMinus().getStart().getLine();
int column = ctx.unaryMinus().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de unaryMinus @line: "+line+" @column: "+column));
return null;
}
getInterCode().toMinus();
return obj;
}else{
Object obj = visit(ctx.atom());
if (obj == null){
int line = ctx.atom().getStart().getLine();
int column = ctx.atom().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de atom @line: "+line+" @column: "+column));
return null;
}
return obj;
}
}
public Object visitAtom (AtomContext ctx){
if (ctx.plusOrMinus() != null) return visit(ctx.plusOrMinus());
return visitChildren(ctx);
}
public Object visitBool_literal (Bool_literalContext ctx){
getInterCode().setBoolLiteral(ctx.getText());
Object[] returnO = {"boolean",ctx.getText()};
return returnO;
}
public Object visitChar_literal (Char_literalContext ctx){
getInterCode().setCharLiteral(ctx.getText());
Object[] returnO = {"char",ctx.getText()};
return returnO;
}
public Object visitInt_literal (Int_literalContext ctx){
getInterCode().setIntLiteral(ctx.getText());
Object[] returnO = {"int",ctx.getText()};
return returnO;
}
public Object visitParameter (ParameterContext ctx){
Object obj = visit(ctx.parameterType());
if (obj == null){
int line = ctx.parameterType().getStart().getLine();
int column = ctx.parameterType().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en parameterType @line: "+line+" @column: "+column));
return null;
}
Object[] type = (Object[])obj;
String varType = (String) type[0];
int varSize = (int)type[1];
String varName = ctx.ID().getText();
Variable var = new Variable(varName,varType,varSize);
if (ctx.getChildCount()>2){
var.setArray(true);
}
return var;
}
public Object visitParameterType(ParameterTypeContext ctx){
if (ctx.getText().equals("int")){
Object[] obj = {"int", 4};
return obj;
}
if (ctx.getText().equals("char")){
Object[] obj = {"char", 1};
return obj;
}
if (ctx.getText().equals("boolean")){
Object[] obj = {"boolean", 1};
}
return null;
}
public Stack<Exception> getError(){
return _errors;
}
public String toStringError(){
String st = "";
while (!_errors.isEmpty()){
st += _errors.pop().toString()+"\n";
}
return st;
}
/**
* @return the _interCode
*/
public IntermediateCodeBuilder getInterCode() {
return _interCode;
}
/**
* @param _interCode the _interCode to set
*/
public void setInterCode(IntermediateCodeBuilder _interCode) {
this._interCode = _interCode;
}
public Object visitExpression(ExpressionContext ctx){
getInterCode().setNeeds_value(true);
return visitChildren(ctx);
}
}
|
UTF-8
|
Java
| 68,000 |
java
|
MyVisitor.java
|
Java
|
[
{
"context": " the template in the editor.\n */\n/**\n *\n * @author Kevin\n */\npublic class MyVisitor extends decafBaseVisito",
"end": 471,
"score": 0.800908088684082,
"start": 466,
"tag": "NAME",
"value": "Kevin"
}
] | null |
[] |
package project;
import grammar.ANTLR.decafBaseVisitor;
import java.util.ArrayList;
import java.util.Stack;
import grammar.ANTLR.decafParser.*;
import static java.lang.Integer.parseInt;
import java.util.LinkedHashSet;
import org.antlr.v4.runtime.tree.ParseTree;
/*
* 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.
*/
/**
*
* @author Kevin
*/
public class MyVisitor extends decafBaseVisitor<Object> {
private LinkedHashSet<String> _types;//tipos predefinidos
private Stack<Scope> _scopes;//ambiente global
private Stack<Exception> _errors;//errores
private Method _methodRevision;
private IntermediateCodeBuilder _interCode = new IntermediateCodeBuilder();
public void initAll(){
_types = new LinkedHashSet();
_scopes = new Stack();
_scopes.push(new Scope());
_errors = new Stack();
setInterCode(new IntermediateCodeBuilder());
}
public Object visitProgram(ProgramContext ctx){
initAll();
//'class' ID '{' (declaration)* '}'
for (DeclarationContext child: ctx.declaration()){
Object obj = visit(child);//visitamos hijo
if (obj == null){
int line = child.getStart().getLine();
int column = child.getStart().getCharPositionInLine();
_errors.add(new Exception("Error en declaration @line: "+line+" @column: "+column));
}
}
if (_errors.empty()){
//System.out.println(getInterCode());
Method mt = _scopes.peek().hasMethodDef("main");
if (mt == null){
_errors.add(new Exception("main no definido"));
}
if (!mt.getMetType().equals("void")){
_errors.add(new Exception("main no definido como void"));
}
if (mt.getParams().size()>0){
_errors.add(new Exception("main espera parametros, no deberia"));
}
getInterCode().buildStringValue();
getInterCode().buildReturnValues();
getInterCode().finishBuilding();
return null;
}
//else: crear codigo intermedio
return null;
}
public Object visitDeclaration(DeclarationContext ctx){
if (ctx.methodDeclaration() != null){
Object obj = visitChildren(ctx);//
if (obj == null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error en methodDeclaration @line: "+line+" @column: "+column));
return null;
}
return "void";
}
if (ctx.structDeclaration() != null){
Object obj = visitChildren(ctx);
if (obj == null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error en structDeclaration @line: "+line+" @column: "+column));
return null;
}
Object[] structDec = (Object[]) obj;
//Object[] objR = {"struct", sd.getSize(), sd};
StructDef sd = _scopes.peek().hasStructDef(((StructDef) structDec[2]).getStructID());
if (sd != null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error struct '"+sd.getStructID()+"' previamente definido @line: "+line+" @column: "+column));
return null;
}
_scopes.peek().getStructures().add((StructDef) structDec[2]);//agregamos structure
return "void";
}
if (ctx.varDeclaration() != null){
Object obj = visitChildren(ctx);
if (obj == null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error en varDeclaration @line: "+line+" @column: "+column));
return null;
}
Variable varDec = (Variable) obj;
Variable var = _scopes.peek().hasVariableDef(varDec.getVarId());
if (var != null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable definida anteriormente '"+varDec.getVarId()+"' @line: "+line+" @column: "+column));
return null;
}
_scopes.peek().getVars().add(varDec);//agregamos variable
return "void";
}
return null;
}
public Object visitVarDeclaration(VarDeclarationContext ctx){
Object obj1 = visit(ctx.varType());
if (obj1 == null){
int line = ctx.varType().getStart().getLine();
int column = ctx.varType().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en varType @line: "+line+" @column: "+column));
return null;
}
Variable var;
Object[] varType = (Object[]) obj1;//casteamos obj1 como array
if (((String)varType[0]).equals("struct")){
var = new StructVar(ctx.ID().getText(),(StructDef) varType[2]);//si es struct, se crea un struct
}else{
var = new Variable(ctx.ID().getText(), (String)varType[0], (int)varType[1]);//si es variable, se crea variable
}
var.updateTotalSize();
if (ctx.getChildCount()<=3)
return var;
//de lo contrario
int length = Integer.parseInt(ctx.NUM().getText());//parseamos length
var.setArray(true);//lo identificamos como array
var.setArraySize(length);//iniciamos su tamanio
var.updateTotalSize();//
return var;//retornamos variable
}
public Object visitVarType(VarTypeContext ctx){
if (ctx.getChild(0).getText().equals("int")){
Object[] obj = {"int", 4};
return obj;
}
if (ctx.getChild(0).getText().equals("char")){
Object[] obj = {"char", 4};
return obj;
}
if (ctx.getChild(0).getText().equals("boolean")){
Object[] obj = {"boolean", 4};
return obj;
}
if (ctx.getChild(0).getText().equals("struct")){
String id = ctx.ID().getText();
StructDef sd = _scopes.peek().hasStructDef(id);
if (sd == null){
sd = _scopes.get(0).hasStructDef(id);
if (sd == null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error tipo struct '"+id+"' no definido @line: "+line+" @column: "+column));
return null;
}
}
Object[] obj = {"struct", sd.getSize(),sd};//retornamos struct, tamanio y struct referencia
return obj;
}
//visita structDeclaration
Object obj = visitChildren(ctx);
if (obj == null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error en structDeclaration @line: "+line+" @column: "+column));
return null;
}
Object[] structDec = (Object[]) obj;
//Object[] objR = {"struct", sd.getSize(), sd};
StructDef sd = _scopes.peek().hasStructDef(((StructDef) structDec[2]).getStructID());
if (sd != null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error struct '"+sd.getStructID()+"' previamente definido @line: "+line+" @column: "+column));
return null;
}
_scopes.peek().getStructures().add((StructDef) structDec[2]);//agregamos structure
return structDec;
}
public Object visitStructDeclaration(StructDeclarationContext ctx){
StructDef sd = _scopes.peek().hasStructDef(ctx.ID().getText());//buscamos
if (sd != null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error tipo struct '"+ctx.ID().getText()+"' ya definido @line: "+line+" @column: "+column));
return null;
}
sd = new StructDef(ctx.ID().getText());
boolean errores = false;
for (VarDeclarationContext vd: ctx.varDeclaration()){
if (vd.varType().structDeclaration() != null){
int line = vd.getStart().getLine();
int column = vd.getStart().getCharPositionInLine();
_errors.add(new Exception("Error no se puede declarar tipo struct en struct @line: "+line+" @column: "+column));
errores = true;
}else{
Object obj = visit(vd);//visitamos
if (obj == null){
int line = vd.getStart().getLine();
int column = vd.getStart().getCharPositionInLine();
_errors.add(new Exception("Error declaracion de variable @line: "+line+" @column: "+column));
errores = true;
}else{
Variable var = (Variable)obj;//casteamos el objeto a variable
Variable v2 = sd.hasVariable(var.getVarId());//identificamos si ya la tiene
if (v2 != null){
int line = vd.getStart().getLine();
int column = vd.getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable '"+v2.getVarId()+"' previamente definida @line: "+line+" @column: "+column));
errores = true;
}else{
sd.add(var);//agregamos la variable si no tiene errores y no existe previamente
}
}
}
}
if (errores){
return null;
}
sd.updateSize();
Object[] objR = {"struct", sd.getSize(), sd};//creamos el objeto de retorno
return objR;
}
public Object visitMethodDeclaration(MethodDeclarationContext ctx){
String type = ctx.methodType().getText();
String id = ctx.ID().toString();
getInterCode().newMethod(id);
LinkedHashSet<Variable> parameters = new LinkedHashSet();
boolean errores = false;
for (ParameterContext pr: ctx.parameter()){
Object obj = visit(pr);
if (obj == null){
int line = pr.getStart().getLine();
int column = pr.getStart().getCharPositionInLine();
_errors.add(new Exception("Error en parameter @line: "+line+" @column: "+column));
errores = true;
}else{
Variable var = (Variable) obj;//variable de retorno
int contador= 0;
for (Variable param: parameters){
if (param.getVarId().equals(var.getVarId())){
int line = pr.getStart().getLine();
int column = pr.getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable definida anteriormente '"+param.getVarId()+"' @line: "+line+" @column: "+column));
errores = true;
contador++;
}
}
if (contador==0){
parameters.add(var);
}
}
}
Method mt = new Method(id,type);
mt.setParams(parameters);//agregamos parametros
mt.setParamsAsVars();//agregamos los parametros como variables locales
int tamanio_de_parametro = mt.getVarsSize();
getInterCode().setParam_size(tamanio_de_parametro);
LinkedHashSet<Method> tempMethods = new LinkedHashSet();
tempMethods.addAll(_scopes.peek().getMethods());//guardamos los metodos pervios
_scopes.peek().getMethods().add(mt);//agregamos el metodo por si hay recursion
_scopes.push(new Scope());
_scopes.peek().setVars(mt.getVars());//generamos el nuevo scope con las variables ya definidas
_scopes.peek().getMethods().add(mt);//agregamos metodo a nuevo scope para evaluacion de tipo
//
Object obj = visit(ctx.block());//visitamos block
Scope nscope = _scopes.pop();
if (obj == null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error en declaracion de metodo '"+mt.getMetID()+"' @line: "+line+" @column: "+column));
_scopes.peek().setMethods(tempMethods);//regresamos a los metodos previos
errores = true;
}
Method mtn = new Method();
for (Method m: nscope.getMethods()){
mtn = m;
}
if (!mtn.isReturn() && !mtn.getMetType().equals("void") ){//si no tiene retorno y no es void
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error en declaracion de metodo '"+mt.getMetID()+"' sin retorno @line: "+line+" @column: "+column));
_scopes.peek().setMethods(tempMethods);//regresamos a los metodos previos
errores = true;
}
if (!mtn.getMetType().equals("void")){//si no es void, se crea variable de retorno
getInterCode().setNewReturn();
}
//asignamos las cosas nuevas al metodo
mt.setReturn(true);
mt.setVars(nscope.getVars());
mt.setStructures(nscope.getStructures());
if (errores) return null;
getInterCode().buildMethod();
return "void";
}
public Object visitBlock (BlockContext ctx){
LinkedHashSet<Variable> _vars = new LinkedHashSet();//variables definidas en este scope
LinkedHashSet<Method> _methods = new LinkedHashSet();//metodos definidos en este scope
LinkedHashSet<StructDef> _structures = new LinkedHashSet();//estructuras definidas
_vars.addAll(_scopes.peek().getVars());
_methods.addAll(_scopes.peek().getMethods());
_structures.addAll(_scopes.peek().getStructures());
boolean errores = false;
for (int i = 1; i < ctx.getChildCount()-1; i++){
ParseTree child = ctx.getChild(i);
if (child instanceof VarDeclarationContext){
VarDeclarationContext vdc = (VarDeclarationContext) child;
Object obj = visit(vdc);//visitamos varDeclaration
if (obj == null){
int line = vdc.getStart().getLine();
int column = vdc.getStart().getCharPositionInLine();
_errors.add(new Exception("Error en parameter @line: "+line+" @column: "+column));
errores = true;
}else{
Variable varDec = (Variable) obj;
Variable var = _scopes.peek().hasVariableDef(varDec.getVarId());
if (var != null){
int line = vdc.getStart().getLine();
int column = vdc.getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable definida anteriormente '"+varDec.getVarId()+"' @line: "+line+" @column: "+column));
errores = true;
}else{
_scopes.peek().getVars().add(varDec);//agregamos variable
}
}
}else if (child instanceof StatementContext){
StatementContext st = (StatementContext) child;
Object obj = visit(st);//visitamos statement
if (obj == null){
int line = st.getStart().getLine();
int column = st.getStart().getCharPositionInLine();
_errors.add(new Exception("Error en statement @line: "+line+" @column: "+column));
errores = true;
}else{
Object[] type_code = (Object[])obj;
String type = (String) type_code[0];//guarda el tipo del statement
String code = (String) type_code[1];//guarda el codigo intermedio del statement
}
}
}
/*
for (VarDeclarationContext vdc: ctx.varDeclaration()){//para cada definicion de variable
Object obj = visit(vdc);//visitamos varDeclaration
if (obj == null){
int line = vdc.getStart().getLine();
int column = vdc.getStart().getCharPositionInLine();
_errors.add(new Exception("Error en parameter @line: "+line+" @column: "+column));
errores = true;
}else{
Variable varDec = (Variable) obj;
Variable var = _scopes.peek().hasVariableDef(varDec.getVarId());
if (var != null){
int line = vdc.getStart().getLine();
int column = vdc.getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable definida anteriormente '"+varDec.getVarId()+"' @line: "+line+" @column: "+column));
errores = true;
}else{
_scopes.peek().getVars().add(varDec);//agregamos variable
}
}
}
for (StatementContext st: ctx.statement()){
Object obj = visit(st);//visitamos statement
if (obj == null){
int line = st.getStart().getLine();
int column = st.getStart().getCharPositionInLine();
_errors.add(new Exception("Error en statement @line: "+line+" @column: "+column));
errores = true;
}else{
Object[] type_code = (Object[])obj;
String type = (String) type_code[0];//guarda el tipo del statement
String code = (String) type_code[1];//guarda el codigo intermedio del statement
}
}
*/
_scopes.peek().setMethods(_methods);
_scopes.peek().setStructures(_structures);
_scopes.peek().setVars(_vars);
if (errores) return null;
Object[] returnO = {"void",""};
return returnO;
}
public Object visitStatementIf (StatementIfContext ctx){
Object obj = visit(ctx.expression());//visitamos expression
if (obj == null){
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en expression @line: "+line+" @column: "+column));
return null;
}
Object[] type_code = (Object[])obj;
String type = (String) type_code[0];//guarda el tipo del statement
String code = (String) type_code[1];//guarda el codigo intermedio del statement
if (!type.equals("boolean")){
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en expression no booleana @line: "+line+" @column: "+column));
return null;
}
getInterCode().newIf();
int i = 0;
for (BlockContext bc: ctx.block()){
Object objB = visit(bc);//visitamos bloque
if (objB == null){
int line = bc.getStart().getLine();
int column = bc.getStart().getCharPositionInLine();
_errors.add(new Exception("Error en bloque if @line: "+line+" @column: "+column));
return null;
}
Object[] type_codeB = (Object[])objB;
String typeB = (String) type_code[0];//guarda el tipo del statement
String codeB = (String) type_code[1];//guarda el codigo intermedio del statement
if (i==0) getInterCode().newElse();
i++;
}
getInterCode().endIf();
Object[] returnO = {"void",""};
return returnO ;
}
public Object visitStatementWhile (StatementWhileContext ctx){
getInterCode().newWhile();
Object obj = visit(ctx.expression());//visitamos expression
if (obj == null){
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en expression @line: "+line+" @column: "+column));
return null;
}
getInterCode().meanWhile();
Object[] type_code = (Object[])obj;
String type = (String) type_code[0];//guarda el tipo del statement
String code = (String) type_code[1];//guarda el codigo intermedio del statement
if (!type.equals("boolean")){
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en expression no booleana @line: "+line+" @column: "+column));
return null;
}
Object objB = visit(ctx.block());//visitamos bloque
if (objB == null){
int line = ctx.block().getStart().getLine();
int column = ctx.block().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en bloque while @line: "+line+" @column: "+column));
return null;
}
Object[] type_codeB = (Object[])objB;
String typeB = (String) type_code[0];//guarda el tipo del statement
String codeB = (String) type_code[1];//guarda el codigo intermedio del statement
getInterCode().endWhile();
Object[] returnO = {"void",""};
return returnO;
}
public Object visitStatementReturn (StatementReturnContext ctx){
if (ctx.expression() == null){
//como se que solo puede haber un metodo en este momento
for (Method mt: _scopes.peek().getMethods()){
String methodType = mt.getMetType();
if (!methodType.equals("void")){
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en tipo de metodo: '"+methodType+"' no es tipo expression: 'void' @line: "+line+" @column: "+column));
return null;
}else{
mt.setReturn(true);
getInterCode().buildReturnVoid();
Object[] returnO = {"void",""};
return returnO;
}
}
}
Object obj = visit(ctx.expression());//visitamos expression
if (obj == null){
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en expression @line: "+line+" @column: "+column));
return null;
}
Object[] type_code = (Object[])obj;
String type = (String) type_code[0];//guarda el tipo del statement
String code = (String) type_code[1];//guarda el codigo intermedio del statement
for (Method mt: _scopes.peek().getMethods()){
String methodType = mt.getMetType();
if (!methodType.equals(type)){
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en tipo de metodo: '"+methodType+"' no es tipo expression: '"+type+"' @line: "+line+" @column: "+column));
return null;
}else{
mt.setReturn(true);
getInterCode().buildReturn();
Object[] returnO = {"void",""};
return returnO;
}
}
Object[] returnO = {"void",""};
return returnO;
}
public Object visitStatementAsign (StatementAsignContext ctx){
getInterCode().setNeeds_value(false);
Object objL = visit(ctx.location());
if (objL == null){
int line = ctx.location().getStart().getLine();
int column = ctx.location().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en location @line: "+line+" @column: "+column));
return null;
}
Object[] type_codeL = (Object[])objL;
String typeL = (String) type_codeL[0];//guarda el tipo del statement
String codeL = (String) type_codeL[1];//guarda el codigo intermedio del statement
//location
getInterCode().pushTempActual();
getInterCode().setNeeds_value(true);
Object objE = visit(ctx.expression());
if (objE == null){
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en expression @line: "+line+" @column: "+column));
return null;
}
Object[] type_codeE = (Object[])objE;
String typeE = (String) type_codeE[0];//guarda el tipo del statement
String codeE = (String) type_codeE[1];//guarda el codigo intermedio del statement
if (!typeL.equals(typeE)){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error tipo location: '"+typeL+"' no concuerda tipo expression: '"+typeE+"' @line: "+line+" @column: "+column));
return null;
}
//tenemos expression
getInterCode().setLastAsLeft();
getInterCode().popTempActual();
getInterCode().setLastAsEq();
getInterCode().buildEqual();
Object[] returnO = {"void",""};
return returnO;
}
public Object visitStatementExp (StatementExpContext ctx){
getInterCode().setNeeds_value(true);
return visit(ctx.expression());//retornamos valor de expression
}
public Object visitStatementPrint(StatementPrintContext ctx){
String value = ctx.STRING().getText();
System.out.println(value);
_interCode.addNewString(value);
boolean param = false;
if (ctx.expression() != null){
getInterCode().setNeeds_value(true);
Object obj = visit(ctx.expression());
if (obj == null){
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en expression @line: "+line+" @column: "+column));
return null;
}
getInterCode().setLastAsLeft();
param = true;
}
getInterCode().setNewPrint(param);
Object[] returnO = {"void",""};
return returnO;
}
public Object visitLocationID(LocationIDContext ctx){
Variable var = _scopes.peek().hasVariableDef(ctx.ID().getText());
int offset =0;
boolean global = false;
if (var == null){
var = _scopes.get(0).hasVariableDef(ctx.ID().getText());
if (var == null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable '"+ctx.ID().getText()+"' no definida @line: "+line+" @column: "+column));
return null;
}
offset = _scopes.get(0).offsetOfVar(ctx.ID().getText());
getInterCode().setIntLiteral(""+offset);
getInterCode().setGlobalPointer();
}else{
offset = _scopes.peek().offsetOfVar(ctx.ID().getText());//extraigo offset desde inicio
//getInterCode().setIntLiteral(""+offset);
getInterCode().setOffset(offset);//regresar
getInterCode().setLocalPointer();
}
String type = var.getVarType();//'tipo'
if (type.equals("struct")){
type+= ((StructVar) var).getStructID().getStructID();
}
if (var.isArray()) type += "array";
Object[] returnO = {type,""};
return returnO;
}
public Object visitLocationExp(LocationExpContext ctx){
Variable var = _scopes.peek().hasVariableDef(ctx.ID().getText());
int offset =0;
boolean global = false;
if (var == null){
var = _scopes.get(0).hasVariableDef(ctx.ID().getText());
if (var == null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable '"+ctx.ID().getText()+"' no definida @line: "+line+" @column: "+column));
return null;
}
offset = _scopes.get(0).offsetOfVar(ctx.ID().getText());
global = true;
}else{
offset = _scopes.peek().offsetOfVar(ctx.ID().getText());//extraigo offset desde inicio
}
if (!var.isArray()){
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable '"+ctx.ID().getText()+"' no definida como array @line: "+line+" @column: "+column));
return null;
}
//quiere decir que si es array, y se esta llamando expression
Object obj = visit(ctx.expression());//visitamos expression
if (obj == null){//error en expression
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en expression @line: "+line+" @column: "+column));
return null;
}
//si no existe error
Object[] type_codeE = (Object[])obj;
String typeE = (String) type_codeE[0];//guarda el tipo del expression
String codeE = (String) type_codeE[1];//guarda el codigo intermedio del expression
//expression ya tiene el valor del indice
if (!typeE.equals("int")){
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en expression no de tipo int @line: "+line+" @column: "+column));
return null;
}
getInterCode().setLastAsLeft();//tenemos las posiciones en la izquierda gracias a expression
//_interCode.setIntLiteral(""+offset);
Variable var1 = new Variable();
if (var.getVarType().equals("struct")){
var1 = new StructVar(ctx.ID().getText(),((StructVar)var).getStructID());
}else{
var1 = new Variable(var.getVarId(),var.getVarType(), var.getSize());
}
getInterCode().setIntLiteral(var1.getTotalSize()+"");//tomamos el tamanio de dicha variable
getInterCode().setLastAsRight();
getInterCode().buildOperation("*");//multiplicamos para llegar al offset
getInterCode().setLastAsLeft();
getInterCode().setIntLiteral(""+offset);
getInterCode().setLastAsRight();
getInterCode().buildOperation("+");
if (global){
getInterCode().setGlobalPointer();
}else{
getInterCode().setLocalPointer();
}
String type = var1.getVarType();//'tipo'
if (type.equals("struct")){
type+= ((StructVar) var1).getStructID().getStructID();
}
if (var1.isArray()) type += "array";
Object[] returnO = {type,""};
return returnO;
}
public Object visitLocationIDlocation(LocationIDlocationContext ctx){
Variable var = _scopes.peek().hasVariableDef(ctx.ID().getText());
int offset =0;
boolean global = false;
if (var == null){
var = _scopes.get(0).hasVariableDef(ctx.ID().getText());
if (var == null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable '"+ctx.ID().getText()+"' no definida @line: "+line+" @column: "+column));
return null;
}
offset = _scopes.get(0).offsetOfVar(ctx.ID().getText());
global = true;
}else{
offset = _scopes.peek().offsetOfVar(ctx.ID().getText());//extraigo offset desde inicio
}
String type = var.getVarType();//'tipo'
if (!type.equals("struct")){//no es struct y se llama a location
int line = ctx.location().getStart().getLine();
int column = ctx.location().getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable no definida como 'struct' @line: "+line+" @column: "+column));
return null;
}
if (var.isArray()){
int line = ctx.location().getStart().getLine();
int column = ctx.location().getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable tipo array no tiene location definido @line: "+line+" @column: "+column));
return null;
}
Object obj = visitLocationContinuos(ctx.location(), (StructVar)var);
//retorna el valor del offset
getInterCode().setLastAsLeft();
getInterCode().setIntLiteral(""+offset);
getInterCode().setLastAsRight();
getInterCode().buildOperation("+");
if (global){
getInterCode().setGlobalPointer();
}else{
getInterCode().setLocalPointer();
}
return obj;
}
public Object visitLocationExplocation (LocationExplocationContext ctx){
Variable var = _scopes.peek().hasVariableDef(ctx.ID().getText());
int offset =0;
boolean global = false;
if (var == null){
var = _scopes.get(0).hasVariableDef(ctx.ID().getText());
if (var == null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable '"+ctx.ID().getText()+"' no definida @line: "+line+" @column: "+column));
return null;
}
offset = _scopes.get(0).offsetOfVar(ctx.ID().getText());
global = true;
}else{
offset = _scopes.peek().offsetOfVar(ctx.ID().getText());//extraigo offset desde inicio
}
if (!var.isArray()){//si no es array
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable tipo array no tiene location definido @line: "+line+" @column: "+column));
return null;
}
Object obj = visit(ctx.expression());//visitamos expression
if (obj == null){//error en expression
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en expression @line: "+line+" @column: "+column));
return null;
}
//si no existe error
Object[] type_codeE = (Object[])obj;
String typeE = (String) type_codeE[0];//guarda el tipo del expression
String codeE = (String) type_codeE[1];//guarda el codigo intermedio del expression
if (!typeE.equals("int")){
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en expression no de tipo int @line: "+line+" @column: "+column));
return null;
}
//si todo esta bien, expression tiene el offset en el ultimo
getInterCode().setLastAsLeft();//tomamos el tamanio y lo ponemos de izquierdo
String type = var.getVarType();//'tipo'
if (!type.equals("struct")){//no es struct y se llama a location
int line = ctx.location().getStart().getLine();
int column = ctx.location().getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable no definida como 'struct' @line: "+line+" @column: "+column));
return null;
}
int objLength = 0;
StructVar nvar = new StructVar(var.getVarId(),((StructVar)var).getStructID());
objLength = nvar.getTotalSize();//tomamos todo el tamanio de esa onda
type+= ((StructVar) var).getStructID().getStructID();
getInterCode().setIntLiteral(""+objLength);//tomamos el tamanio de cada objeto
getInterCode().setLastAsRight();
getInterCode().buildOperation("*");//multiplicamos ambas partes
getInterCode().setLastAsLeft();//tomamos el resultado y lo colocamos a la izquierda
getInterCode().setIntLiteral(""+offset);//agregamos el offset de esta variable
getInterCode().setLastAsRight();
getInterCode().buildOperation("+");
getInterCode().pushTempActual();
Object obj1 = visitLocationContinuos(ctx.location(),nvar);
getInterCode().setLastAsLeft();//colocamos el offset a la izquierda
getInterCode().popTempActual();
getInterCode().setLastAsRight();
getInterCode().buildOperation("+");
if (global){
getInterCode().setGlobalPointer();
}else{
getInterCode().setLocalPointer();
}
return obj1;
}
public Object visitLocationIDContext(LocationIDContext ctx, StructVar varCheck){
Variable var = varCheck.getStructID().hasVariable(ctx.ID().getText());
if (var == null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable '"+ctx.ID().getText()+"' no definida @line: "+line+" @column: "+column));
return null;
}
int offset = varCheck.getStructID().offsetOfVar(ctx.ID().getText());
getInterCode().setIntLiteral(""+offset);
String type = var.getVarType();//'tipo'
if (type.equals("struct")){
type+= ((StructVar) var).getStructID().getStructID();
}
if (var.isArray()) type += "array";
Object[] returnO = {type,""};
return returnO;
}
public Object visitLocationIDlocation(LocationIDlocationContext ctx, StructVar varCheck){
Variable var = varCheck.getStructID().hasVariable(ctx.ID().getText());
if (var == null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable '"+ctx.ID().getText()+"' no definida @line: "+line+" @column: "+column));
return null;
}
String type = var.getVarType();//'tipo'
if (!type.equals("struct")){//no es struct y se llama a location
int line = ctx.location().getStart().getLine();
int column = ctx.location().getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable no definida como 'struct' @line: "+line+" @column: "+column));
return null;
}
if (var.isArray()){
int line = ctx.location().getStart().getLine();
int column = ctx.location().getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable tipo array no tiene location definido @line: "+line+" @column: "+column));
return null;
}
Object obj = visitLocationContinuos(ctx.location(), (StructVar)var);
//retorna el valor del offset
getInterCode().setLastAsLeft();
int offset = varCheck.getStructID().offsetOfVar(ctx.ID().getText());
getInterCode().setIntLiteral(""+offset);
getInterCode().setLastAsRight();
getInterCode().buildOperation("+");
return obj;
}
public Object visitLocationExpContext(LocationExpContext ctx, StructVar varCheck){
Variable var = varCheck.getStructID().hasVariable(ctx.ID().getText());
if (var == null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable '"+ctx.ID().getText()+"' no definida @line: "+line+" @column: "+column));
return null;
}
int offset = varCheck.getStructID().offsetOfVar(ctx.ID().getText());
if (!var.isArray()){//si no es array
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable tipo array no tiene location definido @line: "+line+" @column: "+column));
return null;
}
Object obj = visit(ctx.expression());//visitamos expression
if (obj == null){//error en expression
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en expression @line: "+line+" @column: "+column));
return null;
}
//si no existe error
Object[] type_codeE = (Object[])obj;
String typeE = (String) type_codeE[0];//guarda el tipo del expression
String codeE = (String) type_codeE[1];//guarda el codigo intermedio del expression
if (!typeE.equals("int")){
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en expression no de tipo int @line: "+line+" @column: "+column));
return null;
}
//si todo esta bien, expression tiene el offset en el ultimo
getInterCode().setLastAsLeft();//tomamos el tamanio y lo ponemos de izquierdo
String type = var.getVarType();//'tipo'
int objLength = 0;
if (type.equals("struct")){//si lo que guarda es un array de struct
StructVar nvar = new StructVar(var.getVarId(),((StructVar)var).getStructID());
objLength = nvar.getTotalSize();//tomamos todo el tamanio de esa onda
type+= ((StructVar) var).getStructID().getStructID();
if (nvar.isArray()) type += "array";
}else{
Variable nvar = new Variable(var.getVarId(),var.getVarType(), var.getSize());
objLength = nvar.getTotalSize();
if (nvar.isArray()) type += "array";
}
getInterCode().setIntLiteral(""+objLength);//tomamos el tamanio de cada objeto
getInterCode().buildOperation("*");//multiplicamos ambas partes
getInterCode().setLastAsLeft();//tomamos el resultado y lo colocamos a la izquierda
getInterCode().setIntLiteral(""+offset);//agregamos el offset de esta variable
getInterCode().setLastAsRight();
getInterCode().buildOperation("+");
Object[] returnO = {type,""};
return returnO;
}
public Object visitLocationExplocationContext(LocationExplocationContext ctx, StructVar varCheck){
Variable var = varCheck.getStructID().hasVariable(ctx.ID().getText());
if (var == null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable '"+ctx.ID().getText()+"' no definida @line: "+line+" @column: "+column));
return null;
}
int offset = varCheck.getStructID().offsetOfVar(ctx.ID().getText());
if (!var.isArray()){//si no es array
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable tipo array no tiene location definido @line: "+line+" @column: "+column));
return null;
}
Object obj = visit(ctx.expression());//visitamos expression
if (obj == null){//error en expression
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en expression @line: "+line+" @column: "+column));
return null;
}
//si no existe error
Object[] type_codeE = (Object[])obj;
String typeE = (String) type_codeE[0];//guarda el tipo del expression
String codeE = (String) type_codeE[1];//guarda el codigo intermedio del expression
if (!typeE.equals("int")){
int line = ctx.expression().getStart().getLine();
int column = ctx.expression().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en expression no de tipo int @line: "+line+" @column: "+column));
return null;
}
//si todo esta bien, expression tiene el offset en el ultimo
getInterCode().setLastAsLeft();//tomamos el tamanio y lo ponemos de izquierdo
String type = var.getVarType();//'tipo'
if (!type.equals("struct")){//no es struct y se llama a location
int line = ctx.location().getStart().getLine();
int column = ctx.location().getStart().getCharPositionInLine();
_errors.add(new Exception("Error variable no definida como 'struct' @line: "+line+" @column: "+column));
return null;
}
int objLength = 0;
StructVar nvar = new StructVar(var.getVarId(),((StructVar)var).getStructID());
objLength = nvar.getTotalSize();//tomamos todo el tamanio de esa onda
type+= ((StructVar) var).getStructID().getStructID();
getInterCode().setIntLiteral(""+objLength);//tomamos el tamanio de cada objeto
getInterCode().setLastAsRight();
getInterCode().buildOperation("*");//multiplicamos ambas partes
getInterCode().setLastAsLeft();//tomamos el resultado y lo colocamos a la izquierda
getInterCode().setIntLiteral(""+offset);//agregamos el offset de esta variable
getInterCode().setLastAsRight();
getInterCode().buildOperation("+");
getInterCode().pushTempActual();
Object obj1 = visitLocationContinuos(ctx.location(),nvar);
getInterCode().setLastAsLeft();//colocamos el offset a la izquierda
getInterCode().popTempActual();
getInterCode().setLastAsRight();
getInterCode().buildOperation("+");
return obj1;
}
public Object visitLocationContinuos(LocationContext ctx, StructVar varCheck){
if (ctx instanceof LocationIDContext){
return visitLocationIDContext((LocationIDContext) ctx, varCheck);
}
if (ctx instanceof LocationIDlocationContext){
return visitLocationIDlocation((LocationIDlocationContext) ctx, varCheck);
}
if (ctx instanceof LocationExpContext){
return visitLocationExpContext((LocationExpContext) ctx, varCheck);
}
if (ctx instanceof LocationExplocationContext ){
return visitLocationExplocationContext((LocationExplocationContext) ctx, varCheck);
}
return null;
}
public Object visitMethodCall (MethodCallContext ctx){
String id = ctx.ID().getText();//nombre
Method mt = _scopes.get(0).hasMethodDef(id);
if (mt == null){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error metodo '"+id+"' no definido @line: "+line+" @column: "+column));
return null;
}
ArrayList<String> params = new ArrayList();
for (ArgContext arg: ctx.arg()){
Object obj = visit(arg);
if (obj == null){
int line = arg.getStart().getLine();
int column = arg.getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de parametro @line: "+line+" @column: "+column));
return null;
}
Object[] type_code = (Object[])obj;
String type = (String) type_code[0];//guarda el tipo del expression
String code = (String) type_code[1];//guarda el codigo intermedio del expression
params.add(type);
getInterCode().pushParam();
}
if (params.size() != mt.getParams().size()){
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de parametros, se esperan "+mt.getParams().size()+"' parametros @line: "+line+" @column: "+column));
return null;
}
int i = 0;
for (Variable v: mt.getParams()){
String typeParam = params.get(i);
String typeVar = v.getVarType();
if (typeVar.equals("struct")){
typeVar += ((StructVar)v).getStructID().getStructID();
}
if (v.isArray()) typeVar += "array";
if (!typeParam.equals(typeVar)){//si no son iguales
int line = ctx.getStart().getLine();
int column = ctx.getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de parametros, se esperaba "+typeVar+"', se obtuvo '"+typeParam+"' @line: "+line+" @column: "+column));
return null;
}
i++;
}
getInterCode().callMethod(id);
Object[] returnO = {mt.getMetType(),""};
return returnO;
}
public Object visitCondOp (CondOpContext ctx){
if (ctx.getChildCount()<=1) return visitChildren(ctx);//retornamos mulOrDiv
Object obj1 = visit(ctx.condOp());
if (obj1 == null){
int line = ctx.condOp().getStart().getLine();
int column = ctx.condOp().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de condOp @line: "+line+" @column: "+column));
return null;
}
getInterCode().pushTempActual();//guardamos el actual
//getInterCode().setLastAsLeft();
Object obj2 = visit(ctx.assignOp());
if (obj2 == null){
int line = ctx.assignOp().getStart().getLine();
int column = ctx.assignOp().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de assignOp @line: "+line+" @column: "+column));
return null;
}
getInterCode().setLastAsRight();
getInterCode().popTempActual();
getInterCode().setLastAsLeft();
Object[] type_code1 = (Object[])obj1;
String type1 = (String) type_code1[0];//guarda el tipo del expression
String code1 = (String) type_code1[1];//guarda el codigo intermedio del expression
Object[] type_code2 = (Object[])obj2;
String type2 = (String) type_code2[0];//guarda el tipo del expression
String code2 = (String) type_code2[1];//guarda el codigo intermedio del expression
if (!type1.equals("boolean")){
int line = ctx.condOp().getStart().getLine();
int column = ctx.condOp().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de condOp no es de tipo boolean @line: "+line+" @column: "+column));
return null;
}
if (!type2.equals("boolean")){
int line = ctx.assignOp().getStart().getLine();
int column = ctx.assignOp().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de assignOp no es de tipo boolean @line: "+line+" @column: "+column));
return null;
}
getInterCode().buildOperation(ctx.getChild(1).getText());
Object[] returnO = {"boolean",""};
return returnO;
}
public Object visitAssignOp (AssignOpContext ctx){
if (ctx.getChildCount() <=1) return visitChildren(ctx);
Object obj1 = visit(ctx.assignOp());
if (obj1 == null){
int line = ctx.assignOp().getStart().getLine();
int column = ctx.assignOp().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de assignOp @line: "+line+" @column: "+column));
return null;
}
getInterCode().pushTempActual();//metemos el actual a la pila
//getInterCode().setLastAsLeft();
Object obj2 = visit(ctx.pow2());
if (obj2 == null){
int line = ctx.pow2().getStart().getLine();
int column = ctx.pow2().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de pow2 @line: "+line+" @column: "+column));
return null;
}
getInterCode().setLastAsRight();//ponemos el ultimo de lado derecho
getInterCode().popTempActual();//sacamos el del lado izquierdo
getInterCode().setLastAsLeft();//lo ponemos como lado izquierdo
Object[] type_code1 = (Object[])obj1;
String typeE1 = (String) type_code1[0];//guarda el tipo del expression
String code1 = (String) type_code1[1];//guarda el codigo intermedio del expression
Object[] type_code2 = (Object[])obj2;
String typeE2 = (String) type_code2[0];//guarda el tipo del expression
String code2 = (String) type_code2[1];//guarda el codigo intermedio del expression
String op = (String)visit(ctx.op());//op
if (!typeE2.equals(typeE1)){
int line = ctx.op().getStart().getLine();
int column = ctx.op().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en tipo: '"+typeE1+"' no comparable con tipo: '"+typeE2+"' @line: "+line+" @column: "+column));
return null;
}
//'<' | '>' | '<=' | '>='
//'==' | '!='
//'&&' | '||'
switch (op){
case "<":
if (!typeE1.equals("int")){
int line = ctx.op().getStart().getLine();
int column = ctx.op().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en tipo: '"+typeE1+"' no comparable '<' @line: "+line+" @column: "+column));
return null;
}
break;
case ">":
if (!typeE1.equals("int")){
int line = ctx.op().getStart().getLine();
int column = ctx.op().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en tipo: '"+typeE1+"' no comparable '>' @line: "+line+" @column: "+column));
return null;
}
break;
case "<=":
if (!typeE1.equals("int")){
int line = ctx.op().getStart().getLine();
int column = ctx.op().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en tipo: '"+typeE1+"' no comparable '<=' @line: "+line+" @column: "+column));
return null;
}
break;
case ">=":
if (!typeE1.equals("int")){
int line = ctx.op().getStart().getLine();
int column = ctx.op().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en tipo: '"+typeE1+"' no comparable '>=' @line: "+line+" @column: "+column));
return null;
}
break;
case "==":
break;
case "!=":
break;
}
getInterCode().buildOperation(op);
Object[] returnO = {"boolean",""};
return returnO;
}
public Object visitUnaryMinus2 (UnaryMinus2Context ctx){
if (ctx.unaryMinus2() != null){
Object obj = visit(ctx.unaryMinus2());
if (obj == null){
int line = ctx.unaryMinus2().getStart().getLine();
int column = ctx.unaryMinus2().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de unaryMinus2 @line: "+line+" @column: "+column));
return null;
}
getInterCode().toNot();
return obj;
}
return visitChildren(ctx);
}
public Object visitAtom2 (Atom2Context ctx){
if (ctx.condOp() != null) return visit(ctx.condOp());
return visitChildren(ctx);
}
public Object visitPlusOrMinus (PlusOrMinusContext ctx){
if (ctx.getChildCount()<=1) return visitChildren(ctx);//retornamos mulOrDiv
Object obj1 = visit(ctx.plusOrMinus());
if (obj1 == null){
int line = ctx.plusOrMinus().getStart().getLine();
int column = ctx.plusOrMinus().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de plusOrMinus @line: "+line+" @column: "+column));
return null;
}
getInterCode().pushTempActual();
//getInterCode().setLastAsLeft();
Object obj2 = visit(ctx.multOrDiv());
if (obj2 == null){
int line = ctx.multOrDiv().getStart().getLine();
int column = ctx.multOrDiv().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de multOrDiv @line: "+line+" @column: "+column));
return null;
}
getInterCode().setLastAsRight();
getInterCode().popTempActual();
getInterCode().setLastAsLeft();
Object[] type_code1 = (Object[])obj1;
String type1 = (String) type_code1[0];//guarda el tipo del expression
String code1 = (String) type_code1[1];//guarda el codigo intermedio del expression
Object[] type_code2 = (Object[])obj2;
String type2 = (String) type_code2[0];//guarda el tipo del expression
String code2 = (String) type_code2[1];//guarda el codigo intermedio del expression
if (!type1.equals("int")){
int line = ctx.plusOrMinus().getStart().getLine();
int column = ctx.plusOrMinus().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de plusOrMinus no es de tipo int @line: "+line+" @column: "+column));
return null;
}
if (!type2.equals("int")){
int line = ctx.multOrDiv().getStart().getLine();
int column = ctx.multOrDiv().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de multOrDiv no es tipo int @line: "+line+" @column: "+column));
return null;
}
getInterCode().buildOperation(ctx.getChild(1).getText());
Object[] returnO = {"int",""};
return returnO;
}
public Object visitMultOrDiv (MultOrDivContext ctx){
if (ctx.getChildCount() <=1) return visitChildren(ctx);
Object obj1 = visit(ctx.multOrDiv());
if (obj1 == null){
int line = ctx.multOrDiv().getStart().getLine();
int column = ctx.multOrDiv().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de multOrDiv @line: "+line+" @column: "+column));
return null;
}
getInterCode().pushTempActual();
//getInterCode().setLastAsLeft();
Object obj2 = visit(ctx.pow());
if (obj2 == null){
int line = ctx.pow().getStart().getLine();
int column = ctx.pow().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de pow @line: "+line+" @column: "+column));
return null;
}
getInterCode().setLastAsRight();
getInterCode().popTempActual();
getInterCode().setLastAsLeft();
Object[] type_code1 = (Object[])obj1;
String type1 = (String) type_code1[0];//guarda el tipo del expression
String code1 = (String) type_code1[1];//guarda el codigo intermedio del expression
Object[] type_code2 = (Object[])obj2;
String type2 = (String) type_code2[0];//guarda el tipo del expression
String code2 = (String) type_code2[1];//guarda el codigo intermedio del expression
if (!type1.equals("int")){
int line = ctx.multOrDiv().getStart().getLine();
int column = ctx.multOrDiv().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de multOrDiv no es de tipo int @line: "+line+" @column: "+column));
return null;
}
if (!type2.equals("int")){
int line = ctx.pow().getStart().getLine();
int column = ctx.pow().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de multOrDiv no es tipo int @line: "+line+" @column: "+column));
return null;
}
getInterCode().buildOperation(ctx.getChild(1).getText());
Object[] returnO = {"int",""};
return returnO;
}
public Object visitOp (OpContext ctx){
return ctx.getText();
}
public Object visitUnaryMinus (UnaryMinusContext ctx){
if (ctx.unaryMinus() != null){
Object obj = visit(ctx.unaryMinus());
if (obj == null){
int line = ctx.unaryMinus().getStart().getLine();
int column = ctx.unaryMinus().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de unaryMinus @line: "+line+" @column: "+column));
return null;
}
getInterCode().toMinus();
return obj;
}else{
Object obj = visit(ctx.atom());
if (obj == null){
int line = ctx.atom().getStart().getLine();
int column = ctx.atom().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en definicion de atom @line: "+line+" @column: "+column));
return null;
}
return obj;
}
}
public Object visitAtom (AtomContext ctx){
if (ctx.plusOrMinus() != null) return visit(ctx.plusOrMinus());
return visitChildren(ctx);
}
public Object visitBool_literal (Bool_literalContext ctx){
getInterCode().setBoolLiteral(ctx.getText());
Object[] returnO = {"boolean",ctx.getText()};
return returnO;
}
public Object visitChar_literal (Char_literalContext ctx){
getInterCode().setCharLiteral(ctx.getText());
Object[] returnO = {"char",ctx.getText()};
return returnO;
}
public Object visitInt_literal (Int_literalContext ctx){
getInterCode().setIntLiteral(ctx.getText());
Object[] returnO = {"int",ctx.getText()};
return returnO;
}
public Object visitParameter (ParameterContext ctx){
Object obj = visit(ctx.parameterType());
if (obj == null){
int line = ctx.parameterType().getStart().getLine();
int column = ctx.parameterType().getStart().getCharPositionInLine();
_errors.add(new Exception("Error en parameterType @line: "+line+" @column: "+column));
return null;
}
Object[] type = (Object[])obj;
String varType = (String) type[0];
int varSize = (int)type[1];
String varName = ctx.ID().getText();
Variable var = new Variable(varName,varType,varSize);
if (ctx.getChildCount()>2){
var.setArray(true);
}
return var;
}
public Object visitParameterType(ParameterTypeContext ctx){
if (ctx.getText().equals("int")){
Object[] obj = {"int", 4};
return obj;
}
if (ctx.getText().equals("char")){
Object[] obj = {"char", 1};
return obj;
}
if (ctx.getText().equals("boolean")){
Object[] obj = {"boolean", 1};
}
return null;
}
public Stack<Exception> getError(){
return _errors;
}
public String toStringError(){
String st = "";
while (!_errors.isEmpty()){
st += _errors.pop().toString()+"\n";
}
return st;
}
/**
* @return the _interCode
*/
public IntermediateCodeBuilder getInterCode() {
return _interCode;
}
/**
* @param _interCode the _interCode to set
*/
public void setInterCode(IntermediateCodeBuilder _interCode) {
this._interCode = _interCode;
}
public Object visitExpression(ExpressionContext ctx){
getInterCode().setNeeds_value(true);
return visitChildren(ctx);
}
}
| 68,000 | 0.546118 | 0.543 | 1,633 | 40.641151 | 31.860264 | 166 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.595836 | false | false |
5
|
7037114953134dbaba21ee01dd6fe4e0d39b5245
| 7,086,696,053,194 |
39ca0ffd95f31037069929e0d51f1bc54d59dda2
|
/469/A/Main.java
|
a2e07783346205f8ee8b8b079cbd53df2248bcf7
|
[] |
no_license
|
Dareten/Codeforces
|
https://github.com/Dareten/Codeforces
|
80de662d9d439520e52581d7d3ecdf4fb0985d57
|
9929f63ef03d3055f6698a4c8a1a5cf47f8e3ae1
|
refs/heads/master
| 2021-05-21T22:51:24.453000 | 2020-04-03T22:02:50 | 2020-04-03T22:02:50 | 252,843,011 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.util.HashSet;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt(), t;
HashSet<Integer> set = new HashSet<>();
for(int i=0;i<2;i++){
t = scan.nextInt();
for(int j=0;j<t;j++){
set.add(scan.nextInt());
}
}
String s;
if(n - set.size() == 0){
s = "I become the guy.";
}else{
s = "Oh, my keyboard!";
}
System.out.print(s);
}
}
|
UTF-8
|
Java
| 594 |
java
|
Main.java
|
Java
|
[] | null |
[] |
import java.util.HashSet;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt(), t;
HashSet<Integer> set = new HashSet<>();
for(int i=0;i<2;i++){
t = scan.nextInt();
for(int j=0;j<t;j++){
set.add(scan.nextInt());
}
}
String s;
if(n - set.size() == 0){
s = "I become the guy.";
}else{
s = "Oh, my keyboard!";
}
System.out.print(s);
}
}
| 594 | 0.461279 | 0.454545 | 23 | 24.869566 | 13.932459 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.73913 | false | false |
5
|
7f3ce51c5f15e397cfd08bd2f60611c9f089a6ea
| 29,248,727,320,774 |
4f48ed28ee131d74a13e753be9d8d185584a6c12
|
/src/main/java/org/chmodke/ipview/buis/ip/job/JobListener.java
|
c3c5f5f2dae7e9a405533fc777a3baf1944871eb
|
[] |
no_license
|
chmodke/ipview
|
https://github.com/chmodke/ipview
|
793935793582696989514a4b7bbe9e9ddebf5faa
|
704b0716fdd6fa49d742787c892d78b3f07b3eb0
|
refs/heads/master
| 2023-03-02T02:30:24.423000 | 2020-07-23T08:58:34 | 2020-07-23T08:58:34 | 216,610,824 | 0 | 0 | null | false | 2019-11-14T12:25:27 | 2019-10-21T16:09:31 | 2019-11-14T12:25:03 | 2019-11-14T12:25:01 | 49 | 0 | 0 | 0 |
Java
| false | false |
package org.chmodke.ipview.buis.ip.job;
import org.chmodke.ipview.common.config.AppConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.Date;
import java.util.Timer;
/****************************************************************
* <p>Filename: JobListener.java
* <p>Description:
* <p>
* <p>Create at: 2019/11/10 16:17
* <p>
* <p>Modification History:
* <p>Date Author Version Description
* <p>------------------------------------------------------------------
* <p>2019/11/10 kehao 1.0
* <p>------------------------------------------------------------------
*
* @author kehao
* @version 1.0
* @since
*******************************************************************/
public class JobListener implements ServletContextListener {
private static final Logger logger = LoggerFactory.getLogger(JobListener.class);
private static final int DEFAULT_TIME_INTERVAL = 5 * 60;//秒
private static int waitTime = 0;//秒
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
waitTime = AppConfig.getInteger("timeInterval", 5) * 60;
if (waitTime <= 0) {
waitTime = DEFAULT_TIME_INTERVAL;
}
logger.info("JobListener.contextInitialized,timeInterval is:{}ms", waitTime);
Timer timer = new Timer();
RefreshIpJob job = RefreshIpJob.getInstance();
job.init();
timer.schedule(job, new Date(), waitTime * 1000);
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
}
public static int getWaitTime() {
return waitTime;
}
}
|
UTF-8
|
Java
| 1,779 |
java
|
JobListener.java
|
Java
|
[
{
"context": "---------------------------- \n * <p>2019/11/10 kehao 1.0 \n * <p>---------------------------",
"end": 644,
"score": 0.9945276379585266,
"start": 639,
"tag": "USERNAME",
"value": "kehao"
},
{
"context": "------------------------------------\n *\n * @author kehao\n * @version 1.0\n * @since\n **********************",
"end": 753,
"score": 0.9970207214355469,
"start": 748,
"tag": "USERNAME",
"value": "kehao"
}
] | null |
[] |
package org.chmodke.ipview.buis.ip.job;
import org.chmodke.ipview.common.config.AppConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.Date;
import java.util.Timer;
/****************************************************************
* <p>Filename: JobListener.java
* <p>Description:
* <p>
* <p>Create at: 2019/11/10 16:17
* <p>
* <p>Modification History:
* <p>Date Author Version Description
* <p>------------------------------------------------------------------
* <p>2019/11/10 kehao 1.0
* <p>------------------------------------------------------------------
*
* @author kehao
* @version 1.0
* @since
*******************************************************************/
public class JobListener implements ServletContextListener {
private static final Logger logger = LoggerFactory.getLogger(JobListener.class);
private static final int DEFAULT_TIME_INTERVAL = 5 * 60;//秒
private static int waitTime = 0;//秒
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
waitTime = AppConfig.getInteger("timeInterval", 5) * 60;
if (waitTime <= 0) {
waitTime = DEFAULT_TIME_INTERVAL;
}
logger.info("JobListener.contextInitialized,timeInterval is:{}ms", waitTime);
Timer timer = new Timer();
RefreshIpJob job = RefreshIpJob.getInstance();
job.init();
timer.schedule(job, new Date(), waitTime * 1000);
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
}
public static int getWaitTime() {
return waitTime;
}
}
| 1,779 | 0.566761 | 0.545352 | 56 | 30.696428 | 26.041807 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.446429 | false | false |
5
|
6fecb7262175da3ba50792234960146f8b5f373d
| 9,285,719,356,290 |
29726c79e5aa3545ecb91bb6763a37e94f453d6a
|
/AbstractFactory/src/com/heraldo/ConexionRESTFabrica.java
|
bfa76b5c0b8e8c6e46fea0cfc75dec2f62d0dbce
|
[
"Apache-2.0"
] |
permissive
|
reicampos/JAVA_EE_Design_Patterns
|
https://github.com/reicampos/JAVA_EE_Design_Patterns
|
23e70b72f25540a66227f6bd93a06905757d699b
|
9fadd269c7cc81fcb8c52eaab3d14cdc401bcd97
|
refs/heads/master
| 2020-03-23T07:41:17.453000 | 2018-09-30T19:14:41 | 2018-09-30T19:14:41 | 141,285,780 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.heraldo;
import com.heraldo.inter.IFabricaAbstracta;
import com.heraldo.inter.IConexionBD;
import com.heraldo.inter.IConexionREST;
import com.heraldo.inter.impl.ConexionRESTCompras;
import com.heraldo.inter.impl.ConexionRESTNoArea;
import com.heraldo.inter.impl.ConexionRESTVentas;
public class ConexionRESTFabrica implements IFabricaAbstracta {
@Override
public IConexionREST getREST(String area) {
if (area == null) {
return new ConexionRESTNoArea();
}
if (area.equalsIgnoreCase("COMPRAS")) {
return new ConexionRESTCompras();
} else if (area.equalsIgnoreCase("VENTAS")) {
return new ConexionRESTVentas();
}
return new ConexionRESTNoArea();
}
@Override
public IConexionBD getBD(String motor) {
return null;
}
}
|
UTF-8
|
Java
| 758 |
java
|
ConexionRESTFabrica.java
|
Java
|
[] | null |
[] |
package com.heraldo;
import com.heraldo.inter.IFabricaAbstracta;
import com.heraldo.inter.IConexionBD;
import com.heraldo.inter.IConexionREST;
import com.heraldo.inter.impl.ConexionRESTCompras;
import com.heraldo.inter.impl.ConexionRESTNoArea;
import com.heraldo.inter.impl.ConexionRESTVentas;
public class ConexionRESTFabrica implements IFabricaAbstracta {
@Override
public IConexionREST getREST(String area) {
if (area == null) {
return new ConexionRESTNoArea();
}
if (area.equalsIgnoreCase("COMPRAS")) {
return new ConexionRESTCompras();
} else if (area.equalsIgnoreCase("VENTAS")) {
return new ConexionRESTVentas();
}
return new ConexionRESTNoArea();
}
@Override
public IConexionBD getBD(String motor) {
return null;
}
}
| 758 | 0.769129 | 0.769129 | 30 | 24.299999 | 19.973566 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.366667 | false | false |
5
|
ea93a5dadf83a03317975d389c89a69ef9774760
| 37,091,337,575,846 |
11580f857d21cd5ece2bb00064ab7ff66a8e7512
|
/fitnessChallenge/src/main/java/it/fitnesschallenge/UserListActivity.java
|
c625a207fae1d557c24981d0a511db9f9590904a
|
[] |
no_license
|
sardone220/FitnessChallenge
|
https://github.com/sardone220/FitnessChallenge
|
eee8a83964c774a86be177db37e7225d52d2425d
|
126b705a33df0e288e8cff1de9ebea959d74278a
|
refs/heads/master
| 2023-03-08T07:46:18.087000 | 2021-02-26T09:52:36 | 2021-02-26T09:52:36 | 342,516,847 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package it.fitnesschallenge;
import android.os.Bundle;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
import it.fitnesschallenge.adapter.UserItemAdapter;
public class UserListActivity extends AppCompatActivity {
private List<String> arrayListUser = new ArrayList<>();
private UserItemAdapter mUserItemAdapter;
private boolean mTwoPane;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_list);
Toolbar toolbar = findViewById(R.id.user_list_toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
RecyclerView recyclerView = findViewById(R.id.user_list);
if (findViewById(R.id.user_detail_container) != null) {
mTwoPane = true;
}
mUserItemAdapter = new UserItemAdapter(this, arrayListUser, mTwoPane);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(mUserItemAdapter);
/**
* otteniamo collection user firebase
*/
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("user").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot documentSnapshot : task.getResult()) {
arrayListUser.add(documentSnapshot.getId());
mUserItemAdapter.notifyDataSetChanged();
}
}
}
});
}
}
|
UTF-8
|
Java
| 2,385 |
java
|
UserListActivity.java
|
Java
|
[] | null |
[] |
package it.fitnesschallenge;
import android.os.Bundle;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
import it.fitnesschallenge.adapter.UserItemAdapter;
public class UserListActivity extends AppCompatActivity {
private List<String> arrayListUser = new ArrayList<>();
private UserItemAdapter mUserItemAdapter;
private boolean mTwoPane;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_list);
Toolbar toolbar = findViewById(R.id.user_list_toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
RecyclerView recyclerView = findViewById(R.id.user_list);
if (findViewById(R.id.user_detail_container) != null) {
mTwoPane = true;
}
mUserItemAdapter = new UserItemAdapter(this, arrayListUser, mTwoPane);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(mUserItemAdapter);
/**
* otteniamo collection user firebase
*/
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("user").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot documentSnapshot : task.getResult()) {
arrayListUser.add(documentSnapshot.getId());
mUserItemAdapter.notifyDataSetChanged();
}
}
}
});
}
}
| 2,385 | 0.68218 | 0.68218 | 69 | 33.565216 | 25.961777 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.521739 | false | false |
5
|
a8bfc0a87115384b138629a229da42a1bf15df56
| 31,026,843,785,796 |
2d373408c8c16f98feaf06568b6642e2b7aee67e
|
/cpf-media-service/src/main/java/com/hcc/cpf/media/controller/VehicleController.java
|
b32bf6c7e2a369c1dbe0e8fbfd59ea0f9778e2b4
|
[] |
no_license
|
huynhngochieu034/vehicle
|
https://github.com/huynhngochieu034/vehicle
|
377642dd4ac476f2479500d67c4faefcc53bf207
|
de085c828e5da20299d0df5781c978f641d81641
|
refs/heads/master
| 2022-12-21T22:53:22.850000 | 2019-07-29T07:11:35 | 2019-07-29T07:11:35 | 199,394,973 | 0 | 0 | null | false | 2022-12-10T05:13:15 | 2019-07-29T06:47:45 | 2019-07-29T07:11:37 | 2022-12-10T05:13:14 | 14,691 | 0 | 0 | 28 |
Java
| false | false |
package com.hcc.cpf.media.controller;
import com.hcc.cpf.media.dto.VehicleUserDTO;
import com.hcc.cpf.media.service.IVehicleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
//@CrossOrigin(origins = "http://localhost:4200")
@CrossOrigin(allowCredentials = "true")
@RestController
@RequestMapping({ "/api/car" })
public class VehicleController {
@Autowired
private IVehicleService vehicleService;
@GetMapping(value={"/{id}"}, produces = "application/json")
public List<VehicleUserDTO> getVehicleId(@PathVariable("id") Long id) {
return vehicleService.findByUserId(id);
}
@GetMapping(value={"/update/{id}"}, produces = "application/json")
public VehicleUserDTO getVehicleById(@PathVariable("id") Long id) {
return vehicleService.findByVehicleID(id);
}
@PostMapping
public ResponseEntity<VehicleUserDTO> createVehicle(@RequestBody VehicleUserDTO vehicleDTO) {
return ResponseEntity.ok(vehicleService.save(vehicleDTO,vehicleDTO.getId()));
}
@PutMapping("/{id}")
public ResponseEntity<VehicleUserDTO> updateVehicle(@RequestBody VehicleUserDTO vehicleDTO, @PathVariable("id") Long id) {
return ResponseEntity.ok(vehicleService.save(vehicleDTO, id));
}
@DeleteMapping
public ResponseEntity<Void> deleteVehicle(@RequestParam("ids") Long[] ids) {
if (ids.length > 0) {
vehicleService.deleteVehicle(ids);
}
return ResponseEntity.noContent().build();
}
}
|
UTF-8
|
Java
| 1,634 |
java
|
VehicleController.java
|
Java
|
[] | null |
[] |
package com.hcc.cpf.media.controller;
import com.hcc.cpf.media.dto.VehicleUserDTO;
import com.hcc.cpf.media.service.IVehicleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
//@CrossOrigin(origins = "http://localhost:4200")
@CrossOrigin(allowCredentials = "true")
@RestController
@RequestMapping({ "/api/car" })
public class VehicleController {
@Autowired
private IVehicleService vehicleService;
@GetMapping(value={"/{id}"}, produces = "application/json")
public List<VehicleUserDTO> getVehicleId(@PathVariable("id") Long id) {
return vehicleService.findByUserId(id);
}
@GetMapping(value={"/update/{id}"}, produces = "application/json")
public VehicleUserDTO getVehicleById(@PathVariable("id") Long id) {
return vehicleService.findByVehicleID(id);
}
@PostMapping
public ResponseEntity<VehicleUserDTO> createVehicle(@RequestBody VehicleUserDTO vehicleDTO) {
return ResponseEntity.ok(vehicleService.save(vehicleDTO,vehicleDTO.getId()));
}
@PutMapping("/{id}")
public ResponseEntity<VehicleUserDTO> updateVehicle(@RequestBody VehicleUserDTO vehicleDTO, @PathVariable("id") Long id) {
return ResponseEntity.ok(vehicleService.save(vehicleDTO, id));
}
@DeleteMapping
public ResponseEntity<Void> deleteVehicle(@RequestParam("ids") Long[] ids) {
if (ids.length > 0) {
vehicleService.deleteVehicle(ids);
}
return ResponseEntity.noContent().build();
}
}
| 1,634 | 0.72093 | 0.71787 | 49 | 32.346939 | 30.780693 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.387755 | false | false |
5
|
9dc02825ab2f8ab400a2673773fe7e403ac24cdb
| 36,713,380,461,334 |
f6ac256a1e9d67cd3701e4707727a849247072d0
|
/src/main/java/com/java/service/FriendService.java
|
e295cdccf1957a4af8b84051c8697389916b3f91
|
[] |
no_license
|
jordanzeeg/Project_02_Spring
|
https://github.com/jordanzeeg/Project_02_Spring
|
9962260e8003e90a5806341d349979df282eb2e9
|
e46a3891b13a4706e971d943b1a95953d09df338
|
refs/heads/master
| 2020-05-15T07:40:10.122000 | 2019-04-29T14:25:01 | 2019-04-29T14:25:01 | 182,143,350 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.java.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.java.dao.FriendDao;
import com.java.dto.Friend;
import com.java.salt.PasswordAndSalt;
import com.java.util.LoggerSingleton;
@Service
public class FriendService implements FriendServiceInterface<Friend> {
@Autowired
FriendDao dao;
@Override
public Friend get(int id) {
LoggerSingleton.getLogger().info("FETCHING Friend object based on friendId: " + id);
Friend friend = dao.get(id);
LoggerSingleton.getLogger().info("FETCHED Friend object based on friendId: " + id);
return friend;
}
@Override
public List<Friend> getAll() {
LoggerSingleton.getLogger().info("FETCHING ALL Friend objects");
List<Friend> friend = dao.getAll();
LoggerSingleton.getLogger().info("FETCHED ALL Friend objects");
return friend;
}
@Override
public void save(Friend t) {
LoggerSingleton.getLogger().info("SAVING a Friend object to database");
PasswordAndSalt ps = new PasswordAndSalt();
String salt = ps.getSalt(30);// generating a random salt
String passwordToDB = ps.generateSecurePassword(t.getPassword(), salt); // encrypting the password
t.setSalt(salt); // setting salt to be save in the db
t.setPassword(passwordToDB); // setting encrypted password to be save in the db
dao.save(t);
LoggerSingleton.getLogger().info("SAVED a Friend object to database");
}
@Override
public void update(Friend t) {
LoggerSingleton.getLogger().info("UPDATING a Friend object to database");
PasswordAndSalt ps = new PasswordAndSalt();
String salt = ps.getSalt(30);// generating a new random salt
String passwordToDB = ps.generateSecurePassword(t.getPassword(), salt); // encrypting the password
t.setSalt(salt); // setting salt to be save in the db
t.setPassword(passwordToDB); // setting encrypted password to be save in the db
dao.update(t);
LoggerSingleton.getLogger().info("UPDATED a Friend object to database");
}
@Override
public void delete(Friend t) {
LoggerSingleton.getLogger().info("DELETING a Friend object from database");
dao.delete(t);
LoggerSingleton.getLogger().info("DELETED a Friend object to database");
}
public List<Friend> search(String param) {
List<Friend> all = dao.getAll();
List<Friend> friends = new ArrayList<Friend>();
if (param == "" || param == null || param == " ") {
return all;
}
for (int i = 0; i < all.size(); i++) {
if (all.get(i).getUsername().toLowerCase().contains(param.toLowerCase())) {
friends.add(all.get(i));
}
}
return friends;
}
public Friend getByUsername(String username) {
LoggerSingleton.getLogger().info("FETCHING Friend object based on friendUsername: " + username);
Friend friend = dao.getByUsername(username);
LoggerSingleton.getLogger().info("FETCHED Friend object based on friendUsername: " + username);
LoggerSingleton.getLogger().info("FETCHED Friend object based on friendId: " + friend.getId());
return friend;
}
public Friend storeFriend(Friend friend) {
Friend friend2 = new Friend();
friend2.setId(friend.getId());
friend2.setUsername(friend.getUsername());
friend2.setFirstName(friend.getFirstName());
friend2.setLastName(friend.getLastName());
friend2.setPassword(friend.getPassword());
friend2.setPosts(friend.getPosts());
friend2.setEmail(friend.getEmail());
// new thing added by poho
friend2.setSalt(friend.getSalt());
return friend2;
}
public boolean passwordValidation(String username, String password) {
PasswordAndSalt ps = new PasswordAndSalt();
Friend friend = getUsername(username);
String salt = friend.getSalt(); // getting salt from db
if (ps.verifyUserPassword(password, friend.getPassword(), salt)) {
return true;
}
return false;
}
public Friend getUsername(String username) {
List<Friend> friends = getAll();
for (int i = 0; i < friends.size(); i++) {
if (username.equals(friends.get(i).getUsername())) {
LoggerSingleton.getLogger().info("Found friend in List by Username " + username);
return friends.get(i);
}
}
LoggerSingleton.getLogger().info("FETCHED Friend object based on username: " + username);
return new Friend();
}
public Friend getEmail(String email) {
List<Friend> friends = getAll();
for (int i = 0; i < friends.size(); i++) {
if (email.equals(friends.get(i).getEmail())) {
LoggerSingleton.getLogger().info("Found friend in List by Email " + email);
return friends.get(i);
}
}
LoggerSingleton.getLogger().info("FETCHED Friend object based on Email: " + email);
return null;
}
public Friend getByResetKey(String resetKey) {
List<Friend> friends = this.getAll();
Friend friend = new Friend();
System.out.println("reset Key: " +resetKey );
for(int i = 0;i<friends.size();i++) {
System.out.println("test against: " + friends.get(i).getResetkey());
if(friends.get(i).getResetkey()!=null) {
if(resetKey.equals(friends.get(i).getResetkey())){
friend = friends.get(i);
System.out.println("made it inside the if statement");
}
}
}
return friend;
}
}
|
UTF-8
|
Java
| 5,177 |
java
|
FriendService.java
|
Java
|
[
{
"context": "setting salt to be save in the db\n\t\tt.setPassword(passwordToDB); // setting encrypted password to be save in the",
"end": 1906,
"score": 0.9780712723731995,
"start": 1894,
"tag": "PASSWORD",
"value": "passwordToDB"
}
] | null |
[] |
package com.java.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.java.dao.FriendDao;
import com.java.dto.Friend;
import com.java.salt.PasswordAndSalt;
import com.java.util.LoggerSingleton;
@Service
public class FriendService implements FriendServiceInterface<Friend> {
@Autowired
FriendDao dao;
@Override
public Friend get(int id) {
LoggerSingleton.getLogger().info("FETCHING Friend object based on friendId: " + id);
Friend friend = dao.get(id);
LoggerSingleton.getLogger().info("FETCHED Friend object based on friendId: " + id);
return friend;
}
@Override
public List<Friend> getAll() {
LoggerSingleton.getLogger().info("FETCHING ALL Friend objects");
List<Friend> friend = dao.getAll();
LoggerSingleton.getLogger().info("FETCHED ALL Friend objects");
return friend;
}
@Override
public void save(Friend t) {
LoggerSingleton.getLogger().info("SAVING a Friend object to database");
PasswordAndSalt ps = new PasswordAndSalt();
String salt = ps.getSalt(30);// generating a random salt
String passwordToDB = ps.generateSecurePassword(t.getPassword(), salt); // encrypting the password
t.setSalt(salt); // setting salt to be save in the db
t.setPassword(passwordToDB); // setting encrypted password to be save in the db
dao.save(t);
LoggerSingleton.getLogger().info("SAVED a Friend object to database");
}
@Override
public void update(Friend t) {
LoggerSingleton.getLogger().info("UPDATING a Friend object to database");
PasswordAndSalt ps = new PasswordAndSalt();
String salt = ps.getSalt(30);// generating a new random salt
String passwordToDB = ps.generateSecurePassword(t.getPassword(), salt); // encrypting the password
t.setSalt(salt); // setting salt to be save in the db
t.setPassword(<PASSWORD>); // setting encrypted password to be save in the db
dao.update(t);
LoggerSingleton.getLogger().info("UPDATED a Friend object to database");
}
@Override
public void delete(Friend t) {
LoggerSingleton.getLogger().info("DELETING a Friend object from database");
dao.delete(t);
LoggerSingleton.getLogger().info("DELETED a Friend object to database");
}
public List<Friend> search(String param) {
List<Friend> all = dao.getAll();
List<Friend> friends = new ArrayList<Friend>();
if (param == "" || param == null || param == " ") {
return all;
}
for (int i = 0; i < all.size(); i++) {
if (all.get(i).getUsername().toLowerCase().contains(param.toLowerCase())) {
friends.add(all.get(i));
}
}
return friends;
}
public Friend getByUsername(String username) {
LoggerSingleton.getLogger().info("FETCHING Friend object based on friendUsername: " + username);
Friend friend = dao.getByUsername(username);
LoggerSingleton.getLogger().info("FETCHED Friend object based on friendUsername: " + username);
LoggerSingleton.getLogger().info("FETCHED Friend object based on friendId: " + friend.getId());
return friend;
}
public Friend storeFriend(Friend friend) {
Friend friend2 = new Friend();
friend2.setId(friend.getId());
friend2.setUsername(friend.getUsername());
friend2.setFirstName(friend.getFirstName());
friend2.setLastName(friend.getLastName());
friend2.setPassword(friend.getPassword());
friend2.setPosts(friend.getPosts());
friend2.setEmail(friend.getEmail());
// new thing added by poho
friend2.setSalt(friend.getSalt());
return friend2;
}
public boolean passwordValidation(String username, String password) {
PasswordAndSalt ps = new PasswordAndSalt();
Friend friend = getUsername(username);
String salt = friend.getSalt(); // getting salt from db
if (ps.verifyUserPassword(password, friend.getPassword(), salt)) {
return true;
}
return false;
}
public Friend getUsername(String username) {
List<Friend> friends = getAll();
for (int i = 0; i < friends.size(); i++) {
if (username.equals(friends.get(i).getUsername())) {
LoggerSingleton.getLogger().info("Found friend in List by Username " + username);
return friends.get(i);
}
}
LoggerSingleton.getLogger().info("FETCHED Friend object based on username: " + username);
return new Friend();
}
public Friend getEmail(String email) {
List<Friend> friends = getAll();
for (int i = 0; i < friends.size(); i++) {
if (email.equals(friends.get(i).getEmail())) {
LoggerSingleton.getLogger().info("Found friend in List by Email " + email);
return friends.get(i);
}
}
LoggerSingleton.getLogger().info("FETCHED Friend object based on Email: " + email);
return null;
}
public Friend getByResetKey(String resetKey) {
List<Friend> friends = this.getAll();
Friend friend = new Friend();
System.out.println("reset Key: " +resetKey );
for(int i = 0;i<friends.size();i++) {
System.out.println("test against: " + friends.get(i).getResetkey());
if(friends.get(i).getResetkey()!=null) {
if(resetKey.equals(friends.get(i).getResetkey())){
friend = friends.get(i);
System.out.println("made it inside the if statement");
}
}
}
return friend;
}
}
| 5,175 | 0.710643 | 0.707166 | 163 | 30.760736 | 28.428974 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.11043 | false | false |
5
|
10c678552115079c27d17e6c5fb41b91d26035c7
| 37,873,021,623,804 |
2429e5e391dbe804fe2701ad7e64020e4f335531
|
/src/com/rongpengli/designpattern/_2SimpleFactory/Client.java
|
cb231bfc05987b807cc61b4363e7313366fd539f
|
[] |
no_license
|
lrp1223/MyLearningProject
|
https://github.com/lrp1223/MyLearningProject
|
9f8b3e10603efdeb2f700a4a61036d4fa4b6a745
|
97fd470ee879cade417ca7a384afde22279d50f8
|
refs/heads/master
| 2021-01-10T07:38:08.592000 | 2016-03-13T13:42:49 | 2016-03-13T13:42:49 | 48,092,234 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.rongpengli.designpattern._2SimpleFactory;
public class Client {
public static void main(String[] args) {
Api api = Factory.createApi(1);
api.operation("Using simple factory.");
Api api2 = Factory.createApi2();
api2.operation("test");
}
}
|
UTF-8
|
Java
| 294 |
java
|
Client.java
|
Java
|
[] | null |
[] |
package com.rongpengli.designpattern._2SimpleFactory;
public class Client {
public static void main(String[] args) {
Api api = Factory.createApi(1);
api.operation("Using simple factory.");
Api api2 = Factory.createApi2();
api2.operation("test");
}
}
| 294 | 0.639456 | 0.622449 | 13 | 21.615385 | 20.435785 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.384615 | false | false |
5
|
bc24ca4010658b9983d438050c89f9fb8e9a15a5
| 18,734,647,394,379 |
12ffd60d093e63a5cf3986849c52917cecc56ba2
|
/desktop/src/com/inkostilation/pong/desktop/display/ObserverTree.java
|
3e9d3a059dc84c319222037c34b91eb28daa2c6c
|
[] |
no_license
|
VladoCC/Pong-Online
|
https://github.com/VladoCC/Pong-Online
|
e5c2647b3bea30df9b80c092682de57bbc47bf9e
|
c399376602c38c693eb7a8c866ebcc88c2a4f6e3
|
refs/heads/master
| 2023-03-08T12:41:20.553000 | 2021-02-22T08:13:22 | 2021-02-22T08:13:22 | 310,240,378 | 3 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.inkostilation.pong.desktop.display;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.ui.Tree;
import com.inkostilation.pong.desktop.notification.ClientNotifier;
import com.inkostilation.pong.notifications.IObserver;
import com.kotcrab.vis.ui.widget.VisTree;
public abstract class ObserverTree<A extends Actor, D> extends VisTree<ObserverTree.LobbyNode, A> implements IObserver<D> {
public ObserverTree(Class<D> observableClass) {
super();
ClientNotifier.getInstance().subscribe(this, observableClass);
}
@Override
public void observe(D... observable) {
clearChildren();
int pos = 0;
for (D data: observable) {
add(new LobbyNode(toActor(data), pos));
pos++;
}
}
abstract A toActor(D data);
public static class LobbyNode extends Tree.Node {
private int pos;
public LobbyNode(Actor actor, int pos) {
super(actor);
this.pos = pos;
}
public int getPos() {
return pos;
}
}
}
|
UTF-8
|
Java
| 1,106 |
java
|
ObserverTree.java
|
Java
|
[] | null |
[] |
package com.inkostilation.pong.desktop.display;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.ui.Tree;
import com.inkostilation.pong.desktop.notification.ClientNotifier;
import com.inkostilation.pong.notifications.IObserver;
import com.kotcrab.vis.ui.widget.VisTree;
public abstract class ObserverTree<A extends Actor, D> extends VisTree<ObserverTree.LobbyNode, A> implements IObserver<D> {
public ObserverTree(Class<D> observableClass) {
super();
ClientNotifier.getInstance().subscribe(this, observableClass);
}
@Override
public void observe(D... observable) {
clearChildren();
int pos = 0;
for (D data: observable) {
add(new LobbyNode(toActor(data), pos));
pos++;
}
}
abstract A toActor(D data);
public static class LobbyNode extends Tree.Node {
private int pos;
public LobbyNode(Actor actor, int pos) {
super(actor);
this.pos = pos;
}
public int getPos() {
return pos;
}
}
}
| 1,106 | 0.644665 | 0.641953 | 41 | 25.975609 | 25.804602 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.536585 | false | false |
5
|
f6c4df0b8a343b586d9b6c04db7e2727c112c45c
| 27,453,431,023,893 |
3a50663a348b4dbf36fd46f7fd2b5726e4825109
|
/plt/src/edu/rice/cs/plt/recur/RecurUtil.java
|
882c0eb93942b77b1f5f1d57f47f3a68e36a7dd3
|
[
"BSD-3-Clause"
] |
permissive
|
DrJavaAtRice/drjava
|
https://github.com/DrJavaAtRice/drjava
|
c18565762e119f2fe890e815f15a2cbaec21256f
|
158033081d5e269a2fd321d9872f1c5197f545a1
|
refs/heads/master
| 2023-02-17T23:04:44.221000 | 2023-02-16T21:04:42 | 2023-02-16T21:04:42 | 25,469,922 | 32 | 42 | null | false | 2019-10-17T13:37:03 | 2014-10-20T14:23:35 | 2019-10-12T09:09:39 | 2019-08-14T15:51:27 | 286,546 | 13 | 23 | 3 |
Java
| false | false |
/*BEGIN_COPYRIGHT_BLOCK*
PLT Utilities BSD License
Copyright (c) 2007-2010 JavaPLT group at Rice University
All rights reserved.
Developed by: Java Programming Languages Team
Rice University
http://www.cs.rice.edu/~javaplt/
Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of
conditions and the following disclaimer in the documentation and/or other materials provided
with the distribution.
- Neither the name of the JavaPLT group, Rice University, nor the names of the library's
contributors may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*END_COPYRIGHT_BLOCK*/
package edu.rice.cs.plt.recur;
import java.util.Arrays;
import edu.rice.cs.plt.lambda.Lambda;
import edu.rice.cs.plt.lambda.Lambda2;
import edu.rice.cs.plt.lambda.Predicate2;
import edu.rice.cs.plt.lambda.LambdaUtil;
import edu.rice.cs.plt.collect.TotalMap;
import edu.rice.cs.plt.reflect.ReflectUtil;
import edu.rice.cs.plt.text.TextUtil;
/**
* TODO: Is the extra overhead required to check for infinite loops enough to justify non-checking
* alternatives to safeToString, safeEquals, and safeHashCode?
*/
public final class RecurUtil {
private static final TotalMap<Thread, RecursionStack<Object>> TO_STRING_STACKS;
private static final TotalMap<Thread, RecursionStack2<Object, Object>> EQUALS_STACKS;
private static final TotalMap<Thread, RecursionStack<Object>> HASH_CODE_STACKS;
private static final Lambda<ArrayStringMode, Lambda<Object, String>> TO_STRING_GENERATOR;
private static final Lambda<ArrayStringMode, Lambda<Object, String>> DEFAULT_INF_STRING_GENERATOR;
private static final Lambda2<Object, Object, Boolean> EQUALS;
private static final Lambda<Object, Integer> HASH_CODE;
private static final Lambda<Object, Integer> DEFAULT_INF_HASH_CODE;
static {
Lambda<Thread, RecursionStack<Object>> makeNew = new Lambda<Thread, RecursionStack<Object>>() {
public RecursionStack<Object> value(Thread t) { return new RecursionStack<Object>(); }
};
Lambda<Thread, RecursionStack2<Object, Object>> makeNew2 =
new Lambda<Thread, RecursionStack2<Object, Object>>() {
public RecursionStack2<Object, Object> value(Thread t) {
return new RecursionStack2<Object, Object>();
}
};
// caching must be enabled (otherwise, a new stack is produced every time)
TO_STRING_STACKS = new TotalMap<Thread, RecursionStack<Object>>(makeNew, true);
EQUALS_STACKS = new TotalMap<Thread, RecursionStack2<Object, Object>>(makeNew2, true);
HASH_CODE_STACKS = new TotalMap<Thread, RecursionStack<Object>>(makeNew, true);
TO_STRING_GENERATOR = LambdaUtil.curry(new Lambda2<ArrayStringMode, Object, String>() {
public String value(ArrayStringMode mode, Object obj) {
if (obj.getClass().isArray()) { return arrayToString(obj, mode); }
else { return obj.toString(); }
}
});
DEFAULT_INF_STRING_GENERATOR = LambdaUtil.curry(new Lambda2<ArrayStringMode, Object, String>() {
public String value(ArrayStringMode mode, Object obj) {
if (obj.getClass().isArray()) { return mode.prefix() + "..." + mode.suffix(); }
else { return ReflectUtil.simpleName(obj.getClass()) + "..."; }
}
});
EQUALS = new Lambda2<Object, Object, Boolean>() {
public Boolean value(Object obj1, Object obj2) {
if (obj1.getClass().isArray()) {
if (obj2.getClass().isArray()) { return arrayEquals(obj1, obj2); }
else { return false; }
}
else {
if (obj2.getClass().isArray()) { return false; }
else { return obj1.equals(obj2); }
}
}
};
HASH_CODE = new Lambda<Object, Integer>() {
public Integer value(Object obj) {
if (obj.getClass().isArray()) { return arrayHashCode(obj); }
else { return obj.hashCode(); }
}
};
DEFAULT_INF_HASH_CODE = LambdaUtil.valueLambda(0xB32FC891);
}
/** Prevents instance creation */
private RecurUtil() {}
/**
* Invokes {@link #safeToString(Object, Lambda, int, ArrayStringMode)} using a default
* {@code infiniteString} like {@code "ClassName..."} or <code>"{ ... }"</code>, a default
* {@code depth} of {@code 1}, and {@link ArrayStringMode#DEEP_BRACED} as a default array
* string mode.
*/
public static String safeToString(Object obj) {
return safeToString(obj, DEFAULT_INF_STRING_GENERATOR.value(ArrayStringMode.DEEP_BRACED),
1, ArrayStringMode.DEEP_BRACED);
}
/**
* Invokes {@link #safeToString(Object, Lambda, int, ArrayStringMode)} using the given string as
* the {@code infiniteString}, a default {@code depth} of {@code 1}, and
* {@link ArrayStringMode#DEEP_BRACED} as a default array string mode.
*/
public static String safeToString(Object obj, String infiniteString) {
return safeToString(obj, infiniteString, 1, ArrayStringMode.DEEP_BRACED);
}
/**
* Invokes {@link #safeToString(Object, Lambda, int, ArrayStringMode)} with a default
* {@code depth} of {@code 1}, and using {@link ArrayStringMode#DEEP_BRACED} as a default array
* string mode.
*/
public static <T> String safeToString(T obj, Lambda<? super T, String> infiniteString) {
return safeToString(obj, infiniteString, 1, ArrayStringMode.DEEP_BRACED);
}
/**
* Invokes {@link #safeToString(Object, Lambda, int, ArrayStringMode)} using a default
* {@code infiniteString} like {@code "ClassName..."} or <code>"{ ... }"</code>, and a default
* {@code depth} of {@code 1}.
*/
public static String safeToString(Object obj, ArrayStringMode arrayMode) {
return safeToString(obj, DEFAULT_INF_STRING_GENERATOR.value(arrayMode), 1, arrayMode);
}
/**
* Invokes {@link #safeToString(Object, Lambda, int, ArrayStringMode)} using the given
* string as the {@code infiniteString}, and a default {@code depth} of {@code 1}.
*/
public static String safeToString(Object obj, String infiniteString, ArrayStringMode arrayMode) {
return safeToString(obj, LambdaUtil.valueLambda(infiniteString), 1, arrayMode);
}
/**
* Invokes {@link #safeToString(Object, Lambda, int, ArrayStringMode)} using a default
* {@code depth} of {@code 1}.
*/
public static <T> String safeToString(T obj, Lambda<? super T, String> infiniteString,
ArrayStringMode arrayMode) {
return safeToString(obj, infiniteString, 1, arrayMode);
}
/**
* Invokes {@link #safeToString(Object, Lambda, int, ArrayStringMode)} using a default
* {@code infiniteString} like {@code "ClassName..."} or <code>"{ ... }"</code>, and
* {@link ArrayStringMode#DEEP_BRACED} as a default array string mode.
*/
public static String safeToString(Object obj, int depth) {
return safeToString(obj, DEFAULT_INF_STRING_GENERATOR.value(ArrayStringMode.DEEP_BRACED),
depth, ArrayStringMode.DEEP_BRACED);
}
/**
* Invokes {@link #safeToString(Object, Lambda, int, ArrayStringMode)} using the given string as
* the {@code infiniteString}, and {@link ArrayStringMode#DEEP_BRACED} as a default array string
* mode.
*/
public static String safeToString(Object obj, String infiniteString, int depth) {
return safeToString(obj, infiniteString, depth, ArrayStringMode.DEEP_BRACED);
}
/**
* Invokes {@link #safeToString(Object, Lambda, int, ArrayStringMode)} using
* {@link ArrayStringMode#DEEP_BRACED} as a default array string mode.
*/
public static <T> String safeToString(T obj, Lambda<? super T, String> infiniteString, int depth) {
return safeToString(obj, infiniteString, depth, ArrayStringMode.DEEP_BRACED);
}
/**
* Invokes {@link #safeToString(Object, Lambda, int, ArrayStringMode)} using a default
* {@code infiniteString} like {@code "ClassName..."} or <code>"{ ... }"</code>.
*/
public static String safeToString(Object obj, int depth, ArrayStringMode arrayMode) {
return safeToString(obj, DEFAULT_INF_STRING_GENERATOR.value(arrayMode), depth, arrayMode);
}
/**
* Invokes {@link #safeToString(Object, Lambda, int, ArrayStringMode)} using the given
* string as the {@code infiniteString}.
*/
public static String safeToString(Object obj, String infiniteString, int depth,
ArrayStringMode arrayMode) {
return safeToString(obj, LambdaUtil.valueLambda(infiniteString), depth, arrayMode);
}
/**
* <p>Evaluate {@code obj.toString()} under the protection of an infinite-recursion check.
* If a string for {@code obj} is already in the process of being computed by this method
* {@code depth} times (that is, this is the {@code depth+1}st nested invocation),
* {@code infiniteString} will be applied. Otherwise, the result is {@code obj.toString()}.</p>
*
* <p>To simplify client code, this method also handles {@code null} values (returning
* {@code "null"}) and arrays (calling {@link #arrayToString(Object, ArrayStringMode)}).</p>
*
* @param obj An object (may be {@code null} or an array)
* @param infiniteString A lambda to generate a string for {@code obj} if its {@code toString}
* method has already been invoked {@code depth} times
* @param depth The number of times to allow a {@code toString} invocation before using
* {@code infiniteString} instead
* @param arrayMode The {@link ArrayStringMode} to use if {@code obj} is an array
* @return A string representation of {@code obj}
*/
public static <T> String safeToString(T obj, Lambda<? super T, String> infiniteString, int depth,
ArrayStringMode arrayMode) {
if (obj == null) { return "null"; }
else {
RecursionStack<Object> stack;
Thread t = Thread.currentThread();
synchronized (TO_STRING_STACKS) { stack = TO_STRING_STACKS.get(t); }
// no synchronization on stack, because it is only used in this thread
String result = stack.<T, String>apply(TO_STRING_GENERATOR.value(arrayMode), infiniteString, obj);
if (stack.isEmpty()) {
synchronized (TO_STRING_STACKS) { TO_STRING_STACKS.revert(t); }
}
return result;
}
}
/**
* Invoke {@link #arrayToString(Object, ArrayStringMode)} with a default string mode
* {@link ArrayStringMode#DEEP_BRACED}
*/
public static String arrayToString(Object array) {
return arrayToString(array, ArrayStringMode.DEEP_BRACED);
}
/**
* Generate a string representation of the given array. If the {@code stringMode} is
* {@link ArrayStringMode#CLASS_NAME} or {@link ArrayStringMode#TYPE_AND_SIZE}, generate
* a simple name, as specified; otherwise, generate a list of each of the elements (calling
* {@link #safeToString(Object, ArrayStringMode)} where applicable, using the mode
* produced by {@link ArrayStringMode#nestedMode()}).
*
* @throws IllegalArgumentException If {@code array} is not an array
*/
public static String arrayToString(Object array, ArrayStringMode stringMode) {
if (array instanceof Object[]) { return arrayToString((Object[]) array, stringMode); }
else if (array instanceof int[]) { return arrayToString((int[]) array, stringMode); }
else if (array instanceof char[]) { return arrayToString((char[]) array, stringMode); }
else if (array instanceof byte[]) { return arrayToString((byte[]) array, stringMode); }
else if (array instanceof double[]) { return arrayToString((double[]) array, stringMode); }
else if (array instanceof boolean[]) { return arrayToString((boolean[]) array, stringMode); }
else if (array instanceof short[]) { return arrayToString((short[]) array, stringMode); }
else if (array instanceof long[]) { return arrayToString((long[]) array, stringMode); }
else if (array instanceof float[]) { return arrayToString((float[]) array, stringMode); }
else { throw new IllegalArgumentException("Non-array argument"); }
}
/**
* Invoke {@link #arrayToString(Object[], ArrayStringMode)} with a default string mode
* {@link ArrayStringMode#DEEP_BRACED}
*/
public static String arrayToString(Object[] array) {
return arrayToString(array, ArrayStringMode.DEEP_BRACED);
}
/**
* Generate a string representation of the given array. If the {@code stringMode} is
* {@link ArrayStringMode#CLASS_NAME} or {@link ArrayStringMode#TYPE_AND_SIZE}, generate
* a simple name, as specified; otherwise call {@link #safeToString(Object, ArrayStringMode)}
* on each of the elements, using the mode produced by {@link ArrayStringMode#nestedMode()}.
* If {@code stringMode} is {@link ArrayStringMode#SHALLOW_BRACKETED}, the result will match
* that of {@link Arrays#toString(Object[])}; if {@code stringMode} is
* {@link ArrayStringMode#DEEP_BRACKETED}, the result will match that of
* {@link Arrays#deepToString}.
*/
public static String arrayToString(Object[] array, ArrayStringMode stringMode) {
switch (stringMode) {
case CLASS_NAME:
return array.toString();
case TYPE_AND_SIZE:
return ReflectUtil.simpleName(array.getClass().getComponentType()) + "[" + array.length + "]";
default:
StringBuilder result = new StringBuilder();
result.append(stringMode.prefix());
boolean first = true;
for (Object elt : array) {
if (first) { first = false; }
else { result.append(stringMode.delimiter()); }
result.append(safeToString(elt, stringMode.nestedMode()));
}
result.append(stringMode.suffix());
return result.toString();
}
}
/**
* Invoke {@link #arrayToString(boolean[], ArrayStringMode)} with a default string mode
* {@link ArrayStringMode#DEEP_BRACED}
*/
public static String arrayToString(boolean[] array) {
return arrayToString(array, ArrayStringMode.DEEP_BRACED);
}
/**
* Generate a string representation of the given array. If the {@code stringMode} is
* {@link ArrayStringMode#CLASS_NAME} or {@link ArrayStringMode#TYPE_AND_SIZE}, generate
* a simple name, as specified; otherwise, generate a list containing each element.
*/
public static String arrayToString(boolean[] array, ArrayStringMode stringMode) {
switch (stringMode) {
case CLASS_NAME:
return array.toString();
case TYPE_AND_SIZE:
return "boolean[" + array.length + "]";
default:
StringBuilder result = new StringBuilder();
result.append(stringMode.prefix());
boolean first = true;
for (boolean elt : array) {
if (first) { first = false; }
else { result.append(stringMode.delimiter()); }
result.append(elt);
}
result.append(stringMode.suffix());
return result.toString();
}
}
/**
* Invoke {@link #arrayToString(char[], ArrayStringMode)} with a default string mode
* {@link ArrayStringMode#DEEP_BRACED}
*/
public static String arrayToString(char[] array) {
return arrayToString(array, ArrayStringMode.DEEP_BRACED);
}
/**
* Generate a string representation of the given array. If the {@code stringMode} is
* {@link ArrayStringMode#CLASS_NAME} or {@link ArrayStringMode#TYPE_AND_SIZE}, generate
* a simple name, as specified; otherwise, generate a list containing each element.
*/
public static String arrayToString(char[] array, ArrayStringMode stringMode) {
switch (stringMode) {
case CLASS_NAME:
return array.toString();
case TYPE_AND_SIZE:
return "char[" + array.length + "]";
default:
StringBuilder result = new StringBuilder();
result.append(stringMode.prefix());
boolean first = true;
for (char elt : array) {
if (first) { first = false; }
else { result.append(stringMode.delimiter()); }
result.append(elt);
}
result.append(stringMode.suffix());
return result.toString();
}
}
/**
* Invoke {@link #arrayToString(byte[], ArrayStringMode)} with a default string mode
* {@link ArrayStringMode#DEEP_BRACED}
*/
public static String arrayToString(byte[] array) {
return arrayToString(array, ArrayStringMode.DEEP_BRACED);
}
/**
* Generate a string representation of the given array. If the {@code stringMode} is
* {@link ArrayStringMode#CLASS_NAME} or {@link ArrayStringMode#TYPE_AND_SIZE}, generate
* a simple name, as specified; otherwise, generate a list containing each element.
*/
public static String arrayToString(byte[] array, ArrayStringMode stringMode) {
switch (stringMode) {
case CLASS_NAME:
return array.toString();
case TYPE_AND_SIZE:
return "byte[" + array.length + "]";
default:
StringBuilder result = new StringBuilder();
result.append(stringMode.prefix());
boolean first = true;
for (byte elt : array) {
if (first) { first = false; }
else { result.append(stringMode.delimiter()); }
result.append(elt);
}
result.append(stringMode.suffix());
return result.toString();
}
}
/**
* Invoke {@link #arrayToString(short[], ArrayStringMode)} with a default string mode
* {@link ArrayStringMode#DEEP_BRACED}
*/
public static String arrayToString(short[] array) {
return arrayToString(array, ArrayStringMode.DEEP_BRACED);
}
/**
* Generate a string representation of the given array. If the {@code stringMode} is
* {@link ArrayStringMode#CLASS_NAME} or {@link ArrayStringMode#TYPE_AND_SIZE}, generate
* a simple name, as specified; otherwise, generate a list containing each element.
*/
public static String arrayToString(short[] array, ArrayStringMode stringMode) {
switch (stringMode) {
case CLASS_NAME:
return array.toString();
case TYPE_AND_SIZE:
return "short[" + array.length + "]";
default:
StringBuilder result = new StringBuilder();
result.append(stringMode.prefix());
boolean first = true;
for (short elt : array) {
if (first) { first = false; }
else { result.append(stringMode.delimiter()); }
result.append(elt);
}
result.append(stringMode.suffix());
return result.toString();
}
}
/**
* Invoke {@link #arrayToString(int[], ArrayStringMode)} with a default string mode
* {@link ArrayStringMode#DEEP_BRACED}
*/
public static String arrayToString(int[] array) {
return arrayToString(array, ArrayStringMode.DEEP_BRACED);
}
/**
* Generate a string representation of the given array. If the {@code stringMode} is
* {@link ArrayStringMode#CLASS_NAME} or {@link ArrayStringMode#TYPE_AND_SIZE}, generate
* a simple name, as specified; otherwise, generate a list containing each element.
*/
public static String arrayToString(int[] array, ArrayStringMode stringMode) {
switch (stringMode) {
case CLASS_NAME:
return array.toString();
case TYPE_AND_SIZE:
return "int[" + array.length + "]";
default:
StringBuilder result = new StringBuilder();
result.append(stringMode.prefix());
boolean first = true;
for (int elt : array) {
if (first) { first = false; }
else { result.append(stringMode.delimiter()); }
result.append(elt);
}
result.append(stringMode.suffix());
return result.toString();
}
}
/**
* Invoke {@link #arrayToString(long[], ArrayStringMode)} with a default string mode
* {@link ArrayStringMode#DEEP_BRACED}
*/
public static String arrayToString(long[] array) {
return arrayToString(array, ArrayStringMode.DEEP_BRACED);
}
/**
* Generate a string representation of the given array. If the {@code stringMode} is
* {@link ArrayStringMode#CLASS_NAME} or {@link ArrayStringMode#TYPE_AND_SIZE}, generate
* a simple name, as specified; otherwise, generate a list containing each element.
*/
public static String arrayToString(long[] array, ArrayStringMode stringMode) {
switch (stringMode) {
case CLASS_NAME:
return array.toString();
case TYPE_AND_SIZE:
return "long[" + array.length + "]";
default:
StringBuilder result = new StringBuilder();
result.append(stringMode.prefix());
boolean first = true;
for (long elt : array) {
if (first) { first = false; }
else { result.append(stringMode.delimiter()); }
result.append(elt);
}
result.append(stringMode.suffix());
return result.toString();
}
}
/**
* Invoke {@link #arrayToString(float[], ArrayStringMode)} with a default string mode
* {@link ArrayStringMode#DEEP_BRACED}
*/
public static String arrayToString(float[] array) {
return arrayToString(array, ArrayStringMode.DEEP_BRACED);
}
/**
* Generate a string representation of the given array. If the {@code stringMode} is
* {@link ArrayStringMode#CLASS_NAME} or {@link ArrayStringMode#TYPE_AND_SIZE}, generate
* a simple name, as specified; otherwise, generate a list containing each element.
*/
public static String arrayToString(float[] array, ArrayStringMode stringMode) {
switch (stringMode) {
case CLASS_NAME:
return array.toString();
case TYPE_AND_SIZE:
return "float[" + array.length + "]";
default:
StringBuilder result = new StringBuilder();
result.append(stringMode.prefix());
boolean first = true;
for (float elt : array) {
if (first) { first = false; }
else { result.append(stringMode.delimiter()); }
result.append(elt);
}
result.append(stringMode.suffix());
return result.toString();
}
}
/**
* Invoke {@link #arrayToString(double[], ArrayStringMode)} with a default string mode
* {@link ArrayStringMode#DEEP_BRACED}
*/
public static String arrayToString(double[] array) {
return arrayToString(array, ArrayStringMode.DEEP_BRACED);
}
/**
* Generate a string representation of the given array. If the {@code stringMode} is
* {@link ArrayStringMode#CLASS_NAME} or {@link ArrayStringMode#TYPE_AND_SIZE}, generate
* a simple name, as specified; otherwise, generate a list containing each element.
*/
public static String arrayToString(double[] array, ArrayStringMode stringMode) {
switch (stringMode) {
case CLASS_NAME:
return array.toString();
case TYPE_AND_SIZE:
return "double[" + array.length + "]";
default:
StringBuilder result = new StringBuilder();
result.append(stringMode.prefix());
boolean first = true;
for (double elt : array) {
if (first) { first = false; }
else { result.append(stringMode.delimiter()); }
result.append(elt);
}
result.append(stringMode.suffix());
return result.toString();
}
}
/**
* Invokes {@link #safeEquals(Object, Object, Predicate2)} using {@code true} for
* {@code infiniteEquals} (note that {@code false} is not a reasonable value for
* {@code infiniteEquals}, since an infinite structure must be equal to itself)
*
*/
public static boolean safeEquals(Object obj1, Object obj2) {
return safeEquals(obj1, obj2, LambdaUtil.TRUE);
}
/**
* <p>Evaluate {@code obj1.equals(obj2)} under the protection of an infinite-recursion check.
* If the equality of {@code obj1} and {@code obj2} is already in the process of being computed
* by this method, {@code infiniteEquals} will be applied. Otherwise, the result is
* {@code obj1.equals(obj2)}.</p>
*
* <p>To simplify client code, this method also handles {@code null} values (equal iff both
* values are {@code null}) and arrays (calling {@link #arrayEquals(Object, Object)}.</p>
*
* @param obj1 An object (may be {@code null} or an array)
* @param obj2 An object (may be {@code null} or an array)
* @param infiniteEquals A predicate to determine equality of {@code obj1.equals(obj2)} has
* already been invoked
* @return {@code true} iff the two objects are equal
*/
public static <T1, T2> boolean safeEquals(T1 obj1, T2 obj2,
Predicate2<? super T1, ? super T2> infiniteEquals) {
if (obj1 == null) { return obj2 == null; }
else if (obj2 == null) { return false; }
else {
RecursionStack2<Object, Object> stack;
Thread t = Thread.currentThread();
synchronized (EQUALS_STACKS) { stack = EQUALS_STACKS.get(t); }
// no synchronization on stack, because it is only used in this thread
boolean result = stack.<T1, T2, Boolean>apply(EQUALS, LambdaUtil.asLambda(infiniteEquals), obj1, obj2);
if (stack.isEmpty()) {
synchronized (EQUALS_STACKS) { EQUALS_STACKS.revert(t); }
}
return result;
}
}
/**
* Test the equality of the given arrays. The result is calculated by comparing the lengths,
* types (in the primitive cases), and corresponding elements of the arguments, recurring on
* any nested objects (including arrays) using {@link #safeEquals(Object, Object)}. Unlike
* {@link Arrays#deepEquals}, this method is able to handle an array nested within
* itself.
*
* @throws IllegalArgumentException If {@code array1} or {@code array2} is not an array
*/
public static boolean arrayEquals(Object a1, Object a2) {
if (!a1.getClass().isArray() || !a2.getClass().isArray()) {
throw new IllegalArgumentException("Non-array argument");
}
if (a1 instanceof Object[] && a2 instanceof Object[]) {
return arrayEquals((Object[]) a1, (Object[]) a2);
}
else if (!a1.getClass().equals(a2.getClass())) { return false; }
else if (a1 instanceof int[]) { return Arrays.equals((int[]) a1, (int[]) a2); }
else if (a1 instanceof char[]) { return Arrays.equals((char[]) a1, (char[]) a2); }
else if (a1 instanceof byte[]) { return Arrays.equals((byte[]) a1, (byte[]) a2); }
else if (a1 instanceof double[]) { return Arrays.equals((double[]) a1, (double[]) a2); }
else if (a1 instanceof boolean[]) { return Arrays.equals((boolean[]) a1, (boolean[]) a2); }
else if (a1 instanceof short[]) { return Arrays.equals((short[]) a1, (short[]) a2); }
else if (a1 instanceof long[]) { return Arrays.equals((long[]) a1, (long[]) a2); }
else if (a1 instanceof float[]) { return Arrays.equals((float[]) a1, (float[]) a2); }
else { throw new IllegalArgumentException("Unrecognized array type"); }
}
/**
* Test the equality of the given arrays. The result is calculated by comparing the lengths
* and corresponding elements of the arguments, recurring on nested objects (including arrays)
* using {@link #safeEquals(Object, Object)}. Note that arrays of different runtime types
* may still be equal if their elements are equal. Unlike {@link Arrays#deepEquals}, this
* method is able to handle an array nested within itself.
*/
public static boolean arrayEquals(Object[] a1, Object[] a2) {
if (a1.length != a2.length) { return false; }
for (int i = 0; i < a1.length; i++) { if (!safeEquals(a1[i], a2[i])) { return false; } }
return true;
}
/**
* Invokes {@link #safeHashCode(Object, Lambda)} using an arbitrary default value as the
* {@code infiniteHashCode}.
*/
public static int safeHashCode(Object obj) {
return safeHashCode(obj, DEFAULT_INF_HASH_CODE);
}
/**
* Invokes {@link #safeHashCode(Object, Lambda)} using the given value as the
* {@code infiniteHashCode}.
*/
public static int safeHashCode(Object obj, int infiniteHashCode) {
return safeHashCode(obj, LambdaUtil.valueLambda(infiniteHashCode));
}
/**
* <p>Evaluate {@code obj.hashCode()} under the protection of an infinite-recursion check.
* If the hash code for {@code obj} is already in the process of being computed by this method,
* {@code infiniteHashCode} will be applied. Otherwise, the result is {@code obj.hashCode()}.</p>
*
* <p>To simplify client code, this method also handles {@code null} values (returning {@code 0})
* and arrays (calling {@link #arrayHashCode(Object)}).</p>
*
* @param obj An object (may be {@code null} or an array)
* @param infiniteHashCode A lambda to generate a hash code for {@code obj} if its
* {@code hashCode} method has already been invoked
* @return A hash code for of {@code obj}
*/
public static <T> int safeHashCode(T obj, Lambda<? super T, Integer> infiniteHashCode) {
if (obj == null) { return 0; }
else {
RecursionStack<Object> stack;
Thread t = Thread.currentThread();
synchronized (HASH_CODE_STACKS) { stack = HASH_CODE_STACKS.get(t); }
// no synchronization on stack, because it is only used in this thread
int result = stack.<T, Integer>apply(HASH_CODE, infiniteHashCode, obj);
if (stack.isEmpty()) {
synchronized (HASH_CODE_STACKS) { HASH_CODE_STACKS.revert(t); }
}
return result;
}
}
/**
* Generate a hash code for the given array. The result is calculated as specified by
* {@link java.util.List#hashCode}, recurring on any nested objects (including arrays)
* using {@link #safeHashCode(Object)}. Unlike {@link Arrays#deepHashCode},
* this method is able to handle an array nested within itself.
*
* @throws IllegalArgumentException If {@code array} is not an array
*/
public static int arrayHashCode(Object array) {
if (array instanceof Object[]) { return arrayHashCode((Object[]) array); }
else if (array instanceof int[]) { return arrayHashCode((int[]) array); }
else if (array instanceof char[]) { return arrayHashCode((char[]) array); }
else if (array instanceof byte[]) { return arrayHashCode((byte[]) array); }
else if (array instanceof double[]) { return arrayHashCode((double[]) array); }
else if (array instanceof boolean[]) { return arrayHashCode((boolean[]) array); }
else if (array instanceof short[]) { return arrayHashCode((short[]) array); }
else if (array instanceof long[]) { return arrayHashCode((long[]) array); }
else if (array instanceof float[]) { return arrayHashCode((float[]) array); }
else { throw new IllegalArgumentException("Non-array argument"); }
}
/**
* Generate a hash code for the given array. The result is calculated as specified by
* {@link java.util.List#hashCode}, recurring on each element using {@link #safeHashCode(Object)}.
* Unlike {@link Arrays#deepHashCode}, this method is able to handle an array nested
* within itself.
*/
public static int arrayHashCode(Object[] array) {
int result = 1;
for (Object elt : array) { result = result*31 + safeHashCode(elt); }
return result;
}
/**
* Generate a hash code for the given array. The result is calculated as specified by
* {@link java.util.List#hashCode}, invoking the {@code Boolean#hashCode} method on
* each element. (Note that {@link Arrays#hashCode(boolean[])} implements the
* same method; this is defined here for compatibility with earlier APIs.)
*/
public static int arrayHashCode(boolean[] array) {
int result = 1;
for (boolean elt : array) { result = result*31 + ((Boolean) elt).hashCode(); }
return result;
}
/**
* Generate a hash code for the given array. The result is calculated as specified by
* {@link java.util.List#hashCode}, invoking the {@code Character#hashCode} method on
* each element. (Note that {@link Arrays#hashCode(char[])} implements the
* same method; this is defined here for compatibility with earlier APIs.)
*/
public static int arrayHashCode(char[] array) {
int result = 1;
for (char elt : array) { result = result*31 + ((Character) elt).hashCode(); }
return result;
}
/**
* Generate a hash code for the given array. The result is calculated as specified by
* {@link java.util.List#hashCode}, invoking the {@code Byte#hashCode} method on
* each element. (Note that {@link Arrays#hashCode(byte[])} implements the
* same method; this is defined here for compatibility with earlier APIs.)
*/
public static int arrayHashCode(byte[] array) {
int result = 1;
for (byte elt : array) { result = result*31 + ((Byte) elt).hashCode(); }
return result;
}
/**
* Generate a hash code for the given array. The result is calculated as specified by
* {@link java.util.List#hashCode}, invoking the {@code Short#hashCode} method on
* each element. (Note that {@link Arrays#hashCode(short[])} implements the
* same method; this is defined here for compatibility with earlier APIs.)
*/
public static int arrayHashCode(short[] array) {
int result = 1;
for (short elt : array) { result = result*31 + ((Short) elt).hashCode(); }
return result;
}
/**
* Generate a hash code for the given array. The result is calculated as specified by
* {@link java.util.List#hashCode}, invoking the {@code Integer#hashCode} method on
* each element. (Note that {@link Arrays#hashCode(int[])} implements the
* same method; this is defined here for compatibility with earlier APIs.)
*/
public static int arrayHashCode(int[] array) {
int result = 1;
for (int elt : array) { result = result*31 + ((Integer) elt).hashCode(); }
return result;
}
/**
* Generate a hash code for the given array. The result is calculated as specified by
* {@link java.util.List#hashCode}, invoking the {@code Long#hashCode} method on
* each element. (Note that {@link Arrays#hashCode(long[])} implements the
* same method; this is defined here for compatibility with earlier APIs.)
*/
public static int arrayHashCode(long[] array) {
int result = 1;
for (long elt : array) { result = result*31 + ((Long) elt).hashCode(); }
return result;
}
/**
* Generate a hash code for the given array. The result is calculated as specified by
* {@link java.util.List#hashCode}, invoking the {@code Float#hashCode} method on
* each element. (Note that {@link Arrays#hashCode(float[])} implements the
* same method; this is defined here for compatibility with earlier APIs.)
*/
public static int arrayHashCode(float[] array) {
int result = 1;
for (float elt : array) { result = result*31 + ((Float) elt).hashCode(); }
return result;
}
/**
* Generate a hash code for the given array. The result is calculated as specified by
* {@link java.util.List#hashCode}, invoking the {@code Double#hashCode} method on
* each element. (Note that {@link Arrays#hashCode(double[])} implements the
* same method; this is defined here for compatibility with earlier APIs.)
*/
public static int arrayHashCode(double[] array) {
int result = 1;
for (double elt : array) { result = result*31 + ((Double) elt).hashCode(); }
return result;
}
/** Defines the representation to be used in array string-generating methods */
public static enum ArrayStringMode {
/** Arrays are printed according to the array {@code toString} method */
CLASS_NAME {
protected String prefix() { throw new IllegalArgumentException(); }
protected String delimiter() { throw new IllegalArgumentException(); }
protected String suffix() { throw new IllegalArgumentException(); }
protected ArrayStringMode nestedMode() { throw new IllegalArgumentException(); }
},
/** Arrays are printed with an element type name and a size, like {@code "String[10]"} */
TYPE_AND_SIZE {
protected String prefix() { throw new IllegalArgumentException(); }
protected String delimiter() { throw new IllegalArgumentException(); }
protected String suffix() { throw new IllegalArgumentException(); }
protected ArrayStringMode nestedMode() { throw new IllegalArgumentException(); }
},
/**
* Arrays are printed as in {@code Arrays#toString(Object[])}, like
* {@code "[1, 2, 3]"}; nested arrays use {@link #CLASS_NAME}
*/
SHALLOW_BRACKETED {
protected String prefix() { return "["; }
protected String delimiter() { return ", "; }
protected String suffix() { return "]"; }
protected ArrayStringMode nestedMode() { return CLASS_NAME; }
},
/**
* Arrays are printed as in {@code Arrays#deepToString}, like {@code "[1, 2, 3]"};
* nested arrays also use {@code #DEEP_BRACKETED}
*/
DEEP_BRACKETED {
protected String prefix() { return "["; }
protected String delimiter() { return ", "; }
protected String suffix() { return "]"; }
protected ArrayStringMode nestedMode() { return DEEP_BRACKETED; }
},
/**
* Arrays are printed like array initializers, using braces (<code>"{ 1, 2, 3 }"</code>);
* nested arrays use {@link #TYPE_AND_SIZE}
*/
SHALLOW_BRACED {
protected String prefix() { return "{ "; }
protected String delimiter() { return ", "; }
protected String suffix() { return " }"; }
protected ArrayStringMode nestedMode() { return TYPE_AND_SIZE; }
},
/**
* Arrays are printed like array initializers, using braces (<code>"{ 1, 2, 3 }"</code>);
* nested arrays also use {@link #DEEP_BRACED}
*/
DEEP_BRACED {
protected String prefix() { return "{ "; }
protected String delimiter() { return ", "; }
protected String suffix() { return " }"; }
protected ArrayStringMode nestedMode() { return DEEP_BRACED; }
},
/** Arrays are printed with a single entry on each line; nested arrays use {@link #DEEP_BRACED} */
DEEP_MULTILINE {
protected String prefix() { return ""; }
protected String delimiter() { return TextUtil.NEWLINE; }
protected String suffix() { return ""; }
protected ArrayStringMode nestedMode() { return DEEP_BRACED; }
},
/** Arrays are printed with a single entry on each line; nested arrays use {@link #SHALLOW_BRACED} */
SHALLOW_MULTILINE {
protected String prefix() { return ""; }
protected String delimiter() { return TextUtil.NEWLINE; }
protected String suffix() { return ""; }
protected ArrayStringMode nestedMode() { return SHALLOW_BRACED; }
};
protected abstract String prefix();
protected abstract String delimiter();
protected abstract String suffix();
protected abstract ArrayStringMode nestedMode();
}
}
|
UTF-8
|
Java
| 40,043 |
java
|
RecurUtil.java
|
Java
|
[
{
"context": "ersity\n http://www.cs.rice.edu/~javaplt/\n\nRedistribution and use in source and binary for",
"end": 259,
"score": 0.9323451519012451,
"start": 255,
"tag": "USERNAME",
"value": "aplt"
}
] | null |
[] |
/*BEGIN_COPYRIGHT_BLOCK*
PLT Utilities BSD License
Copyright (c) 2007-2010 JavaPLT group at Rice University
All rights reserved.
Developed by: Java Programming Languages Team
Rice University
http://www.cs.rice.edu/~javaplt/
Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of
conditions and the following disclaimer in the documentation and/or other materials provided
with the distribution.
- Neither the name of the JavaPLT group, Rice University, nor the names of the library's
contributors may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*END_COPYRIGHT_BLOCK*/
package edu.rice.cs.plt.recur;
import java.util.Arrays;
import edu.rice.cs.plt.lambda.Lambda;
import edu.rice.cs.plt.lambda.Lambda2;
import edu.rice.cs.plt.lambda.Predicate2;
import edu.rice.cs.plt.lambda.LambdaUtil;
import edu.rice.cs.plt.collect.TotalMap;
import edu.rice.cs.plt.reflect.ReflectUtil;
import edu.rice.cs.plt.text.TextUtil;
/**
* TODO: Is the extra overhead required to check for infinite loops enough to justify non-checking
* alternatives to safeToString, safeEquals, and safeHashCode?
*/
public final class RecurUtil {
private static final TotalMap<Thread, RecursionStack<Object>> TO_STRING_STACKS;
private static final TotalMap<Thread, RecursionStack2<Object, Object>> EQUALS_STACKS;
private static final TotalMap<Thread, RecursionStack<Object>> HASH_CODE_STACKS;
private static final Lambda<ArrayStringMode, Lambda<Object, String>> TO_STRING_GENERATOR;
private static final Lambda<ArrayStringMode, Lambda<Object, String>> DEFAULT_INF_STRING_GENERATOR;
private static final Lambda2<Object, Object, Boolean> EQUALS;
private static final Lambda<Object, Integer> HASH_CODE;
private static final Lambda<Object, Integer> DEFAULT_INF_HASH_CODE;
static {
Lambda<Thread, RecursionStack<Object>> makeNew = new Lambda<Thread, RecursionStack<Object>>() {
public RecursionStack<Object> value(Thread t) { return new RecursionStack<Object>(); }
};
Lambda<Thread, RecursionStack2<Object, Object>> makeNew2 =
new Lambda<Thread, RecursionStack2<Object, Object>>() {
public RecursionStack2<Object, Object> value(Thread t) {
return new RecursionStack2<Object, Object>();
}
};
// caching must be enabled (otherwise, a new stack is produced every time)
TO_STRING_STACKS = new TotalMap<Thread, RecursionStack<Object>>(makeNew, true);
EQUALS_STACKS = new TotalMap<Thread, RecursionStack2<Object, Object>>(makeNew2, true);
HASH_CODE_STACKS = new TotalMap<Thread, RecursionStack<Object>>(makeNew, true);
TO_STRING_GENERATOR = LambdaUtil.curry(new Lambda2<ArrayStringMode, Object, String>() {
public String value(ArrayStringMode mode, Object obj) {
if (obj.getClass().isArray()) { return arrayToString(obj, mode); }
else { return obj.toString(); }
}
});
DEFAULT_INF_STRING_GENERATOR = LambdaUtil.curry(new Lambda2<ArrayStringMode, Object, String>() {
public String value(ArrayStringMode mode, Object obj) {
if (obj.getClass().isArray()) { return mode.prefix() + "..." + mode.suffix(); }
else { return ReflectUtil.simpleName(obj.getClass()) + "..."; }
}
});
EQUALS = new Lambda2<Object, Object, Boolean>() {
public Boolean value(Object obj1, Object obj2) {
if (obj1.getClass().isArray()) {
if (obj2.getClass().isArray()) { return arrayEquals(obj1, obj2); }
else { return false; }
}
else {
if (obj2.getClass().isArray()) { return false; }
else { return obj1.equals(obj2); }
}
}
};
HASH_CODE = new Lambda<Object, Integer>() {
public Integer value(Object obj) {
if (obj.getClass().isArray()) { return arrayHashCode(obj); }
else { return obj.hashCode(); }
}
};
DEFAULT_INF_HASH_CODE = LambdaUtil.valueLambda(0xB32FC891);
}
/** Prevents instance creation */
private RecurUtil() {}
/**
* Invokes {@link #safeToString(Object, Lambda, int, ArrayStringMode)} using a default
* {@code infiniteString} like {@code "ClassName..."} or <code>"{ ... }"</code>, a default
* {@code depth} of {@code 1}, and {@link ArrayStringMode#DEEP_BRACED} as a default array
* string mode.
*/
public static String safeToString(Object obj) {
return safeToString(obj, DEFAULT_INF_STRING_GENERATOR.value(ArrayStringMode.DEEP_BRACED),
1, ArrayStringMode.DEEP_BRACED);
}
/**
* Invokes {@link #safeToString(Object, Lambda, int, ArrayStringMode)} using the given string as
* the {@code infiniteString}, a default {@code depth} of {@code 1}, and
* {@link ArrayStringMode#DEEP_BRACED} as a default array string mode.
*/
public static String safeToString(Object obj, String infiniteString) {
return safeToString(obj, infiniteString, 1, ArrayStringMode.DEEP_BRACED);
}
/**
* Invokes {@link #safeToString(Object, Lambda, int, ArrayStringMode)} with a default
* {@code depth} of {@code 1}, and using {@link ArrayStringMode#DEEP_BRACED} as a default array
* string mode.
*/
public static <T> String safeToString(T obj, Lambda<? super T, String> infiniteString) {
return safeToString(obj, infiniteString, 1, ArrayStringMode.DEEP_BRACED);
}
/**
* Invokes {@link #safeToString(Object, Lambda, int, ArrayStringMode)} using a default
* {@code infiniteString} like {@code "ClassName..."} or <code>"{ ... }"</code>, and a default
* {@code depth} of {@code 1}.
*/
public static String safeToString(Object obj, ArrayStringMode arrayMode) {
return safeToString(obj, DEFAULT_INF_STRING_GENERATOR.value(arrayMode), 1, arrayMode);
}
/**
* Invokes {@link #safeToString(Object, Lambda, int, ArrayStringMode)} using the given
* string as the {@code infiniteString}, and a default {@code depth} of {@code 1}.
*/
public static String safeToString(Object obj, String infiniteString, ArrayStringMode arrayMode) {
return safeToString(obj, LambdaUtil.valueLambda(infiniteString), 1, arrayMode);
}
/**
* Invokes {@link #safeToString(Object, Lambda, int, ArrayStringMode)} using a default
* {@code depth} of {@code 1}.
*/
public static <T> String safeToString(T obj, Lambda<? super T, String> infiniteString,
ArrayStringMode arrayMode) {
return safeToString(obj, infiniteString, 1, arrayMode);
}
/**
* Invokes {@link #safeToString(Object, Lambda, int, ArrayStringMode)} using a default
* {@code infiniteString} like {@code "ClassName..."} or <code>"{ ... }"</code>, and
* {@link ArrayStringMode#DEEP_BRACED} as a default array string mode.
*/
public static String safeToString(Object obj, int depth) {
return safeToString(obj, DEFAULT_INF_STRING_GENERATOR.value(ArrayStringMode.DEEP_BRACED),
depth, ArrayStringMode.DEEP_BRACED);
}
/**
* Invokes {@link #safeToString(Object, Lambda, int, ArrayStringMode)} using the given string as
* the {@code infiniteString}, and {@link ArrayStringMode#DEEP_BRACED} as a default array string
* mode.
*/
public static String safeToString(Object obj, String infiniteString, int depth) {
return safeToString(obj, infiniteString, depth, ArrayStringMode.DEEP_BRACED);
}
/**
* Invokes {@link #safeToString(Object, Lambda, int, ArrayStringMode)} using
* {@link ArrayStringMode#DEEP_BRACED} as a default array string mode.
*/
public static <T> String safeToString(T obj, Lambda<? super T, String> infiniteString, int depth) {
return safeToString(obj, infiniteString, depth, ArrayStringMode.DEEP_BRACED);
}
/**
* Invokes {@link #safeToString(Object, Lambda, int, ArrayStringMode)} using a default
* {@code infiniteString} like {@code "ClassName..."} or <code>"{ ... }"</code>.
*/
public static String safeToString(Object obj, int depth, ArrayStringMode arrayMode) {
return safeToString(obj, DEFAULT_INF_STRING_GENERATOR.value(arrayMode), depth, arrayMode);
}
/**
* Invokes {@link #safeToString(Object, Lambda, int, ArrayStringMode)} using the given
* string as the {@code infiniteString}.
*/
public static String safeToString(Object obj, String infiniteString, int depth,
ArrayStringMode arrayMode) {
return safeToString(obj, LambdaUtil.valueLambda(infiniteString), depth, arrayMode);
}
/**
* <p>Evaluate {@code obj.toString()} under the protection of an infinite-recursion check.
* If a string for {@code obj} is already in the process of being computed by this method
* {@code depth} times (that is, this is the {@code depth+1}st nested invocation),
* {@code infiniteString} will be applied. Otherwise, the result is {@code obj.toString()}.</p>
*
* <p>To simplify client code, this method also handles {@code null} values (returning
* {@code "null"}) and arrays (calling {@link #arrayToString(Object, ArrayStringMode)}).</p>
*
* @param obj An object (may be {@code null} or an array)
* @param infiniteString A lambda to generate a string for {@code obj} if its {@code toString}
* method has already been invoked {@code depth} times
* @param depth The number of times to allow a {@code toString} invocation before using
* {@code infiniteString} instead
* @param arrayMode The {@link ArrayStringMode} to use if {@code obj} is an array
* @return A string representation of {@code obj}
*/
public static <T> String safeToString(T obj, Lambda<? super T, String> infiniteString, int depth,
ArrayStringMode arrayMode) {
if (obj == null) { return "null"; }
else {
RecursionStack<Object> stack;
Thread t = Thread.currentThread();
synchronized (TO_STRING_STACKS) { stack = TO_STRING_STACKS.get(t); }
// no synchronization on stack, because it is only used in this thread
String result = stack.<T, String>apply(TO_STRING_GENERATOR.value(arrayMode), infiniteString, obj);
if (stack.isEmpty()) {
synchronized (TO_STRING_STACKS) { TO_STRING_STACKS.revert(t); }
}
return result;
}
}
/**
* Invoke {@link #arrayToString(Object, ArrayStringMode)} with a default string mode
* {@link ArrayStringMode#DEEP_BRACED}
*/
public static String arrayToString(Object array) {
return arrayToString(array, ArrayStringMode.DEEP_BRACED);
}
/**
* Generate a string representation of the given array. If the {@code stringMode} is
* {@link ArrayStringMode#CLASS_NAME} or {@link ArrayStringMode#TYPE_AND_SIZE}, generate
* a simple name, as specified; otherwise, generate a list of each of the elements (calling
* {@link #safeToString(Object, ArrayStringMode)} where applicable, using the mode
* produced by {@link ArrayStringMode#nestedMode()}).
*
* @throws IllegalArgumentException If {@code array} is not an array
*/
public static String arrayToString(Object array, ArrayStringMode stringMode) {
if (array instanceof Object[]) { return arrayToString((Object[]) array, stringMode); }
else if (array instanceof int[]) { return arrayToString((int[]) array, stringMode); }
else if (array instanceof char[]) { return arrayToString((char[]) array, stringMode); }
else if (array instanceof byte[]) { return arrayToString((byte[]) array, stringMode); }
else if (array instanceof double[]) { return arrayToString((double[]) array, stringMode); }
else if (array instanceof boolean[]) { return arrayToString((boolean[]) array, stringMode); }
else if (array instanceof short[]) { return arrayToString((short[]) array, stringMode); }
else if (array instanceof long[]) { return arrayToString((long[]) array, stringMode); }
else if (array instanceof float[]) { return arrayToString((float[]) array, stringMode); }
else { throw new IllegalArgumentException("Non-array argument"); }
}
/**
* Invoke {@link #arrayToString(Object[], ArrayStringMode)} with a default string mode
* {@link ArrayStringMode#DEEP_BRACED}
*/
public static String arrayToString(Object[] array) {
return arrayToString(array, ArrayStringMode.DEEP_BRACED);
}
/**
* Generate a string representation of the given array. If the {@code stringMode} is
* {@link ArrayStringMode#CLASS_NAME} or {@link ArrayStringMode#TYPE_AND_SIZE}, generate
* a simple name, as specified; otherwise call {@link #safeToString(Object, ArrayStringMode)}
* on each of the elements, using the mode produced by {@link ArrayStringMode#nestedMode()}.
* If {@code stringMode} is {@link ArrayStringMode#SHALLOW_BRACKETED}, the result will match
* that of {@link Arrays#toString(Object[])}; if {@code stringMode} is
* {@link ArrayStringMode#DEEP_BRACKETED}, the result will match that of
* {@link Arrays#deepToString}.
*/
public static String arrayToString(Object[] array, ArrayStringMode stringMode) {
switch (stringMode) {
case CLASS_NAME:
return array.toString();
case TYPE_AND_SIZE:
return ReflectUtil.simpleName(array.getClass().getComponentType()) + "[" + array.length + "]";
default:
StringBuilder result = new StringBuilder();
result.append(stringMode.prefix());
boolean first = true;
for (Object elt : array) {
if (first) { first = false; }
else { result.append(stringMode.delimiter()); }
result.append(safeToString(elt, stringMode.nestedMode()));
}
result.append(stringMode.suffix());
return result.toString();
}
}
/**
* Invoke {@link #arrayToString(boolean[], ArrayStringMode)} with a default string mode
* {@link ArrayStringMode#DEEP_BRACED}
*/
public static String arrayToString(boolean[] array) {
return arrayToString(array, ArrayStringMode.DEEP_BRACED);
}
/**
* Generate a string representation of the given array. If the {@code stringMode} is
* {@link ArrayStringMode#CLASS_NAME} or {@link ArrayStringMode#TYPE_AND_SIZE}, generate
* a simple name, as specified; otherwise, generate a list containing each element.
*/
public static String arrayToString(boolean[] array, ArrayStringMode stringMode) {
switch (stringMode) {
case CLASS_NAME:
return array.toString();
case TYPE_AND_SIZE:
return "boolean[" + array.length + "]";
default:
StringBuilder result = new StringBuilder();
result.append(stringMode.prefix());
boolean first = true;
for (boolean elt : array) {
if (first) { first = false; }
else { result.append(stringMode.delimiter()); }
result.append(elt);
}
result.append(stringMode.suffix());
return result.toString();
}
}
/**
* Invoke {@link #arrayToString(char[], ArrayStringMode)} with a default string mode
* {@link ArrayStringMode#DEEP_BRACED}
*/
public static String arrayToString(char[] array) {
return arrayToString(array, ArrayStringMode.DEEP_BRACED);
}
/**
* Generate a string representation of the given array. If the {@code stringMode} is
* {@link ArrayStringMode#CLASS_NAME} or {@link ArrayStringMode#TYPE_AND_SIZE}, generate
* a simple name, as specified; otherwise, generate a list containing each element.
*/
public static String arrayToString(char[] array, ArrayStringMode stringMode) {
switch (stringMode) {
case CLASS_NAME:
return array.toString();
case TYPE_AND_SIZE:
return "char[" + array.length + "]";
default:
StringBuilder result = new StringBuilder();
result.append(stringMode.prefix());
boolean first = true;
for (char elt : array) {
if (first) { first = false; }
else { result.append(stringMode.delimiter()); }
result.append(elt);
}
result.append(stringMode.suffix());
return result.toString();
}
}
/**
* Invoke {@link #arrayToString(byte[], ArrayStringMode)} with a default string mode
* {@link ArrayStringMode#DEEP_BRACED}
*/
public static String arrayToString(byte[] array) {
return arrayToString(array, ArrayStringMode.DEEP_BRACED);
}
/**
* Generate a string representation of the given array. If the {@code stringMode} is
* {@link ArrayStringMode#CLASS_NAME} or {@link ArrayStringMode#TYPE_AND_SIZE}, generate
* a simple name, as specified; otherwise, generate a list containing each element.
*/
public static String arrayToString(byte[] array, ArrayStringMode stringMode) {
switch (stringMode) {
case CLASS_NAME:
return array.toString();
case TYPE_AND_SIZE:
return "byte[" + array.length + "]";
default:
StringBuilder result = new StringBuilder();
result.append(stringMode.prefix());
boolean first = true;
for (byte elt : array) {
if (first) { first = false; }
else { result.append(stringMode.delimiter()); }
result.append(elt);
}
result.append(stringMode.suffix());
return result.toString();
}
}
/**
* Invoke {@link #arrayToString(short[], ArrayStringMode)} with a default string mode
* {@link ArrayStringMode#DEEP_BRACED}
*/
public static String arrayToString(short[] array) {
return arrayToString(array, ArrayStringMode.DEEP_BRACED);
}
/**
* Generate a string representation of the given array. If the {@code stringMode} is
* {@link ArrayStringMode#CLASS_NAME} or {@link ArrayStringMode#TYPE_AND_SIZE}, generate
* a simple name, as specified; otherwise, generate a list containing each element.
*/
public static String arrayToString(short[] array, ArrayStringMode stringMode) {
switch (stringMode) {
case CLASS_NAME:
return array.toString();
case TYPE_AND_SIZE:
return "short[" + array.length + "]";
default:
StringBuilder result = new StringBuilder();
result.append(stringMode.prefix());
boolean first = true;
for (short elt : array) {
if (first) { first = false; }
else { result.append(stringMode.delimiter()); }
result.append(elt);
}
result.append(stringMode.suffix());
return result.toString();
}
}
/**
* Invoke {@link #arrayToString(int[], ArrayStringMode)} with a default string mode
* {@link ArrayStringMode#DEEP_BRACED}
*/
public static String arrayToString(int[] array) {
return arrayToString(array, ArrayStringMode.DEEP_BRACED);
}
/**
* Generate a string representation of the given array. If the {@code stringMode} is
* {@link ArrayStringMode#CLASS_NAME} or {@link ArrayStringMode#TYPE_AND_SIZE}, generate
* a simple name, as specified; otherwise, generate a list containing each element.
*/
public static String arrayToString(int[] array, ArrayStringMode stringMode) {
switch (stringMode) {
case CLASS_NAME:
return array.toString();
case TYPE_AND_SIZE:
return "int[" + array.length + "]";
default:
StringBuilder result = new StringBuilder();
result.append(stringMode.prefix());
boolean first = true;
for (int elt : array) {
if (first) { first = false; }
else { result.append(stringMode.delimiter()); }
result.append(elt);
}
result.append(stringMode.suffix());
return result.toString();
}
}
/**
* Invoke {@link #arrayToString(long[], ArrayStringMode)} with a default string mode
* {@link ArrayStringMode#DEEP_BRACED}
*/
public static String arrayToString(long[] array) {
return arrayToString(array, ArrayStringMode.DEEP_BRACED);
}
/**
* Generate a string representation of the given array. If the {@code stringMode} is
* {@link ArrayStringMode#CLASS_NAME} or {@link ArrayStringMode#TYPE_AND_SIZE}, generate
* a simple name, as specified; otherwise, generate a list containing each element.
*/
public static String arrayToString(long[] array, ArrayStringMode stringMode) {
switch (stringMode) {
case CLASS_NAME:
return array.toString();
case TYPE_AND_SIZE:
return "long[" + array.length + "]";
default:
StringBuilder result = new StringBuilder();
result.append(stringMode.prefix());
boolean first = true;
for (long elt : array) {
if (first) { first = false; }
else { result.append(stringMode.delimiter()); }
result.append(elt);
}
result.append(stringMode.suffix());
return result.toString();
}
}
/**
* Invoke {@link #arrayToString(float[], ArrayStringMode)} with a default string mode
* {@link ArrayStringMode#DEEP_BRACED}
*/
public static String arrayToString(float[] array) {
return arrayToString(array, ArrayStringMode.DEEP_BRACED);
}
/**
* Generate a string representation of the given array. If the {@code stringMode} is
* {@link ArrayStringMode#CLASS_NAME} or {@link ArrayStringMode#TYPE_AND_SIZE}, generate
* a simple name, as specified; otherwise, generate a list containing each element.
*/
public static String arrayToString(float[] array, ArrayStringMode stringMode) {
switch (stringMode) {
case CLASS_NAME:
return array.toString();
case TYPE_AND_SIZE:
return "float[" + array.length + "]";
default:
StringBuilder result = new StringBuilder();
result.append(stringMode.prefix());
boolean first = true;
for (float elt : array) {
if (first) { first = false; }
else { result.append(stringMode.delimiter()); }
result.append(elt);
}
result.append(stringMode.suffix());
return result.toString();
}
}
/**
* Invoke {@link #arrayToString(double[], ArrayStringMode)} with a default string mode
* {@link ArrayStringMode#DEEP_BRACED}
*/
public static String arrayToString(double[] array) {
return arrayToString(array, ArrayStringMode.DEEP_BRACED);
}
/**
* Generate a string representation of the given array. If the {@code stringMode} is
* {@link ArrayStringMode#CLASS_NAME} or {@link ArrayStringMode#TYPE_AND_SIZE}, generate
* a simple name, as specified; otherwise, generate a list containing each element.
*/
public static String arrayToString(double[] array, ArrayStringMode stringMode) {
switch (stringMode) {
case CLASS_NAME:
return array.toString();
case TYPE_AND_SIZE:
return "double[" + array.length + "]";
default:
StringBuilder result = new StringBuilder();
result.append(stringMode.prefix());
boolean first = true;
for (double elt : array) {
if (first) { first = false; }
else { result.append(stringMode.delimiter()); }
result.append(elt);
}
result.append(stringMode.suffix());
return result.toString();
}
}
/**
* Invokes {@link #safeEquals(Object, Object, Predicate2)} using {@code true} for
* {@code infiniteEquals} (note that {@code false} is not a reasonable value for
* {@code infiniteEquals}, since an infinite structure must be equal to itself)
*
*/
public static boolean safeEquals(Object obj1, Object obj2) {
return safeEquals(obj1, obj2, LambdaUtil.TRUE);
}
/**
* <p>Evaluate {@code obj1.equals(obj2)} under the protection of an infinite-recursion check.
* If the equality of {@code obj1} and {@code obj2} is already in the process of being computed
* by this method, {@code infiniteEquals} will be applied. Otherwise, the result is
* {@code obj1.equals(obj2)}.</p>
*
* <p>To simplify client code, this method also handles {@code null} values (equal iff both
* values are {@code null}) and arrays (calling {@link #arrayEquals(Object, Object)}.</p>
*
* @param obj1 An object (may be {@code null} or an array)
* @param obj2 An object (may be {@code null} or an array)
* @param infiniteEquals A predicate to determine equality of {@code obj1.equals(obj2)} has
* already been invoked
* @return {@code true} iff the two objects are equal
*/
public static <T1, T2> boolean safeEquals(T1 obj1, T2 obj2,
Predicate2<? super T1, ? super T2> infiniteEquals) {
if (obj1 == null) { return obj2 == null; }
else if (obj2 == null) { return false; }
else {
RecursionStack2<Object, Object> stack;
Thread t = Thread.currentThread();
synchronized (EQUALS_STACKS) { stack = EQUALS_STACKS.get(t); }
// no synchronization on stack, because it is only used in this thread
boolean result = stack.<T1, T2, Boolean>apply(EQUALS, LambdaUtil.asLambda(infiniteEquals), obj1, obj2);
if (stack.isEmpty()) {
synchronized (EQUALS_STACKS) { EQUALS_STACKS.revert(t); }
}
return result;
}
}
/**
* Test the equality of the given arrays. The result is calculated by comparing the lengths,
* types (in the primitive cases), and corresponding elements of the arguments, recurring on
* any nested objects (including arrays) using {@link #safeEquals(Object, Object)}. Unlike
* {@link Arrays#deepEquals}, this method is able to handle an array nested within
* itself.
*
* @throws IllegalArgumentException If {@code array1} or {@code array2} is not an array
*/
public static boolean arrayEquals(Object a1, Object a2) {
if (!a1.getClass().isArray() || !a2.getClass().isArray()) {
throw new IllegalArgumentException("Non-array argument");
}
if (a1 instanceof Object[] && a2 instanceof Object[]) {
return arrayEquals((Object[]) a1, (Object[]) a2);
}
else if (!a1.getClass().equals(a2.getClass())) { return false; }
else if (a1 instanceof int[]) { return Arrays.equals((int[]) a1, (int[]) a2); }
else if (a1 instanceof char[]) { return Arrays.equals((char[]) a1, (char[]) a2); }
else if (a1 instanceof byte[]) { return Arrays.equals((byte[]) a1, (byte[]) a2); }
else if (a1 instanceof double[]) { return Arrays.equals((double[]) a1, (double[]) a2); }
else if (a1 instanceof boolean[]) { return Arrays.equals((boolean[]) a1, (boolean[]) a2); }
else if (a1 instanceof short[]) { return Arrays.equals((short[]) a1, (short[]) a2); }
else if (a1 instanceof long[]) { return Arrays.equals((long[]) a1, (long[]) a2); }
else if (a1 instanceof float[]) { return Arrays.equals((float[]) a1, (float[]) a2); }
else { throw new IllegalArgumentException("Unrecognized array type"); }
}
/**
* Test the equality of the given arrays. The result is calculated by comparing the lengths
* and corresponding elements of the arguments, recurring on nested objects (including arrays)
* using {@link #safeEquals(Object, Object)}. Note that arrays of different runtime types
* may still be equal if their elements are equal. Unlike {@link Arrays#deepEquals}, this
* method is able to handle an array nested within itself.
*/
public static boolean arrayEquals(Object[] a1, Object[] a2) {
if (a1.length != a2.length) { return false; }
for (int i = 0; i < a1.length; i++) { if (!safeEquals(a1[i], a2[i])) { return false; } }
return true;
}
/**
* Invokes {@link #safeHashCode(Object, Lambda)} using an arbitrary default value as the
* {@code infiniteHashCode}.
*/
public static int safeHashCode(Object obj) {
return safeHashCode(obj, DEFAULT_INF_HASH_CODE);
}
/**
* Invokes {@link #safeHashCode(Object, Lambda)} using the given value as the
* {@code infiniteHashCode}.
*/
public static int safeHashCode(Object obj, int infiniteHashCode) {
return safeHashCode(obj, LambdaUtil.valueLambda(infiniteHashCode));
}
/**
* <p>Evaluate {@code obj.hashCode()} under the protection of an infinite-recursion check.
* If the hash code for {@code obj} is already in the process of being computed by this method,
* {@code infiniteHashCode} will be applied. Otherwise, the result is {@code obj.hashCode()}.</p>
*
* <p>To simplify client code, this method also handles {@code null} values (returning {@code 0})
* and arrays (calling {@link #arrayHashCode(Object)}).</p>
*
* @param obj An object (may be {@code null} or an array)
* @param infiniteHashCode A lambda to generate a hash code for {@code obj} if its
* {@code hashCode} method has already been invoked
* @return A hash code for of {@code obj}
*/
public static <T> int safeHashCode(T obj, Lambda<? super T, Integer> infiniteHashCode) {
if (obj == null) { return 0; }
else {
RecursionStack<Object> stack;
Thread t = Thread.currentThread();
synchronized (HASH_CODE_STACKS) { stack = HASH_CODE_STACKS.get(t); }
// no synchronization on stack, because it is only used in this thread
int result = stack.<T, Integer>apply(HASH_CODE, infiniteHashCode, obj);
if (stack.isEmpty()) {
synchronized (HASH_CODE_STACKS) { HASH_CODE_STACKS.revert(t); }
}
return result;
}
}
/**
* Generate a hash code for the given array. The result is calculated as specified by
* {@link java.util.List#hashCode}, recurring on any nested objects (including arrays)
* using {@link #safeHashCode(Object)}. Unlike {@link Arrays#deepHashCode},
* this method is able to handle an array nested within itself.
*
* @throws IllegalArgumentException If {@code array} is not an array
*/
public static int arrayHashCode(Object array) {
if (array instanceof Object[]) { return arrayHashCode((Object[]) array); }
else if (array instanceof int[]) { return arrayHashCode((int[]) array); }
else if (array instanceof char[]) { return arrayHashCode((char[]) array); }
else if (array instanceof byte[]) { return arrayHashCode((byte[]) array); }
else if (array instanceof double[]) { return arrayHashCode((double[]) array); }
else if (array instanceof boolean[]) { return arrayHashCode((boolean[]) array); }
else if (array instanceof short[]) { return arrayHashCode((short[]) array); }
else if (array instanceof long[]) { return arrayHashCode((long[]) array); }
else if (array instanceof float[]) { return arrayHashCode((float[]) array); }
else { throw new IllegalArgumentException("Non-array argument"); }
}
/**
* Generate a hash code for the given array. The result is calculated as specified by
* {@link java.util.List#hashCode}, recurring on each element using {@link #safeHashCode(Object)}.
* Unlike {@link Arrays#deepHashCode}, this method is able to handle an array nested
* within itself.
*/
public static int arrayHashCode(Object[] array) {
int result = 1;
for (Object elt : array) { result = result*31 + safeHashCode(elt); }
return result;
}
/**
* Generate a hash code for the given array. The result is calculated as specified by
* {@link java.util.List#hashCode}, invoking the {@code Boolean#hashCode} method on
* each element. (Note that {@link Arrays#hashCode(boolean[])} implements the
* same method; this is defined here for compatibility with earlier APIs.)
*/
public static int arrayHashCode(boolean[] array) {
int result = 1;
for (boolean elt : array) { result = result*31 + ((Boolean) elt).hashCode(); }
return result;
}
/**
* Generate a hash code for the given array. The result is calculated as specified by
* {@link java.util.List#hashCode}, invoking the {@code Character#hashCode} method on
* each element. (Note that {@link Arrays#hashCode(char[])} implements the
* same method; this is defined here for compatibility with earlier APIs.)
*/
public static int arrayHashCode(char[] array) {
int result = 1;
for (char elt : array) { result = result*31 + ((Character) elt).hashCode(); }
return result;
}
/**
* Generate a hash code for the given array. The result is calculated as specified by
* {@link java.util.List#hashCode}, invoking the {@code Byte#hashCode} method on
* each element. (Note that {@link Arrays#hashCode(byte[])} implements the
* same method; this is defined here for compatibility with earlier APIs.)
*/
public static int arrayHashCode(byte[] array) {
int result = 1;
for (byte elt : array) { result = result*31 + ((Byte) elt).hashCode(); }
return result;
}
/**
* Generate a hash code for the given array. The result is calculated as specified by
* {@link java.util.List#hashCode}, invoking the {@code Short#hashCode} method on
* each element. (Note that {@link Arrays#hashCode(short[])} implements the
* same method; this is defined here for compatibility with earlier APIs.)
*/
public static int arrayHashCode(short[] array) {
int result = 1;
for (short elt : array) { result = result*31 + ((Short) elt).hashCode(); }
return result;
}
/**
* Generate a hash code for the given array. The result is calculated as specified by
* {@link java.util.List#hashCode}, invoking the {@code Integer#hashCode} method on
* each element. (Note that {@link Arrays#hashCode(int[])} implements the
* same method; this is defined here for compatibility with earlier APIs.)
*/
public static int arrayHashCode(int[] array) {
int result = 1;
for (int elt : array) { result = result*31 + ((Integer) elt).hashCode(); }
return result;
}
/**
* Generate a hash code for the given array. The result is calculated as specified by
* {@link java.util.List#hashCode}, invoking the {@code Long#hashCode} method on
* each element. (Note that {@link Arrays#hashCode(long[])} implements the
* same method; this is defined here for compatibility with earlier APIs.)
*/
public static int arrayHashCode(long[] array) {
int result = 1;
for (long elt : array) { result = result*31 + ((Long) elt).hashCode(); }
return result;
}
/**
* Generate a hash code for the given array. The result is calculated as specified by
* {@link java.util.List#hashCode}, invoking the {@code Float#hashCode} method on
* each element. (Note that {@link Arrays#hashCode(float[])} implements the
* same method; this is defined here for compatibility with earlier APIs.)
*/
public static int arrayHashCode(float[] array) {
int result = 1;
for (float elt : array) { result = result*31 + ((Float) elt).hashCode(); }
return result;
}
/**
* Generate a hash code for the given array. The result is calculated as specified by
* {@link java.util.List#hashCode}, invoking the {@code Double#hashCode} method on
* each element. (Note that {@link Arrays#hashCode(double[])} implements the
* same method; this is defined here for compatibility with earlier APIs.)
*/
public static int arrayHashCode(double[] array) {
int result = 1;
for (double elt : array) { result = result*31 + ((Double) elt).hashCode(); }
return result;
}
/** Defines the representation to be used in array string-generating methods */
public static enum ArrayStringMode {
/** Arrays are printed according to the array {@code toString} method */
CLASS_NAME {
protected String prefix() { throw new IllegalArgumentException(); }
protected String delimiter() { throw new IllegalArgumentException(); }
protected String suffix() { throw new IllegalArgumentException(); }
protected ArrayStringMode nestedMode() { throw new IllegalArgumentException(); }
},
/** Arrays are printed with an element type name and a size, like {@code "String[10]"} */
TYPE_AND_SIZE {
protected String prefix() { throw new IllegalArgumentException(); }
protected String delimiter() { throw new IllegalArgumentException(); }
protected String suffix() { throw new IllegalArgumentException(); }
protected ArrayStringMode nestedMode() { throw new IllegalArgumentException(); }
},
/**
* Arrays are printed as in {@code Arrays#toString(Object[])}, like
* {@code "[1, 2, 3]"}; nested arrays use {@link #CLASS_NAME}
*/
SHALLOW_BRACKETED {
protected String prefix() { return "["; }
protected String delimiter() { return ", "; }
protected String suffix() { return "]"; }
protected ArrayStringMode nestedMode() { return CLASS_NAME; }
},
/**
* Arrays are printed as in {@code Arrays#deepToString}, like {@code "[1, 2, 3]"};
* nested arrays also use {@code #DEEP_BRACKETED}
*/
DEEP_BRACKETED {
protected String prefix() { return "["; }
protected String delimiter() { return ", "; }
protected String suffix() { return "]"; }
protected ArrayStringMode nestedMode() { return DEEP_BRACKETED; }
},
/**
* Arrays are printed like array initializers, using braces (<code>"{ 1, 2, 3 }"</code>);
* nested arrays use {@link #TYPE_AND_SIZE}
*/
SHALLOW_BRACED {
protected String prefix() { return "{ "; }
protected String delimiter() { return ", "; }
protected String suffix() { return " }"; }
protected ArrayStringMode nestedMode() { return TYPE_AND_SIZE; }
},
/**
* Arrays are printed like array initializers, using braces (<code>"{ 1, 2, 3 }"</code>);
* nested arrays also use {@link #DEEP_BRACED}
*/
DEEP_BRACED {
protected String prefix() { return "{ "; }
protected String delimiter() { return ", "; }
protected String suffix() { return " }"; }
protected ArrayStringMode nestedMode() { return DEEP_BRACED; }
},
/** Arrays are printed with a single entry on each line; nested arrays use {@link #DEEP_BRACED} */
DEEP_MULTILINE {
protected String prefix() { return ""; }
protected String delimiter() { return TextUtil.NEWLINE; }
protected String suffix() { return ""; }
protected ArrayStringMode nestedMode() { return DEEP_BRACED; }
},
/** Arrays are printed with a single entry on each line; nested arrays use {@link #SHALLOW_BRACED} */
SHALLOW_MULTILINE {
protected String prefix() { return ""; }
protected String delimiter() { return TextUtil.NEWLINE; }
protected String suffix() { return ""; }
protected ArrayStringMode nestedMode() { return SHALLOW_BRACED; }
};
protected abstract String prefix();
protected abstract String delimiter();
protected abstract String suffix();
protected abstract ArrayStringMode nestedMode();
}
}
| 40,043 | 0.660365 | 0.656145 | 935 | 41.826736 | 34.049351 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.687701 | false | false |
5
|
8f3a7936384bf9da71b5fc89cdd6297964bb83e1
| 35,218,731,857,663 |
78df5af1c2775933de31a3a91f831c0326d6464d
|
/kcwiki/web/api/jsonpatch.java
|
dc135da135b7dbb0abaa5b50c8029cf85c6f35ce
|
[] |
no_license
|
kcwikizh/KCServerMonitor
|
https://github.com/kcwikizh/KCServerMonitor
|
2096986be7b5476d9a2949f76079b58c1071951d
|
eb5f22e639018bfaaa3b6b0973939452a8192c0d
|
refs/heads/master
| 2021-01-23T15:58:33.277000 | 2018-03-24T10:21:15 | 2018-03-24T10:21:15 | 102,718,779 | 4 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* 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 moe.kcwiki.web.api;
import com.alibaba.fastjson.JSON;
import moe.kcwiki.database.DBCenter;
import static moe.kcwiki.tools.constant.constant.LINESEPARATOR;
/**
*
* @author iTeam_VEP
*/
public class jsonpatch {
private StringBuilder sb = null;
public String getData() {
sb = new StringBuilder();
if(DBCenter.JsonPatch.isEmpty()){
this.addString("<!DOCTYPE html><html><body>");
this.addString("没有发现差分JSON内容或者抓包程序未运行,请等待后台抓包进程执行。");
this.addString("</body></html>");
} else {
this.addString(LINESEPARATOR);
/*for (String key:DBCenter.JsonPatch.keySet()) {
this.addString(JSON.toJSONString(DBCenter.JsonPatch.get(key)));
}*/
this.addString(JSON.toJSONString(DBCenter.JsonPatch));
}
return sb.toString();
}
public void addData(String str) {
if(sb == null){
sb = new StringBuilder();
}
this.addString(str);
}
private void addString(String str) {
sb.append(str).append(LINESEPARATOR).append("</br>").append(LINESEPARATOR);
}
}
|
UTF-8
|
Java
| 1,414 |
java
|
jsonpatch.java
|
Java
|
[
{
"context": "onstant.constant.LINESEPARATOR;\n\n/**\n *\n * @author iTeam_VEP\n */\npublic class jsonpatch {\n private StringBu",
"end": 377,
"score": 0.9995269775390625,
"start": 368,
"tag": "USERNAME",
"value": "iTeam_VEP"
}
] | null |
[] |
/*
* 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 moe.kcwiki.web.api;
import com.alibaba.fastjson.JSON;
import moe.kcwiki.database.DBCenter;
import static moe.kcwiki.tools.constant.constant.LINESEPARATOR;
/**
*
* @author iTeam_VEP
*/
public class jsonpatch {
private StringBuilder sb = null;
public String getData() {
sb = new StringBuilder();
if(DBCenter.JsonPatch.isEmpty()){
this.addString("<!DOCTYPE html><html><body>");
this.addString("没有发现差分JSON内容或者抓包程序未运行,请等待后台抓包进程执行。");
this.addString("</body></html>");
} else {
this.addString(LINESEPARATOR);
/*for (String key:DBCenter.JsonPatch.keySet()) {
this.addString(JSON.toJSONString(DBCenter.JsonPatch.get(key)));
}*/
this.addString(JSON.toJSONString(DBCenter.JsonPatch));
}
return sb.toString();
}
public void addData(String str) {
if(sb == null){
sb = new StringBuilder();
}
this.addString(str);
}
private void addString(String str) {
sb.append(str).append(LINESEPARATOR).append("</br>").append(LINESEPARATOR);
}
}
| 1,414 | 0.610783 | 0.610783 | 47 | 27.80851 | 24.168415 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.404255 | false | false |
5
|
57a00cf5d79d3482e3c0fd64ef01819c065f322c
| 8,761,733,327,004 |
a4d29ae60e2e93c3c90fe820fdb08ab5611f1049
|
/src/com/basicFrameWork/extentReport/test.java
|
9797188121b7960dc316cb91247a72078734ec63
|
[] |
no_license
|
ya1439555396/BaseFrameWork
|
https://github.com/ya1439555396/BaseFrameWork
|
a6f440319806e59e8f1b854ee68e4899fb3cd11a
|
318e2084980c72c5dbd1a73e77f4d2ce7adc2247
|
refs/heads/master
| 2017-12-01T03:10:48.943000 | 2017-02-22T02:16:44 | 2017-02-22T02:16:44 | 82,038,686 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.basicFrameWork.extentReport;
import java.io.IOException;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
/**
* * @author author:gaozeya2@bluemoon.com.cn
*
* @date date:2017年2月16日 下午4:01:56
* @version 1.0 * @parameter * @since * @return
*/
public class test {
public static void main(String[] args) {
// start reporters
ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter("extent.html");
htmlReporter.config().setEncoding("GB2312");
htmlReporter.config().setDocumentTitle("我的测试报告");
htmlReporter.config().setReportName("测试报告标题");
// create ExtentReports and attach reporter(s)
ExtentReports extent = new ExtentReports();
extent.attachReporter(htmlReporter);
// creates a toggle for the given test, adds all log events under it
ExtentTest test = extent.createTest("MyFirstTest", "Sample description");
// info(details)
test.info("This step shows usage of info(details)");
// test with snapshot
try {
test.addScreenCaptureFromPath("C:\\Users\\gzy\\workspace\\BasicFrameWork\\123.png");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// calling flush writes everything to the log file
extent.flush();
}
}
|
GB18030
|
Java
| 1,706 |
java
|
test.java
|
Java
|
[
{
"context": "r.ExtentHtmlReporter;\r\n\r\n/**\r\n * * @author author:gaozeya2@bluemoon.com.cn\r\n * \r\n * @date date:2017年2月16日 下午4:01:56\r\n * @ver",
"end": 428,
"score": 0.9997344613075256,
"start": 404,
"tag": "EMAIL",
"value": "gaozeya2@bluemoon.com.cn"
}
] | null |
[] |
package com.basicFrameWork.extentReport;
import java.io.IOException;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
/**
* * @author author:<EMAIL>
*
* @date date:2017年2月16日 下午4:01:56
* @version 1.0 * @parameter * @since * @return
*/
public class test {
public static void main(String[] args) {
// start reporters
ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter("extent.html");
htmlReporter.config().setEncoding("GB2312");
htmlReporter.config().setDocumentTitle("我的测试报告");
htmlReporter.config().setReportName("测试报告标题");
// create ExtentReports and attach reporter(s)
ExtentReports extent = new ExtentReports();
extent.attachReporter(htmlReporter);
// creates a toggle for the given test, adds all log events under it
ExtentTest test = extent.createTest("MyFirstTest", "Sample description");
// info(details)
test.info("This step shows usage of info(details)");
// test with snapshot
try {
test.addScreenCaptureFromPath("C:\\Users\\gzy\\workspace\\BasicFrameWork\\123.png");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// calling flush writes everything to the log file
extent.flush();
}
}
| 1,689 | 0.655689 | 0.642515 | 51 | 30.745098 | 25.677366 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.176471 | false | false |
5
|
8409d4a2e5a84884d911a637fe18df4e8410291d
| 24,756,191,538,409 |
b439610df43c9e0649af7c3a90782a088038fd38
|
/Semester_3/Advanced_Methods_Programming/Toy_Langauge_InterpretorFx/src/Model/Stament/CondAsg.java
|
22b7697b058d0b4dc84fb959b0a7db772832b574
|
[] |
no_license
|
tcoca27/UBB
|
https://github.com/tcoca27/UBB
|
b01be23005e918e6887dc854600262c08c24393f
|
1821a2c2a0443bb1f1327b9d2f6acb72408352b4
|
refs/heads/master
| 2022-01-17T01:44:33.344000 | 2022-01-06T10:35:50 | 2022-01-06T10:35:50 | 245,382,814 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Model.Stament;
import Collection.Dictionary.MyIDictionary;
import Exceptions.MyException;
import Model.Expressions.Exp;
import Model.PrgState;
import Model.Types.BoolType;
import Model.Types.Type;
import Model.Values.Value;
public class CondAsg implements IStmt {
private Exp v,exp1,exp2,exp3;
public CondAsg(Exp v,Exp e1, Exp e2,Exp e3){
this.v=v;
exp1=e1;
exp2=e2;
exp3=e3;
}
@Override
public String toString() {
return v.toString()+"="+exp1.toString()+"?"+exp2.toString()+":"+exp3.toString();
}
@Override
public PrgState execute(PrgState state) throws MyException {
IStmt st=new IfStmt(exp1,new AssignStmt(v.toString(),exp2),new AssignStmt(v.toString(),exp3));
state.getStk().push(st);
return null;
}
@Override
public MyIDictionary<String, Type> typecheck(MyIDictionary<String, Type> typeEnv) throws MyException {
Type t1=exp1.typecheck(typeEnv);
if(t1.equals(new BoolType())){
Type t2=exp2.typecheck(typeEnv);
Type t3=exp3.typecheck(typeEnv);
Type vt=v.typecheck(typeEnv);
if(vt.equals(t3)){
if(t3.equals(t2)){
return typeEnv;
}
else throw new MyException("types don't match");
}
else throw new MyException("types don't match");
}
else throw new MyException(exp1.toString()+" not a bool type");
}
}
|
UTF-8
|
Java
| 1,501 |
java
|
CondAsg.java
|
Java
|
[] | null |
[] |
package Model.Stament;
import Collection.Dictionary.MyIDictionary;
import Exceptions.MyException;
import Model.Expressions.Exp;
import Model.PrgState;
import Model.Types.BoolType;
import Model.Types.Type;
import Model.Values.Value;
public class CondAsg implements IStmt {
private Exp v,exp1,exp2,exp3;
public CondAsg(Exp v,Exp e1, Exp e2,Exp e3){
this.v=v;
exp1=e1;
exp2=e2;
exp3=e3;
}
@Override
public String toString() {
return v.toString()+"="+exp1.toString()+"?"+exp2.toString()+":"+exp3.toString();
}
@Override
public PrgState execute(PrgState state) throws MyException {
IStmt st=new IfStmt(exp1,new AssignStmt(v.toString(),exp2),new AssignStmt(v.toString(),exp3));
state.getStk().push(st);
return null;
}
@Override
public MyIDictionary<String, Type> typecheck(MyIDictionary<String, Type> typeEnv) throws MyException {
Type t1=exp1.typecheck(typeEnv);
if(t1.equals(new BoolType())){
Type t2=exp2.typecheck(typeEnv);
Type t3=exp3.typecheck(typeEnv);
Type vt=v.typecheck(typeEnv);
if(vt.equals(t3)){
if(t3.equals(t2)){
return typeEnv;
}
else throw new MyException("types don't match");
}
else throw new MyException("types don't match");
}
else throw new MyException(exp1.toString()+" not a bool type");
}
}
| 1,501 | 0.610926 | 0.591606 | 50 | 29.02 | 25.307302 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.74 | false | false |
5
|
e65bb38b58ef1ec9e271324ca05f3ff69427f10b
| 38,216,619,001,869 |
7cd57dbfd21b2017156c34085a23a9f8a0bfc050
|
/app/src/main/java/tech/mlsn/eatgo/adapter/UsersAdapter.java
|
568f66bf7b78e897221d0607961f77ffb3824d96
|
[] |
no_license
|
Rzzkan/eatgo
|
https://github.com/Rzzkan/eatgo
|
807e80cf4aa2af2c59c93db940ebb11f8300ff7a
|
9d2d66d240d2ac2b4cf0c6307a5ccd5d804962fc
|
refs/heads/master
| 2023-08-18T00:43:51.312000 | 2021-09-14T10:46:36 | 2021-09-14T10:46:36 | 372,732,335 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package tech.mlsn.eatgo.adapter;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.mikhaellopez.circularimageview.CircularImageView;
import java.util.ArrayList;
import java.util.List;
import tech.mlsn.eatgo.R;
import tech.mlsn.eatgo.model.UserModel;
import tech.mlsn.eatgo.network.ApiClient;
import tech.mlsn.eatgo.response.user.UserDataResponse;
public class UsersAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<UserDataResponse> items;
private List<UserDataResponse> itemsFiltered;
private Context ctx;
private OnItemClickListener mOnItemClickListener;
public interface OnItemClickListener {
void onItemClick(View view, UserDataResponse obj, int position);
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mOnItemClickListener = mItemClickListener;
}
public UsersAdapter(Context context, List<UserDataResponse> items) {
this.items = items;
this.itemsFiltered = items;
ctx = context;
}
public class OriginalViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public TextView phone;
public CircularImageView ivProfile;
public View lyt_parent;
public OriginalViewHolder(View v) {
super(v);
name = v.findViewById(R.id.tvName);
phone = v.findViewById(R.id.tvPhone);
ivProfile = v.findViewById(R.id.ivPhoto);
lyt_parent = v.findViewById(R.id.lyt_parent);
}
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder vh;
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_users, parent, false);
vh = new OriginalViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof OriginalViewHolder) {
OriginalViewHolder view = (OriginalViewHolder) holder;
UserDataResponse x = itemsFiltered.get(position);
view.name.setText(x.getName());
view.phone.setText("62"+x.getPhone());
Glide.with(ctx).load(ApiClient.BASE_URL+x.getImage()).into(view.ivProfile);
view.lyt_parent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(view, itemsFiltered.get(position), position);
}
}
});
}
}
public Filter getFilter(){
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
Log.d("Filter", "performFiltering: "+charString);
if (charString.isEmpty()) {
itemsFiltered = items;
} else {
List<UserDataResponse> filteredList = new ArrayList<>();
for (UserDataResponse data : items) {
String name = data.getName().toLowerCase().trim();
if(name.contains(charString.toLowerCase().trim())){
filteredList.add(data);
}
}
itemsFiltered = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = itemsFiltered;
return filterResults;
}
@Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
itemsFiltered = (ArrayList<UserDataResponse>) filterResults.values;
notifyDataSetChanged();
}
};
}
@Override
public int getItemCount() {
return itemsFiltered.size();
}
}
|
UTF-8
|
Java
| 4,435 |
java
|
UsersAdapter.java
|
Java
|
[
{
"context": "iew;\n\nimport com.bumptech.glide.Glide;\nimport com.mikhaellopez.circularimageview.CircularImageView;\n\nimport java",
"end": 354,
"score": 0.9728800058364868,
"start": 342,
"tag": "USERNAME",
"value": "mikhaellopez"
}
] | null |
[] |
package tech.mlsn.eatgo.adapter;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.mikhaellopez.circularimageview.CircularImageView;
import java.util.ArrayList;
import java.util.List;
import tech.mlsn.eatgo.R;
import tech.mlsn.eatgo.model.UserModel;
import tech.mlsn.eatgo.network.ApiClient;
import tech.mlsn.eatgo.response.user.UserDataResponse;
public class UsersAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<UserDataResponse> items;
private List<UserDataResponse> itemsFiltered;
private Context ctx;
private OnItemClickListener mOnItemClickListener;
public interface OnItemClickListener {
void onItemClick(View view, UserDataResponse obj, int position);
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mOnItemClickListener = mItemClickListener;
}
public UsersAdapter(Context context, List<UserDataResponse> items) {
this.items = items;
this.itemsFiltered = items;
ctx = context;
}
public class OriginalViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public TextView phone;
public CircularImageView ivProfile;
public View lyt_parent;
public OriginalViewHolder(View v) {
super(v);
name = v.findViewById(R.id.tvName);
phone = v.findViewById(R.id.tvPhone);
ivProfile = v.findViewById(R.id.ivPhoto);
lyt_parent = v.findViewById(R.id.lyt_parent);
}
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder vh;
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_users, parent, false);
vh = new OriginalViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof OriginalViewHolder) {
OriginalViewHolder view = (OriginalViewHolder) holder;
UserDataResponse x = itemsFiltered.get(position);
view.name.setText(x.getName());
view.phone.setText("62"+x.getPhone());
Glide.with(ctx).load(ApiClient.BASE_URL+x.getImage()).into(view.ivProfile);
view.lyt_parent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(view, itemsFiltered.get(position), position);
}
}
});
}
}
public Filter getFilter(){
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
Log.d("Filter", "performFiltering: "+charString);
if (charString.isEmpty()) {
itemsFiltered = items;
} else {
List<UserDataResponse> filteredList = new ArrayList<>();
for (UserDataResponse data : items) {
String name = data.getName().toLowerCase().trim();
if(name.contains(charString.toLowerCase().trim())){
filteredList.add(data);
}
}
itemsFiltered = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = itemsFiltered;
return filterResults;
}
@Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
itemsFiltered = (ArrayList<UserDataResponse>) filterResults.values;
notifyDataSetChanged();
}
};
}
@Override
public int getItemCount() {
return itemsFiltered.size();
}
}
| 4,435 | 0.627508 | 0.627057 | 127 | 33.929134 | 27.206177 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.559055 | false | false |
5
|
f10bd161282dc835c594e176415fe0ae5e1603f8
| 23,691,039,655,071 |
4c8388d0715d9df34626837ee62beb6b4c6f4618
|
/java/test/PIZELE_WEB/src/indra/bbva/pizele/service/ConfBasicaMetaService.java
|
7018fa9a8a57f344f21d69d3cab615017e845567
|
[] |
no_license
|
jquedena/explora-titania
|
https://github.com/jquedena/explora-titania
|
d1d22ad9b0574ffe93fc5565767d16f8a6013196
|
df535fd759c757cfa518b7a027a062442b0dbe21
|
refs/heads/master
| 2016-09-06T10:54:46.427000 | 2014-02-28T10:16:38 | 2014-02-28T10:16:38 | 40,458,673 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package indra.bbva.pizele.service;
import indra.bbva.pizele.domain.base.ConfBasicaMeta;
import indra.bbva.pizele.persistence.ConfBasicaMetaPersistence;
import java.util.HashMap;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class ConfBasicaMetaService {
@Autowired
private ConfBasicaMetaPersistence confBasicaMetaPersistence;
@SuppressWarnings("unchecked")
public ConfBasicaMeta obtenerConfBasicaMeta(String cod_terr,String cod_ofic,Long anio, Long mes)
{
HashMap map = new HashMap();
map.put("PI_COD_TERR", cod_terr);
map.put("PI_COD_OFI", cod_ofic);
map.put("PI_ANIO", anio);
map.put("PI_MES", mes);
confBasicaMetaPersistence.obtenerConfBasicaMeta(map);
List<ConfBasicaMeta> lista = (List<ConfBasicaMeta>)map.get("CONF_BASICA_META_CUR_REF");
if(lista.size() > 0)
return lista.get(0);
else
return null;
}
@SuppressWarnings("unchecked")
public ConfBasicaMeta obtenerConfBasicaMeta_x_CAB(String cod_terr,String cod_ofic,Long anio, Long mes)
{
HashMap map = new HashMap();
map.put("PI_COD_TERR", cod_terr);
map.put("PI_COD_OFI", cod_ofic);
map.put("PI_ANIO", anio);
map.put("PI_MES", mes);
confBasicaMetaPersistence.obtenerConfBasicaMeta_x_CAB(map);
List<ConfBasicaMeta> lista = (List<ConfBasicaMeta>)map.get("CONF_BASICA_META_CUR_REF");
if(lista.size() > 0)
return lista.get(0);
else
return null;
}
@Transactional
public void insertarConfMetaBasica(ConfBasicaMeta objConfBasicaMeta)
{
confBasicaMetaPersistence.insertarConfBasicaMeta(objConfBasicaMeta);
}
@Transactional
public void actualizarConfMetaBasica(ConfBasicaMeta objConfBasicaMeta)
{
confBasicaMetaPersistence.actualizarConfBasicaMeta(objConfBasicaMeta);
}
@Transactional
public void eliminarConfMetaBasica(ConfBasicaMeta objConfBasicaMeta)
{
confBasicaMetaPersistence.eliminarConfBasicaMeta(objConfBasicaMeta);
}
}
|
UTF-8
|
Java
| 2,121 |
java
|
ConfBasicaMetaService.java
|
Java
|
[] | null |
[] |
package indra.bbva.pizele.service;
import indra.bbva.pizele.domain.base.ConfBasicaMeta;
import indra.bbva.pizele.persistence.ConfBasicaMetaPersistence;
import java.util.HashMap;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class ConfBasicaMetaService {
@Autowired
private ConfBasicaMetaPersistence confBasicaMetaPersistence;
@SuppressWarnings("unchecked")
public ConfBasicaMeta obtenerConfBasicaMeta(String cod_terr,String cod_ofic,Long anio, Long mes)
{
HashMap map = new HashMap();
map.put("PI_COD_TERR", cod_terr);
map.put("PI_COD_OFI", cod_ofic);
map.put("PI_ANIO", anio);
map.put("PI_MES", mes);
confBasicaMetaPersistence.obtenerConfBasicaMeta(map);
List<ConfBasicaMeta> lista = (List<ConfBasicaMeta>)map.get("CONF_BASICA_META_CUR_REF");
if(lista.size() > 0)
return lista.get(0);
else
return null;
}
@SuppressWarnings("unchecked")
public ConfBasicaMeta obtenerConfBasicaMeta_x_CAB(String cod_terr,String cod_ofic,Long anio, Long mes)
{
HashMap map = new HashMap();
map.put("PI_COD_TERR", cod_terr);
map.put("PI_COD_OFI", cod_ofic);
map.put("PI_ANIO", anio);
map.put("PI_MES", mes);
confBasicaMetaPersistence.obtenerConfBasicaMeta_x_CAB(map);
List<ConfBasicaMeta> lista = (List<ConfBasicaMeta>)map.get("CONF_BASICA_META_CUR_REF");
if(lista.size() > 0)
return lista.get(0);
else
return null;
}
@Transactional
public void insertarConfMetaBasica(ConfBasicaMeta objConfBasicaMeta)
{
confBasicaMetaPersistence.insertarConfBasicaMeta(objConfBasicaMeta);
}
@Transactional
public void actualizarConfMetaBasica(ConfBasicaMeta objConfBasicaMeta)
{
confBasicaMetaPersistence.actualizarConfBasicaMeta(objConfBasicaMeta);
}
@Transactional
public void eliminarConfMetaBasica(ConfBasicaMeta objConfBasicaMeta)
{
confBasicaMetaPersistence.eliminarConfBasicaMeta(objConfBasicaMeta);
}
}
| 2,121 | 0.742574 | 0.740688 | 71 | 27.87324 | 28.177471 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.859155 | false | false |
5
|
afbee38a046cd54dff9325137bfb5b2ad9320c55
| 35,433,480,219,399 |
24bbdce13d43632eb5f34cb9b5059a11ebb98349
|
/app/src/main/java/com/ngti/leandro/lol/splash/GetSpells.java
|
932bc6cbc0ef128eaa310b3b3db6a3c88791e300
|
[] |
no_license
|
lmercado/lolosito
|
https://github.com/lmercado/lolosito
|
5400c394ad3ac2d157eacf9ea11a2ac0fd0e17eb
|
8a0b31c550e40708fce1414e60598cba21beb693
|
refs/heads/master
| 2020-03-26T05:59:59.158000 | 2018-09-11T08:44:54 | 2018-09-11T08:44:54 | 144,556,152 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.ngti.leandro.lol.splash;
import android.os.AsyncTask;
import com.ngti.leandro.lol.model.RequestInterface;
import com.ngti.leandro.lol.model.ddragon.Spell;
import com.ngti.leandro.lol.model.ddragon.SpellsContainer;
import java.io.IOException;
import java.util.Map;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import timber.log.Timber;
import static com.ngti.leandro.lol.splash.GetGameVersion.DDRAGON_SUMMONER_VERSION;
public class GetSpells extends AsyncTask {
private static String BASE_URL = "http://ddragon.leagueoflegends.com";
public static Map<Integer, Spell> allSpells = null;
private SplashActivity splashActivity;
private static Retrofit retrofit;
public GetSpells(SplashActivity splashActivity) {
this.splashActivity = splashActivity;
}
@Override
protected Object doInBackground(Object[] objects) {
if (retrofit == null) {
retrofit = new retrofit2.Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
RequestInterface service = retrofit.create(RequestInterface.class);
Call<SpellsContainer> getSummonerSpells = service.getSummonerSpells(DDRAGON_SUMMONER_VERSION);
try {
Response<SpellsContainer> getSummonerSpellResponse = getSummonerSpells.execute();
if (getSummonerSpellResponse.code() == 200) {
SpellsContainer spells = getSummonerSpellResponse.body();
allSpells = spells.getSpellById();
} else {
Timber.e(String.valueOf("Get summoner spells error: " + getSummonerSpellResponse.code()));
}
} catch (IOException e) {
e.printStackTrace();
}
return allSpells;
}
}
|
UTF-8
|
Java
| 1,920 |
java
|
GetSpells.java
|
Java
|
[] | null |
[] |
package com.ngti.leandro.lol.splash;
import android.os.AsyncTask;
import com.ngti.leandro.lol.model.RequestInterface;
import com.ngti.leandro.lol.model.ddragon.Spell;
import com.ngti.leandro.lol.model.ddragon.SpellsContainer;
import java.io.IOException;
import java.util.Map;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import timber.log.Timber;
import static com.ngti.leandro.lol.splash.GetGameVersion.DDRAGON_SUMMONER_VERSION;
public class GetSpells extends AsyncTask {
private static String BASE_URL = "http://ddragon.leagueoflegends.com";
public static Map<Integer, Spell> allSpells = null;
private SplashActivity splashActivity;
private static Retrofit retrofit;
public GetSpells(SplashActivity splashActivity) {
this.splashActivity = splashActivity;
}
@Override
protected Object doInBackground(Object[] objects) {
if (retrofit == null) {
retrofit = new retrofit2.Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
RequestInterface service = retrofit.create(RequestInterface.class);
Call<SpellsContainer> getSummonerSpells = service.getSummonerSpells(DDRAGON_SUMMONER_VERSION);
try {
Response<SpellsContainer> getSummonerSpellResponse = getSummonerSpells.execute();
if (getSummonerSpellResponse.code() == 200) {
SpellsContainer spells = getSummonerSpellResponse.body();
allSpells = spells.getSpellById();
} else {
Timber.e(String.valueOf("Get summoner spells error: " + getSummonerSpellResponse.code()));
}
} catch (IOException e) {
e.printStackTrace();
}
return allSpells;
}
}
| 1,920 | 0.682813 | 0.678646 | 56 | 33.285713 | 28.311857 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
5
|
98f1cdaf41349e2fc2ccb814c9b1d2b6bb7f9f98
| 15,015,205,729,520 |
c3654a8fe8a9a7802868d3178160666674e5ab2b
|
/app/src/main/java/com/dicoding/picodiploma/KamusKu/fragment/EnglishFragment.java
|
4805a7711e1f77bf387dfd46a080cf0a957b022b
|
[] |
no_license
|
fiqriakbar9/KamusKu_V1.3
|
https://github.com/fiqriakbar9/KamusKu_V1.3
|
871e98051e2439a7e3218b6817ab6ab0e39df91f
|
44d600c8b2b4ff2e6f88ca07327875aba76af15c
|
refs/heads/master
| 2023-07-10T23:28:35.399000 | 2021-08-02T04:37:06 | 2021-08-02T04:37:06 | 396,178,259 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.dicoding.picodiploma.KamusKu.fragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import com.dicoding.picodiploma.KamusKu.R;
import com.dicoding.picodiploma.KamusKu.adapter.WordAdapter;
import com.dicoding.picodiploma.KamusKu.database.WordHelper;
import com.dicoding.picodiploma.KamusKu.model.WordModel;
import java.util.ArrayList;
/**
* A simple {@link Fragment} subclass.
*/
public class EnglishFragment extends Fragment {
public EnglishFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_english, container, false);
RecyclerView rvEnglish = view.findViewById(R.id.rv_english);
EditText etEnglish = view.findViewById(R.id.edt_english);
final WordHelper wordHelper = new WordHelper(getActivity());
final WordAdapter wordAdapter = new WordAdapter(getActivity());
etEnglish.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
wordAdapter.filter(charSequence.toString());
}
@Override
public void afterTextChanged(Editable editable) {
}
});
rvEnglish.setLayoutManager(new LinearLayoutManager(getActivity()));
rvEnglish.setAdapter(wordAdapter);
wordHelper.open();
// Ambil semua data Kamus English di database
ArrayList<WordModel> wordModels = wordHelper.getAllDataEng();
wordHelper.close();
wordAdapter.setData(wordModels);
return view;
}
}
|
UTF-8
|
Java
| 2,317 |
java
|
EnglishFragment.java
|
Java
|
[] | null |
[] |
package com.dicoding.picodiploma.KamusKu.fragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import com.dicoding.picodiploma.KamusKu.R;
import com.dicoding.picodiploma.KamusKu.adapter.WordAdapter;
import com.dicoding.picodiploma.KamusKu.database.WordHelper;
import com.dicoding.picodiploma.KamusKu.model.WordModel;
import java.util.ArrayList;
/**
* A simple {@link Fragment} subclass.
*/
public class EnglishFragment extends Fragment {
public EnglishFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_english, container, false);
RecyclerView rvEnglish = view.findViewById(R.id.rv_english);
EditText etEnglish = view.findViewById(R.id.edt_english);
final WordHelper wordHelper = new WordHelper(getActivity());
final WordAdapter wordAdapter = new WordAdapter(getActivity());
etEnglish.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
wordAdapter.filter(charSequence.toString());
}
@Override
public void afterTextChanged(Editable editable) {
}
});
rvEnglish.setLayoutManager(new LinearLayoutManager(getActivity()));
rvEnglish.setAdapter(wordAdapter);
wordHelper.open();
// Ambil semua data Kamus English di database
ArrayList<WordModel> wordModels = wordHelper.getAllDataEng();
wordHelper.close();
wordAdapter.setData(wordModels);
return view;
}
}
| 2,317 | 0.697454 | 0.694432 | 77 | 29.09091 | 27.134672 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.532468 | false | false |
5
|
b58e2c3652c159116b056dde80d9f69b7eeb67c3
| 15,015,205,730,072 |
16a74b826bb717c1d882252fefa5acc16a4031ea
|
/print-api/src/main/java/com/store59/printapi/model/result/order/OrderCenterDTO.java
|
85f5db8ba4cfd7fbe888cabab3adaaf28eacd6e9
|
[] |
no_license
|
a91sheep/chaos
|
https://github.com/a91sheep/chaos
|
f01887439a591f439d0c684bfeda15f8df154822
|
a8a74b804695234c55d6eacbf76860a00d3d8c1a
|
refs/heads/master
| 2021-01-12T03:51:39.680000 | 2017-01-07T11:27:54 | 2017-01-07T11:27:54 | 77,674,557 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.store59.printapi.model.result.order;
import com.store59.print.common.model.PrintOrder;
import java.util.Map;
/**
* @author <a href="mailto:linxh@59store.com">linxiaohui</a>
* @version 1.0 16/7/12
* @since 1.0
*/
public class OrderCenterDTO {
private PrintOrder printOrder;
private String sellerId; //卖家id
private String sellerName; //卖家名字
private String sellerPhone; //卖家手机
private String sellerAddress; //卖家地址
private Integer sellerSiteId; //卖家校区id
private Integer sellerDormentryId; //卖家楼栋id
private String sellerShopId; //卖家店铺id
private Map<String, String> extension;
public String getSellerId() {
return sellerId;
}
public void setSellerId(String sellerId) {
this.sellerId = sellerId;
}
public String getSellerName() {
return sellerName;
}
public void setSellerName(String sellerName) {
this.sellerName = sellerName;
}
public String getSellerPhone() {
return sellerPhone;
}
public void setSellerPhone(String sellerPhone) {
this.sellerPhone = sellerPhone;
}
public String getSellerAddress() {
return sellerAddress;
}
public void setSellerAddress(String sellerAddress) {
this.sellerAddress = sellerAddress;
}
public Integer getSellerSiteId() {
return sellerSiteId;
}
public void setSellerSiteId(Integer sellerSiteId) {
this.sellerSiteId = sellerSiteId;
}
public Integer getSellerDormentryId() {
return sellerDormentryId;
}
public void setSellerDormentryId(Integer sellerDormentryId) {
this.sellerDormentryId = sellerDormentryId;
}
public String getSellerShopId() {
return sellerShopId;
}
public void setSellerShopId(String sellerShopId) {
this.sellerShopId = sellerShopId;
}
public PrintOrder getPrintOrder() {
return printOrder;
}
public void setPrintOrder(PrintOrder printOrder) {
this.printOrder = printOrder;
}
public Map<String, String> getExtension() {
return extension;
}
public void setExtension(Map<String, String> extension) {
this.extension = extension;
}
}
|
UTF-8
|
Java
| 2,391 |
java
|
OrderCenterDTO.java
|
Java
|
[
{
"context": "rt java.util.Map;\n\n/**\n * @author <a href=\"mailto:linxh@59store.com\">linxiaohui</a>\n * @version 1.0 16/7/12\n * @since",
"end": 172,
"score": 0.999926745891571,
"start": 155,
"tag": "EMAIL",
"value": "linxh@59store.com"
},
{
"context": "/**\n * @author <a href=\"mailto:linxh@59store.com\">linxiaohui</a>\n * @version 1.0 16/7/12\n * @since 1.0\n */\npub",
"end": 184,
"score": 0.9375089406967163,
"start": 174,
"tag": "USERNAME",
"value": "linxiaohui"
}
] | null |
[] |
package com.store59.printapi.model.result.order;
import com.store59.print.common.model.PrintOrder;
import java.util.Map;
/**
* @author <a href="mailto:<EMAIL>">linxiaohui</a>
* @version 1.0 16/7/12
* @since 1.0
*/
public class OrderCenterDTO {
private PrintOrder printOrder;
private String sellerId; //卖家id
private String sellerName; //卖家名字
private String sellerPhone; //卖家手机
private String sellerAddress; //卖家地址
private Integer sellerSiteId; //卖家校区id
private Integer sellerDormentryId; //卖家楼栋id
private String sellerShopId; //卖家店铺id
private Map<String, String> extension;
public String getSellerId() {
return sellerId;
}
public void setSellerId(String sellerId) {
this.sellerId = sellerId;
}
public String getSellerName() {
return sellerName;
}
public void setSellerName(String sellerName) {
this.sellerName = sellerName;
}
public String getSellerPhone() {
return sellerPhone;
}
public void setSellerPhone(String sellerPhone) {
this.sellerPhone = sellerPhone;
}
public String getSellerAddress() {
return sellerAddress;
}
public void setSellerAddress(String sellerAddress) {
this.sellerAddress = sellerAddress;
}
public Integer getSellerSiteId() {
return sellerSiteId;
}
public void setSellerSiteId(Integer sellerSiteId) {
this.sellerSiteId = sellerSiteId;
}
public Integer getSellerDormentryId() {
return sellerDormentryId;
}
public void setSellerDormentryId(Integer sellerDormentryId) {
this.sellerDormentryId = sellerDormentryId;
}
public String getSellerShopId() {
return sellerShopId;
}
public void setSellerShopId(String sellerShopId) {
this.sellerShopId = sellerShopId;
}
public PrintOrder getPrintOrder() {
return printOrder;
}
public void setPrintOrder(PrintOrder printOrder) {
this.printOrder = printOrder;
}
public Map<String, String> getExtension() {
return extension;
}
public void setExtension(Map<String, String> extension) {
this.extension = extension;
}
}
| 2,381 | 0.639162 | 0.632749 | 94 | 23.882978 | 21.423717 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.351064 | false | false |
5
|
e321666bb47a67e07f8471ffe772166e3b4919f0
| 34,187,939,717,971 |
2c7fdf50975bba30334f335b284365edab554127
|
/src/com/leetcode/simple/LeetCode705.java
|
48262cd0051f82e88b90687a08cd955030f2ea8d
|
[] |
no_license
|
mcwx/leetcode
|
https://github.com/mcwx/leetcode
|
6a70b5586eb2d7ceda4682ddc7ff3d448c19deff
|
37085c751388ceb2847fb66004f6d11b213e9593
|
refs/heads/master
| 2020-06-11T05:15:16.302000 | 2020-06-03T23:59:59 | 2020-06-03T23:59:59 | 193,860,091 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.leetcode.simple;
import java.util.LinkedList;
/**
* @Description:设计哈希集合 不使用任何内建的哈希表库设计一个哈希集合
* 具体地说,你的设计应该包含以下的功能
* add(value):向哈希集合中插入一个值。
* contains(value) :返回哈希集合中是否存在这个值。
* remove(value):将给定值从哈希集合中删除。如果哈希集合中没有这个值,什么也不做。
* 示例:
* MyHashSet hashSet = new MyHashSet();
* hashSet.add(1);
* hashSet.add(2);
* hashSet.contains(1); // 返回 true
* hashSet.contains(3); // 返回 false (未找到)
* hashSet.add(2);
* hashSet.contains(2); // 返回 true
* hashSet.remove(2);
* hashSet.contains(2); // 返回 false (已经被删除)
* 注意:
* 所有的值都在 [0, 1000000]的范围内。
* 操作的总数目在[1, 10000]范围内。
* 不要使用内建的哈希集合库。
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/design-hashset
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
* @Auther: houpeng
* @Date: 2020/5/23
*/
public class LeetCode705 {
class Bucket {
private LinkedList<Integer> container;
public Bucket() {
container = new LinkedList<Integer>();
}
public void insert(Integer key) {
int index = this.container.indexOf(key);
if (index == -1) {
this.container.addFirst(key);
}
}
public void delete(Integer key) {
this.container.remove(key);
}
public boolean exists(Integer key) {
int index = this.container.indexOf(key);
return (index != -1);
}
}
private Bucket[] bucketArray;
private int keyRange;
public LeetCode705() {
this.keyRange = 769;
this.bucketArray = new Bucket[this.keyRange];
for (int i = 0; i < this.keyRange; ++i)
this.bucketArray[i] = new Bucket();
}
protected int _hash(int key) {
return (key % this.keyRange);
}
public void add(int key) {
int bucketIndex = this._hash(key);
this.bucketArray[bucketIndex].insert(key);
}
public void remove(int key) {
int bucketIndex = this._hash(key);
this.bucketArray[bucketIndex].delete(key);
}
/**
* Returns true if this set contains the specified element
*/
public boolean contains(int key) {
int bucketIndex = this._hash(key);
return this.bucketArray[bucketIndex].exists(key);
}
}
|
UTF-8
|
Java
| 2,720 |
java
|
LeetCode705.java
|
Java
|
[
{
"context": "\n * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\n * @Auther: houpeng\n * @Date: 2020/5/23\n */\npublic class LeetCode705 ",
"end": 781,
"score": 0.9993827939033508,
"start": 774,
"tag": "USERNAME",
"value": "houpeng"
},
{
"context": " public LeetCode705() {\n this.keyRange = 769;\n this.bucketArray = new Bucket[this.keyRa",
"end": 1543,
"score": 0.8098739385604858,
"start": 1541,
"tag": "KEY",
"value": "69"
}
] | null |
[] |
package com.leetcode.simple;
import java.util.LinkedList;
/**
* @Description:设计哈希集合 不使用任何内建的哈希表库设计一个哈希集合
* 具体地说,你的设计应该包含以下的功能
* add(value):向哈希集合中插入一个值。
* contains(value) :返回哈希集合中是否存在这个值。
* remove(value):将给定值从哈希集合中删除。如果哈希集合中没有这个值,什么也不做。
* 示例:
* MyHashSet hashSet = new MyHashSet();
* hashSet.add(1);
* hashSet.add(2);
* hashSet.contains(1); // 返回 true
* hashSet.contains(3); // 返回 false (未找到)
* hashSet.add(2);
* hashSet.contains(2); // 返回 true
* hashSet.remove(2);
* hashSet.contains(2); // 返回 false (已经被删除)
* 注意:
* 所有的值都在 [0, 1000000]的范围内。
* 操作的总数目在[1, 10000]范围内。
* 不要使用内建的哈希集合库。
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/design-hashset
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
* @Auther: houpeng
* @Date: 2020/5/23
*/
public class LeetCode705 {
class Bucket {
private LinkedList<Integer> container;
public Bucket() {
container = new LinkedList<Integer>();
}
public void insert(Integer key) {
int index = this.container.indexOf(key);
if (index == -1) {
this.container.addFirst(key);
}
}
public void delete(Integer key) {
this.container.remove(key);
}
public boolean exists(Integer key) {
int index = this.container.indexOf(key);
return (index != -1);
}
}
private Bucket[] bucketArray;
private int keyRange;
public LeetCode705() {
this.keyRange = 769;
this.bucketArray = new Bucket[this.keyRange];
for (int i = 0; i < this.keyRange; ++i)
this.bucketArray[i] = new Bucket();
}
protected int _hash(int key) {
return (key % this.keyRange);
}
public void add(int key) {
int bucketIndex = this._hash(key);
this.bucketArray[bucketIndex].insert(key);
}
public void remove(int key) {
int bucketIndex = this._hash(key);
this.bucketArray[bucketIndex].delete(key);
}
/**
* Returns true if this set contains the specified element
*/
public boolean contains(int key) {
int bucketIndex = this._hash(key);
return this.bucketArray[bucketIndex].exists(key);
}
}
| 2,720 | 0.586737 | 0.568731 | 88 | 24.863636 | 18.185398 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.386364 | false | false |
5
|
6d3649abe2d36ec29f284ba7245daaefc095dffb
| 34,187,939,715,769 |
493ff82c0d87bed762d57a8cfc7c69bb02b0d6f5
|
/javaOOP/ObjectMaster/HumanTest.java
|
500a4933ebf00ac5b83c5e31a42e1978cca9ffe8
|
[] |
no_license
|
mazurbeam/java-assignments
|
https://github.com/mazurbeam/java-assignments
|
ef2ebd472c464b84b2e08bb5729d1587ddd524a2
|
b5dd3efea3fa5aa120d4bf84b3e2bc9f51c17c16
|
refs/heads/master
| 2021-01-23T12:53:30.984000 | 2017-09-21T22:11:19 | 2017-09-21T22:11:19 | 102,655,763 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ObjectMaster;
public class HumanTest {
public static void main(String[] args) {
Human testHuman1 = new Human("human1");
Human testHuman2 = new Human("human2");
System.out.println("testHuman1 attacks testHuman2");
testHuman1.attack(testHuman2);
System.out.println("testHuman2's health "+testHuman2.getHealth());
Wizard wizardMerlin = new Wizard("Merlin");
System.out.println(wizardMerlin.getName());
System.out.println(wizardMerlin.getName()+"'s stealth " +wizardMerlin.getStealth());
System.out.println("Wizards health " +wizardMerlin.getHealth());
Samurai samuraiJack = new Samurai("Jack");
System.out.println("Number of samurai: "+Samurai.getNumberOfSamurai());
}
}
|
UTF-8
|
Java
| 719 |
java
|
HumanTest.java
|
Java
|
[
{
"context": "Health());\n\t\t\n\t\tWizard wizardMerlin = new Wizard(\"Merlin\");\n\t\tSystem.out.println(wizardMerlin.getName());\n",
"end": 382,
"score": 0.9992207288742065,
"start": 376,
"tag": "NAME",
"value": "Merlin"
},
{
"context": "ealth());\n\t\t\n\t\tSamurai samuraiJack = new Samurai(\"Jack\");\n\t\t\n\t\tSystem.out.println(\"Number of samurai: \"+",
"end": 633,
"score": 0.9993640780448914,
"start": 629,
"tag": "NAME",
"value": "Jack"
}
] | null |
[] |
package ObjectMaster;
public class HumanTest {
public static void main(String[] args) {
Human testHuman1 = new Human("human1");
Human testHuman2 = new Human("human2");
System.out.println("testHuman1 attacks testHuman2");
testHuman1.attack(testHuman2);
System.out.println("testHuman2's health "+testHuman2.getHealth());
Wizard wizardMerlin = new Wizard("Merlin");
System.out.println(wizardMerlin.getName());
System.out.println(wizardMerlin.getName()+"'s stealth " +wizardMerlin.getStealth());
System.out.println("Wizards health " +wizardMerlin.getHealth());
Samurai samuraiJack = new Samurai("Jack");
System.out.println("Number of samurai: "+Samurai.getNumberOfSamurai());
}
}
| 719 | 0.721836 | 0.707928 | 23 | 30.26087 | 26.912447 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.086957 | false | false |
5
|
0962b33d07f12f1f0edc2f1c4cb3b42e51c3279e
| 32,598,801,836,070 |
a098faaa235f4820b9c50cadb26f963c4ce602d1
|
/src/main/java/xyh/crm/service/UserService.java
|
877e63d4b1f3424863d9744317f3e979206042de
|
[] |
no_license
|
xiangyida/attendanceSystem
|
https://github.com/xiangyida/attendanceSystem
|
53655b0c714699d61ea01e0b87ab6ab64ae833b5
|
7b288ee438d9295579634b4b38601ff44f485794
|
refs/heads/master
| 2020-04-13T15:58:24.358000 | 2019-05-16T02:16:45 | 2019-05-16T02:16:45 | 163,308,345 | 7 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package xyh.crm.service;
import xyh.crm.dto.GroupAndLastDate;
import xyh.crm.dto.UserRecords;
import xyh.crm.entity.Group;
import xyh.crm.entity.User;
import java.io.IOException;
import java.util.List;
/**
* @author XiangYida
* @version 2018/10/18 0:23
* 普通用户的相关服务
*/
public interface UserService {
/**
* 用户登录,传用户的openid
* @param userId
* @return
* 若存在用户,返回User
* 不存在用户,返回空对象
*/
public User userLogin(String userId);
/**
* 注册
* @param user
* @return
* 填写详细信息
* 注册成功,返回1
*/
public int userRegister(User user);
/**
* 搜索
* @param groupId
* @return
* 若存在群组则返回群组
* 若不存在群组则返回空对象
*/
public Group queryGroup(String groupId);
/**
* 用户加入群组
* 需要邀请码
* @param groupId
* @param userId
* @param password
* 添加成功返回1
* 用户已经在群组中返回0
* 密码错误返回-1
*/
public int joinGroup(String userId, String groupId, String password);
/**
* 根据userId返回考勤记录,以及未出勤的记录
* @param userId
* @return
*/
public UserRecords getAttendanceRecords(String userId, String groupId);
/**
* 根据userId返回对应的小组信息
* @param userId
* @return
*/
public List<GroupAndLastDate>getGroups(String userId);
/**
* user获取出勤率
* @param userId
* @return
*/
public double getAttendanceRate(String userId);
/**
* 向另一个服务端发请求上传图片,成功返回true,失败返回false
* @param url
* @param openid
* @param fileName
*/
public boolean sendPhotoRequest(String url, String openid, String fileName) throws IOException;
}
|
UTF-8
|
Java
| 1,947 |
java
|
UserService.java
|
Java
|
[
{
"context": "OException;\nimport java.util.List;\n\n/**\n * @author XiangYida\n * @version 2018/10/18 0:23\n * 普通用户的相关服务\n */\npubl",
"end": 229,
"score": 0.99690842628479,
"start": 220,
"tag": "NAME",
"value": "XiangYida"
}
] | null |
[] |
package xyh.crm.service;
import xyh.crm.dto.GroupAndLastDate;
import xyh.crm.dto.UserRecords;
import xyh.crm.entity.Group;
import xyh.crm.entity.User;
import java.io.IOException;
import java.util.List;
/**
* @author XiangYida
* @version 2018/10/18 0:23
* 普通用户的相关服务
*/
public interface UserService {
/**
* 用户登录,传用户的openid
* @param userId
* @return
* 若存在用户,返回User
* 不存在用户,返回空对象
*/
public User userLogin(String userId);
/**
* 注册
* @param user
* @return
* 填写详细信息
* 注册成功,返回1
*/
public int userRegister(User user);
/**
* 搜索
* @param groupId
* @return
* 若存在群组则返回群组
* 若不存在群组则返回空对象
*/
public Group queryGroup(String groupId);
/**
* 用户加入群组
* 需要邀请码
* @param groupId
* @param userId
* @param password
* 添加成功返回1
* 用户已经在群组中返回0
* 密码错误返回-1
*/
public int joinGroup(String userId, String groupId, String password);
/**
* 根据userId返回考勤记录,以及未出勤的记录
* @param userId
* @return
*/
public UserRecords getAttendanceRecords(String userId, String groupId);
/**
* 根据userId返回对应的小组信息
* @param userId
* @return
*/
public List<GroupAndLastDate>getGroups(String userId);
/**
* user获取出勤率
* @param userId
* @return
*/
public double getAttendanceRate(String userId);
/**
* 向另一个服务端发请求上传图片,成功返回true,失败返回false
* @param url
* @param openid
* @param fileName
*/
public boolean sendPhotoRequest(String url, String openid, String fileName) throws IOException;
}
| 1,947 | 0.599753 | 0.590488 | 88 | 17.397728 | 17.373268 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false |
5
|
ef4b5eb6cc5c5c720ba354b397a67a6a4ac5ccaf
| 35,150,012,389,932 |
3ac08f55efef77a3b6fb8df086793462bc03cb56
|
/src/api/java/org/openkinect/freenect2/Device.java
|
f0e0b067df62ec9fd67a5666952c4adfd63daef9
|
[
"Apache-2.0"
] |
permissive
|
OpenISS/OpenISS
|
https://github.com/OpenISS/OpenISS
|
85ad89c93199e41b51752cb2b469199622f843e4
|
3bb6e4507f3876cf0b5587be4099fa92f4e19102
|
refs/heads/master
| 2023-07-23T08:16:04.312000 | 2023-07-19T02:42:12 | 2023-07-19T02:42:12 | 71,680,484 | 20 | 20 |
Apache-2.0
| false | 2023-07-19T02:42:35 | 2016-10-23T03:54:58 | 2022-10-12T18:53:18 | 2023-07-19T02:42:20 | 85,570 | 22 | 21 | 25 |
C
| false | false |
package org.openkinect.freenect2;
import java.awt.image.BufferedImage;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
/*
openKinect2 library for Processing
Copyright (c) 2014 Thomas Sanchez Lengeling
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
openKinect2 library for Processing is free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
openKinect2 for Processing 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with openKinect2 for Processing. If not, see
<http://www.gnu.org/licenses/>.
*/
import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;
public class Device {
static String PROJECT_HOME = System.getProperty("user.dir");
static {
//load OS an arch difference
int arch = Integer.parseInt(System.getProperty("sun.arch.data.model"));
String osName = System.getProperty("os.name").toLowerCase();
if (osName.contains("win")) {
// System.out.println(arch + " windows");
// System.loadLibrary("v2/msvc/turbojpeg");
// System.loadLibrary("v2/msvc/libusb-1.0");
// System.loadLibrary("v2/msvc/libJNILibfreenect2");
} else if (osName.contains("mac")) {
System.out.println(arch + " mac");
// LibraryPath libPath = new LibraryPath();
// String path = libPath.getDir() + "/v2/mac/";
// System.out.println(System.getProperty("java.library.path"));
String path = PROJECT_HOME + "/lib/v2/mac/";
System.out.println("Found path v2: " + path);
System.load(path + "libturbojpeg.dylib");
System.load(path + "libJNILibfreenect2.dylib");
} else if (osName.contains("linux")) {
System.out.println(arch + " linux");
// LibraryPath libPath = new LibraryPath();
// String path = libPath.getDir() + "/v2/linux/";
// System.out.println(System.getProperty("java.library.path"));
String path = PROJECT_HOME + "/lib/v2/linux/";
System.out.println("Found path v2: " + path);
System.load(path + "libfreenect2.so");
System.load(path + "libturbojpeg.so.0");
} else {
System.err.println("not compatible with the current OS or is a 32 bit system");
}
}
public int depthWidth = 512;
public int depthHeight = 424;
public int colorWidth = 1920;
public int colorHeight = 1080;
// private PApplet parent;
private long ptr;
//version control for openKinect2
private String version = "";
PImage depthImg;
PImage irImg;
PImage colorImg;
PImage undistortedImg;
PImage registeredImg;
// BufferedImage depthImg;
// BufferedImage irImg;
// BufferedImage colorImg;
// BufferedImage undistortedImg;
// BufferedImage registeredImg;
FloatBuffer depthPositions;
IntBuffer depthColorBuffer;
IntBuffer irColorBuffer;
IntBuffer registeredColorBuffer;
/**
* Constructor for openKinect 2
*
* // @param _p parent
*/
// public Device(PApplet _p) {
// parent = _p;
public Device() {
ptr = jniInit();
depthImg = new PImage(depthWidth, depthHeight, PImage.ALPHA);
irImg = new PImage(depthWidth, depthHeight, PImage.ALPHA);
colorImg = new PImage(colorWidth, colorHeight, PImage.ARGB);
undistortedImg = new PImage(depthWidth, depthHeight, PImage.ALPHA);
registeredImg = new PImage(depthWidth, depthHeight, PImage.ARGB);
// depthImg = new BufferedImage(depthWidth, depthHeight, BufferedImage.TYPE_3BYTE_BGR);
// irImg = new BufferedImage(depthWidth, depthHeight, BufferedImage.TYPE_3BYTE_BGR);
// colorImg = new BufferedImage(colorWidth, colorHeight, BufferedImage.TYPE_3BYTE_BGR);
// undistortedImg = new BufferedImage(depthWidth, depthHeight, BufferedImage.TYPE_3BYTE_BGR);
// registeredImg = new BufferedImage(depthWidth, depthHeight, BufferedImage.TYPE_3BYTE_BGR);
//Buffers for openGL calls
depthPositions = FloatBuffer.allocate(depthWidth * depthHeight * 3);
//colors
depthColorBuffer = IntBuffer.allocate(depthWidth * depthHeight);
irColorBuffer = IntBuffer.allocate(depthWidth * depthHeight);
registeredColorBuffer = IntBuffer.allocate(depthWidth * depthHeight);
depthImg.loadPixels();
irImg.loadPixels();
colorImg.loadPixels();
undistortedImg.loadPixels();
registeredImg.loadPixels();
for (int i = 0; i < depthWidth; i++) {
for (int j = 0; j < depthHeight; j++) {
int pos = i + j * depthWidth;
depthImg.pixels[pos] = color(0);
irImg.pixels[pos] = color(0);
undistortedImg.pixels[pos] = color(0);
registeredImg.pixels[pos] = color(0);
}
}
depthImg.updatePixels();
irImg.updatePixels();
undistortedImg.updatePixels();
registeredImg.updatePixels();
for (int i = 0; i < colorWidth; i++) {
for (int j = 0; j < colorHeight; j++) {
int pos = i + j * colorWidth;
colorImg.pixels[pos] = color(0);
}
}
colorImg.updatePixels();
//System.out.println(version());
}
// / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /
// some methods grab from:
// https://github.com/processing/processing/blob/master/core/src/processing/core/PApplet.java
public static final int color(int gray) {
if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
return 0xff000000 | (gray << 16) | (gray << 8) | gray;
}
// / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /
/**
* Open and initialize the a default Device
*/
public void initDevice() {
jniOpen();
}
/**
* Open and initialize a specific Device index [0, numDevices - 1]
*
* @param index
*/
public void initDevice(int index) {
jniOpenM(index);
}
/**
* Close Device
*/
public void stopDevice() {
jniStop();
}
/**
* Process Depth Image (512 x 424)
*
* @return PImage
*/
public BufferedImage getDepthImage() {
int[] depthRawData = jniGetDepthData();
arrayCopy(depthRawData, 0, depthImg.pixels, 0, depthImg.width * depthImg.height);
depthColorBuffer.put(depthRawData, 0, depthWidth * depthHeight);
depthColorBuffer.rewind();
depthImg.updatePixels();
return (BufferedImage) depthImg.getNative();
}
/**
* Process Infrared Image (512 x 424)
*
* @return PImage
*/
public BufferedImage getIrImage() {
int[] irRawData = jniGetIrData();
arrayCopy(irRawData, 0, irImg.pixels, 0, irImg.width * irImg.height);
irColorBuffer.put(irRawData, 0, depthWidth * depthHeight);
irColorBuffer.rewind();
irImg.updatePixels();
return (BufferedImage) irImg.getNative();
}
/**
* Process Color Image (1920 x 1080)
*
* @return PImage
*/
public BufferedImage getVideoImage() {
int[] colorRawData = jniGetColorData();
arrayCopy(colorRawData, 0, colorImg.pixels, 0, colorImg.width * colorImg.height);
colorImg.updatePixels();
return (BufferedImage) colorImg.getNative();
}
/**
* Process the undistored Image (512 x 442) Image output
*
* @return PImage
*/
public PImage getUndistoredImage() {
int[] undistoredData = jniGetUndistorted();
arrayCopy(undistoredData,
0, undistortedImg.pixels,
0, undistortedImg.width * undistortedImg.height);
undistortedImg.updatePixels();
return undistortedImg;
}
/**
* Process the registered Image RGB and Depth mapping (512 x 442) Image output
*
* @return PImage
*/
public PImage getRegisteredImage() {
int[] registeredData = jniGetRegistered();
arrayCopy(registeredData,
0, registeredImg.pixels,
0, registeredImg.width * registeredImg.height);
registeredColorBuffer.put(registeredImg.pixels, 0, depthWidth * depthHeight);
registeredColorBuffer.rewind();
registeredImg.updatePixels();
return registeredImg;
}
static public void arrayCopy(Object src, int srcPosition,
Object dst, int dstPosition,
int length) {
System.arraycopy(src, srcPosition, dst, dstPosition, length);
}
/**
* Get depth camera positions based on the Kinect v2 hardware
*
* @return float array of 512 x 424 x 3 elements
*/
public float[] getDepthToCameraPositions() {
return jniGetDepthCameraPositions();
}
/**
* Get depth camera positions as a float buffer data structure
*
* @return FloatBuffer 512 x 424 x 3 floats
*/
public FloatBuffer getDepthBufferPositions() {
float[] pcRawData = jniGetDepthCameraPositions();
depthPositions.put(pcRawData, 0, depthWidth * depthHeight * 3);
depthPositions.rewind();
return depthPositions;
}
/**
* get the IR color data as an Int Buffer data structure
*
* @return IntBuffer Ir color Data
*/
public IntBuffer getIrColorBuffer() {
return irColorBuffer;
}
/**
* get the color map to depth data as an Int Buffer data structure
*
* @return IntBuffer registered color data
*/
public IntBuffer getRegisteredColorBuffer() {
return registeredColorBuffer;
}
/**
* get the depth color data as an Int Buffer data structure
*
* @return IntBuffer depth color data
*/
public IntBuffer getDepthColorBuffer() {
return depthColorBuffer;
}
/**
* get the raw depth data 512 x 424
*
* @return array of ints from 0 - 4500
*/
public int[] getRawDepth() {
return jniGetRawDepthData();
}
/**
* Get the number of Devices connected to the computer
*
* @return int
*/
public int getNumKinects() {
return jniGetNumDevices();
}
/**
* Get the Serial Number
*
* @return
*/
public String getDefaulSerialNum() {
if (jniGetNumDevices() > 0)
return jniGetSerialDevice(0);
return "123456789";
}
/**
* Get the Serial Number
*
* @return
*/
public String getSerialNum(int index) {
if (jniGetNumDevices() > 0 && jniGetNumDevices() < index)
return jniGetSerialDevice(index);
return "123456789";
}
/**
* Print Number of Kinect v2 connected and Information about the Devices
*/
public void printDevices() {
jniEumerateDevices();
}
/**
* Enable the depth capture of the Kinect 2
*/
public void initDepth() {
jniEnableDepth(true);
}
/**
* Enable the Video capture of the Kinect 2
*/
public void initVideo() {
jniEnableVideo(true);
}
/**
* Enable the IR capture of the Kinect 2
*/
public void initIR() {
jniEnableIR(true);
}
/**
* Enable the Video + Depth mapping of the Kinect 2
*/
public void initRegistered() {
jniEnableRegistered(true);
}
/**
* Enable all the capture frames of the kinect 2
*/
public void init() {
initDepth();
initVideo();
initIR();
initRegistered();
}
//JNI Functions
private native long jniInit();
private native void jniOpen();
private native void jniOpenM(int index);
private native void jniStop();
private native void jniEumerateDevices();
//Multiple Kinect Funtions
private native void jniOpenSerial(String serialNumber);
private native int jniGetNumDevices();
private native String jniGetSerialDevice(int index);
//Get data functions
private native int[] jniGetDepthData();
private native int[] jniGetRawDepthData();
private native int[] jniGetIrData();
private native int[] jniGetColorData();
private native int[] jniGetUndistorted();
private native int[] jniGetRegistered();
private native float[] jniGetDepthCameraPositions();
//Enables functions
private native void jniEnableVideo(boolean enable);
private native void jniEnableDepth(boolean enable);
private native void jniEnableIR(boolean enable);
private native void jniEnableRegistered(boolean enable);
}
|
UTF-8
|
Java
| 13,571 |
java
|
Device.java
|
Java
|
[
{
"context": "nKinect2 library for Processing\nCopyright (c) 2014 Thomas Sanchez Lengeling\n\n* Redistribution and use in source and binary fo",
"end": 210,
"score": 0.9998836517333984,
"start": 186,
"tag": "NAME",
"value": "Thomas Sanchez Lengeling"
},
{
"context": "some methods grab from:\n // https://github.com/processing/processing/blob/master/core/src/processing/core/P",
"end": 6322,
"score": 0.9825108647346497,
"start": 6312,
"tag": "USERNAME",
"value": "processing"
}
] | null |
[] |
package org.openkinect.freenect2;
import java.awt.image.BufferedImage;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
/*
openKinect2 library for Processing
Copyright (c) 2014 <NAME>
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
openKinect2 library for Processing is free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
openKinect2 for Processing 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with openKinect2 for Processing. If not, see
<http://www.gnu.org/licenses/>.
*/
import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;
public class Device {
static String PROJECT_HOME = System.getProperty("user.dir");
static {
//load OS an arch difference
int arch = Integer.parseInt(System.getProperty("sun.arch.data.model"));
String osName = System.getProperty("os.name").toLowerCase();
if (osName.contains("win")) {
// System.out.println(arch + " windows");
// System.loadLibrary("v2/msvc/turbojpeg");
// System.loadLibrary("v2/msvc/libusb-1.0");
// System.loadLibrary("v2/msvc/libJNILibfreenect2");
} else if (osName.contains("mac")) {
System.out.println(arch + " mac");
// LibraryPath libPath = new LibraryPath();
// String path = libPath.getDir() + "/v2/mac/";
// System.out.println(System.getProperty("java.library.path"));
String path = PROJECT_HOME + "/lib/v2/mac/";
System.out.println("Found path v2: " + path);
System.load(path + "libturbojpeg.dylib");
System.load(path + "libJNILibfreenect2.dylib");
} else if (osName.contains("linux")) {
System.out.println(arch + " linux");
// LibraryPath libPath = new LibraryPath();
// String path = libPath.getDir() + "/v2/linux/";
// System.out.println(System.getProperty("java.library.path"));
String path = PROJECT_HOME + "/lib/v2/linux/";
System.out.println("Found path v2: " + path);
System.load(path + "libfreenect2.so");
System.load(path + "libturbojpeg.so.0");
} else {
System.err.println("not compatible with the current OS or is a 32 bit system");
}
}
public int depthWidth = 512;
public int depthHeight = 424;
public int colorWidth = 1920;
public int colorHeight = 1080;
// private PApplet parent;
private long ptr;
//version control for openKinect2
private String version = "";
PImage depthImg;
PImage irImg;
PImage colorImg;
PImage undistortedImg;
PImage registeredImg;
// BufferedImage depthImg;
// BufferedImage irImg;
// BufferedImage colorImg;
// BufferedImage undistortedImg;
// BufferedImage registeredImg;
FloatBuffer depthPositions;
IntBuffer depthColorBuffer;
IntBuffer irColorBuffer;
IntBuffer registeredColorBuffer;
/**
* Constructor for openKinect 2
*
* // @param _p parent
*/
// public Device(PApplet _p) {
// parent = _p;
public Device() {
ptr = jniInit();
depthImg = new PImage(depthWidth, depthHeight, PImage.ALPHA);
irImg = new PImage(depthWidth, depthHeight, PImage.ALPHA);
colorImg = new PImage(colorWidth, colorHeight, PImage.ARGB);
undistortedImg = new PImage(depthWidth, depthHeight, PImage.ALPHA);
registeredImg = new PImage(depthWidth, depthHeight, PImage.ARGB);
// depthImg = new BufferedImage(depthWidth, depthHeight, BufferedImage.TYPE_3BYTE_BGR);
// irImg = new BufferedImage(depthWidth, depthHeight, BufferedImage.TYPE_3BYTE_BGR);
// colorImg = new BufferedImage(colorWidth, colorHeight, BufferedImage.TYPE_3BYTE_BGR);
// undistortedImg = new BufferedImage(depthWidth, depthHeight, BufferedImage.TYPE_3BYTE_BGR);
// registeredImg = new BufferedImage(depthWidth, depthHeight, BufferedImage.TYPE_3BYTE_BGR);
//Buffers for openGL calls
depthPositions = FloatBuffer.allocate(depthWidth * depthHeight * 3);
//colors
depthColorBuffer = IntBuffer.allocate(depthWidth * depthHeight);
irColorBuffer = IntBuffer.allocate(depthWidth * depthHeight);
registeredColorBuffer = IntBuffer.allocate(depthWidth * depthHeight);
depthImg.loadPixels();
irImg.loadPixels();
colorImg.loadPixels();
undistortedImg.loadPixels();
registeredImg.loadPixels();
for (int i = 0; i < depthWidth; i++) {
for (int j = 0; j < depthHeight; j++) {
int pos = i + j * depthWidth;
depthImg.pixels[pos] = color(0);
irImg.pixels[pos] = color(0);
undistortedImg.pixels[pos] = color(0);
registeredImg.pixels[pos] = color(0);
}
}
depthImg.updatePixels();
irImg.updatePixels();
undistortedImg.updatePixels();
registeredImg.updatePixels();
for (int i = 0; i < colorWidth; i++) {
for (int j = 0; j < colorHeight; j++) {
int pos = i + j * colorWidth;
colorImg.pixels[pos] = color(0);
}
}
colorImg.updatePixels();
//System.out.println(version());
}
// / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /
// some methods grab from:
// https://github.com/processing/processing/blob/master/core/src/processing/core/PApplet.java
public static final int color(int gray) {
if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
return 0xff000000 | (gray << 16) | (gray << 8) | gray;
}
// / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /
/**
* Open and initialize the a default Device
*/
public void initDevice() {
jniOpen();
}
/**
* Open and initialize a specific Device index [0, numDevices - 1]
*
* @param index
*/
public void initDevice(int index) {
jniOpenM(index);
}
/**
* Close Device
*/
public void stopDevice() {
jniStop();
}
/**
* Process Depth Image (512 x 424)
*
* @return PImage
*/
public BufferedImage getDepthImage() {
int[] depthRawData = jniGetDepthData();
arrayCopy(depthRawData, 0, depthImg.pixels, 0, depthImg.width * depthImg.height);
depthColorBuffer.put(depthRawData, 0, depthWidth * depthHeight);
depthColorBuffer.rewind();
depthImg.updatePixels();
return (BufferedImage) depthImg.getNative();
}
/**
* Process Infrared Image (512 x 424)
*
* @return PImage
*/
public BufferedImage getIrImage() {
int[] irRawData = jniGetIrData();
arrayCopy(irRawData, 0, irImg.pixels, 0, irImg.width * irImg.height);
irColorBuffer.put(irRawData, 0, depthWidth * depthHeight);
irColorBuffer.rewind();
irImg.updatePixels();
return (BufferedImage) irImg.getNative();
}
/**
* Process Color Image (1920 x 1080)
*
* @return PImage
*/
public BufferedImage getVideoImage() {
int[] colorRawData = jniGetColorData();
arrayCopy(colorRawData, 0, colorImg.pixels, 0, colorImg.width * colorImg.height);
colorImg.updatePixels();
return (BufferedImage) colorImg.getNative();
}
/**
* Process the undistored Image (512 x 442) Image output
*
* @return PImage
*/
public PImage getUndistoredImage() {
int[] undistoredData = jniGetUndistorted();
arrayCopy(undistoredData,
0, undistortedImg.pixels,
0, undistortedImg.width * undistortedImg.height);
undistortedImg.updatePixels();
return undistortedImg;
}
/**
* Process the registered Image RGB and Depth mapping (512 x 442) Image output
*
* @return PImage
*/
public PImage getRegisteredImage() {
int[] registeredData = jniGetRegistered();
arrayCopy(registeredData,
0, registeredImg.pixels,
0, registeredImg.width * registeredImg.height);
registeredColorBuffer.put(registeredImg.pixels, 0, depthWidth * depthHeight);
registeredColorBuffer.rewind();
registeredImg.updatePixels();
return registeredImg;
}
static public void arrayCopy(Object src, int srcPosition,
Object dst, int dstPosition,
int length) {
System.arraycopy(src, srcPosition, dst, dstPosition, length);
}
/**
* Get depth camera positions based on the Kinect v2 hardware
*
* @return float array of 512 x 424 x 3 elements
*/
public float[] getDepthToCameraPositions() {
return jniGetDepthCameraPositions();
}
/**
* Get depth camera positions as a float buffer data structure
*
* @return FloatBuffer 512 x 424 x 3 floats
*/
public FloatBuffer getDepthBufferPositions() {
float[] pcRawData = jniGetDepthCameraPositions();
depthPositions.put(pcRawData, 0, depthWidth * depthHeight * 3);
depthPositions.rewind();
return depthPositions;
}
/**
* get the IR color data as an Int Buffer data structure
*
* @return IntBuffer Ir color Data
*/
public IntBuffer getIrColorBuffer() {
return irColorBuffer;
}
/**
* get the color map to depth data as an Int Buffer data structure
*
* @return IntBuffer registered color data
*/
public IntBuffer getRegisteredColorBuffer() {
return registeredColorBuffer;
}
/**
* get the depth color data as an Int Buffer data structure
*
* @return IntBuffer depth color data
*/
public IntBuffer getDepthColorBuffer() {
return depthColorBuffer;
}
/**
* get the raw depth data 512 x 424
*
* @return array of ints from 0 - 4500
*/
public int[] getRawDepth() {
return jniGetRawDepthData();
}
/**
* Get the number of Devices connected to the computer
*
* @return int
*/
public int getNumKinects() {
return jniGetNumDevices();
}
/**
* Get the Serial Number
*
* @return
*/
public String getDefaulSerialNum() {
if (jniGetNumDevices() > 0)
return jniGetSerialDevice(0);
return "123456789";
}
/**
* Get the Serial Number
*
* @return
*/
public String getSerialNum(int index) {
if (jniGetNumDevices() > 0 && jniGetNumDevices() < index)
return jniGetSerialDevice(index);
return "123456789";
}
/**
* Print Number of Kinect v2 connected and Information about the Devices
*/
public void printDevices() {
jniEumerateDevices();
}
/**
* Enable the depth capture of the Kinect 2
*/
public void initDepth() {
jniEnableDepth(true);
}
/**
* Enable the Video capture of the Kinect 2
*/
public void initVideo() {
jniEnableVideo(true);
}
/**
* Enable the IR capture of the Kinect 2
*/
public void initIR() {
jniEnableIR(true);
}
/**
* Enable the Video + Depth mapping of the Kinect 2
*/
public void initRegistered() {
jniEnableRegistered(true);
}
/**
* Enable all the capture frames of the kinect 2
*/
public void init() {
initDepth();
initVideo();
initIR();
initRegistered();
}
//JNI Functions
private native long jniInit();
private native void jniOpen();
private native void jniOpenM(int index);
private native void jniStop();
private native void jniEumerateDevices();
//Multiple Kinect Funtions
private native void jniOpenSerial(String serialNumber);
private native int jniGetNumDevices();
private native String jniGetSerialDevice(int index);
//Get data functions
private native int[] jniGetDepthData();
private native int[] jniGetRawDepthData();
private native int[] jniGetIrData();
private native int[] jniGetColorData();
private native int[] jniGetUndistorted();
private native int[] jniGetRegistered();
private native float[] jniGetDepthCameraPositions();
//Enables functions
private native void jniEnableVideo(boolean enable);
private native void jniEnableDepth(boolean enable);
private native void jniEnableIR(boolean enable);
private native void jniEnableRegistered(boolean enable);
}
| 13,553 | 0.615577 | 0.602461 | 470 | 27.876596 | 25.071253 | 100 | false | false | 0 | 0 | 0 | 0 | 70 | 0.005158 | 0.504255 | false | false |
5
|
7ff90fcaf8ff3d17fc82be507338e28cd4c3f81e
| 33,844,342,338,442 |
8d24d95a561183d40a2534ee4d69bfa46689fae8
|
/lss-web/src/main/java/org/lss/erp/Beans/AddInvoiceBean.java
|
78b88ddbfced122e2fefee69405385227bc98194
|
[] |
no_license
|
mansoor67890/lss
|
https://github.com/mansoor67890/lss
|
7bf0ab48f55fc81b406d1fe6d8a05d7d9ea999da
|
ec9203e8d49b6bc974fb126d3abcbc1828e5d471
|
refs/heads/master
| 2021-03-11T19:07:42.227000 | 2017-05-30T09:56:08 | 2017-05-30T09:56:08 | 89,452,971 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.lss.erp.Beans;
public class AddInvoiceBean {
private String annualFee;
private String monthlyFee;
private String examFee;
private int studentId;
public String getAnnualFee() {
return annualFee;
}
public void setAnnualFee(String annualFee) {
this.annualFee = annualFee;
}
public String getMonthlyFee() {
return monthlyFee;
}
public void setMonthlyFee(String monthlyFee) {
this.monthlyFee = monthlyFee;
}
public String getExamFee() {
return examFee;
}
public void setExamFee(String examFee) {
this.examFee = examFee;
}
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
}
|
UTF-8
|
Java
| 691 |
java
|
AddInvoiceBean.java
|
Java
|
[] | null |
[] |
package org.lss.erp.Beans;
public class AddInvoiceBean {
private String annualFee;
private String monthlyFee;
private String examFee;
private int studentId;
public String getAnnualFee() {
return annualFee;
}
public void setAnnualFee(String annualFee) {
this.annualFee = annualFee;
}
public String getMonthlyFee() {
return monthlyFee;
}
public void setMonthlyFee(String monthlyFee) {
this.monthlyFee = monthlyFee;
}
public String getExamFee() {
return examFee;
}
public void setExamFee(String examFee) {
this.examFee = examFee;
}
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
}
| 691 | 0.738061 | 0.738061 | 34 | 19.32353 | 14.686369 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.470588 | false | false |
5
|
399b5ff91f3975813b0fb4a556b7dd3a26ac3f42
| 33,844,342,337,188 |
1f43f15ab37ec742158d8ab5be3f6dbe87700d1b
|
/src/main/java/com/armelle/fitness/controller/WellnessController.java
|
8377a46150a2c807162d696a290118042be40df1
|
[] |
no_license
|
ArmelleDawson/Wellness
|
https://github.com/ArmelleDawson/Wellness
|
fb89779498148897a41be6658aebef775f668e42
|
f2251edcf4a1506e86019b875ddc3e0e6d1e4bef
|
refs/heads/master
| 2021-01-20T14:04:44.881000 | 2018-09-30T15:56:36 | 2018-09-30T15:56:36 | 90,558,215 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.armelle.fitness.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* Created by armelle on 5/14/17.
*/
@Controller
public class WellnessController {
@RequestMapping("/")
public String listWorkouts() {
return "home";
}
@RequestMapping("/workout")
@ResponseBody
public String getWorkout() {
return "Most recent workout";
}
}
|
UTF-8
|
Java
| 524 |
java
|
WellnessController.java
|
Java
|
[
{
"context": "b.bind.annotation.ResponseBody;\n\n/**\n * Created by armelle on 5/14/17.\n */\n@Controller\npublic class Wellness",
"end": 241,
"score": 0.9995641708374023,
"start": 234,
"tag": "USERNAME",
"value": "armelle"
}
] | null |
[] |
package com.armelle.fitness.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* Created by armelle on 5/14/17.
*/
@Controller
public class WellnessController {
@RequestMapping("/")
public String listWorkouts() {
return "home";
}
@RequestMapping("/workout")
@ResponseBody
public String getWorkout() {
return "Most recent workout";
}
}
| 524 | 0.71374 | 0.704198 | 23 | 21.782608 | 19.426464 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.26087 | false | false |
5
|
52d43e848a2646b80fe97f8a85bb11daf00eff3c
| 37,976,100,848,577 |
e653fef1453fa887101037cb8157c697817f71bd
|
/LayChats/app/src/main/java/com/example/ashutosh/laychats/UserDetail.java
|
d449ad94f45e8280de8eba33a5a881c8c3419c49
|
[] |
no_license
|
ashutosh1919/LayChats
|
https://github.com/ashutosh1919/LayChats
|
9e12907a78c4f8bfff387aa74d5a5e123aa56013
|
36b0f51cf99dc022fe090327f4aecf5a72882659
|
refs/heads/master
| 2021-08-31T07:38:22.226000 | 2017-12-20T16:43:07 | 2017-12-20T16:43:07 | 114,909,393 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.ashutosh.laychats;
/**
* Created by Ashutosh on 14-12-2017.
*/
public class UserDetail
{
public static String userName="";
public static String password="";
public static String chatWith="";
}
|
UTF-8
|
Java
| 229 |
java
|
UserDetail.java
|
Java
|
[
{
"context": " com.example.ashutosh.laychats;\n\n/**\n * Created by Ashutosh on 14-12-2017.\n */\n\npublic class UserDetail\n{\n ",
"end": 66,
"score": 0.7502301931381226,
"start": 58,
"tag": "USERNAME",
"value": "Ashutosh"
}
] | null |
[] |
package com.example.ashutosh.laychats;
/**
* Created by Ashutosh on 14-12-2017.
*/
public class UserDetail
{
public static String userName="";
public static String password="";
public static String chatWith="";
}
| 229 | 0.694323 | 0.659389 | 12 | 18.083334 | 17.187487 | 38 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false |
5
|
34f9d534d0cc20d0c9700d571ec64c08daef9662
| 36,318,243,489,951 |
f156332dcc33bec35d7085d844dfed31453d4833
|
/src/main/java/ToolbarMain.java
|
949e6862e1e8c6b8be8ba7f70f77c1267179bc94
|
[
"MIT"
] |
permissive
|
filipjonckers/imgui-java-sandbox
|
https://github.com/filipjonckers/imgui-java-sandbox
|
3b855fe762b876bfb5db5d7dbd46e05691a14b71
|
3d400ea6df825154bff579b903d1c8408aaddd59
|
refs/heads/main
| 2023-01-23T00:50:13.093000 | 2020-11-24T22:46:02 | 2020-11-24T22:46:02 | 312,336,931 | 0 | 1 |
MIT
| false | 2020-11-21T21:10:50 | 2020-11-12T16:42:02 | 2020-11-19T22:32:29 | 2020-11-21T21:10:49 | 213 | 0 | 1 | 0 |
C++
| false | false |
import imgui.ImColor;
import imgui.ImGuiViewport;
import imgui.flag.ImGuiCol;
import imgui.flag.ImGuiCond;
import imgui.flag.ImGuiStyleVar;
import imgui.flag.ImGuiWindowFlags;
import imgui.internal.ImGui;
import imgui.type.ImBoolean;
public class ToolbarMain {
public ToolbarMain() {
}
public void render() {
final ImGuiViewport mainViewport = ImGui.getMainViewport();
ImGui.setNextWindowPos(mainViewport.getWorkPosX(), mainViewport.getWorkPosY() + 300, ImGuiCond.Once);
ImGui.setNextWindowSize(80.0f, 0.0f, ImGuiCond.Once);
ImGui.pushStyleVar(ImGuiStyleVar.FramePadding, 5f, 5f);
ImGui.begin("##Main Toolbar", new ImBoolean(), ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.NoDecoration | ImGuiWindowFlags.NoResize);
ImGui.getStyle().setFrameRounding(2f);
ImGui.getStyle().setColor(ImGuiCol.Text, ImColor.rgbToColor(T2Colors.T2_STYLE_600));
ImGui.getStyle().setColor(ImGuiCol.Button, ImColor.rgbToColor(T2Colors.T2_STYLE_200));
ImGui.getStyle().setColor(ImGuiCol.ButtonHovered, ImColor.rgbToColor(T2Colors.T2_BLUE_200));
ImGui.button(FontMaterialDesignIcons.EXIT_TO_APP, -1, 0);
ImGui.button(FontMaterialDesignIcons.FULLSCREEN, -1, 0);
ImGui.button(FontMaterialDesignIcons.SETTINGS_APPLICATIONS, -1, 0);
ImGui.button("DEBUG", -1, 0);
ImGui.button("SRC", -1, 0);
ImGui.button("LABEL", -1, 0);
ImGui.button("MAPS", -1, 0);
ImGui.button("BRT", -1, 0);
ImGui.button("QDM", -1, 0);
ImGui.button("FIM", -1, 0);
ImGui.end();
imgui.ImGui.popStyleVar();
}
}
|
UTF-8
|
Java
| 1,640 |
java
|
ToolbarMain.java
|
Java
|
[] | null |
[] |
import imgui.ImColor;
import imgui.ImGuiViewport;
import imgui.flag.ImGuiCol;
import imgui.flag.ImGuiCond;
import imgui.flag.ImGuiStyleVar;
import imgui.flag.ImGuiWindowFlags;
import imgui.internal.ImGui;
import imgui.type.ImBoolean;
public class ToolbarMain {
public ToolbarMain() {
}
public void render() {
final ImGuiViewport mainViewport = ImGui.getMainViewport();
ImGui.setNextWindowPos(mainViewport.getWorkPosX(), mainViewport.getWorkPosY() + 300, ImGuiCond.Once);
ImGui.setNextWindowSize(80.0f, 0.0f, ImGuiCond.Once);
ImGui.pushStyleVar(ImGuiStyleVar.FramePadding, 5f, 5f);
ImGui.begin("##Main Toolbar", new ImBoolean(), ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.NoDecoration | ImGuiWindowFlags.NoResize);
ImGui.getStyle().setFrameRounding(2f);
ImGui.getStyle().setColor(ImGuiCol.Text, ImColor.rgbToColor(T2Colors.T2_STYLE_600));
ImGui.getStyle().setColor(ImGuiCol.Button, ImColor.rgbToColor(T2Colors.T2_STYLE_200));
ImGui.getStyle().setColor(ImGuiCol.ButtonHovered, ImColor.rgbToColor(T2Colors.T2_BLUE_200));
ImGui.button(FontMaterialDesignIcons.EXIT_TO_APP, -1, 0);
ImGui.button(FontMaterialDesignIcons.FULLSCREEN, -1, 0);
ImGui.button(FontMaterialDesignIcons.SETTINGS_APPLICATIONS, -1, 0);
ImGui.button("DEBUG", -1, 0);
ImGui.button("SRC", -1, 0);
ImGui.button("LABEL", -1, 0);
ImGui.button("MAPS", -1, 0);
ImGui.button("BRT", -1, 0);
ImGui.button("QDM", -1, 0);
ImGui.button("FIM", -1, 0);
ImGui.end();
imgui.ImGui.popStyleVar();
}
}
| 1,640 | 0.683537 | 0.655488 | 41 | 39 | 33.080093 | 144 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.512195 | false | false |
5
|
d30f06eef706f9e658c1547e7fd8e8fe9cbe5a36
| 36,318,243,492,931 |
242d79bd38f456bdb9d17aa1698d4c6759723923
|
/core/api/src/main/java/org/trellisldp/api/ImmutableDataService.java
|
21f11fe57e84e30de8728403acf308204196c49d
|
[
"Apache-2.0"
] |
permissive
|
ajs6f/trellis
|
https://github.com/ajs6f/trellis
|
3a2a42a0be81cf7b88afd7f273aa5c23268452ce
|
6c9c59a1229002b5a97e8ec6d117702bf765cbf6
|
refs/heads/master
| 2021-10-21T18:36:51.193000 | 2019-02-11T00:39:19 | 2019-02-11T00:39:19 | 118,954,770 | 0 | 0 |
Apache-2.0
| true | 2019-02-11T18:16:24 | 2018-01-25T18:59:31 | 2018-04-03T13:55:05 | 2019-02-11T18:16:02 | 1,905 | 0 | 0 | 1 |
Java
| false | null |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trellisldp.api;
import java.util.concurrent.CompletionStage;
import org.apache.commons.rdf.api.Dataset;
import org.apache.commons.rdf.api.IRI;
/**
* A service that persists resources by appending to their records. Nothing that
* is recorded by {@link #add} will be deleted by using {@code add} again.
*
* @author ajs6f
*
* @param <T> the type of resource that can be persisted by this service
*/
public interface ImmutableDataService<T> extends RetrievalService<T> {
/**
* @param identifier the identifier under which to persist a dataset
* @param dataset a dataset to persist
* @return a new completion stage that, when the stage completes normally, indicates that the supplied data
* were successfully stored in the corresponding persistence layer. In the case of an unsuccessful write operation,
* the {@link CompletionStage} will complete exceptionally and can be handled with
* {@link CompletionStage#handle}, {@link CompletionStage#exceptionally} or similar methods.
*/
CompletionStage<Void> add(IRI identifier, Dataset dataset);
}
|
UTF-8
|
Java
| 1,670 |
java
|
ImmutableDataService.java
|
Java
|
[
{
"context": "deleted by using {@code add} again.\n * \n * @author ajs6f\n *\n * @param <T> the type of resource that can be",
"end": 901,
"score": 0.9995175004005432,
"start": 896,
"tag": "USERNAME",
"value": "ajs6f"
}
] | null |
[] |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.trellisldp.api;
import java.util.concurrent.CompletionStage;
import org.apache.commons.rdf.api.Dataset;
import org.apache.commons.rdf.api.IRI;
/**
* A service that persists resources by appending to their records. Nothing that
* is recorded by {@link #add} will be deleted by using {@code add} again.
*
* @author ajs6f
*
* @param <T> the type of resource that can be persisted by this service
*/
public interface ImmutableDataService<T> extends RetrievalService<T> {
/**
* @param identifier the identifier under which to persist a dataset
* @param dataset a dataset to persist
* @return a new completion stage that, when the stage completes normally, indicates that the supplied data
* were successfully stored in the corresponding persistence layer. In the case of an unsuccessful write operation,
* the {@link CompletionStage} will complete exceptionally and can be handled with
* {@link CompletionStage#handle}, {@link CompletionStage#exceptionally} or similar methods.
*/
CompletionStage<Void> add(IRI identifier, Dataset dataset);
}
| 1,670 | 0.741317 | 0.738323 | 43 | 37.837208 | 35.71133 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.348837 | false | false |
5
|
5103d05f071ba913fa528cb26b4d3a7ea0210493
| 37,546,604,120,254 |
562f9e6c402ae178e8b8e6cbc0fb949525c09a1c
|
/src/com/inventoryManagement/MainStatement.java
|
62eb2aac7ba24b547816994c4b88d8c95011849b
|
[] |
no_license
|
Dolly3g/Inventory-Management
|
https://github.com/Dolly3g/Inventory-Management
|
adb07149fbc80e2451150b8ee89b4cf8e76455d8
|
6c96721bbefd92f95b4a744861ba3c6d23f4e0d4
|
refs/heads/master
| 2021-01-20T12:06:37.688000 | 2015-04-21T04:28:41 | 2015-04-21T04:28:41 | 33,913,019 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.inventoryManagement;
import java.util.List;
public class MainStatement {
private List<Store> stores;
private Price cost;
public MainStatement(List<Store> stores, Price cost) {
this.stores = stores;
this.cost = cost;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MainStatement that = (MainStatement) o;
if (stores != null ? !stores.equals(that.stores) : that.stores != null) return false;
return !(cost != null ? !cost.equals(that.cost) : that.cost != null);
}
@Override
public int hashCode() {
int result = stores != null ? stores.hashCode() : 0;
result = 31 * result + (cost != null ? cost.hashCode() : 0);
return result;
}
@Override
public String toString() {
String statement = "";
for (Store store : stores) {
statement += store.getStatement();
statement += System.lineSeparator();
}
if(cost != null)
statement += cost;
return statement;
}
}
|
UTF-8
|
Java
| 1,162 |
java
|
MainStatement.java
|
Java
|
[] | null |
[] |
package com.inventoryManagement;
import java.util.List;
public class MainStatement {
private List<Store> stores;
private Price cost;
public MainStatement(List<Store> stores, Price cost) {
this.stores = stores;
this.cost = cost;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MainStatement that = (MainStatement) o;
if (stores != null ? !stores.equals(that.stores) : that.stores != null) return false;
return !(cost != null ? !cost.equals(that.cost) : that.cost != null);
}
@Override
public int hashCode() {
int result = stores != null ? stores.hashCode() : 0;
result = 31 * result + (cost != null ? cost.hashCode() : 0);
return result;
}
@Override
public String toString() {
String statement = "";
for (Store store : stores) {
statement += store.getStatement();
statement += System.lineSeparator();
}
if(cost != null)
statement += cost;
return statement;
}
}
| 1,162 | 0.567986 | 0.564544 | 44 | 25.40909 | 23.201017 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
5
|
8189fe4f888aacefca28785b90a3caa291b7e291
| 35,485,019,840,987 |
b3e211f6b979984689e3d600980501487357056c
|
/茶百科/src/com/qianfeng/webview_activity/WebViewActivity.java
|
47a4b20e658a63c790e81e3d3eec745a89d43811
|
[] |
no_license
|
SunnyWangXu/GreeTreeInn
|
https://github.com/SunnyWangXu/GreeTreeInn
|
032a3d9b40275ddac004683950606a83cac6c55d
|
fe4432db567897fcc2501d4782ec36a0618a5a16
|
refs/heads/master
| 2021-01-01T18:29:36.532000 | 2015-07-28T09:41:27 | 2015-07-28T09:41:27 | 39,770,963 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.qianfeng.webview_activity;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.webkit.WebView;
import com.qianfeng.tea_cyclopedia.R;
public class WebViewActivity extends Activity {
private WebView web;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview_activity);
Intent intent = getIntent();
String ID = intent.getStringExtra("id");
String url = "http://sns.maimaicha.com/api?apikey=b4f4ee31a8b9acc866ef2afb754c33e6&format=json&method=news.getNewsContent&id=";
listItemTask mListItemTask = new listItemTask(getApplicationContext(), ID);
mListItemTask.execute(url);
web = (WebView) findViewById(R.id.webview);
}
private String data;
private String baseUrl;
private class listItemTask extends AsyncTask<String, Void, String> {
private String mID;
private Context mContext;
public listItemTask(Context context, String itemID) {
mID = itemID;
mContext = context;
}
// 请求解析网页接口数据
@Override
protected String doInBackground(String... params) {
String JSONStr = null;
baseUrl = params[0] + mID;
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(baseUrl);
try {
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() == 200) {
JSONStr = EntityUtils.toString(response.getEntity());
}
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
JSONObject obj = new JSONObject(JSONStr);
String result = obj.getString("errorMessage");
if (result.equals("success")) {
JSONObject dataObj = obj.getJSONObject("data");
data = dataObj.getString("wap_content");
}
} catch (JSONException e) {
e.printStackTrace();
}
return data;
}
@Override
protected void onPostExecute(String result) {
// 用webView的方法 打开网页显示数据
web.loadDataWithBaseURL(baseUrl, result, "text/html", "utf_8", null);
}
}
}
|
UTF-8
|
Java
| 2,654 |
java
|
WebViewActivity.java
|
Java
|
[
{
"context": "String url = \"http://sns.maimaicha.com/api?apikey=b4f4ee31a8b9acc866ef2afb754c33e6&format=json&method=news.getNewsContent&id=\";\r\n\t\tl",
"end": 1035,
"score": 0.999668538570404,
"start": 1003,
"tag": "KEY",
"value": "b4f4ee31a8b9acc866ef2afb754c33e6"
}
] | null |
[] |
package com.qianfeng.webview_activity;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.webkit.WebView;
import com.qianfeng.tea_cyclopedia.R;
public class WebViewActivity extends Activity {
private WebView web;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview_activity);
Intent intent = getIntent();
String ID = intent.getStringExtra("id");
String url = "http://sns.maimaicha.com/api?apikey=b4f4ee31a8b9acc866ef2afb754c33e6&format=json&method=news.getNewsContent&id=";
listItemTask mListItemTask = new listItemTask(getApplicationContext(), ID);
mListItemTask.execute(url);
web = (WebView) findViewById(R.id.webview);
}
private String data;
private String baseUrl;
private class listItemTask extends AsyncTask<String, Void, String> {
private String mID;
private Context mContext;
public listItemTask(Context context, String itemID) {
mID = itemID;
mContext = context;
}
// 请求解析网页接口数据
@Override
protected String doInBackground(String... params) {
String JSONStr = null;
baseUrl = params[0] + mID;
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(baseUrl);
try {
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() == 200) {
JSONStr = EntityUtils.toString(response.getEntity());
}
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
JSONObject obj = new JSONObject(JSONStr);
String result = obj.getString("errorMessage");
if (result.equals("success")) {
JSONObject dataObj = obj.getJSONObject("data");
data = dataObj.getString("wap_content");
}
} catch (JSONException e) {
e.printStackTrace();
}
return data;
}
@Override
protected void onPostExecute(String result) {
// 用webView的方法 打开网页显示数据
web.loadDataWithBaseURL(baseUrl, result, "text/html", "utf_8", null);
}
}
}
| 2,654 | 0.708046 | 0.698467 | 93 | 26.064516 | 22.892365 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.215054 | false | false |
5
|
f9580a8241119e42a11fd53ef840d3e0ff5464b2
| 16,810,502,052,772 |
07c74dadfebac13fb9012ec786279b255f75c981
|
/Jupiter Website Testing/src/com/chrometesting/AutomatedTesting.java
|
9ab2d3a7373326480668ce27fb329333fd137cec
|
[] |
no_license
|
Klaudyta/Jupiter-Website-Testing
|
https://github.com/Klaudyta/Jupiter-Website-Testing
|
c509b88d510d6c46dca90eeec3fffabd3d4c7dba
|
bbe701d5cb11ac0932457731211a3ec2ceb3dcae
|
refs/heads/master
| 2023-04-23T18:23:38.986000 | 2021-05-20T21:28:41 | 2021-05-20T21:28:41 | 369,338,497 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.chrometesting;
import org.openqa.selenium.*;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.*;
public class AutomatedTesting {
private static String url = "https://jupiter.cloud.planittesting.com/#/";
private static String driverPath = "C:\\Users\\claud\\Selenium Files\\chromedriver_win32\\chromedriver.exe";
static WebDriver driver;
public static void main(String[] args) throws InterruptedException {
launchBrowser();
verifyWebsiteTitle();
startShopping();
Thread.sleep(2000);
addProductsCart();
viewCart();
Thread.sleep(2000);
removeItem();
checkout();
terminateBrowser();
}
public static void launchBrowser() {
System.setProperty("webdriver.chrome.driver", driverPath );
driver = new ChromeDriver();
driver.get(url);
driver.manage().window().maximize();
}
public static void terminateBrowser() {
driver.close();
}
public static void verifyWebsiteTitle() {
String expectedTitle = "Jupiter Toys";
String actualTitle = driver.getTitle();
Assert.assertEquals(actualTitle, expectedTitle);
}
public static void startShopping() {
driver.findElement(By.className("btn-success")).click();
String currentUrl = driver.getCurrentUrl();
String expectedUrl = "https://jupiter.cloud.planittesting.com/#/shop";
Assert.assertEquals(currentUrl, expectedUrl);
}
public static void addProductsCart() {
driver.findElement(By.className("btn-success")).click();
String actualCountFirstP = driver.findElement(By.cssSelector("span[class='cart-count ng-binding']")).getText();
Assert.assertEquals(actualCountFirstP, "1");
driver.findElement(By.className("btn-success")).click();
String actualCountSecondP = driver.findElement(By.cssSelector("span[class='cart-count ng-binding']")).getText();
Assert.assertEquals(actualCountSecondP, "2");
}
public static void viewCart() {
driver.findElement(By.cssSelector("span[class='cart-count ng-binding']")).click();
}
public static void removeItem() {
driver.findElement(By.className("remove-item")).click();
driver.findElement(By.xpath("/html/body/div[3]/div[3]/a[1]")).click();
WebElement alert = driver.findElement(By.xpath("/html/body/div[2]/div/div/strong"));
String actualText = alert.getText();
String expectedText = "Your cart is empty";
Assert.assertEquals(actualText, expectedText);
}
public static void checkout() {
startShopping();
addProductsCart();
viewCart();
driver.findElement(By.className("btn-checkout")).click();
}
}
|
UTF-8
|
Java
| 2,666 |
java
|
AutomatedTesting.java
|
Java
|
[] | null |
[] |
package com.chrometesting;
import org.openqa.selenium.*;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.*;
public class AutomatedTesting {
private static String url = "https://jupiter.cloud.planittesting.com/#/";
private static String driverPath = "C:\\Users\\claud\\Selenium Files\\chromedriver_win32\\chromedriver.exe";
static WebDriver driver;
public static void main(String[] args) throws InterruptedException {
launchBrowser();
verifyWebsiteTitle();
startShopping();
Thread.sleep(2000);
addProductsCart();
viewCart();
Thread.sleep(2000);
removeItem();
checkout();
terminateBrowser();
}
public static void launchBrowser() {
System.setProperty("webdriver.chrome.driver", driverPath );
driver = new ChromeDriver();
driver.get(url);
driver.manage().window().maximize();
}
public static void terminateBrowser() {
driver.close();
}
public static void verifyWebsiteTitle() {
String expectedTitle = "Jupiter Toys";
String actualTitle = driver.getTitle();
Assert.assertEquals(actualTitle, expectedTitle);
}
public static void startShopping() {
driver.findElement(By.className("btn-success")).click();
String currentUrl = driver.getCurrentUrl();
String expectedUrl = "https://jupiter.cloud.planittesting.com/#/shop";
Assert.assertEquals(currentUrl, expectedUrl);
}
public static void addProductsCart() {
driver.findElement(By.className("btn-success")).click();
String actualCountFirstP = driver.findElement(By.cssSelector("span[class='cart-count ng-binding']")).getText();
Assert.assertEquals(actualCountFirstP, "1");
driver.findElement(By.className("btn-success")).click();
String actualCountSecondP = driver.findElement(By.cssSelector("span[class='cart-count ng-binding']")).getText();
Assert.assertEquals(actualCountSecondP, "2");
}
public static void viewCart() {
driver.findElement(By.cssSelector("span[class='cart-count ng-binding']")).click();
}
public static void removeItem() {
driver.findElement(By.className("remove-item")).click();
driver.findElement(By.xpath("/html/body/div[3]/div[3]/a[1]")).click();
WebElement alert = driver.findElement(By.xpath("/html/body/div[2]/div/div/strong"));
String actualText = alert.getText();
String expectedText = "Your cart is empty";
Assert.assertEquals(actualText, expectedText);
}
public static void checkout() {
startShopping();
addProductsCart();
viewCart();
driver.findElement(By.className("btn-checkout")).click();
}
}
| 2,666 | 0.710052 | 0.704051 | 80 | 31.325001 | 27.805923 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.075 | false | false |
5
|
ea65ca67f56b1c4eed7421f8c03594aedfda609c
| 36,610,301,262,635 |
76f2d0a0d2fcd155a448a3b29611f1de41aed94f
|
/SoccerManager/Android/app/src/main/java/com/jiwonkim/soccermanager/Main/TeamPage/TeamManage/FindTeamMember/FindTeamMemberResult.java
|
ed03588018af0c202f3918e81f0b40f8c33c5b4e
|
[] |
no_license
|
HangyuChoi/SoccerManager
|
https://github.com/HangyuChoi/SoccerManager
|
4abdf7d1d358d8a137e2c037e7b7009926e9dcb2
|
d0fff5680a798054175464e0038fa2d9940c4af9
|
refs/heads/master
| 2021-01-19T07:42:57.639000 | 2017-08-17T21:04:31 | 2017-08-17T21:04:31 | 100,644,413 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.jiwonkim.soccermanager.Main.TeamPage.TeamManage.FindTeamMember;
import com.jiwonkim.soccermanager.Main.Login.UserData;
import java.util.ArrayList;
/**
* Created by user on 2017-06-22.
*/
public class FindTeamMemberResult {
public String status;
public String reason;
public ArrayList<UserData> resultData;
}
|
UTF-8
|
Java
| 338 |
java
|
FindTeamMemberResult.java
|
Java
|
[] | null |
[] |
package com.jiwonkim.soccermanager.Main.TeamPage.TeamManage.FindTeamMember;
import com.jiwonkim.soccermanager.Main.Login.UserData;
import java.util.ArrayList;
/**
* Created by user on 2017-06-22.
*/
public class FindTeamMemberResult {
public String status;
public String reason;
public ArrayList<UserData> resultData;
}
| 338 | 0.769231 | 0.745562 | 15 | 21.533333 | 22.600492 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false |
5
|
cb67f6a39c116d49af1063586f6b3585bbb3244b
| 38,010,460,596,123 |
10d46b0c7c3eabdb0a77415d8604c06f8e801787
|
/src/main/java/lorikeet/VersionElement.java
|
7feb79884661ab7c83d8573fb36197e9563cc83c
|
[] |
no_license
|
blairehh/lorikeet-versioning
|
https://github.com/blairehh/lorikeet-versioning
|
8b593a8969d2040954c688e807f58dc3b9b0c752
|
6d01119cd44da5e345c6ea10a87bc5f859ff3a8e
|
refs/heads/main
| 2023-04-19T09:02:01.075000 | 2021-05-13T22:22:21 | 2021-05-13T22:22:21 | 367,177,511 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package lorikeet;
public enum VersionElement {
MILESTONE,
CONTRACT,
VERSION,
TAG
}
|
UTF-8
|
Java
| 100 |
java
|
VersionElement.java
|
Java
|
[] | null |
[] |
package lorikeet;
public enum VersionElement {
MILESTONE,
CONTRACT,
VERSION,
TAG
}
| 100 | 0.66 | 0.66 | 8 | 11.5 | 8.470537 | 28 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
5
|
6ac0733c70de783671cc85c6d4fb2e751a3813c5
| 36,696,200,604,687 |
653845ff260dc28ecb80fca5764043b5e0604fe3
|
/src/main/java/com/itsupportme/services/communicator/model/tracking/TrackingResponse.java
|
869fe5f590aa9f348b6574418b2198522d706d41
|
[] |
no_license
|
AnPiakhota/delivery-tracker-demo
|
https://github.com/AnPiakhota/delivery-tracker-demo
|
5aff740dec42f409b352d27f986b8d5b4e16401f
|
8d0c96ae35f2028db33df9da4f9712a22f85c6ba
|
refs/heads/master
| 2020-03-07T09:07:20.839000 | 2018-03-30T09:40:56 | 2018-03-30T09:40:56 | 127,398,943 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.itsupportme.services.communicator.model.tracking;
import com.itsupportme.services.communicator.model.ResponseStatus;
import java.util.LinkedList;
public class TrackingResponse {
private final ResponseStatus status;
private final LinkedList<TrackingShipment> shipments;
public TrackingResponse(ResponseStatus status, LinkedList<TrackingShipment> shipments) {
this.status = status;
this.shipments = shipments;
}
/**
* Overall status of the request.
*
* @return
*/
public ResponseStatus getStatus() {
return status;
}
/**
* Returns tracking data for all shipments that matched the tracking number.
*
* If tracking information exists this list will contain a single record. However, sometimes when package is
* rejected by recipient, it appears in the carriers system as 2 shipments with same tracking number (one for
* delivery and second for return). In such cases the returned list will contain more than 1 shipment.
*
* @return tracking data for all shipments found for corresponding tracking number
*/
public LinkedList<TrackingShipment> getShipments() {
return shipments;
}
}
|
UTF-8
|
Java
| 1,231 |
java
|
TrackingResponse.java
|
Java
|
[] | null |
[] |
package com.itsupportme.services.communicator.model.tracking;
import com.itsupportme.services.communicator.model.ResponseStatus;
import java.util.LinkedList;
public class TrackingResponse {
private final ResponseStatus status;
private final LinkedList<TrackingShipment> shipments;
public TrackingResponse(ResponseStatus status, LinkedList<TrackingShipment> shipments) {
this.status = status;
this.shipments = shipments;
}
/**
* Overall status of the request.
*
* @return
*/
public ResponseStatus getStatus() {
return status;
}
/**
* Returns tracking data for all shipments that matched the tracking number.
*
* If tracking information exists this list will contain a single record. However, sometimes when package is
* rejected by recipient, it appears in the carriers system as 2 shipments with same tracking number (one for
* delivery and second for return). In such cases the returned list will contain more than 1 shipment.
*
* @return tracking data for all shipments found for corresponding tracking number
*/
public LinkedList<TrackingShipment> getShipments() {
return shipments;
}
}
| 1,231 | 0.709992 | 0.708367 | 40 | 29.775 | 34.566956 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3 | false | false |
5
|
02d0d44594cd8e5a5e120f342b078fe11a1b1d31
| 11,295,764,054,906 |
895f837991c8aece2df81668023ed391f9ee3aab
|
/app/src/main/java/hackutd/com/dormdash/Restraunts.java
|
7d8b4c14b988bf8612bdac2825be9b80c11a84a5
|
[] |
no_license
|
CoppellCoders/HackUTD
|
https://github.com/CoppellCoders/HackUTD
|
9a7b2a8e74c751956155862b25cabe640e61c03d
|
c205e585523f4654f71173eca2025abf3f02563f
|
refs/heads/master
| 2020-04-24T21:05:40.257000 | 2019-02-25T15:13:34 | 2019-02-25T15:13:34 | 172,265,755 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package hackutd.com.dormdash;
import org.json.JSONArray;
import java.io.Serializable;
class Restraunts implements Serializable{
String rName;
String imageUrl;
String rating;
String rType;
String distance;
String menu;
String address;
public Restraunts(String rName, String imageUrl, String rating, String rType, String distance, JSONArray menu, String address){
this.rName = rName;
this.imageUrl = imageUrl;
this.rating = rating;
this.rType = rType;
this.distance = distance;
this.menu = menu.toString();
this.address = address;
}
public String getrName() {
return rName;
}
public void setrName(String rName) {
this.rName = rName;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
public String getrType() {
return rType;
}
public void setrType(String rType) {
this.rType = rType;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
}
|
UTF-8
|
Java
| 1,348 |
java
|
Restraunts.java
|
Java
|
[] | null |
[] |
package hackutd.com.dormdash;
import org.json.JSONArray;
import java.io.Serializable;
class Restraunts implements Serializable{
String rName;
String imageUrl;
String rating;
String rType;
String distance;
String menu;
String address;
public Restraunts(String rName, String imageUrl, String rating, String rType, String distance, JSONArray menu, String address){
this.rName = rName;
this.imageUrl = imageUrl;
this.rating = rating;
this.rType = rType;
this.distance = distance;
this.menu = menu.toString();
this.address = address;
}
public String getrName() {
return rName;
}
public void setrName(String rName) {
this.rName = rName;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
public String getrType() {
return rType;
}
public void setrType(String rType) {
this.rType = rType;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
}
| 1,348 | 0.616469 | 0.616469 | 62 | 20.741936 | 20.051495 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.532258 | false | false |
5
|
cad402f02c8da56e79dcb3bb0a2122a45dec3dd8
| 919,123,019,374 |
03be3f540f93a1507e82e4e84a651e205ba2971e
|
/trunk/IVRAppliction/sourcecode/DM/WEB-INF/src/flow/ResetVar.java
|
80108377905f07bc62146b32894be4d4c28f8928
|
[] |
no_license
|
Tarunjain19/DXC_SVN
|
https://github.com/Tarunjain19/DXC_SVN
|
448103f0c56e79616a2801acbf5d369d6e256b36
|
99a90150d30374929382c3181ee8b1f914c905ae
|
refs/heads/master
| 2022-06-04T10:36:52.755000 | 2020-05-06T08:44:47 | 2020-05-06T08:44:47 | 261,372,252 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package flow;
import com.avaya.sce.runtimecommon.IVariable;
import com.dm.util.Constants;
/**
* A basic servlet which allows a user to define their code, generate
* any output, and to select where to transition to next.
* Last generated by Orchestration Designer at: 2013-OCT-11 03:14:04 PM
*/
public class ResetVar extends com.avaya.sce.runtime.BasicServlet {
//{{START:CLASS:FIELDS
//}}END:CLASS:FIELDS
/**
* Default constructor
* Last generated by Orchestration Designer at: 2013-OCT-11 03:14:04 PM
*/
public ResetVar() {
//{{START:CLASS:CONSTRUCTOR
super();
//}}END:CLASS:CONSTRUCTOR
}
/**
* This method allows for custom integration with other Java components.
* You may use Java for sophisticated logic or to integrate with custom
* connectors (i.e. JMS, custom web services, sockets, XML, JAXB, etc.)
*
* Any custom code added here should work as efficiently as possible to prevent delays.
* It's important to design your callflow so that the voice browser (Voice Portal/IR)
* is not waiting too long for a response as this can lead to a poor caller experience.
* Additionally, if the response to the client voice browser exceeds the configured
* timeout, the platform may throw an "error.badfetch".
*
* Using this method, you have access to all session variables through the
* SCESession object.
*
* The code generator will *** NOT *** overwrite this method in the future.
* Last generated by Orchestration Designer at: 2013-OCT-11 03:14:04 PM
*/
public void servletImplementation(com.avaya.sce.runtimecommon.SCESession mySession) {
//-----------------------SET DM VARIABLE-----------------------
IVariable IDMVar = mySession.getVariable(IProjectVariables.IDM__VARIABLES);
IVariable flagVar = mySession.getVariable(IProjectVariables.FLAGS);
int i = 0;
IDMVar.getComplexVariable().getField(IProjectVariables.IDM__VARIABLES_FIELD_COUNT).setValue(i);
IDMVar.getComplexVariable().getField(IProjectVariables.IDM__VARIABLES_FIELD_NOINPUTCOUNT).setValue(i);
IDMVar.getComplexVariable().getField(IProjectVariables.IDM__VARIABLES_FIELD_NOMATCHCOUNT).setValue(i);
IDMVar.getComplexVariable().getField(IProjectVariables.IDM__VARIABLES_FIELD_COUNTRETRYCONFIRMATION).setValue(i);
IDMVar.getComplexVariable().getField(IProjectVariables.IDM__VARIABLES_FIELD_RETRYCONFIRMATION).setValue(true);
IDMVar.getComplexVariable().getField(IProjectVariables.IDM__VARIABLES_FIELD_FIRSTCONFIRMATIONATTEMPT).setValue(false);
IDMVar.getComplexVariable().getField(IProjectVariables.IDM__VARIABLES_FIELD_FIRSTNOINPUTATTEMPT).setValue(false);
IDMVar.getComplexVariable().getField(IProjectVariables.IDM__VARIABLES_FIELD_FIRSTNOMATCHATTEMPT).setValue(false);
IDMVar.getComplexVariable().getField(IProjectVariables.IDM__VARIABLES_FIELD_FIRSTNOINPUTREPROMPTATTEMPT).setValue(false);
IDMVar.getComplexVariable().getField(IProjectVariables.IDM__VARIABLES_FIELD_FIRSTNOMATCHREPROMPTATTEMPT).setValue(false);
IDMVar.getComplexVariable().getField(IProjectVariables.IDM__VARIABLES_FIELD_FIRSTRETRY).setValue(false);
IDMVar.getComplexVariable().getField(IProjectVariables.IDM__VARIABLES_FIELD_REPROMPTACTIVE).setValue(false);
flagVar.getComplexVariable().getField(IProjectVariables.FLAGS_FIELD_NM).setValue(Constants.TRUE);
flagVar.getComplexVariable().getField(IProjectVariables.FLAGS_FIELD_NI).setValue(Constants.FALSE);
}
/**
* Builds the list of branches that are defined for this servlet object.
* This list is built automatically by defining Goto nodes in the call flow editor.
* It is the programmer's responsibilty to provide at least one enabled Goto.<BR>
*
* The user should override updateBranches() to determine which Goto that the
* framework will activate. If there is not at least one enabled Goto item,
* the framework will throw a runtime exception.<BR>
*
* This method is generated automatically and changes to it may
* be overwritten next time code is generated. To modify the list
* of branches for the flow item, override:
* <code>updateBranches(Collection branches, SCESession mySession)</code>
*
* @return a Collection of <code>com.avaya.sce.runtime.Goto</code>
* objects that will be evaluated at runtime. If there are no gotos
* defined in the Servlet node, then this returns null.
* Last generated by Orchestration Designer at: 2017-SEP-04 04:23:31 PM
*/
public java.util.Collection getBranches(com.avaya.sce.runtimecommon.SCESession mySession) {
java.util.List list = null;
com.avaya.sce.runtime.Goto aGoto = null;
list = new java.util.ArrayList(1);
aGoto = new com.avaya.sce.runtime.Goto("RepromptCheck", 0, true, "Default");
list.add(aGoto);
return list;
}
}
|
UTF-8
|
Java
| 4,727 |
java
|
ResetVar.java
|
Java
|
[] | null |
[] |
package flow;
import com.avaya.sce.runtimecommon.IVariable;
import com.dm.util.Constants;
/**
* A basic servlet which allows a user to define their code, generate
* any output, and to select where to transition to next.
* Last generated by Orchestration Designer at: 2013-OCT-11 03:14:04 PM
*/
public class ResetVar extends com.avaya.sce.runtime.BasicServlet {
//{{START:CLASS:FIELDS
//}}END:CLASS:FIELDS
/**
* Default constructor
* Last generated by Orchestration Designer at: 2013-OCT-11 03:14:04 PM
*/
public ResetVar() {
//{{START:CLASS:CONSTRUCTOR
super();
//}}END:CLASS:CONSTRUCTOR
}
/**
* This method allows for custom integration with other Java components.
* You may use Java for sophisticated logic or to integrate with custom
* connectors (i.e. JMS, custom web services, sockets, XML, JAXB, etc.)
*
* Any custom code added here should work as efficiently as possible to prevent delays.
* It's important to design your callflow so that the voice browser (Voice Portal/IR)
* is not waiting too long for a response as this can lead to a poor caller experience.
* Additionally, if the response to the client voice browser exceeds the configured
* timeout, the platform may throw an "error.badfetch".
*
* Using this method, you have access to all session variables through the
* SCESession object.
*
* The code generator will *** NOT *** overwrite this method in the future.
* Last generated by Orchestration Designer at: 2013-OCT-11 03:14:04 PM
*/
public void servletImplementation(com.avaya.sce.runtimecommon.SCESession mySession) {
//-----------------------SET DM VARIABLE-----------------------
IVariable IDMVar = mySession.getVariable(IProjectVariables.IDM__VARIABLES);
IVariable flagVar = mySession.getVariable(IProjectVariables.FLAGS);
int i = 0;
IDMVar.getComplexVariable().getField(IProjectVariables.IDM__VARIABLES_FIELD_COUNT).setValue(i);
IDMVar.getComplexVariable().getField(IProjectVariables.IDM__VARIABLES_FIELD_NOINPUTCOUNT).setValue(i);
IDMVar.getComplexVariable().getField(IProjectVariables.IDM__VARIABLES_FIELD_NOMATCHCOUNT).setValue(i);
IDMVar.getComplexVariable().getField(IProjectVariables.IDM__VARIABLES_FIELD_COUNTRETRYCONFIRMATION).setValue(i);
IDMVar.getComplexVariable().getField(IProjectVariables.IDM__VARIABLES_FIELD_RETRYCONFIRMATION).setValue(true);
IDMVar.getComplexVariable().getField(IProjectVariables.IDM__VARIABLES_FIELD_FIRSTCONFIRMATIONATTEMPT).setValue(false);
IDMVar.getComplexVariable().getField(IProjectVariables.IDM__VARIABLES_FIELD_FIRSTNOINPUTATTEMPT).setValue(false);
IDMVar.getComplexVariable().getField(IProjectVariables.IDM__VARIABLES_FIELD_FIRSTNOMATCHATTEMPT).setValue(false);
IDMVar.getComplexVariable().getField(IProjectVariables.IDM__VARIABLES_FIELD_FIRSTNOINPUTREPROMPTATTEMPT).setValue(false);
IDMVar.getComplexVariable().getField(IProjectVariables.IDM__VARIABLES_FIELD_FIRSTNOMATCHREPROMPTATTEMPT).setValue(false);
IDMVar.getComplexVariable().getField(IProjectVariables.IDM__VARIABLES_FIELD_FIRSTRETRY).setValue(false);
IDMVar.getComplexVariable().getField(IProjectVariables.IDM__VARIABLES_FIELD_REPROMPTACTIVE).setValue(false);
flagVar.getComplexVariable().getField(IProjectVariables.FLAGS_FIELD_NM).setValue(Constants.TRUE);
flagVar.getComplexVariable().getField(IProjectVariables.FLAGS_FIELD_NI).setValue(Constants.FALSE);
}
/**
* Builds the list of branches that are defined for this servlet object.
* This list is built automatically by defining Goto nodes in the call flow editor.
* It is the programmer's responsibilty to provide at least one enabled Goto.<BR>
*
* The user should override updateBranches() to determine which Goto that the
* framework will activate. If there is not at least one enabled Goto item,
* the framework will throw a runtime exception.<BR>
*
* This method is generated automatically and changes to it may
* be overwritten next time code is generated. To modify the list
* of branches for the flow item, override:
* <code>updateBranches(Collection branches, SCESession mySession)</code>
*
* @return a Collection of <code>com.avaya.sce.runtime.Goto</code>
* objects that will be evaluated at runtime. If there are no gotos
* defined in the Servlet node, then this returns null.
* Last generated by Orchestration Designer at: 2017-SEP-04 04:23:31 PM
*/
public java.util.Collection getBranches(com.avaya.sce.runtimecommon.SCESession mySession) {
java.util.List list = null;
com.avaya.sce.runtime.Goto aGoto = null;
list = new java.util.ArrayList(1);
aGoto = new com.avaya.sce.runtime.Goto("RepromptCheck", 0, true, "Default");
list.add(aGoto);
return list;
}
}
| 4,727 | 0.75989 | 0.749101 | 96 | 48.239582 | 40.001755 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.572917 | false | false |
5
|
5dddab890f18371f4038501ed400a43cafbe8d01
| 27,504,970,588,101 |
fc5cc83d9f727e7fa8b3e7706f387d76f1d3c646
|
/app/src/main/java/com/example/ashutoshtiwari/popularmovies/SettingsActivity.java
|
f1c7fac9550114e6e458412fe909f78e28eddf68
|
[] |
no_license
|
Ashutosh-Tiwari/PopularMovies
|
https://github.com/Ashutosh-Tiwari/PopularMovies
|
0e8b190824cb145adaa0b911d46bd03b8e5516f8
|
bad4335a33ba50fae36b7ddede19955085f797bc
|
refs/heads/master
| 2021-01-11T13:36:06.315000 | 2017-06-27T14:56:27 | 2017-06-27T14:56:27 | 95,001,555 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.ashutoshtiwari.popularmovies;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
/**
* Created by Ashutosh.tiwari on 23/06/17.
*/
public class SettingsActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
Fragment fragment = new SettingsFragment();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(android.R.id.content, fragment, "settings_fragment");
fragmentTransaction.commit();
}
@Override
public void onBackPressed() {
finish();
}
}
|
UTF-8
|
Java
| 828 |
java
|
SettingsActivity.java
|
Java
|
[
{
"context": "package com.example.ashutoshtiwari.popularmovies;\n\nimport android.app.Fragment;\nimpo",
"end": 34,
"score": 0.9880391359329224,
"start": 20,
"tag": "USERNAME",
"value": "ashutoshtiwari"
},
{
"context": "pport.v7.app.AppCompatActivity;\n\n/**\n * Created by Ashutosh.tiwari on 23/06/17.\n */\n\npublic class SettingsActivity e",
"end": 229,
"score": 0.9986372590065002,
"start": 214,
"tag": "NAME",
"value": "Ashutosh.tiwari"
}
] | null |
[] |
package com.example.ashutoshtiwari.popularmovies;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
/**
* Created by Ashutosh.tiwari on 23/06/17.
*/
public class SettingsActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
Fragment fragment = new SettingsFragment();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(android.R.id.content, fragment, "settings_fragment");
fragmentTransaction.commit();
}
@Override
public void onBackPressed() {
finish();
}
}
| 828 | 0.730676 | 0.722222 | 30 | 26.6 | 26.320587 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.466667 | false | false |
5
|
98ecebcccdc0e69ef7cd5cfb7217e341d3a951a7
| 13,408,887,905,412 |
50bb6d48e87525b75a4df021bbf4c430479d3b87
|
/src/main/java/gg/revival/factions/listeners/cont/WorldEventsListener.java
|
f06c76f2152bef86c9a9fdaaa13cfeb8516122d8
|
[] |
no_license
|
TheRealGuru/Factions
|
https://github.com/TheRealGuru/Factions
|
5df5a0404512d5984d4143ff3ff8fc692fe90c8c
|
9003a84ed631a957d51e22db1f2ec4bf671cc463
|
refs/heads/master
| 2021-07-18T01:48:36.492000 | 2017-10-27T09:49:46 | 2017-10-27T09:49:46 | 110,689,437 | 0 | 1 | null | true | 2017-11-14T12:48:39 | 2017-11-14T12:48:38 | 2017-10-30T02:23:46 | 2017-10-27T09:49:54 | 522 | 0 | 0 | 0 | null | false | null |
package gg.revival.factions.listeners.cont;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockFromToEvent;
import org.bukkit.event.block.BlockSpreadEvent;
public class WorldEventsListener implements Listener {
@EventHandler
public void onBlockSpread(BlockSpreadEvent event) {
if (!event.getBlock().getType().equals(Material.FIRE))
return;
event.setCancelled(true);
}
@EventHandler
public void onBlockChange(BlockFromToEvent event) {
Block block = event.getToBlock();
if (block.getType().equals(Material.OBSIDIAN) || block.getType().equals(Material.COBBLESTONE) || block.getType().equals(Material.STONE))
event.setCancelled(true);
}
@EventHandler
public void onBlockBurn(BlockBurnEvent event) {
event.setCancelled(true);
}
}
|
UTF-8
|
Java
| 994 |
java
|
WorldEventsListener.java
|
Java
|
[] | null |
[] |
package gg.revival.factions.listeners.cont;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockFromToEvent;
import org.bukkit.event.block.BlockSpreadEvent;
public class WorldEventsListener implements Listener {
@EventHandler
public void onBlockSpread(BlockSpreadEvent event) {
if (!event.getBlock().getType().equals(Material.FIRE))
return;
event.setCancelled(true);
}
@EventHandler
public void onBlockChange(BlockFromToEvent event) {
Block block = event.getToBlock();
if (block.getType().equals(Material.OBSIDIAN) || block.getType().equals(Material.COBBLESTONE) || block.getType().equals(Material.STONE))
event.setCancelled(true);
}
@EventHandler
public void onBlockBurn(BlockBurnEvent event) {
event.setCancelled(true);
}
}
| 994 | 0.720322 | 0.720322 | 34 | 28.235294 | 28.672655 | 144 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
5
|
941068ce93702b4ea38609a8fb11268c8772c4b3
| 18,940,805,791,223 |
544fb5293aca995825a28456000d9eafaa37e9d8
|
/src/test/java/ExceptionHandling/TryCatchBlock.java
|
e3d5bcfaec2648a1d1b3b58c70a17082ca3a8033
|
[] |
no_license
|
DevopsLearning20/AutomationPratice
|
https://github.com/DevopsLearning20/AutomationPratice
|
e3b280f8648e3d0d1512e140144d1f34891991ab
|
9a0f0de8e209dc165d89b0009954f3a33c17e190
|
refs/heads/main
| 2023-06-15T15:55:50.611000 | 2021-07-14T13:47:17 | 2021-07-14T13:47:17 | 385,922,024 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ExceptionHandling;
public class TryCatchBlock {
public static void main(String[] args) {
System.out.println("Hi");
System.out.println("Hi");
System.out.println("Hi");
System.out.println("Hi");
int k = 10/0;
try {
System.out.println("Hello");
int i = 9/3;
System.out.println("testing");
System.out.println("testing");
System.out.println("testing");
}
catch(ArithmeticException e) {
System.out.println("some exception is coming...bye!!");
//e.printStackTrace();
//System.out.println(e.getMessage());
}
System.out.println("Hi");
System.out.println("Hi");
}
}
|
UTF-8
|
Java
| 766 |
java
|
TryCatchBlock.java
|
Java
|
[] | null |
[] |
package ExceptionHandling;
public class TryCatchBlock {
public static void main(String[] args) {
System.out.println("Hi");
System.out.println("Hi");
System.out.println("Hi");
System.out.println("Hi");
int k = 10/0;
try {
System.out.println("Hello");
int i = 9/3;
System.out.println("testing");
System.out.println("testing");
System.out.println("testing");
}
catch(ArithmeticException e) {
System.out.println("some exception is coming...bye!!");
//e.printStackTrace();
//System.out.println(e.getMessage());
}
System.out.println("Hi");
System.out.println("Hi");
}
}
| 766 | 0.522193 | 0.515666 | 34 | 21.529411 | 18.729082 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.470588 | false | false |
5
|
07bf9660998dfb42e7a0e87f7f6d9d313cb5a13f
| 12,257,836,733,613 |
78c80218220acff74dc7a6ca5a87e15b91f1ef40
|
/boletin16/Persona.java
|
551d6c120188c8f51f1457d1e1b4bab1dc515fb5
|
[] |
no_license
|
jgarciaodowd/Boletin16
|
https://github.com/jgarciaodowd/Boletin16
|
7f166a8fad5b30717d1acbb0f92178ae891094ee
|
0607b764a6d5ef9b11b883e02cc1cbfc82e4097c
|
refs/heads/master
| 2022-03-30T20:34:25.057000 | 2020-01-24T13:03:05 | 2020-01-24T13:03:05 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.mycompany.boletin16;
/**
*
* @author jaimg
*/
public class Persona {
public void cantar() {
System.out.println("doremifasollasido");
}
}
|
UTF-8
|
Java
| 198 |
java
|
Persona.java
|
Java
|
[
{
"context": "ge com.mycompany.boletin16;\r\n\r\n/**\r\n *\r\n * @author jaimg\r\n */\r\npublic class Persona {\r\n \r\n public vo",
"end": 61,
"score": 0.9992512464523315,
"start": 56,
"tag": "USERNAME",
"value": "jaimg"
}
] | null |
[] |
package com.mycompany.boletin16;
/**
*
* @author jaimg
*/
public class Persona {
public void cantar() {
System.out.println("doremifasollasido");
}
}
| 198 | 0.535354 | 0.525253 | 13 | 12.769231 | 14.423026 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.153846 | false | false |
5
|
c3d6c497892063b940d8785ab82841dfe4ef84f4
| 32,238,024,535,612 |
cc591a25c43373fccdc749bdeeeb724b4fbfbcb0
|
/TechnicalNormSoft/src/main/java/co/com/technicalnormsoft/model/dto/CategoriaRequisitoDTO.java
|
c158b3935c5e9d193cce859e95a79a506f65c8cf
|
[] |
no_license
|
jclopez1143/TechnicalNormSoft
|
https://github.com/jclopez1143/TechnicalNormSoft
|
488ae0293f3610e761ac8d6b4c462bf1570be17e
|
fce0cfa5eda9ef446189c3f6e56a6b8b92a8aaf9
|
refs/heads/master
| 2022-12-21T14:37:22.455000 | 2020-09-18T05:41:15 | 2020-09-18T05:41:15 | 251,152,648 | 0 | 0 | null | false | 2022-12-16T11:55:19 | 2020-03-29T23:03:05 | 2020-09-18T05:41:24 | 2022-12-16T11:55:16 | 70,148 | 0 | 0 | 12 |
Java
| false | false |
package co.com.technicalnormsoft.model.dto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Serializable;
import java.sql.*;
import java.util.Date;
/**
*
* @author Silicon Cali
*
*
*/
public class CategoriaRequisitoDTO implements Serializable {
private static final long serialVersionUID = 1L;
private static final Logger log = LoggerFactory.getLogger(CategoriaRequisitoDTO.class);
private Date dateIn;
private Date dateUpdate;
private String descripcion;
private Integer idCategoriaRequisito;
public Date getDateIn() {
return dateIn;
}
public void setDateIn(Date dateIn) {
this.dateIn = dateIn;
}
public Date getDateUpdate() {
return dateUpdate;
}
public void setDateUpdate(Date dateUpdate) {
this.dateUpdate = dateUpdate;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public Integer getIdCategoriaRequisito() {
return idCategoriaRequisito;
}
public void setIdCategoriaRequisito(Integer idCategoriaRequisito) {
this.idCategoriaRequisito = idCategoriaRequisito;
}
}
|
UTF-8
|
Java
| 1,309 |
java
|
CategoriaRequisitoDTO.java
|
Java
|
[
{
"context": ";\r\n\r\nimport java.util.Date;\r\n\r\n\r\n/**\r\n*\r\n* @author Silicon Cali\r\n* \r\n*\r\n*/\r\npublic class CategoriaRequisitoDTO im",
"end": 220,
"score": 0.9998475313186646,
"start": 208,
"tag": "NAME",
"value": "Silicon Cali"
}
] | null |
[] |
package co.com.technicalnormsoft.model.dto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Serializable;
import java.sql.*;
import java.util.Date;
/**
*
* @author <NAME>
*
*
*/
public class CategoriaRequisitoDTO implements Serializable {
private static final long serialVersionUID = 1L;
private static final Logger log = LoggerFactory.getLogger(CategoriaRequisitoDTO.class);
private Date dateIn;
private Date dateUpdate;
private String descripcion;
private Integer idCategoriaRequisito;
public Date getDateIn() {
return dateIn;
}
public void setDateIn(Date dateIn) {
this.dateIn = dateIn;
}
public Date getDateUpdate() {
return dateUpdate;
}
public void setDateUpdate(Date dateUpdate) {
this.dateUpdate = dateUpdate;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public Integer getIdCategoriaRequisito() {
return idCategoriaRequisito;
}
public void setIdCategoriaRequisito(Integer idCategoriaRequisito) {
this.idCategoriaRequisito = idCategoriaRequisito;
}
}
| 1,303 | 0.666921 | 0.664629 | 58 | 20.568966 | 21.53034 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.344828 | false | false |
5
|
d7eed8b5e949eeebf6ea386d8e5e61a124c17970
| 13,812,614,824,388 |
b05e22a8d7eb09f1f42ecd76d41683b44d5adc52
|
/src/main/java/com/o2/cz/cip/hashseek/logs/timelog/LogRecordTimeLog.java
|
a5d047bb2687a936f09c89f16f78c5bdeaee1ba5
|
[] |
no_license
|
PavelNovotny/HashSeek
|
https://github.com/PavelNovotny/HashSeek
|
af72417ce9f930674ed3f6a9dbf5c6abbba4ca1f
|
7291d6cb80f425c72a435db69a72017b933af682
|
refs/heads/master
| 2020-12-30T16:39:54.771000 | 2018-03-08T09:45:16 | 2018-03-08T09:45:16 | 90,998,460 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.o2.cz.cip.hashseek.logs.timelog;
import com.o2.cz.cip.hashseek.logs.AbstractLogRecord;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* User: Pavel
* Date: 18.8.12 11:43
*/
public class LogRecordTimeLog extends AbstractLogRecord {
private boolean alreadyReported = false;
public void setMarkerPrefix(String logFileName) {
Pattern pattern = Pattern.compile(".*_s\\d"); //other_s1, jms_s2, etc...
Matcher matcher = pattern.matcher(logFileName);
if (matcher.find()) {
this.markerPrefix = matcher.group().substring(0,1) + matcher.group().substring(matcher.group().length()-1);
} else {
this.markerPrefix = "??";
}
}
public String lineMarker() {
return String.format("%s%012d",markerPrefix, filePosition);
}
public void setRawData(String rawData) {
this.rawData = rawData;
// Pattern pattern = Pattern.compile(";[0-9a-f\\-\\.]{32,50};"); //bea id pattern
Matcher matcher = Pattern.compile("^\\[([^;]+;){14}[^;]+(;[0-9a-f\\-\\.]{32,50};)").matcher(rawData);
if (matcher.find()) {
setBeaId(matcher.group(2));
} else {
setBeaId("bea_id");
}
}
private String extractService(String part) {
Pattern pattern = Pattern.compile(";\\w+\\$[^;]+");
Matcher matcher = pattern.matcher(part);
if (matcher.find()) {
return matcher.group().substring(1).replaceAll("\\$","/");
}
return "";
}
public void reportData(PrintStream out) {
if (! alreadyReported) {
// out.println(lineMarker());
out.println(logFile.getName());
out.println(parseRawData());
alreadyReported = true;
}
}
public void reportService(PrintStream out) {
if (firstInBeaId) {
out.printf("\n%s %s %s\n", timeStamp, beaId, logFile.getName());
}
out.printf("%s %s -->%s (+%d)\n", lineMarker(), prettyFormatService(), requestOrResponse(), getTimeFromBeginning());
}
protected String prettyFormatService() {
String service = extractService(rawData).replaceAll("BusinessService/|BusinessServices/|ProxyService/|ProxyServices/", "");
Pattern pattern = Pattern.compile("/[0-9]"); //cislo verze
Matcher matcher = pattern.matcher(service);
String[] serviceInfo = service.split("/");
int l = serviceInfo.length;
if (matcher.find()) { //has version
return String.format("%s-%s %s",l>0?serviceInfo[0]:"??????", l>1?serviceInfo[1]:"??", l>2?serviceInfo[2]:"?????????????????" );
} else {
return String.format("%s %s",l>0?serviceInfo[0]:"??????", l>1?serviceInfo[1]:"?????????????????" );
}
}
@Override
public boolean equals(Object o) {
if (o instanceof LogRecordTimeLog) {
LogRecordTimeLog logRecord = (LogRecordTimeLog) o;
return logFile.equals(logFile) && beaId.equals(logRecord.getBeaId());
}
return super.equals(o);
}
@Override
public int hashCode() {
return beaId.hashCode() ^ logFile.hashCode();
}
}
|
UTF-8
|
Java
| 3,499 |
java
|
LogRecordTimeLog.java
|
Java
|
[
{
"context": "her;\nimport java.util.regex.Pattern;\n\n/**\n * User: Pavel\n * Date: 18.8.12 11:43\n */\npublic class LogRecord",
"end": 460,
"score": 0.8223836421966553,
"start": 455,
"tag": "USERNAME",
"value": "Pavel"
}
] | null |
[] |
package com.o2.cz.cip.hashseek.logs.timelog;
import com.o2.cz.cip.hashseek.logs.AbstractLogRecord;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* User: Pavel
* Date: 18.8.12 11:43
*/
public class LogRecordTimeLog extends AbstractLogRecord {
private boolean alreadyReported = false;
public void setMarkerPrefix(String logFileName) {
Pattern pattern = Pattern.compile(".*_s\\d"); //other_s1, jms_s2, etc...
Matcher matcher = pattern.matcher(logFileName);
if (matcher.find()) {
this.markerPrefix = matcher.group().substring(0,1) + matcher.group().substring(matcher.group().length()-1);
} else {
this.markerPrefix = "??";
}
}
public String lineMarker() {
return String.format("%s%012d",markerPrefix, filePosition);
}
public void setRawData(String rawData) {
this.rawData = rawData;
// Pattern pattern = Pattern.compile(";[0-9a-f\\-\\.]{32,50};"); //bea id pattern
Matcher matcher = Pattern.compile("^\\[([^;]+;){14}[^;]+(;[0-9a-f\\-\\.]{32,50};)").matcher(rawData);
if (matcher.find()) {
setBeaId(matcher.group(2));
} else {
setBeaId("bea_id");
}
}
private String extractService(String part) {
Pattern pattern = Pattern.compile(";\\w+\\$[^;]+");
Matcher matcher = pattern.matcher(part);
if (matcher.find()) {
return matcher.group().substring(1).replaceAll("\\$","/");
}
return "";
}
public void reportData(PrintStream out) {
if (! alreadyReported) {
// out.println(lineMarker());
out.println(logFile.getName());
out.println(parseRawData());
alreadyReported = true;
}
}
public void reportService(PrintStream out) {
if (firstInBeaId) {
out.printf("\n%s %s %s\n", timeStamp, beaId, logFile.getName());
}
out.printf("%s %s -->%s (+%d)\n", lineMarker(), prettyFormatService(), requestOrResponse(), getTimeFromBeginning());
}
protected String prettyFormatService() {
String service = extractService(rawData).replaceAll("BusinessService/|BusinessServices/|ProxyService/|ProxyServices/", "");
Pattern pattern = Pattern.compile("/[0-9]"); //cislo verze
Matcher matcher = pattern.matcher(service);
String[] serviceInfo = service.split("/");
int l = serviceInfo.length;
if (matcher.find()) { //has version
return String.format("%s-%s %s",l>0?serviceInfo[0]:"??????", l>1?serviceInfo[1]:"??", l>2?serviceInfo[2]:"?????????????????" );
} else {
return String.format("%s %s",l>0?serviceInfo[0]:"??????", l>1?serviceInfo[1]:"?????????????????" );
}
}
@Override
public boolean equals(Object o) {
if (o instanceof LogRecordTimeLog) {
LogRecordTimeLog logRecord = (LogRecordTimeLog) o;
return logFile.equals(logFile) && beaId.equals(logRecord.getBeaId());
}
return super.equals(o);
}
@Override
public int hashCode() {
return beaId.hashCode() ^ logFile.hashCode();
}
}
| 3,499 | 0.593598 | 0.580166 | 99 | 34.343433 | 32.049885 | 146 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.767677 | false | false |
5
|
b41a3f13a8c2abaae425b5012a76867f02f003da
| 22,016,002,362,188 |
9461698aa02494c138e1cdf299d08bf91358dd77
|
/src/main/java/com/zh/pattern/design/createMode/factory/factoryMethod/IFactory.java
|
8e257ce2c798de7bf73bb9e40c10776932340a62
|
[] |
no_license
|
Creepsins/DesignPattern
|
https://github.com/Creepsins/DesignPattern
|
62b649bcc238a8f989bd56b8b84b0d5855de3070
|
5d8b8276c15ad4c21c3635b2fd286f6f8bd584f4
|
refs/heads/master
| 2023-06-10T13:19:45.080000 | 2021-07-01T09:03:36 | 2021-07-01T09:03:36 | 276,669,201 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.zh.pattern.design.createMode.factory.factoryMethod;
import com.zh.pattern.design.createMode.factory.Operation;
public interface IFactory {
Operation createOperation();
}
|
UTF-8
|
Java
| 188 |
java
|
IFactory.java
|
Java
|
[] | null |
[] |
package com.zh.pattern.design.createMode.factory.factoryMethod;
import com.zh.pattern.design.createMode.factory.Operation;
public interface IFactory {
Operation createOperation();
}
| 188 | 0.808511 | 0.808511 | 7 | 25.857143 | 25.090855 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false |
5
|
d1752f6fafd7d719890ff1f6df6dc1cafc57be04
| 18,502,719,125,989 |
03b8882bd195bf52f00769feb10a08be8563e3c6
|
/CharSelect.java
|
d445d2488b8baa9e25069a895f62e42695a0d887
|
[] |
no_license
|
SeveralFaun/TaylorTitans
|
https://github.com/SeveralFaun/TaylorTitans
|
205d39ddd53cd41c1155cebf1390fc204aa2908e
|
6f36ce81e41279977bd50c5f1cf75761538580c2
|
refs/heads/main
| 2023-08-16T02:21:48.746000 | 2021-10-02T23:50:13 | 2021-10-02T23:50:13 | 412,935,187 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class CharSelect {
private GameGUI game;
private Handler handler;
public CharSelect(GameGUI game, Handler handler)
{
this.game = game;
this.handler = handler;
}
//handler.addObject(new Player1(50, 50, ID.Player1, handler));
//handler.addObject(new Player2(100, 100, ID.Player2, handler));
public void tick() {
}
public void render(Graphics g) {
g.setColor(new Color(237, 237, 237));
g.drawRect(100, 100, 100, 100);
}
}
|
UTF-8
|
Java
| 631 |
java
|
CharSelect.java
|
Java
|
[] | null |
[] |
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class CharSelect {
private GameGUI game;
private Handler handler;
public CharSelect(GameGUI game, Handler handler)
{
this.game = game;
this.handler = handler;
}
//handler.addObject(new Player1(50, 50, ID.Player1, handler));
//handler.addObject(new Player2(100, 100, ID.Player2, handler));
public void tick() {
}
public void render(Graphics g) {
g.setColor(new Color(237, 237, 237));
g.drawRect(100, 100, 100, 100);
}
}
| 631 | 0.673534 | 0.618067 | 29 | 19.689655 | 18.664188 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.758621 | false | false |
5
|
da914de21840200ddd2a9a303edbcdde7967ec89
| 10,419,590,697,297 |
ceaba29e3a0e747c69cd3a463c5c4bee7cf97363
|
/src/main/java/com/fz/mapper/UserDoMapper.java
|
0a27f057c110344d233de50f84ad206f71e67f46
|
[] |
no_license
|
webyuzhuang/grhao
|
https://github.com/webyuzhuang/grhao
|
19fc01d33f72b283b4c8081235639eb2aa209111
|
0e69a443460ef7466d2c0ce475a2efa908262ffa
|
refs/heads/master
| 2021-09-26T20:33:19.437000 | 2018-11-02T08:54:46 | 2018-11-02T08:54:46 | 105,015,850 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.fz.mapper;
import com.fz.model.UserDo;
import com.fz.util.MyMapper;
import org.springframework.stereotype.Service;
@Service
public interface UserDoMapper extends MyMapper<UserDo> {
}
|
UTF-8
|
Java
| 196 |
java
|
UserDoMapper.java
|
Java
|
[] | null |
[] |
package com.fz.mapper;
import com.fz.model.UserDo;
import com.fz.util.MyMapper;
import org.springframework.stereotype.Service;
@Service
public interface UserDoMapper extends MyMapper<UserDo> {
}
| 196 | 0.811224 | 0.811224 | 9 | 20.888889 | 19.398994 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false |
5
|
c4a11b8a8537c92718fb9e1bbb81804a9a763773
| 31,069,793,439,441 |
6c41774581737c295c21d2bcd5dac96b98de9a74
|
/src/main/java/com/eb/server/services/phases/PhaseHandlerBattle.java
|
80e7565d95c1faf4288f54fa608819ce70f78f8b
|
[] |
no_license
|
Rastikko/old-erudite-battles-server
|
https://github.com/Rastikko/old-erudite-battles-server
|
d81c007781de13d18c95c7a274c029733b588cba
|
33fb2e1b264bee706545a0b6bf0499d9061543d2
|
refs/heads/master
| 2021-03-19T14:53:42.824000 | 2018-08-28T15:33:25 | 2018-08-28T15:33:25 | 115,243,203 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.eb.server.services.phases;
import com.eb.server.domain.*;
import com.eb.server.domain.types.GameCommandType;
import com.eb.server.domain.types.GamePhaseType;
import com.eb.server.domain.types.QuestionCategoryType;
import com.eb.server.domain.types.QuestionSubcategoryType;
import com.eb.server.services.QuestionService;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
@Service
public class PhaseHandlerBattle extends AbstractPhaseHandler {
QuestionService questionService;
public PhaseHandlerBattle(QuestionService questionService) {
this.questionService = questionService;
GAME_PHASE_TYPE = GamePhaseType.PHASE_BATTLE;
NEXT_GAME_PHASE_TYPE = GamePhaseType.PHASE_BATTLE_RESOLUTION;
}
@Override
public void definePhaseAttributes(Game game) {
Question question = getNextQuestion(game);
game.getGamePlayers().get(0).setCurrentGameQuestion(getNextGameQuestion(game,question));
game.getGamePlayers().get(1).setCurrentGameQuestion(getNextGameQuestion(game,question));
}
@Override
public void handleCommand(Game game, GameCommand gameCommand) throws Exception {
switch (gameCommand.getType()) {
case COMMAND_ANSWER:
handleCommandAnswer(game, gameCommand);
}
super.handleCommand(game, gameCommand);
}
@Override
public void handleBotCommands(Game game) throws Exception {
handleCommand(game, createBotCommand(GameCommandType.COMMAND_ANSWER, ""));
handleCommand(game, createBotCommand(GameCommandType.COMMAND_END, ""));
}
void handleCommandAnswer(Game game, GameCommand gameCommand) {
GamePlayer gamePlayer = game.getGamePlayerByUserId(gameCommand.getUserId());
GamePlayer otherGamePlayer = game.getOtherGamePlayerByUserId(gameCommand.getUserId());
GameQuestion gameQuestion = gamePlayer.getCurrentGameQuestion();
if (gamePlayer.getIsBot()) {
Calendar endTime = (Calendar) gameQuestion.getStartDate().clone();
endTime.add(Calendar.SECOND, gameQuestion.getQuestion().getAverageAnswerTime());
gameQuestion.setSelectedAnswer(gameQuestion.getQuestion().getCorrectAnswer());
gameQuestion.setEndDate(endTime);
} else {
gameQuestion.setEndDate(Calendar.getInstance());
gameQuestion.setSelectedAnswer(gameCommand.getPayload());
}
if (otherGamePlayer.getCurrentGameQuestion().getEndDate() == null) {
// we wait until both players have answer the question
return;
}
// check both game players questions, if both are correct then use time to tiebreak
setCurrentQuestionOutcome(game);
}
void setCurrentQuestionOutcome(Game game) {
GamePlayer victoriousGamePlayer = game.getGamePlayers().stream()
.filter(gp -> gp.getCurrentGameQuestion().getSelectedAnswer().equals(gp.getCurrentGameQuestion().getQuestion().getCorrectAnswer()))
.sorted((gp1, gp2) -> gp2.getCurrentGameQuestion().getEndDate().compareTo(gp1.getCurrentGameQuestion().getEndDate()))
.findFirst()
.get();
if (victoriousGamePlayer != null) {
GamePlayer defeatedGamePlayer = game.getGamePlayers().stream()
.filter(gp -> gp.getUserId() != victoriousGamePlayer.getUserId())
.findFirst()
.get();
GameQuestion victoriousGameQuestion = victoriousGamePlayer.getCurrentGameQuestion();
GameQuestion defeatedGameQuestion = defeatedGamePlayer.getCurrentGameQuestion();
victoriousGameQuestion.setPerformance(1);
defeatedGameQuestion.setPerformance(0);
victoriousGamePlayer.getGameQuestions().add(victoriousGameQuestion);
defeatedGamePlayer.getGameQuestions().add(defeatedGameQuestion);
victoriousGamePlayer.setCurrentGameQuestion(null);
defeatedGamePlayer.setCurrentGameQuestion(null);
} else {
// TODO: test and reduce the complexity
GameQuestion firstGameQuestion = game.getGamePlayers().get(0).getCurrentGameQuestion();
GameQuestion secondGameQuestion = game.getGamePlayers().get(1).getCurrentGameQuestion();
firstGameQuestion.setPerformance(0);
secondGameQuestion.setPerformance(0);
game.getGamePlayers().get(0).getGameQuestions().add(firstGameQuestion);
game.getGamePlayers().get(1).getGameQuestions().add(secondGameQuestion);
game.getGamePlayers().get(0).setCurrentGameQuestion(null);
game.getGamePlayers().get(1).setCurrentGameQuestion(null);
}
}
Question getNextQuestion(Game game) {
// TODO: calculate next category and subcategory
List<Long> excludedIds = new ArrayList<>();
// HACK: JPA NotIn requires at least 1 element
excludedIds.add(-1L);
QuestionCategoryType category = getMostAlignCategory(game);
return questionService.getRandomQuestionFromCategory(category, excludedIds);
}
QuestionCategoryType getMostAlignCategory(Game game) {
GameAlignment alignment = game.getGameAlignment();
if (alignment.getLogicAlignment() > alignment.getCultureAlignment() && alignment.getLogicAlignment() > alignment.getScienceAlignment()) {
return QuestionCategoryType.LOGIC;
} else if (alignment.getCultureAlignment() > alignment.getScienceAlignment()) {
return QuestionCategoryType.CULTURE;
} else if (alignment.getScienceAlignment() > alignment.getCultureAlignment() ){
return QuestionCategoryType.SCIENCE;
}
return getRandomCategory();
}
QuestionCategoryType getRandomCategory() {
return QuestionCategoryType.LOGIC;
}
GameQuestion getNextGameQuestion(Game game, Question question) {
GameQuestion gameQuestion = new GameQuestion();
gameQuestion.setQuestion(question);
gameQuestion.setStartDate(new GregorianCalendar());
gameQuestion.setTurn(game.getTurn());
return gameQuestion;
}
}
|
UTF-8
|
Java
| 6,293 |
java
|
PhaseHandlerBattle.java
|
Java
|
[] | null |
[] |
package com.eb.server.services.phases;
import com.eb.server.domain.*;
import com.eb.server.domain.types.GameCommandType;
import com.eb.server.domain.types.GamePhaseType;
import com.eb.server.domain.types.QuestionCategoryType;
import com.eb.server.domain.types.QuestionSubcategoryType;
import com.eb.server.services.QuestionService;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
@Service
public class PhaseHandlerBattle extends AbstractPhaseHandler {
QuestionService questionService;
public PhaseHandlerBattle(QuestionService questionService) {
this.questionService = questionService;
GAME_PHASE_TYPE = GamePhaseType.PHASE_BATTLE;
NEXT_GAME_PHASE_TYPE = GamePhaseType.PHASE_BATTLE_RESOLUTION;
}
@Override
public void definePhaseAttributes(Game game) {
Question question = getNextQuestion(game);
game.getGamePlayers().get(0).setCurrentGameQuestion(getNextGameQuestion(game,question));
game.getGamePlayers().get(1).setCurrentGameQuestion(getNextGameQuestion(game,question));
}
@Override
public void handleCommand(Game game, GameCommand gameCommand) throws Exception {
switch (gameCommand.getType()) {
case COMMAND_ANSWER:
handleCommandAnswer(game, gameCommand);
}
super.handleCommand(game, gameCommand);
}
@Override
public void handleBotCommands(Game game) throws Exception {
handleCommand(game, createBotCommand(GameCommandType.COMMAND_ANSWER, ""));
handleCommand(game, createBotCommand(GameCommandType.COMMAND_END, ""));
}
void handleCommandAnswer(Game game, GameCommand gameCommand) {
GamePlayer gamePlayer = game.getGamePlayerByUserId(gameCommand.getUserId());
GamePlayer otherGamePlayer = game.getOtherGamePlayerByUserId(gameCommand.getUserId());
GameQuestion gameQuestion = gamePlayer.getCurrentGameQuestion();
if (gamePlayer.getIsBot()) {
Calendar endTime = (Calendar) gameQuestion.getStartDate().clone();
endTime.add(Calendar.SECOND, gameQuestion.getQuestion().getAverageAnswerTime());
gameQuestion.setSelectedAnswer(gameQuestion.getQuestion().getCorrectAnswer());
gameQuestion.setEndDate(endTime);
} else {
gameQuestion.setEndDate(Calendar.getInstance());
gameQuestion.setSelectedAnswer(gameCommand.getPayload());
}
if (otherGamePlayer.getCurrentGameQuestion().getEndDate() == null) {
// we wait until both players have answer the question
return;
}
// check both game players questions, if both are correct then use time to tiebreak
setCurrentQuestionOutcome(game);
}
void setCurrentQuestionOutcome(Game game) {
GamePlayer victoriousGamePlayer = game.getGamePlayers().stream()
.filter(gp -> gp.getCurrentGameQuestion().getSelectedAnswer().equals(gp.getCurrentGameQuestion().getQuestion().getCorrectAnswer()))
.sorted((gp1, gp2) -> gp2.getCurrentGameQuestion().getEndDate().compareTo(gp1.getCurrentGameQuestion().getEndDate()))
.findFirst()
.get();
if (victoriousGamePlayer != null) {
GamePlayer defeatedGamePlayer = game.getGamePlayers().stream()
.filter(gp -> gp.getUserId() != victoriousGamePlayer.getUserId())
.findFirst()
.get();
GameQuestion victoriousGameQuestion = victoriousGamePlayer.getCurrentGameQuestion();
GameQuestion defeatedGameQuestion = defeatedGamePlayer.getCurrentGameQuestion();
victoriousGameQuestion.setPerformance(1);
defeatedGameQuestion.setPerformance(0);
victoriousGamePlayer.getGameQuestions().add(victoriousGameQuestion);
defeatedGamePlayer.getGameQuestions().add(defeatedGameQuestion);
victoriousGamePlayer.setCurrentGameQuestion(null);
defeatedGamePlayer.setCurrentGameQuestion(null);
} else {
// TODO: test and reduce the complexity
GameQuestion firstGameQuestion = game.getGamePlayers().get(0).getCurrentGameQuestion();
GameQuestion secondGameQuestion = game.getGamePlayers().get(1).getCurrentGameQuestion();
firstGameQuestion.setPerformance(0);
secondGameQuestion.setPerformance(0);
game.getGamePlayers().get(0).getGameQuestions().add(firstGameQuestion);
game.getGamePlayers().get(1).getGameQuestions().add(secondGameQuestion);
game.getGamePlayers().get(0).setCurrentGameQuestion(null);
game.getGamePlayers().get(1).setCurrentGameQuestion(null);
}
}
Question getNextQuestion(Game game) {
// TODO: calculate next category and subcategory
List<Long> excludedIds = new ArrayList<>();
// HACK: JPA NotIn requires at least 1 element
excludedIds.add(-1L);
QuestionCategoryType category = getMostAlignCategory(game);
return questionService.getRandomQuestionFromCategory(category, excludedIds);
}
QuestionCategoryType getMostAlignCategory(Game game) {
GameAlignment alignment = game.getGameAlignment();
if (alignment.getLogicAlignment() > alignment.getCultureAlignment() && alignment.getLogicAlignment() > alignment.getScienceAlignment()) {
return QuestionCategoryType.LOGIC;
} else if (alignment.getCultureAlignment() > alignment.getScienceAlignment()) {
return QuestionCategoryType.CULTURE;
} else if (alignment.getScienceAlignment() > alignment.getCultureAlignment() ){
return QuestionCategoryType.SCIENCE;
}
return getRandomCategory();
}
QuestionCategoryType getRandomCategory() {
return QuestionCategoryType.LOGIC;
}
GameQuestion getNextGameQuestion(Game game, Question question) {
GameQuestion gameQuestion = new GameQuestion();
gameQuestion.setQuestion(question);
gameQuestion.setStartDate(new GregorianCalendar());
gameQuestion.setTurn(game.getTurn());
return gameQuestion;
}
}
| 6,293 | 0.695853 | 0.692992 | 151 | 40.675495 | 34.258183 | 147 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.543046 | false | false |
5
|
b622b12580841f7bd92bf214a41d89aee84cf56a
| 34,832,184,788,447 |
dacdb23603bfdabb524946218d99165ba03570f0
|
/app/src/main/java/com/example/jayti/geekon/QuizQuestion.java
|
a61f0573c7c585eeb1b1cdbe5b95268dea656099
|
[] |
no_license
|
OshinMundada/geekon
|
https://github.com/OshinMundada/geekon
|
c93a32448ecccbf90e77950649410df1b2efba9d
|
bdbd6f35b886205e512610c907f94db6e9c36d65
|
refs/heads/master
| 2021-01-21T22:01:02.880000 | 2017-06-22T18:22:57 | 2017-06-22T18:22:57 | 95,143,589 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.jayti.geekon;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class QuizQuestion extends AppCompatActivity implements View.OnClickListener {
private static final long SPLASH_DISPLAY_LENGTH = 10000;
String ques,ans,op1,op2,op3,op4;
Button q,a,b,c,d,next;
int points;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_question);
points=getIntent().getIntExtra("points",-1);
q=(Button)findViewById(R.id.question);
a= (Button) findViewById(R.id.op1);
b= (Button) findViewById(R.id.op2);
c= (Button) findViewById(R.id.op3);
d= (Button) findViewById(R.id.op4);
next=(Button)findViewById(R.id.next);
ques=getIntent().getStringExtra("question");
Log.i("infy",ques);
ans=getIntent().getStringExtra("answer");
op1=getIntent().getStringExtra("option1");
op2=getIntent().getStringExtra("option2");
op3=getIntent().getStringExtra("option3");
op4=getIntent().getStringExtra("option4");
q.setText(ques);
a.setText(op1);
b.setText(op2);
c.setText(op3);
d.setText(op4);
a.setOnClickListener(this);
b.setOnClickListener(this);
c.setOnClickListener(this);
d.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.op1:
if(ans.equals(a.getText())){
Toast.makeText(this,"A",Toast.LENGTH_SHORT).show();
a.setBackgroundColor(Color.GREEN);
points+=10;
new Handler().postDelayed(new Runnable(){
@Override
public void run() {
}
}, SPLASH_DISPLAY_LENGTH);
}
else
c.setBackgroundColor(Color.RED);
break;
case R.id.op2:
if(ans.equals(b.getText())){
Toast.makeText(this,"B",Toast.LENGTH_SHORT).show();
points+=10;
b.setBackgroundColor(Color.GREEN);
new Handler().postDelayed(new Runnable(){
@Override
public void run() {
}
}, SPLASH_DISPLAY_LENGTH);
}
else
c.setBackgroundColor(Color.RED);
break;
case R.id.op3:
Toast.makeText(this,"C",Toast.LENGTH_SHORT).show();
if(ans.equals(c.getText())){
points+=10;
c.setBackgroundColor(Color.GREEN);
new Handler().postDelayed(new Runnable(){
@Override
public void run() {
}
}, SPLASH_DISPLAY_LENGTH);
}
else
c.setBackgroundColor(Color.RED);
break;
case R.id.op4:
Toast.makeText(this,"D",Toast.LENGTH_SHORT).show();
if(ans.equals(d.getText())){
points+=10;
d.setBackgroundColor(Color.GREEN);
new Handler().postDelayed(new Runnable(){
@Override
public void run() {
}
}, SPLASH_DISPLAY_LENGTH);
}
else
c.setBackgroundColor(Color.RED);
break;
case R.id.next:
Intent returnIntent = new Intent();
returnIntent.putExtra("result",String.valueOf(points));
setResult(Activity.RESULT_OK,returnIntent);
this.finish();
}
}
}
|
UTF-8
|
Java
| 4,370 |
java
|
QuizQuestion.java
|
Java
|
[
{
"context": "package com.example.jayti.geekon;\r\n\r\nimport android.app.Activity;\r\nimport a",
"end": 25,
"score": 0.8110126256942749,
"start": 20,
"tag": "USERNAME",
"value": "jayti"
}
] | null |
[] |
package com.example.jayti.geekon;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class QuizQuestion extends AppCompatActivity implements View.OnClickListener {
private static final long SPLASH_DISPLAY_LENGTH = 10000;
String ques,ans,op1,op2,op3,op4;
Button q,a,b,c,d,next;
int points;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_question);
points=getIntent().getIntExtra("points",-1);
q=(Button)findViewById(R.id.question);
a= (Button) findViewById(R.id.op1);
b= (Button) findViewById(R.id.op2);
c= (Button) findViewById(R.id.op3);
d= (Button) findViewById(R.id.op4);
next=(Button)findViewById(R.id.next);
ques=getIntent().getStringExtra("question");
Log.i("infy",ques);
ans=getIntent().getStringExtra("answer");
op1=getIntent().getStringExtra("option1");
op2=getIntent().getStringExtra("option2");
op3=getIntent().getStringExtra("option3");
op4=getIntent().getStringExtra("option4");
q.setText(ques);
a.setText(op1);
b.setText(op2);
c.setText(op3);
d.setText(op4);
a.setOnClickListener(this);
b.setOnClickListener(this);
c.setOnClickListener(this);
d.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.op1:
if(ans.equals(a.getText())){
Toast.makeText(this,"A",Toast.LENGTH_SHORT).show();
a.setBackgroundColor(Color.GREEN);
points+=10;
new Handler().postDelayed(new Runnable(){
@Override
public void run() {
}
}, SPLASH_DISPLAY_LENGTH);
}
else
c.setBackgroundColor(Color.RED);
break;
case R.id.op2:
if(ans.equals(b.getText())){
Toast.makeText(this,"B",Toast.LENGTH_SHORT).show();
points+=10;
b.setBackgroundColor(Color.GREEN);
new Handler().postDelayed(new Runnable(){
@Override
public void run() {
}
}, SPLASH_DISPLAY_LENGTH);
}
else
c.setBackgroundColor(Color.RED);
break;
case R.id.op3:
Toast.makeText(this,"C",Toast.LENGTH_SHORT).show();
if(ans.equals(c.getText())){
points+=10;
c.setBackgroundColor(Color.GREEN);
new Handler().postDelayed(new Runnable(){
@Override
public void run() {
}
}, SPLASH_DISPLAY_LENGTH);
}
else
c.setBackgroundColor(Color.RED);
break;
case R.id.op4:
Toast.makeText(this,"D",Toast.LENGTH_SHORT).show();
if(ans.equals(d.getText())){
points+=10;
d.setBackgroundColor(Color.GREEN);
new Handler().postDelayed(new Runnable(){
@Override
public void run() {
}
}, SPLASH_DISPLAY_LENGTH);
}
else
c.setBackgroundColor(Color.RED);
break;
case R.id.next:
Intent returnIntent = new Intent();
returnIntent.putExtra("result",String.valueOf(points));
setResult(Activity.RESULT_OK,returnIntent);
this.finish();
}
}
}
| 4,370 | 0.491076 | 0.482151 | 126 | 32.682541 | 19.414301 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.746032 | false | false |
5
|
8bd6975706ec8a304795775f82b4a677b8312ba8
| 36,180,804,510,438 |
cc064d289fab1607e37929035b51201ff44d9090
|
/wenda-message-service/src/main/java/com/chenqincheng/WendaMessageServiceApplication.java
|
c424688af73f2f8591055361e70cc314ada1df4a
|
[] |
no_license
|
chenqincheng/wenda-microservice
|
https://github.com/chenqincheng/wenda-microservice
|
771a0ea01ed6005d96f05154f7faad569e7a0391
|
3a4ee0544dbd3cd39d7bef99120a2422cf788a2a
|
refs/heads/master
| 2017-11-02T05:54:45.968000 | 2017-07-08T09:12:03 | 2017-07-08T09:12:03 | 96,298,285 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.chenqincheng;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class WendaMessageServiceApplication {
public static void main(String[] args) {
SpringApplication.run(WendaMessageServiceApplication.class, args);
}
}
|
UTF-8
|
Java
| 334 |
java
|
WendaMessageServiceApplication.java
|
Java
|
[] | null |
[] |
package com.chenqincheng;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class WendaMessageServiceApplication {
public static void main(String[] args) {
SpringApplication.run(WendaMessageServiceApplication.class, args);
}
}
| 334 | 0.838323 | 0.838323 | 12 | 26.833334 | 25.702896 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false |
5
|
713a541d8a4c02ba9399e0c05b09214b15003d33
| 5,952,824,731,928 |
415e2e38b7e7952063637252398553f2822843f8
|
/spring-boot-action-web/src/main/java/com/spring/action/web/controller/DemoController.java
|
1a12253518060724a88009e54aa034caee71875e
|
[] |
no_license
|
fgm0129/spring-boot-action
|
https://github.com/fgm0129/spring-boot-action
|
657a1e34dfb97ff9a77aa80a614d140b23f287b2
|
77b44a6f885bc55e3ce125081e5dc34f7b3b544d
|
refs/heads/master
| 2021-04-27T02:31:04.598000 | 2018-02-24T04:03:58 | 2018-02-24T04:03:58 | 122,696,425 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.spring.action.web.controller;
import com.spring.action.web.model.DemoObj;
import com.spring.action.web.model.FormObj;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
/**
* Created by fgm on 2017/4/3.
*/
@Controller
@RequestMapping("/anno")
public class DemoController {
@RequestMapping(produces = "text/plain;charset=UTF-8")
public @ResponseBody
String index(HttpServletRequest request){
return "url:"+request.getRequestURL()+" can access";
}
@RequestMapping("/pathVar/{str}")
public @ResponseBody String demoPathVar(@PathVariable String str,HttpServletRequest request){
return "url:"+request.getRequestURL()+" can access,str="+str;
}
@RequestMapping(value = "/requestParam",produces = "text/plain;charset=UTF-8")
public @ResponseBody String requestParam(Long id,HttpServletRequest request){
return "url:"+request.getRequestURL()+"can assess ,id="+id;
}
@RequestMapping(value = "/obj",produces = "application/json;charset=UTF-8")
public @ResponseBody String obj(DemoObj obj, HttpServletRequest request){
return "url:"+request.getRequestURL()+" can access,obj id:"+obj.getId()+", obj name:"+obj.getName();
}
@RequestMapping(value = "/formObj",produces = "application/json;charset=UTF-8",method = RequestMethod.POST)
public @ResponseBody String obj(FormObj obj, HttpServletRequest request){
return "url:"+request.getRequestURL()+" can access,obj name:"+obj.getName()+", obj company:"+obj.getCompany()+", obj country:"+obj.getCountry();
}
@RequestMapping(value = {"/name1","/name2"},produces = "text/plain;charset=UTF-8")
public @ResponseBody String remove(Long id,HttpServletRequest request){
return "url:"+request.getRequestURL()+" can access";
}
@RequestMapping(value = {"/advice"},produces = "text/plain;charset=UTF-8")
public @ResponseBody String advice(DemoObj demoObj, @ModelAttribute("msg") String msg){
throw new IllegalArgumentException("请求参数有误:"+msg);
}
}
|
UTF-8
|
Java
| 2,157 |
java
|
DemoController.java
|
Java
|
[
{
"context": "ervlet.http.HttpServletRequest;\n\n/**\n * Created by fgm on 2017/4/3.\n */\n@Controller\n@RequestMapping(\"/an",
"end": 300,
"score": 0.9996055364608765,
"start": 297,
"tag": "USERNAME",
"value": "fgm"
}
] | null |
[] |
package com.spring.action.web.controller;
import com.spring.action.web.model.DemoObj;
import com.spring.action.web.model.FormObj;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
/**
* Created by fgm on 2017/4/3.
*/
@Controller
@RequestMapping("/anno")
public class DemoController {
@RequestMapping(produces = "text/plain;charset=UTF-8")
public @ResponseBody
String index(HttpServletRequest request){
return "url:"+request.getRequestURL()+" can access";
}
@RequestMapping("/pathVar/{str}")
public @ResponseBody String demoPathVar(@PathVariable String str,HttpServletRequest request){
return "url:"+request.getRequestURL()+" can access,str="+str;
}
@RequestMapping(value = "/requestParam",produces = "text/plain;charset=UTF-8")
public @ResponseBody String requestParam(Long id,HttpServletRequest request){
return "url:"+request.getRequestURL()+"can assess ,id="+id;
}
@RequestMapping(value = "/obj",produces = "application/json;charset=UTF-8")
public @ResponseBody String obj(DemoObj obj, HttpServletRequest request){
return "url:"+request.getRequestURL()+" can access,obj id:"+obj.getId()+", obj name:"+obj.getName();
}
@RequestMapping(value = "/formObj",produces = "application/json;charset=UTF-8",method = RequestMethod.POST)
public @ResponseBody String obj(FormObj obj, HttpServletRequest request){
return "url:"+request.getRequestURL()+" can access,obj name:"+obj.getName()+", obj company:"+obj.getCompany()+", obj country:"+obj.getCountry();
}
@RequestMapping(value = {"/name1","/name2"},produces = "text/plain;charset=UTF-8")
public @ResponseBody String remove(Long id,HttpServletRequest request){
return "url:"+request.getRequestURL()+" can access";
}
@RequestMapping(value = {"/advice"},produces = "text/plain;charset=UTF-8")
public @ResponseBody String advice(DemoObj demoObj, @ModelAttribute("msg") String msg){
throw new IllegalArgumentException("请求参数有误:"+msg);
}
}
| 2,157 | 0.70303 | 0.696504 | 67 | 31.014925 | 37.21759 | 152 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.58209 | false | false |
5
|
1241ffa66ca38fa0fb68ba6a37b001d3d103d104
| 5,952,824,730,190 |
c26d502bef27436196655bdbebbf004db3e2cd1f
|
/tree/bt/bt_236.java
|
2b092d0ac2d5fb558512f9038e11bda6cb2350a6
|
[] |
no_license
|
DiabloBlood/LeetCode
|
https://github.com/DiabloBlood/LeetCode
|
23f8a680debf0d9dc655aee0be17017ee740a5ed
|
9c97bfb42a979d1d110d1f2fafe237f17fd2aa62
|
refs/heads/master
| 2022-03-19T07:21:21.536000 | 2022-02-21T07:45:10 | 2022-02-21T07:45:10 | 169,341,332 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
class Solution236 {
/**
* Back tracking method.
*
* Case Analysis:
* 1. node == null; return node; // return null is OK too.
* 2. node == p; return node;
* 3. node == q; return node;
* Call left, call right
* 4. left == null && right != null; return right;
* 5. left != null && right == null; return left;
* 6. left == null && right == null; return null; //return left/right is OK too.
* 7. left != null && right != null; return node;
*/
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || p == null || q == null) {
return null;
}
return helper(root, p, q);
}
private TreeNode helper(TreeNode node, TreeNode p, TreeNode q) {
if (node == null || node == p || node == q) {
return node;
}
TreeNode left = helper(node.left, p, q);
TreeNode right = helper(node.right, p, q);
if (left != null && right != null) {
return node;
}
return left != null ? left : right;
}
/**
* Back tracking method.
*
* The corner case could conclude into general cases.
*/
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q) {
return root;
}
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if (left != null && right != null) {
return root;
}
return left != null ? left : right;
}
}
|
UTF-8
|
Java
| 1,651 |
java
|
bt_236.java
|
Java
|
[] | null |
[] |
class Solution236 {
/**
* Back tracking method.
*
* Case Analysis:
* 1. node == null; return node; // return null is OK too.
* 2. node == p; return node;
* 3. node == q; return node;
* Call left, call right
* 4. left == null && right != null; return right;
* 5. left != null && right == null; return left;
* 6. left == null && right == null; return null; //return left/right is OK too.
* 7. left != null && right != null; return node;
*/
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || p == null || q == null) {
return null;
}
return helper(root, p, q);
}
private TreeNode helper(TreeNode node, TreeNode p, TreeNode q) {
if (node == null || node == p || node == q) {
return node;
}
TreeNode left = helper(node.left, p, q);
TreeNode right = helper(node.right, p, q);
if (left != null && right != null) {
return node;
}
return left != null ? left : right;
}
/**
* Back tracking method.
*
* The corner case could conclude into general cases.
*/
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q) {
return root;
}
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if (left != null && right != null) {
return root;
}
return left != null ? left : right;
}
}
| 1,651 | 0.521502 | 0.515445 | 50 | 32.02 | 23.691763 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.1 | false | false |
5
|
1b01e16d3531a3a374a61a4abdf64341dbc1f031
| 35,321,811,065,321 |
6eaff9434030e140a037657388d71e5505696376
|
/app/src/main/java/com/example/jacek/streamthegame/GameObjects/GameObject.java
|
af5352697d310ecd921cc5b7df1ef18c31eae147
|
[
"MIT"
] |
permissive
|
jacnik/StreamTheGame
|
https://github.com/jacnik/StreamTheGame
|
94e6621818165af4a0d179d141173b3313d19772
|
82345e33ec7a41bd551c2e975dabb72002afd0c2
|
refs/heads/master
| 2021-01-10T10:29:17.689000 | 2016-01-14T20:27:40 | 2016-01-14T20:27:40 | 45,791,031 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.jacek.streamthegame.GameObjects;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.Point;
import com.example.jacek.streamthegame.Animations.Animation;
import com.example.jacek.streamthegame.Direction;
import com.example.jacek.streamthegame.Exit;
import com.example.jacek.streamthegame.Sprite;
/**
* Created by jacek on 11/15/2015.
*/
public abstract class GameObject {
protected Bitmap image;
protected int widthCells, heightCells; // width and height in cell units!
protected int cellWidth, cellHeight;
protected Exit exit1;
protected Exit exit2;
protected Exit animationStartExit;
protected boolean isStatic;
protected boolean isAnimating;
private boolean finishedAnimating;
protected Animation animation;
protected GameObject(int cellWidth, int cellHeight) {
this.cellWidth = cellWidth;
this.cellHeight = cellHeight;
}
public abstract Sprite getType();
public void update() {
if (this.animation.playedOnce()) {
this.isAnimating = false;
this.finishedAnimating = true;
} else {
this.animation.update();
}
}
public Bitmap getImage() {
if (this.isAnimating || this.finishedAnimating()) {
// images from animation are not scaled
return Bitmap.createScaledBitmap(
this.animation.getImage(),
this.widthCells * this.cellWidth,
this.heightCells * this.cellHeight,
true);
} else {
return this.image;
}
}
public int getWidthCells() {
return this.widthCells;
}
public int getHeightCells() {
return this.heightCells;
}
public boolean isStatic() {
return this.isStatic;
}
public void startAnimation(Exit exit) {
this.animation.setup(exit);
this.animationStartExit = exit;
this.isAnimating = true;
}
public boolean isAnimating() {
return this.isAnimating;
}
public boolean finishedAnimating() {
return this.finishedAnimating;
}
public Exit getAnimationEndExit() {
if (this.animationStartExit == this.exit1) {
return this.exit2;
} else {
return this.exit1;
}
}
public boolean hasExitAt(int row, int col, Direction dir) {
Point crds = this.getCoordsFromCorner(this.exit1.getCorner());
if (this.exit1.getDir() == dir && row == crds.x && col == crds.y) return true;
crds = this.getCoordsFromCorner(this.exit2.getCorner());
if (this.exit2.getDir() == dir && row == crds.x && col == crds.y) return true;
return false;
}
public Exit getExitAt(int row, int col, Direction dir) {
Point crds = this.getCoordsFromCorner(this.exit1.getCorner());
if (this.exit1.getDir() == dir && row == crds.x && col == crds.y) return this.exit1;
crds = this.getCoordsFromCorner(this.exit2.getCorner());
if (this.exit2.getDir() == dir && row == crds.x && col == crds.y) return this.exit2;
return null;
}
/** Rotates current object 90*rotations degrees */
public void rotate(int rotations) {
Matrix matrix = new Matrix();
matrix.postRotate(90 * rotations);
this.image = Bitmap.createBitmap(
this.image, 0, 0, this.image.getWidth(),
this.image.getHeight(), matrix, true);
for (int i = 0; i < rotations % 4; ++i) {
// swap the dimensions
int tmp = this.widthCells;
this.widthCells = this.heightCells;
this.heightCells = tmp;
this.rotateExits();
}
// resize the image so it fits new dimensions
this.image = Bitmap.createScaledBitmap(
this.image,
this.widthCells * this.cellWidth,
this.heightCells * this.cellHeight,
false);
}
/** just rotate 90Deg */
public void rotate() {
this.rotate(1);
}
public void resetAnimation() {
this.animation.reset();
this.isAnimating = false;
this.finishedAnimating = false;
}
/** x = rowCoordinate, y = col coordinate */
public Point getCoordsFromCorner(int corner) {
switch (corner) {
case 0: return new Point(0, 0);
case 1: return new Point(0, this.getWidthCells() - 1);
case 2: return new Point(this.getHeightCells() - 1, this.getWidthCells() - 1);
case 3: return new Point(this.getHeightCells() - 1, 0);
default: return null;
}
}
private void rotateExits() {
this.exit1.rotate();
this.exit2.rotate();
}
}
|
UTF-8
|
Java
| 4,823 |
java
|
GameObject.java
|
Java
|
[
{
"context": "le.jacek.streamthegame.Sprite;\n\n\n/**\n * Created by jacek on 11/15/2015.\n */\npublic abstract class GameObje",
"end": 378,
"score": 0.9996283650398254,
"start": 373,
"tag": "USERNAME",
"value": "jacek"
}
] | null |
[] |
package com.example.jacek.streamthegame.GameObjects;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.Point;
import com.example.jacek.streamthegame.Animations.Animation;
import com.example.jacek.streamthegame.Direction;
import com.example.jacek.streamthegame.Exit;
import com.example.jacek.streamthegame.Sprite;
/**
* Created by jacek on 11/15/2015.
*/
public abstract class GameObject {
protected Bitmap image;
protected int widthCells, heightCells; // width and height in cell units!
protected int cellWidth, cellHeight;
protected Exit exit1;
protected Exit exit2;
protected Exit animationStartExit;
protected boolean isStatic;
protected boolean isAnimating;
private boolean finishedAnimating;
protected Animation animation;
protected GameObject(int cellWidth, int cellHeight) {
this.cellWidth = cellWidth;
this.cellHeight = cellHeight;
}
public abstract Sprite getType();
public void update() {
if (this.animation.playedOnce()) {
this.isAnimating = false;
this.finishedAnimating = true;
} else {
this.animation.update();
}
}
public Bitmap getImage() {
if (this.isAnimating || this.finishedAnimating()) {
// images from animation are not scaled
return Bitmap.createScaledBitmap(
this.animation.getImage(),
this.widthCells * this.cellWidth,
this.heightCells * this.cellHeight,
true);
} else {
return this.image;
}
}
public int getWidthCells() {
return this.widthCells;
}
public int getHeightCells() {
return this.heightCells;
}
public boolean isStatic() {
return this.isStatic;
}
public void startAnimation(Exit exit) {
this.animation.setup(exit);
this.animationStartExit = exit;
this.isAnimating = true;
}
public boolean isAnimating() {
return this.isAnimating;
}
public boolean finishedAnimating() {
return this.finishedAnimating;
}
public Exit getAnimationEndExit() {
if (this.animationStartExit == this.exit1) {
return this.exit2;
} else {
return this.exit1;
}
}
public boolean hasExitAt(int row, int col, Direction dir) {
Point crds = this.getCoordsFromCorner(this.exit1.getCorner());
if (this.exit1.getDir() == dir && row == crds.x && col == crds.y) return true;
crds = this.getCoordsFromCorner(this.exit2.getCorner());
if (this.exit2.getDir() == dir && row == crds.x && col == crds.y) return true;
return false;
}
public Exit getExitAt(int row, int col, Direction dir) {
Point crds = this.getCoordsFromCorner(this.exit1.getCorner());
if (this.exit1.getDir() == dir && row == crds.x && col == crds.y) return this.exit1;
crds = this.getCoordsFromCorner(this.exit2.getCorner());
if (this.exit2.getDir() == dir && row == crds.x && col == crds.y) return this.exit2;
return null;
}
/** Rotates current object 90*rotations degrees */
public void rotate(int rotations) {
Matrix matrix = new Matrix();
matrix.postRotate(90 * rotations);
this.image = Bitmap.createBitmap(
this.image, 0, 0, this.image.getWidth(),
this.image.getHeight(), matrix, true);
for (int i = 0; i < rotations % 4; ++i) {
// swap the dimensions
int tmp = this.widthCells;
this.widthCells = this.heightCells;
this.heightCells = tmp;
this.rotateExits();
}
// resize the image so it fits new dimensions
this.image = Bitmap.createScaledBitmap(
this.image,
this.widthCells * this.cellWidth,
this.heightCells * this.cellHeight,
false);
}
/** just rotate 90Deg */
public void rotate() {
this.rotate(1);
}
public void resetAnimation() {
this.animation.reset();
this.isAnimating = false;
this.finishedAnimating = false;
}
/** x = rowCoordinate, y = col coordinate */
public Point getCoordsFromCorner(int corner) {
switch (corner) {
case 0: return new Point(0, 0);
case 1: return new Point(0, this.getWidthCells() - 1);
case 2: return new Point(this.getHeightCells() - 1, this.getWidthCells() - 1);
case 3: return new Point(this.getHeightCells() - 1, 0);
default: return null;
}
}
private void rotateExits() {
this.exit1.rotate();
this.exit2.rotate();
}
}
| 4,823 | 0.598175 | 0.588223 | 162 | 28.771605 | 22.938263 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.574074 | false | false |
5
|
f97f69d3b90bf7277e372d8d76f9d17de33d7ba7
| 19,963,008,044,099 |
ed3685d29f10998f5c6fba99b781eb9db4c3eabe
|
/src/Arrays/arrayinout.java
|
86aa7bdcafaf730fc610ccf9a209ec9ab6ee2daf
|
[] |
no_license
|
Rishabhgoel21/Crux
|
https://github.com/Rishabhgoel21/Crux
|
31e7f65e2c495bf6159cbd94f044b1a793a3e459
|
6d24c6ee013788bf5ff0e45becfaaab8554bcb20
|
refs/heads/master
| 2020-03-23T06:42:50.796000 | 2018-12-30T03:51:53 | 2018-12-30T03:51:53 | 141,225,076 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Arrays;
/**
* @author Rishabh
*/
import java.util.Scanner;
public class arrayinout {
static Scanner scn = new Scanner(System.in);
public static void main(String[] args) {
int[] array = takeinput();
display(array);
}
public static int[] takeinput()
{
System.out.println("Enter Size ");
int n=scn.nextInt();
int[] arr= new int[n];
for(int i=0; i<arr.length;i++)
{
System.out.println("Enter "+ i + "th value");
arr[i]=scn.nextInt();
}
return arr;
}
public static void display(int[] arr)
{
for(int val : arr)
{
System.out.println(val);
}
}
}
|
UTF-8
|
Java
| 612 |
java
|
arrayinout.java
|
Java
|
[
{
"context": "package Arrays;\n/**\n * @author Rishabh\n */\nimport java.util.Scanner;\n\npublic class array",
"end": 38,
"score": 0.9998666644096375,
"start": 31,
"tag": "NAME",
"value": "Rishabh"
}
] | null |
[] |
package Arrays;
/**
* @author Rishabh
*/
import java.util.Scanner;
public class arrayinout {
static Scanner scn = new Scanner(System.in);
public static void main(String[] args) {
int[] array = takeinput();
display(array);
}
public static int[] takeinput()
{
System.out.println("Enter Size ");
int n=scn.nextInt();
int[] arr= new int[n];
for(int i=0; i<arr.length;i++)
{
System.out.println("Enter "+ i + "th value");
arr[i]=scn.nextInt();
}
return arr;
}
public static void display(int[] arr)
{
for(int val : arr)
{
System.out.println(val);
}
}
}
| 612 | 0.601307 | 0.599673 | 41 | 13.95122 | 14.605297 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.682927 | false | false |
5
|
cb0476b91f42e31c3cfcaacb45823167cd9a9b18
| 35,759,897,731,971 |
02093140f1a778cd8da2f393fa2eaedc78f6e17b
|
/src/test/java/com/codurance/Unit/SocialNetworkShould.java
|
32f437957f60cac0d004893be3603bf485b5ebcf
|
[] |
no_license
|
AurelijaZuba/SocialNetworkKata
|
https://github.com/AurelijaZuba/SocialNetworkKata
|
b6d91867b9549dd482812cd3d4f4cf033c7b9852
|
7ad7868c8001eb7f06bc63bae3341640e4d1b212
|
refs/heads/master
| 2020-07-06T14:18:45.753000 | 2019-08-21T08:26:35 | 2019-08-21T08:26:35 | 179,991,502 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.codurance.Unit;
import com.codurance.model.Message;
import com.codurance.model.User;
import com.codurance.repository.MessageRepository;
import com.codurance.repository.UserRepository;
import com.codurance.service.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.LocalDateTime;
import java.time.Month;
import java.util.Collections;
import static java.util.Arrays.asList;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.verify;
public class SocialNetworkShould {
private static final String ALICE_POST_MESSAGE_WITH_TIME_STAMP_OF_FIVE_MINUTES = "Alice - I love the weather today (5 minutes ago)\n";
private static final String MESSAGE_POSTED_BY_ALICE = "I love the weather today (5 minutes ago)\n";
private final LocalDateTime dateTime = LocalDateTime.of(2019, Month.AUGUST, 18, 12, 19);
private static final String ALICE_POST_MESSAGE = "Alice -> I love the weather today";
private static final String BOB_POST_MESSAGE = "Bob -> Damn! We lost!";
private static final String ALICE_WALL = "Alice wall";
private static final String ALICE_USERNAME = "Alice";
private static final String BOB_WALL = "Bob wall";
private MessageRepository messageRepositoryMock;
private SocialConsole consoleMock;
private UserRepository userRepositoryMock;
private LocalClock clockMock;
@BeforeEach
void setUp() {
messageRepositoryMock = mock(MessageRepository.class);
consoleMock = mock(SocialConsole.class);
userRepositoryMock = mock(UserRepository.class);
clockMock = mock(LocalClock.class);
when(clockMock.now()).thenReturn(dateTime);
when(userRepositoryMock.getFollowedUsers(new User("Charlie"))).thenReturn(Collections.singletonList(ALICE_USERNAME));
}
@Test
void add_new_user_when_post_first_message() {
SocialNetwork socialNetwork = new SocialNetwork(messageRepositoryMock, userRepositoryMock, clockMock, consoleMock);
socialNetwork.messageParser(ALICE_POST_MESSAGE);
verify(userRepositoryMock).addNewUser(new User("Alice"));
}
@Test
void post_single_message_for_one_user() {
SocialNetwork socialNetwork = new SocialNetwork(messageRepositoryMock, userRepositoryMock, clockMock, consoleMock);
socialNetwork.messageParser(ALICE_POST_MESSAGE);
given(clockMock.now()).willReturn(dateTime);
verify(messageRepositoryMock).addMessage(new Message(ALICE_USERNAME, "I love the weather today", clockMock.now()));
}
@Test
void return_one_message_from_users_wall() {
MessageRepository messageRepository = new MessageRepository();
SocialNetwork socialNetwork = new SocialNetwork(messageRepository, userRepositoryMock, clockMock, consoleMock);
given(clockMock.calculateTimeDifference(clockMock.now())).willReturn(300);
socialNetwork.messageParser(ALICE_POST_MESSAGE);
socialNetwork.messageParser(ALICE_WALL);
verify(consoleMock).print(ALICE_POST_MESSAGE_WITH_TIME_STAMP_OF_FIVE_MINUTES);
}
@Test
void return_message_for_the_user_requesting_to_that_wall() {
MessageRepository messageRepository = new MessageRepository();
SocialNetwork socialNetwork = new SocialNetwork(messageRepository, userRepositoryMock, clockMock, consoleMock);
given(clockMock.calculateTimeDifference(clockMock.now())).willReturn(120, 300);
socialNetwork.messageParser(BOB_POST_MESSAGE);
socialNetwork.messageParser(BOB_WALL);
verify(consoleMock).print("Bob - Damn! We lost! (2 minutes ago)\n");
socialNetwork.messageParser(ALICE_POST_MESSAGE);
socialNetwork.messageParser(ALICE_WALL);
verify(consoleMock).print(ALICE_POST_MESSAGE_WITH_TIME_STAMP_OF_FIVE_MINUTES);
}
@Test
void return_one_message_with_time_stamp() {
MessageRepository messageRepository = new MessageRepository();
SocialNetwork socialNetwork = new SocialNetwork(messageRepository, userRepositoryMock, clockMock, consoleMock);
given(clockMock.calculateTimeDifference(clockMock.now())).willReturn(300);
socialNetwork.messageParser(ALICE_POST_MESSAGE);
socialNetwork.messageParser(ALICE_USERNAME);
verify(consoleMock).print(MESSAGE_POSTED_BY_ALICE);
}
@Test
void return_two_messages_with_time_stamp() {
MessageRepository messageRepository = new MessageRepository();
SocialNetwork socialNetwork = new SocialNetwork(messageRepository, userRepositoryMock, clockMock, consoleMock);
given(clockMock.calculateTimeDifference(clockMock.now())).willReturn(300, 240);
socialNetwork.messageParser(ALICE_POST_MESSAGE);
socialNetwork.messageParser("Alice -> It's raining!");
socialNetwork.messageParser(ALICE_USERNAME);
verify(consoleMock).print(MESSAGE_POSTED_BY_ALICE);
verify(consoleMock).print("It's raining! (4 minutes ago)\n");
}
@Test
void return_two_messages_with_time_stamp_of_minutes_and_seconds() {
MessageRepository messageRepository = new MessageRepository();
SocialNetwork socialNetwork = new SocialNetwork(messageRepository, userRepositoryMock, clockMock, consoleMock);
given(clockMock.calculateTimeDifference(clockMock.now())).willReturn(5, 240);
socialNetwork.messageParser(ALICE_POST_MESSAGE);
socialNetwork.messageParser("Alice -> It's raining!");
socialNetwork.messageParser(ALICE_USERNAME);
verify(consoleMock).print("I love the weather today (5 seconds ago)\n");
verify(consoleMock).print("It's raining! (4 minutes ago)\n");
}
@Test
void allow_one_user_to_follow_another() {
MessageRepository messageRepository = new MessageRepository();
SocialNetwork socialNetwork = new SocialNetwork(messageRepository, userRepositoryMock, clockMock, consoleMock);
socialNetwork.messageParser("Alice follows Bob");
verify(userRepositoryMock).follow(ALICE_USERNAME, "Bob");
}
@Test
void return_posted_messages_for_users_being_followed() {
MessageRepository messageRepository = new MessageRepository();
SocialNetwork socialNetwork = new SocialNetwork(messageRepository, userRepositoryMock, clockMock, consoleMock);
given(clockMock.calculateTimeDifference(clockMock.now())).willReturn(2, 300);
given(userRepositoryMock.getFollowedUsers(new User("Charlie"))).willReturn(asList(ALICE_USERNAME));
socialNetwork.messageParser(ALICE_POST_MESSAGE);
socialNetwork.messageParser("Charlie -> I'm in New York today! Anyone want to have a coffee?");
socialNetwork.messageParser("Charlie follows Alice");
socialNetwork.messageParser("Charlie wall");
verify(consoleMock).print("Charlie - I'm in New York today! Anyone want to have a coffee? (2 seconds ago)\n");
verify(consoleMock).print(ALICE_POST_MESSAGE_WITH_TIME_STAMP_OF_FIVE_MINUTES);
}
}
|
UTF-8
|
Java
| 7,070 |
java
|
SocialNetworkShould.java
|
Java
|
[
{
"context": "E_POST_MESSAGE_WITH_TIME_STAMP_OF_FIVE_MINUTES = \"Alice - I love the weather today (5 minutes ago)\\n\";\n ",
"end": 683,
"score": 0.9938566088676453,
"start": 678,
"tag": "NAME",
"value": "Alice"
},
{
"context": "private static final String ALICE_POST_MESSAGE = \"Alice -> I love the weather today\";\n private static ",
"end": 987,
"score": 0.9898154735565186,
"start": 982,
"tag": "NAME",
"value": "Alice"
},
{
"context": " private static final String BOB_POST_MESSAGE = \"Bob -> Damn! We lost!\";\n private static final Stri",
"end": 1073,
"score": 0.9539576768875122,
"start": 1070,
"tag": "NAME",
"value": "Bob"
},
{
"context": " private static final String ALICE_USERNAME = \"Alice\";\n private static final String BOB_WALL = \"Bob",
"end": 1208,
"score": 0.6013486981391907,
"start": 1203,
"tag": "USERNAME",
"value": "Alice"
},
{
"context": "hen(userRepositoryMock.getFollowedUsers(new User(\"Charlie\"))).thenReturn(Collections.singletonList(ALICE_US",
"end": 1808,
"score": 0.9971445798873901,
"start": 1801,
"tag": "NAME",
"value": "Charlie"
},
{
"context": " verify(userRepositoryMock).addNewUser(new User(\"Alice\"));\n }\n\n @Test\n void post_single_message",
"end": 2179,
"score": 0.9997138381004333,
"start": 2174,
"tag": "NAME",
"value": "Alice"
},
{
"context": "ser(BOB_WALL);\n verify(consoleMock).print(\"Bob - Damn! We lost! (2 minutes ago)\\n\");\n\n so",
"end": 3646,
"score": 0.9995912909507751,
"start": 3643,
"tag": "NAME",
"value": "Bob"
},
{
"context": "ST_MESSAGE);\n socialNetwork.messageParser(\"Alice -> It's raining!\");\n socialNetwork.message",
"end": 4836,
"score": 0.9835184812545776,
"start": 4831,
"tag": "NAME",
"value": "Alice"
},
{
"context": "ST_MESSAGE);\n socialNetwork.messageParser(\"Alice -> It's raining!\");\n socialNetwork.message",
"end": 5508,
"score": 0.9789589047431946,
"start": 5503,
"tag": "NAME",
"value": "Alice"
},
{
"context": "nsoleMock);\n\n socialNetwork.messageParser(\"Alice follows Bob\");\n\n verify(userRepositoryMock",
"end": 6031,
"score": 0.9964525699615479,
"start": 6026,
"tag": "NAME",
"value": "Alice"
},
{
"context": " socialNetwork.messageParser(\"Alice follows Bob\");\n\n verify(userRepositoryMock).follow(ALI",
"end": 6043,
"score": 0.9984658360481262,
"start": 6040,
"tag": "NAME",
"value": "Bob"
},
{
"context": "erify(userRepositoryMock).follow(ALICE_USERNAME, \"Bob\");\n }\n\n @Test\n void return_posted_messag",
"end": 6110,
"score": 0.8820787668228149,
"start": 6107,
"tag": "NAME",
"value": "Bob"
},
{
"context": "ven(userRepositoryMock.getFollowedUsers(new User(\"Charlie\"))).willReturn(asList(ALICE_USERNAME));\n\n ",
"end": 6537,
"score": 0.9996786713600159,
"start": 6530,
"tag": "NAME",
"value": "Charlie"
},
{
"context": "ST_MESSAGE);\n socialNetwork.messageParser(\"Charlie -> I'm in New York today! Anyone want to have a c",
"end": 6680,
"score": 0.9997579455375671,
"start": 6673,
"tag": "NAME",
"value": "Charlie"
},
{
"context": "a coffee?\");\n socialNetwork.messageParser(\"Charlie follows Alice\");\n socialNetwork.messagePar",
"end": 6784,
"score": 0.9995477199554443,
"start": 6777,
"tag": "NAME",
"value": "Charlie"
},
{
"context": " socialNetwork.messageParser(\"Charlie follows Alice\");\n socialNetwork.messageParser(\"Charlie w",
"end": 6798,
"score": 0.9996254444122314,
"start": 6793,
"tag": "NAME",
"value": "Alice"
},
{
"context": "ows Alice\");\n socialNetwork.messageParser(\"Charlie wall\");\n\n verify(consoleMock).print(\"Charl",
"end": 6846,
"score": 0.9992456436157227,
"start": 6839,
"tag": "NAME",
"value": "Charlie"
},
{
"context": "arlie wall\");\n\n verify(consoleMock).print(\"Charlie - I'm in New York today! Anyone want to have a co",
"end": 6898,
"score": 0.9996832609176636,
"start": 6891,
"tag": "NAME",
"value": "Charlie"
}
] | null |
[] |
package com.codurance.Unit;
import com.codurance.model.Message;
import com.codurance.model.User;
import com.codurance.repository.MessageRepository;
import com.codurance.repository.UserRepository;
import com.codurance.service.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.LocalDateTime;
import java.time.Month;
import java.util.Collections;
import static java.util.Arrays.asList;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.verify;
public class SocialNetworkShould {
private static final String ALICE_POST_MESSAGE_WITH_TIME_STAMP_OF_FIVE_MINUTES = "Alice - I love the weather today (5 minutes ago)\n";
private static final String MESSAGE_POSTED_BY_ALICE = "I love the weather today (5 minutes ago)\n";
private final LocalDateTime dateTime = LocalDateTime.of(2019, Month.AUGUST, 18, 12, 19);
private static final String ALICE_POST_MESSAGE = "Alice -> I love the weather today";
private static final String BOB_POST_MESSAGE = "Bob -> Damn! We lost!";
private static final String ALICE_WALL = "Alice wall";
private static final String ALICE_USERNAME = "Alice";
private static final String BOB_WALL = "Bob wall";
private MessageRepository messageRepositoryMock;
private SocialConsole consoleMock;
private UserRepository userRepositoryMock;
private LocalClock clockMock;
@BeforeEach
void setUp() {
messageRepositoryMock = mock(MessageRepository.class);
consoleMock = mock(SocialConsole.class);
userRepositoryMock = mock(UserRepository.class);
clockMock = mock(LocalClock.class);
when(clockMock.now()).thenReturn(dateTime);
when(userRepositoryMock.getFollowedUsers(new User("Charlie"))).thenReturn(Collections.singletonList(ALICE_USERNAME));
}
@Test
void add_new_user_when_post_first_message() {
SocialNetwork socialNetwork = new SocialNetwork(messageRepositoryMock, userRepositoryMock, clockMock, consoleMock);
socialNetwork.messageParser(ALICE_POST_MESSAGE);
verify(userRepositoryMock).addNewUser(new User("Alice"));
}
@Test
void post_single_message_for_one_user() {
SocialNetwork socialNetwork = new SocialNetwork(messageRepositoryMock, userRepositoryMock, clockMock, consoleMock);
socialNetwork.messageParser(ALICE_POST_MESSAGE);
given(clockMock.now()).willReturn(dateTime);
verify(messageRepositoryMock).addMessage(new Message(ALICE_USERNAME, "I love the weather today", clockMock.now()));
}
@Test
void return_one_message_from_users_wall() {
MessageRepository messageRepository = new MessageRepository();
SocialNetwork socialNetwork = new SocialNetwork(messageRepository, userRepositoryMock, clockMock, consoleMock);
given(clockMock.calculateTimeDifference(clockMock.now())).willReturn(300);
socialNetwork.messageParser(ALICE_POST_MESSAGE);
socialNetwork.messageParser(ALICE_WALL);
verify(consoleMock).print(ALICE_POST_MESSAGE_WITH_TIME_STAMP_OF_FIVE_MINUTES);
}
@Test
void return_message_for_the_user_requesting_to_that_wall() {
MessageRepository messageRepository = new MessageRepository();
SocialNetwork socialNetwork = new SocialNetwork(messageRepository, userRepositoryMock, clockMock, consoleMock);
given(clockMock.calculateTimeDifference(clockMock.now())).willReturn(120, 300);
socialNetwork.messageParser(BOB_POST_MESSAGE);
socialNetwork.messageParser(BOB_WALL);
verify(consoleMock).print("Bob - Damn! We lost! (2 minutes ago)\n");
socialNetwork.messageParser(ALICE_POST_MESSAGE);
socialNetwork.messageParser(ALICE_WALL);
verify(consoleMock).print(ALICE_POST_MESSAGE_WITH_TIME_STAMP_OF_FIVE_MINUTES);
}
@Test
void return_one_message_with_time_stamp() {
MessageRepository messageRepository = new MessageRepository();
SocialNetwork socialNetwork = new SocialNetwork(messageRepository, userRepositoryMock, clockMock, consoleMock);
given(clockMock.calculateTimeDifference(clockMock.now())).willReturn(300);
socialNetwork.messageParser(ALICE_POST_MESSAGE);
socialNetwork.messageParser(ALICE_USERNAME);
verify(consoleMock).print(MESSAGE_POSTED_BY_ALICE);
}
@Test
void return_two_messages_with_time_stamp() {
MessageRepository messageRepository = new MessageRepository();
SocialNetwork socialNetwork = new SocialNetwork(messageRepository, userRepositoryMock, clockMock, consoleMock);
given(clockMock.calculateTimeDifference(clockMock.now())).willReturn(300, 240);
socialNetwork.messageParser(ALICE_POST_MESSAGE);
socialNetwork.messageParser("Alice -> It's raining!");
socialNetwork.messageParser(ALICE_USERNAME);
verify(consoleMock).print(MESSAGE_POSTED_BY_ALICE);
verify(consoleMock).print("It's raining! (4 minutes ago)\n");
}
@Test
void return_two_messages_with_time_stamp_of_minutes_and_seconds() {
MessageRepository messageRepository = new MessageRepository();
SocialNetwork socialNetwork = new SocialNetwork(messageRepository, userRepositoryMock, clockMock, consoleMock);
given(clockMock.calculateTimeDifference(clockMock.now())).willReturn(5, 240);
socialNetwork.messageParser(ALICE_POST_MESSAGE);
socialNetwork.messageParser("Alice -> It's raining!");
socialNetwork.messageParser(ALICE_USERNAME);
verify(consoleMock).print("I love the weather today (5 seconds ago)\n");
verify(consoleMock).print("It's raining! (4 minutes ago)\n");
}
@Test
void allow_one_user_to_follow_another() {
MessageRepository messageRepository = new MessageRepository();
SocialNetwork socialNetwork = new SocialNetwork(messageRepository, userRepositoryMock, clockMock, consoleMock);
socialNetwork.messageParser("Alice follows Bob");
verify(userRepositoryMock).follow(ALICE_USERNAME, "Bob");
}
@Test
void return_posted_messages_for_users_being_followed() {
MessageRepository messageRepository = new MessageRepository();
SocialNetwork socialNetwork = new SocialNetwork(messageRepository, userRepositoryMock, clockMock, consoleMock);
given(clockMock.calculateTimeDifference(clockMock.now())).willReturn(2, 300);
given(userRepositoryMock.getFollowedUsers(new User("Charlie"))).willReturn(asList(ALICE_USERNAME));
socialNetwork.messageParser(ALICE_POST_MESSAGE);
socialNetwork.messageParser("Charlie -> I'm in New York today! Anyone want to have a coffee?");
socialNetwork.messageParser("Charlie follows Alice");
socialNetwork.messageParser("Charlie wall");
verify(consoleMock).print("Charlie - I'm in New York today! Anyone want to have a coffee? (2 seconds ago)\n");
verify(consoleMock).print(ALICE_POST_MESSAGE_WITH_TIME_STAMP_OF_FIVE_MINUTES);
}
}
| 7,070 | 0.728571 | 0.722489 | 164 | 42.109756 | 37.912769 | 138 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.786585 | false | false |
5
|
b522eb7c47deceb6d00926d5720f89fdc07b4816
| 36,550,171,730,218 |
2da410118e35edf53d9d21314f8bcc203995acd6
|
/javaproject/src/main/java/uk/co/explore/MontyHall.java
|
bc5bfd2fcb779b3ea35727345292fd98884edf27
|
[] |
no_license
|
senthil-repo/explore
|
https://github.com/senthil-repo/explore
|
47161f83213cf20ee0bf0e7f61d89c125e4ede0e
|
6571a9c2a6b8fde83b8df18f66cc4c312cbc34cc
|
refs/heads/master
| 2023-04-02T04:36:31.971000 | 2020-05-23T10:33:59 | 2020-05-23T10:33:59 | 266,306,280 | 0 | 0 | null | false | 2020-10-13T22:13:52 | 2020-05-23T09:42:59 | 2020-05-23T10:34:09 | 2020-10-13T22:13:50 | 6 | 0 | 0 | 1 |
Java
| false | false |
package uk.co.explore;
import java.util.Random;
import java.util.stream.IntStream;
/**
* Created by s.nathan on 22/05/2020.
To build a model, we need to run the program 'n' times, to find the probabilities of
winning the game under the following cases:
1) Player choosen to stick with his initial choice
2) Player change his mind and choose a second choice.
By choosing random numbers for playerDoor, hostDoor & carDoor during each run, we can able to find the percentage
of which the above scenarios are played. From the above, we can able to advise anyone on whether to stick
with original choice or to go for second choice of choosing a door.
*/
public class MontyHall {
public static void main(String[] args) {
int noOfTimesToRun = 10000;
System.out.println(" To find the probability, lets run the program for " + noOfTimesToRun + " times ");
getChancesOfWinning(noOfTimesToRun);
}
private static void getChancesOfWinning(int noOfTimesToRun) {
Random random = new Random();
int doorArray[] = {1, 2, 3};
double firstChoiceCounter = 0;
double secondChoiceCounter = 0;
for (int i = 0; i < noOfTimesToRun; i++) {
//randomly find the door behind which the car is located
int carBehindDoor = random.nextInt(3) + 1;
//radomly find the door which a player can choose initially
int playerChoosenDoor = random.nextInt(3) + 1;
final int playerChoosenDoor_lambda = playerChoosenDoor;
int remainingDoors[] = IntStream.of(doorArray).filter(value -> value != playerChoosenDoor_lambda).toArray();
//radomly find the host picking door
int hostPickupDoor = random.nextBoolean() ? remainingDoors[0] : remainingDoors[1];
//note : if the player already choose a door which has got goat, then HOST will choose only the door which has
//got other goat
if (playerChoosenDoor != carBehindDoor) {
hostPickupDoor = IntStream.of(remainingDoors).filter(value -> value != playerChoosenDoor_lambda && value != carBehindDoor).findFirst().getAsInt();
}
int secondChoiceDoor = remainingDoors[0] != hostPickupDoor ? remainingDoors[0] : remainingDoors[1];
//give a chance for the player to swap the options
boolean hasSecondChoiceChoosen = random.nextBoolean();
playerChoosenDoor = hasSecondChoiceChoosen ? secondChoiceDoor : playerChoosenDoor;
StringBuilder builder = new StringBuilder();
builder.append("Player choosen door : ").append(playerChoosenDoor).append(", Remaining doors : ").append(remainingDoors[0] + " & " + remainingDoors[1]).
append(", Host pickup door : ").append(hostPickupDoor).append(", Second choice door :").append(secondChoiceDoor).append(", Car behind door :").
append(carBehindDoor).append(", Final door choosen by player : ").append(playerChoosenDoor);
//System.out.println(builder.toString());
if (playerChoosenDoor == carBehindDoor) {
if (!hasSecondChoiceChoosen)
firstChoiceCounter++;
else
secondChoiceCounter++;
}
}
double firstChoicePercentage = (firstChoiceCounter / noOfTimesToRun) * 100;
double secondChoicePercentage = (secondChoiceCounter / noOfTimesToRun) * 100;
System.out.println("FirstChoicePercentage :" + firstChoicePercentage + "%");
System.out.println("SecondChoicePercentage :" + secondChoicePercentage + "%");
System.out.println("");
StringBuilder result = new StringBuilder();
System.out.println(" ******* R E S U L T ******* ");
String message = " By running the program for " + noOfTimesToRun + " times, we can find that it is better to ";
result.append(message).append(firstChoicePercentage > secondChoicePercentage ? "stick with the original choice. "
: "change your mind and go for the second choice. ").toString();
System.out.println(result.toString());
}
}
|
UTF-8
|
Java
| 4,173 |
java
|
MontyHall.java
|
Java
|
[
{
"context": "ort java.util.stream.IntStream;\n\n/**\n * Created by s.nathan on 22/05/2020.\n To build a model, we need to run ",
"end": 111,
"score": 0.97648024559021,
"start": 103,
"tag": "USERNAME",
"value": "s.nathan"
}
] | null |
[] |
package uk.co.explore;
import java.util.Random;
import java.util.stream.IntStream;
/**
* Created by s.nathan on 22/05/2020.
To build a model, we need to run the program 'n' times, to find the probabilities of
winning the game under the following cases:
1) Player choosen to stick with his initial choice
2) Player change his mind and choose a second choice.
By choosing random numbers for playerDoor, hostDoor & carDoor during each run, we can able to find the percentage
of which the above scenarios are played. From the above, we can able to advise anyone on whether to stick
with original choice or to go for second choice of choosing a door.
*/
public class MontyHall {
public static void main(String[] args) {
int noOfTimesToRun = 10000;
System.out.println(" To find the probability, lets run the program for " + noOfTimesToRun + " times ");
getChancesOfWinning(noOfTimesToRun);
}
private static void getChancesOfWinning(int noOfTimesToRun) {
Random random = new Random();
int doorArray[] = {1, 2, 3};
double firstChoiceCounter = 0;
double secondChoiceCounter = 0;
for (int i = 0; i < noOfTimesToRun; i++) {
//randomly find the door behind which the car is located
int carBehindDoor = random.nextInt(3) + 1;
//radomly find the door which a player can choose initially
int playerChoosenDoor = random.nextInt(3) + 1;
final int playerChoosenDoor_lambda = playerChoosenDoor;
int remainingDoors[] = IntStream.of(doorArray).filter(value -> value != playerChoosenDoor_lambda).toArray();
//radomly find the host picking door
int hostPickupDoor = random.nextBoolean() ? remainingDoors[0] : remainingDoors[1];
//note : if the player already choose a door which has got goat, then HOST will choose only the door which has
//got other goat
if (playerChoosenDoor != carBehindDoor) {
hostPickupDoor = IntStream.of(remainingDoors).filter(value -> value != playerChoosenDoor_lambda && value != carBehindDoor).findFirst().getAsInt();
}
int secondChoiceDoor = remainingDoors[0] != hostPickupDoor ? remainingDoors[0] : remainingDoors[1];
//give a chance for the player to swap the options
boolean hasSecondChoiceChoosen = random.nextBoolean();
playerChoosenDoor = hasSecondChoiceChoosen ? secondChoiceDoor : playerChoosenDoor;
StringBuilder builder = new StringBuilder();
builder.append("Player choosen door : ").append(playerChoosenDoor).append(", Remaining doors : ").append(remainingDoors[0] + " & " + remainingDoors[1]).
append(", Host pickup door : ").append(hostPickupDoor).append(", Second choice door :").append(secondChoiceDoor).append(", Car behind door :").
append(carBehindDoor).append(", Final door choosen by player : ").append(playerChoosenDoor);
//System.out.println(builder.toString());
if (playerChoosenDoor == carBehindDoor) {
if (!hasSecondChoiceChoosen)
firstChoiceCounter++;
else
secondChoiceCounter++;
}
}
double firstChoicePercentage = (firstChoiceCounter / noOfTimesToRun) * 100;
double secondChoicePercentage = (secondChoiceCounter / noOfTimesToRun) * 100;
System.out.println("FirstChoicePercentage :" + firstChoicePercentage + "%");
System.out.println("SecondChoicePercentage :" + secondChoicePercentage + "%");
System.out.println("");
StringBuilder result = new StringBuilder();
System.out.println(" ******* R E S U L T ******* ");
String message = " By running the program for " + noOfTimesToRun + " times, we can find that it is better to ";
result.append(message).append(firstChoicePercentage > secondChoicePercentage ? "stick with the original choice. "
: "change your mind and go for the second choice. ").toString();
System.out.println(result.toString());
}
}
| 4,173 | 0.652528 | 0.643422 | 84 | 48.67857 | 42.731209 | 166 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.607143 | false | false |
5
|
b2f489f2d5c8d68a5dc1436e5ffe540839d6a4b4
| 38,259,568,704,236 |
4ae8fc4264ee39b55b6b7f4d9ab672ea10eb5a32
|
/src/main/java/com/wql/controller/ListController.java
|
6fa910581565df67eb998c4f4d04675c51cf31ec
|
[] |
no_license
|
weiqilong/wql-love-web
|
https://github.com/weiqilong/wql-love-web
|
5c8a46ae78dc0a4002e254f9afc4caffec72649d
|
db4383724c0ab1ffa94b79ceef5b1eeec4a2bb54
|
refs/heads/master
| 2018-12-19T06:11:30.507000 | 2018-10-31T08:18:48 | 2018-10-31T08:18:48 | 148,727,872 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.wql.controller;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.wql.config.ListIdMappingConfig;
import com.wql.index.service.IndexService;
import com.wql.pojo.TbNewsOnline;
/**
* 文章列表
* @author weiqilong
* CREATE TIME 2018年9月20日 下午4:26:15
*/
@RestController
@RequestMapping("/list")
public class ListController {
private static final Log logger = LogFactory.getLog(ListController.class);
@Autowired
private IndexService indexService;
/**
*
* @author weiqilong
* CREATE TIME 2018年10月23日 下午5:12:18
* @param listNum 栏目id
* @return
*/
@RequestMapping("/{listName}/{listNum}")
public ModelAndView toListHtml(@PathVariable("listNum")Integer listNum){
ModelAndView mav = new ModelAndView("xinjing/list");
//int classId = ListIdMappingConfig.getListIdMapping(listNum);
List<TbNewsOnline> titleList = indexService.getWenZhangListByListId(listNum);
List<TbNewsOnline> rankList = indexService.getColumnRankList(listNum);
mav.addObject("titleList", titleList);
mav.addObject("rankList", rankList);
mav.addObject("classid", listNum);
return mav;
}
}
|
UTF-8
|
Java
| 1,551 |
java
|
ListController.java
|
Java
|
[
{
"context": "wql.pojo.TbNewsOnline;\r\n\r\n/**\r\n * 文章列表\r\n * @author weiqilong\r\n * CREATE TIME 2018年9月20日 下午4:26:15\r\n */\r\n@RestC",
"end": 613,
"score": 0.9994321465492249,
"start": 604,
"tag": "USERNAME",
"value": "weiqilong"
},
{
"context": "xService indexService;\r\n\t\r\n\t/**\r\n\t * \r\n\t * @author weiqilong\r\n\t * CREATE TIME 2018年10月23日 下午5:12:18\r\n\t * @para",
"end": 897,
"score": 0.9993346333503723,
"start": 888,
"tag": "USERNAME",
"value": "weiqilong"
}
] | null |
[] |
package com.wql.controller;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.wql.config.ListIdMappingConfig;
import com.wql.index.service.IndexService;
import com.wql.pojo.TbNewsOnline;
/**
* 文章列表
* @author weiqilong
* CREATE TIME 2018年9月20日 下午4:26:15
*/
@RestController
@RequestMapping("/list")
public class ListController {
private static final Log logger = LogFactory.getLog(ListController.class);
@Autowired
private IndexService indexService;
/**
*
* @author weiqilong
* CREATE TIME 2018年10月23日 下午5:12:18
* @param listNum 栏目id
* @return
*/
@RequestMapping("/{listName}/{listNum}")
public ModelAndView toListHtml(@PathVariable("listNum")Integer listNum){
ModelAndView mav = new ModelAndView("xinjing/list");
//int classId = ListIdMappingConfig.getListIdMapping(listNum);
List<TbNewsOnline> titleList = indexService.getWenZhangListByListId(listNum);
List<TbNewsOnline> rankList = indexService.getColumnRankList(listNum);
mav.addObject("titleList", titleList);
mav.addObject("rankList", rankList);
mav.addObject("classid", listNum);
return mav;
}
}
| 1,551 | 0.757077 | 0.740619 | 48 | 29.645834 | 24.033388 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.166667 | false | false |
5
|
11c1b8705e418b925330c90760b7c501038c2d1e
| 36,850,819,438,326 |
f02d9447ddd4ea77c1c54b3cb0dd1fb6051980b5
|
/SuperRisikoland/src/cui/Land.java
|
1f4e27ce99852f083a35608b5d6c38df3c9f0e95
|
[] |
no_license
|
mellmers/SuperRisikoland
|
https://github.com/mellmers/SuperRisikoland
|
e45312f12ecc0e4e5f8704729d765a40378ba5d6
|
ab13c5b488e1bdc954130791613dddbeb50a5670
|
refs/heads/master
| 2020-12-30T09:38:10.879000 | 2014-07-16T13:21:15 | 2014-07-16T13:21:15 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package cui;
import inf.KontinentInterface;
import inf.LandInterface;
import inf.SpielerInterface;
import java.awt.Color;
import java.io.Serializable;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Vector;
public class Land extends UnicastRemoteObject implements Serializable, LandInterface
{
private KontinentInterface kontinent;
private String name;
private String einheit;
private int truppenStaerke;
private SpielerInterface besitzer;
private LandInterface [] nachbarLaender;
private int benutzteEinheiten = 0;
private Color farbcode;
public Land(KontinentInterface kontinent, String name, String einheit, int anzahlNachbarLaender, Color farbe) throws RemoteException
{
this.kontinent = kontinent;
this.name = name;
this.einheit = einheit;
this.nachbarLaender = new Land[anzahlNachbarLaender];
this.farbcode = farbe;
}
// Getter
public String getName()
{
return this.name;
}
public int getTruppenstaerke()
{
return this.truppenStaerke;
}
public SpielerInterface getBesitzer()
{
return this.besitzer;
}
public String getEinheit()
{
return this.einheit;
}
public KontinentInterface getKontinent()
{
return kontinent;
}
// Setter
public void setTruppenstaerke(int menge)
{
this.truppenStaerke += menge;
}
public void setTruppenstaerkeStandard(int menge)
{
this.truppenStaerke = menge;
}
public void setBesitzer(SpielerInterface s)
{
this.besitzer = s;
}
public void setNachbarLand(int landId, LandInterface land)
{
this.nachbarLaender[landId] = land;
}
// Funktionen
public boolean istNachbar(LandInterface n) throws RemoteException
{
for(int i = 0; i < this.nachbarLaender.length; i++)
{
if(n.getName().equals(this.nachbarLaender[i].getName()))
{
return true;
}
}
return false;
}
public int getBenutzteEinheiten() {
return benutzteEinheiten;
}
public void erhoeheBenutzteEinheiten(int benutzteEinheiten) {
this.benutzteEinheiten += benutzteEinheiten;
}
public void setBenutzteEinheiten(int benutzteEinheiten)
{
this.benutzteEinheiten = benutzteEinheiten;
}
public Color getFarbcode()
{
return farbcode;
}
}
|
UTF-8
|
Java
| 2,198 |
java
|
Land.java
|
Java
|
[] | null |
[] |
package cui;
import inf.KontinentInterface;
import inf.LandInterface;
import inf.SpielerInterface;
import java.awt.Color;
import java.io.Serializable;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Vector;
public class Land extends UnicastRemoteObject implements Serializable, LandInterface
{
private KontinentInterface kontinent;
private String name;
private String einheit;
private int truppenStaerke;
private SpielerInterface besitzer;
private LandInterface [] nachbarLaender;
private int benutzteEinheiten = 0;
private Color farbcode;
public Land(KontinentInterface kontinent, String name, String einheit, int anzahlNachbarLaender, Color farbe) throws RemoteException
{
this.kontinent = kontinent;
this.name = name;
this.einheit = einheit;
this.nachbarLaender = new Land[anzahlNachbarLaender];
this.farbcode = farbe;
}
// Getter
public String getName()
{
return this.name;
}
public int getTruppenstaerke()
{
return this.truppenStaerke;
}
public SpielerInterface getBesitzer()
{
return this.besitzer;
}
public String getEinheit()
{
return this.einheit;
}
public KontinentInterface getKontinent()
{
return kontinent;
}
// Setter
public void setTruppenstaerke(int menge)
{
this.truppenStaerke += menge;
}
public void setTruppenstaerkeStandard(int menge)
{
this.truppenStaerke = menge;
}
public void setBesitzer(SpielerInterface s)
{
this.besitzer = s;
}
public void setNachbarLand(int landId, LandInterface land)
{
this.nachbarLaender[landId] = land;
}
// Funktionen
public boolean istNachbar(LandInterface n) throws RemoteException
{
for(int i = 0; i < this.nachbarLaender.length; i++)
{
if(n.getName().equals(this.nachbarLaender[i].getName()))
{
return true;
}
}
return false;
}
public int getBenutzteEinheiten() {
return benutzteEinheiten;
}
public void erhoeheBenutzteEinheiten(int benutzteEinheiten) {
this.benutzteEinheiten += benutzteEinheiten;
}
public void setBenutzteEinheiten(int benutzteEinheiten)
{
this.benutzteEinheiten = benutzteEinheiten;
}
public Color getFarbcode()
{
return farbcode;
}
}
| 2,198 | 0.748863 | 0.747953 | 109 | 19.165138 | 21.94301 | 133 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.53211 | false | false |
5
|
06b7dda6ab129d660b3dde4138109c70ea70db9e
| 35,330,401,026,669 |
bdc6b1b0005e0fe4993b92d997a5fbc0609447e0
|
/codes/04/01_方法操作/MethodDemo.java
|
13ce0fc9080a3105e000872f853279c7c7a79065
|
[] |
no_license
|
wdqiOS/javaStudy
|
https://github.com/wdqiOS/javaStudy
|
017640135037b160d98efd560fa1e704242cc595
|
355f70d8217c4546eb852c0526b3ebe21b8e00a9
|
refs/heads/master
| 2022-11-04T12:07:00.583000 | 2020-06-23T02:40:42 | 2020-06-23T02:40:42 | 263,803,338 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class MethodDemo {
/*
方法格式:
[修饰符] 返回值的类型 方法名称([形式参数,...]){
方法体;
[return 值];
}
方法必须调用才能生效(看着菜单点菜)
如果方法使用了static修饰:
使用方法所在类的名称.方法名(参数)
如果方法没有使用static修饰:
使用方法所在类的对象调用
方法定义的位置:
1)在类中定义,在Java中最小的程序单元是类。
2)方法定义在其他方法之外,方法和方法是兄弟关系。
3)方法定义的先后顺序不影响
main方法专门有JVM负责调用,我们只负责启动JVM
方法中的术语:
修饰符:public,static等,static表示方法属于类,直接使用类名调用即可,现在都使用static修饰
返回值类型:方法其实是在完成一个功能,该功能操作完成之后,是否需要给调用者返回一个结果。
如果不需要给调用者返回结果,此时使用关键字void来声明,无返回的意思。
方法名称:遵循标识符的规范,使用动词表示,首字母小写。若是多个单词组成,使用驼峰表示法,以后每一个单词首字母都大写,例如:getEmployeeName.
形式参数:方法圆括号中的变量,仅仅只是占位而已,参数的名称其实无所谓。形式参数可以有多个。
参数列表:参数列表 == 参数的类型 + 参数的个数 + 参数的顺序。
方法签名:方法签名 == 方法名称 + 方法参数列表;
在同一个类中,方法签名是唯一的,否则,编译报错。
方法体:方法的{}中的代码,表示具体完成该功能的代码。
返回值:在方法内部,使用return关键字;
功能1:给调用者返回一个结果值,此时该方法不能使用void修饰。
功能2:结束当前方法
实际参数:调用者在调用某一个具体方法的时候,实际传递的参数值。
方法的调用者:在哪里调用某一个方法,那么哪里就是该方法的调用者。
如何定义方法:
1)到底需要定义什么功能方法。
2)是否需要定义返回值类型
如果不需要返回结果数据,此时使用void声明(无返回)
如果需要返回一个结果数据,我们就把该结果数据的类型作为该方法的返回值类型。
例子:
打印操作:在乎的是方法执行的过程,而不是结果,所以此时使用void声明
求两个数之和:在乎方法执行的过程,并且执行完毕之后,需要给调用者一个反馈。
3)是否需要形式参数
该方法在完成该功能的过程之中,是否有未知的因素参与,如果有请作为参数传递,如果没有,则没有形参。
例子:
求两个数之和:这两个数到底是多少,其实对于方法来说,是未知的,仅仅是调用者知道,而且不同的调用者传递不同的参数值。
*/
// 把共同的200行代码,抽离到方法中
// 无参无返回
static void doWork() {
System.out.println("共同的200行代码");
}
public static void main(String[] args) {
System.out.println("代码片段A");
MethodDemo.doWork(); // 调用方法
System.out.println("代码片段C");
MethodDemo.doWork(); // 调用方法
System.out.println("代码片段C");
MethodDemo.doWork(); // 调用方法
}
}
|
UTF-8
|
Java
| 3,977 |
java
|
MethodDemo.java
|
Java
|
[] | null |
[] |
public class MethodDemo {
/*
方法格式:
[修饰符] 返回值的类型 方法名称([形式参数,...]){
方法体;
[return 值];
}
方法必须调用才能生效(看着菜单点菜)
如果方法使用了static修饰:
使用方法所在类的名称.方法名(参数)
如果方法没有使用static修饰:
使用方法所在类的对象调用
方法定义的位置:
1)在类中定义,在Java中最小的程序单元是类。
2)方法定义在其他方法之外,方法和方法是兄弟关系。
3)方法定义的先后顺序不影响
main方法专门有JVM负责调用,我们只负责启动JVM
方法中的术语:
修饰符:public,static等,static表示方法属于类,直接使用类名调用即可,现在都使用static修饰
返回值类型:方法其实是在完成一个功能,该功能操作完成之后,是否需要给调用者返回一个结果。
如果不需要给调用者返回结果,此时使用关键字void来声明,无返回的意思。
方法名称:遵循标识符的规范,使用动词表示,首字母小写。若是多个单词组成,使用驼峰表示法,以后每一个单词首字母都大写,例如:getEmployeeName.
形式参数:方法圆括号中的变量,仅仅只是占位而已,参数的名称其实无所谓。形式参数可以有多个。
参数列表:参数列表 == 参数的类型 + 参数的个数 + 参数的顺序。
方法签名:方法签名 == 方法名称 + 方法参数列表;
在同一个类中,方法签名是唯一的,否则,编译报错。
方法体:方法的{}中的代码,表示具体完成该功能的代码。
返回值:在方法内部,使用return关键字;
功能1:给调用者返回一个结果值,此时该方法不能使用void修饰。
功能2:结束当前方法
实际参数:调用者在调用某一个具体方法的时候,实际传递的参数值。
方法的调用者:在哪里调用某一个方法,那么哪里就是该方法的调用者。
如何定义方法:
1)到底需要定义什么功能方法。
2)是否需要定义返回值类型
如果不需要返回结果数据,此时使用void声明(无返回)
如果需要返回一个结果数据,我们就把该结果数据的类型作为该方法的返回值类型。
例子:
打印操作:在乎的是方法执行的过程,而不是结果,所以此时使用void声明
求两个数之和:在乎方法执行的过程,并且执行完毕之后,需要给调用者一个反馈。
3)是否需要形式参数
该方法在完成该功能的过程之中,是否有未知的因素参与,如果有请作为参数传递,如果没有,则没有形参。
例子:
求两个数之和:这两个数到底是多少,其实对于方法来说,是未知的,仅仅是调用者知道,而且不同的调用者传递不同的参数值。
*/
// 把共同的200行代码,抽离到方法中
// 无参无返回
static void doWork() {
System.out.println("共同的200行代码");
}
public static void main(String[] args) {
System.out.println("代码片段A");
MethodDemo.doWork(); // 调用方法
System.out.println("代码片段C");
MethodDemo.doWork(); // 调用方法
System.out.println("代码片段C");
MethodDemo.doWork(); // 调用方法
}
}
| 3,977 | 0.535358 | 0.528714 | 73 | 27.876713 | 21.282152 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.136986 | false | false |
5
|
ba03270395eba0784d20abdf0064c6853f622264
| 39,324,720,577,510 |
adac4ae0024bcd095056fdc9e8d16c7e90fb7652
|
/hq-web/src/main/java/org/hyperic/hq/ui/action/resource/common/monitor/alerts/config/PortalAction.java
|
1d54335f4d1c8b9d6d71b043db17bc82316c0006
|
[
"Unlicense"
] |
permissive
|
cc14514/hq6
|
https://github.com/cc14514/hq6
|
3f78097e63f611f8f36db8a6c9cc91127ca7b7fa
|
e6ffd0106cbc03d228487ccaa31da39302114399
|
refs/heads/master
| 2016-09-15T21:56:58.160000 | 2013-07-31T09:28:15 | 2013-07-31T09:28:15 | 11,783,584 | 1 | 1 | null | false | 2016-03-10T23:43:33 | 2013-07-31T05:52:40 | 2013-11-27T17:45:22 | 2016-03-10T00:08:36 | 125,172 | 0 | 1 | 0 |
Java
| null | null |
/*
* NOTE: This copyright does *not* cover user programs that use HQ
* program services by normal system calls through the application
* program interfaces provided as part of the Hyperic Plug-in Development
* Kit or the Hyperic Client Development Kit - this is merely considered
* normal use of the program, and does *not* fall under the heading of
* "derived work".
*
* Copyright (C) [2004, 2005, 2006], Hyperic, Inc.
* This file is part of HQ.
*
* HQ is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*/
package org.hyperic.hq.ui.action.resource.common.monitor.alerts.config;
import java.util.HashMap;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hyperic.hq.appdef.shared.AppdefEntityID;
import org.hyperic.hq.appdef.shared.AppdefEntityTypeID;
import org.hyperic.hq.bizapp.shared.AppdefBoss;
import org.hyperic.hq.bizapp.shared.AuthzBoss;
import org.hyperic.hq.bizapp.shared.ControlBoss;
import org.hyperic.hq.bizapp.shared.EventsBoss;
import org.hyperic.hq.events.shared.AlertDefinitionValue;
import org.hyperic.hq.ui.Constants;
import org.hyperic.hq.ui.Portal;
import org.hyperic.hq.ui.Portlet;
import org.hyperic.hq.ui.action.resource.ResourceController;
import org.hyperic.hq.ui.action.resource.common.monitor.alerts.AlertDefUtil;
import org.hyperic.hq.ui.exception.ParameterNotFoundException;
import org.hyperic.hq.ui.util.ActionUtils;
import org.hyperic.hq.ui.util.BizappUtils;
import org.hyperic.hq.ui.util.RequestUtils;
import org.hyperic.hq.ui.util.SessionUtils;
import org.springframework.beans.factory.annotation.Autowired;
/**
* A dispatcher for the alerts portal.
*
*/
public class PortalAction
extends ResourceController {
private final Log log = LogFactory.getLog(PortalAction.class.getName());
protected final Properties keyMethodMap = new Properties();
protected EventsBoss eventsBoss;
@Autowired
public PortalAction(AppdefBoss appdefBoss, AuthzBoss authzBoss, ControlBoss controlBoss, EventsBoss eventsBoss) {
super(appdefBoss, authzBoss, controlBoss);
this.eventsBoss = eventsBoss;
initKeyMethodMap();
}
protected Properties getKeyMethodMap() {
return keyMethodMap;
}
private void initKeyMethodMap() {
keyMethodMap.setProperty(Constants.MODE_LIST, "listDefinitions");
keyMethodMap.setProperty(Constants.MODE_NEW, "newDefinition");
keyMethodMap.setProperty(Constants.MODE_VIEW, "listDefinitions");
keyMethodMap.setProperty("viewDefinition", "viewEscalation");
}
/**
* We override this in case the resource has been deleted ... simply ignore
* that fact.
*/
protected AppdefEntityID setResource(HttpServletRequest request, HttpServletResponse response) throws Exception {
try {
return super.setResource(request, response);
} catch (ParameterNotFoundException e) {
log.warn("No resource found.");
}
return null;
}
private void setTitle(HttpServletRequest request, Portal portal, String titleName) throws Exception {
AppdefEntityID aeid;
try {
aeid = RequestUtils.getEntityTypeId(request);
} catch (ParameterNotFoundException e) {
aeid = RequestUtils.getEntityId(request);
}
titleName = BizappUtils.replacePlatform(titleName, aeid);
portal.setName(titleName);
// if there's an alert definition available, set our second
// title parameter to its name
try {
int sessionId = RequestUtils.getSessionId(request).intValue();
AlertDefinitionValue adv = AlertDefUtil.getAlertDefinition(request, sessionId, eventsBoss);
request.setAttribute(Constants.TITLE_PARAM2_ATTR, adv.getName());
} catch (ParameterNotFoundException e) {
// it's okay
log.trace("couldn't find alert definition: " + e.getMessage());
}
}
public ActionForward newDefinition(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
setResource(request, response);
Portal portal = Portal.createPortal();
setTitle(request, portal, "alert.config.platform.edit.NewAlertDef.Title");
portal.addPortlet(new Portlet(".events.config.new"), 1);
portal.setDialog(true);
request.setAttribute(Constants.PORTAL_KEY, portal);
System.out.println("====================================================================");
System.out.println(request.getParameter("metrics"));
System.out.println(request.getAttribute("metrics"));
System.out.println("====================================================================");
return null;
}
public ActionForward editProperties(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
setResource(request, response);
Portal portal = Portal.createPortal();
setTitle(request, portal, "alert.config.platform.edit.page.Title");
portal.addPortlet(new Portlet(".events.config.edit.properties"), 1);
portal.setDialog(true);
request.setAttribute(Constants.PORTAL_KEY, portal);
return null;
}
public ActionForward editConditions(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
setResource(request, response);
Portal portal = Portal.createPortal();
setTitle(request, portal, "alert.config.platform.edit.condition.Title");
portal.addPortlet(new Portlet(".events.config.edit.conditions"), 1);
portal.setDialog(true);
request.setAttribute(Constants.PORTAL_KEY, portal);
return null;
}
public ActionForward editControlAction(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
setResource(request, response);
Portal portal = Portal.createPortal();
setTitle(request, portal, "alerts.config.platform.EditControlAction.Title");
portal.addPortlet(new Portlet(".events.config.edit.controlaction"), 1);
portal.setDialog(true);
request.setAttribute(Constants.PORTAL_KEY, portal);
return null;
}
public ActionForward editSyslogAction(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
setResource(request, response);
Portal portal = Portal.createPortal();
setTitle(request, portal, "alerts.config.platform.EditSyslogAction.Title");
portal.addPortlet(new Portlet(".events.config.edit.syslogaction"), 1);
portal.setDialog(true);
request.setAttribute(Constants.PORTAL_KEY, portal);
return null;
}
public ActionForward viewOthers(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
setResource(request, response);
Portal portal = Portal.createPortal();
setTitle(request, portal, "alert.config.platform.props.ViewDef.email.Title");
portal.addPortlet(new Portlet(".events.config.view.others"), 1);
// JW - this shouldn't be a dialog ... portal.setDialog(true);
request.setAttribute(Constants.PORTAL_KEY, portal);
return null;
}
public ActionForward viewUsers(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
setResource(request, response);
Portal portal = Portal.createPortal();
setTitle(request, portal, "alert.config.platform.props.ViewDef.users.Title");
portal.addPortlet(new Portlet(".events.config.view.users"), 1);
// JW - this shouldn't be a dialog ... portal.setDialog(true);
request.setAttribute(Constants.PORTAL_KEY, portal);
return null;
}
public ActionForward viewEscalation(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
setResource(request, response);
Portal portal = Portal.createPortal();
setTitle(request, portal, "alert.config.platform.props.ViewDef.escalation.Title");
portal.addPortlet(new Portlet(".events.config.view.escalation"), 1);
request.setAttribute(Constants.PORTAL_KEY, portal);
return null;
}
public ActionForward viewOpenNMS(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
setResource(request, response);
Portal portal = Portal.createPortal();
setTitle(request, portal, "alert.config.platform.props.ViewDef.openNMS.Title");
portal.addPortlet(new Portlet(".events.config.view.opennms"), 1);
request.setAttribute(Constants.PORTAL_KEY, portal);
return null;
}
public ActionForward monitorConfigureAlerts(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
setResource(request, response);
Portal portal = Portal.createPortal();
portal.addPortlet(new Portlet(".events.config.list"), 1);
portal.setDialog(false);
request.setAttribute(Constants.PORTAL_KEY, portal);
return null;
}
public ActionForward listDefinitions(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
AppdefEntityID aeid = setResource(request, response);
setNavMapLocation(request, mapping, Constants.ALERT_CONFIG_LOC);
// clean out the return path
SessionUtils.resetReturnPath(request.getSession());
// set the return path
try {
setReturnPath(request, mapping);
} catch (ParameterNotFoundException pne) {
log.debug(pne);
}
Portal portal = Portal.createPortal();
setTitle(request, portal, "alerts.config.platform.DefinitionList.Title");
portal.setDialog(false);
try {
RequestUtils.getStringParameter(request, Constants.APPDEF_RES_TYPE_ID);
portal.addPortlet(new Portlet(".admin.alerts.List"), 1);
} catch (ParameterNotFoundException e) {
if (aeid != null && aeid.isGroup()) {
portal.addPortlet(new Portlet(".events.group.config.list"), 1);
} else {
portal.addPortlet(new Portlet(".events.config.list"), 1);
}
}
request.setAttribute(Constants.PORTAL_KEY, portal);
return null;
}
public ActionForward addUsers(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
setResource(request, response);
Portal portal = Portal.createPortal();
setTitle(request, portal, "alerts.config.platform.AssignUsersToAlertDefinition.Title");
portal.addPortlet(new Portlet(".events.config.addusers"), 1);
portal.setDialog(false);
request.setAttribute(Constants.PORTAL_KEY, portal);
return null;
}
public ActionForward addOthers(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
setResource(request, response);
Portal portal = Portal.createPortal();
setTitle(request, portal, "alerts.config.platform.AssignOthersToAlertDefinition.Title");
portal.addPortlet(new Portlet(".events.config.addothers"), 1);
portal.setDialog(false);
request.setAttribute(Constants.PORTAL_KEY, portal);
return null;
}
/**
* This sets the return path for a ResourceAction by appending the type and
* resource id to the forward url.
*
* @param request The current controller's request.
* @param mapping The current controller's mapping that contains the input.
*
* @exception ParameterNotFoundException if the type or id are not found
* @exception ServletException If there is not input defined for this form
*/
protected void setReturnPath(HttpServletRequest request, ActionMapping mapping) throws Exception {
HashMap<String, Object> parms = new HashMap<String, Object>();
AppdefEntityID aeid = RequestUtils.getEntityId(request);
parms.put(Constants.RESOURCE_PARAM, aeid.getId());
parms.put(Constants.RESOURCE_TYPE_ID_PARAM, new Integer(aeid.getType()));
try {
Integer ad = RequestUtils.getIntParameter(request, Constants.ALERT_DEFINITION_PARAM);
parms.put(Constants.ALERT_DEFINITION_PARAM, ad);
AppdefEntityTypeID ctype = RequestUtils.getChildResourceTypeId(request);
parms.put(Constants.CHILD_RESOURCE_TYPE_ID_PARAM, ctype);
} catch (ParameterNotFoundException pnfe) {
// that's ok!
log.trace("couldn't find parameter: " + pnfe.getMessage());
}
// sets the returnPath to match the mode we're in.
String mode = request.getParameter(Constants.MODE_PARAM);
parms.put(Constants.MODE_PARAM, mode);
String returnPath = ActionUtils.findReturnPath(mapping, parms);
SessionUtils.setReturnPath(request.getSession(), returnPath);
}
}
|
UTF-8
|
Java
| 14,834 |
java
|
PortalAction.java
|
Java
|
[] | null |
[] |
/*
* NOTE: This copyright does *not* cover user programs that use HQ
* program services by normal system calls through the application
* program interfaces provided as part of the Hyperic Plug-in Development
* Kit or the Hyperic Client Development Kit - this is merely considered
* normal use of the program, and does *not* fall under the heading of
* "derived work".
*
* Copyright (C) [2004, 2005, 2006], Hyperic, Inc.
* This file is part of HQ.
*
* HQ is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*/
package org.hyperic.hq.ui.action.resource.common.monitor.alerts.config;
import java.util.HashMap;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hyperic.hq.appdef.shared.AppdefEntityID;
import org.hyperic.hq.appdef.shared.AppdefEntityTypeID;
import org.hyperic.hq.bizapp.shared.AppdefBoss;
import org.hyperic.hq.bizapp.shared.AuthzBoss;
import org.hyperic.hq.bizapp.shared.ControlBoss;
import org.hyperic.hq.bizapp.shared.EventsBoss;
import org.hyperic.hq.events.shared.AlertDefinitionValue;
import org.hyperic.hq.ui.Constants;
import org.hyperic.hq.ui.Portal;
import org.hyperic.hq.ui.Portlet;
import org.hyperic.hq.ui.action.resource.ResourceController;
import org.hyperic.hq.ui.action.resource.common.monitor.alerts.AlertDefUtil;
import org.hyperic.hq.ui.exception.ParameterNotFoundException;
import org.hyperic.hq.ui.util.ActionUtils;
import org.hyperic.hq.ui.util.BizappUtils;
import org.hyperic.hq.ui.util.RequestUtils;
import org.hyperic.hq.ui.util.SessionUtils;
import org.springframework.beans.factory.annotation.Autowired;
/**
* A dispatcher for the alerts portal.
*
*/
public class PortalAction
extends ResourceController {
private final Log log = LogFactory.getLog(PortalAction.class.getName());
protected final Properties keyMethodMap = new Properties();
protected EventsBoss eventsBoss;
@Autowired
public PortalAction(AppdefBoss appdefBoss, AuthzBoss authzBoss, ControlBoss controlBoss, EventsBoss eventsBoss) {
super(appdefBoss, authzBoss, controlBoss);
this.eventsBoss = eventsBoss;
initKeyMethodMap();
}
protected Properties getKeyMethodMap() {
return keyMethodMap;
}
private void initKeyMethodMap() {
keyMethodMap.setProperty(Constants.MODE_LIST, "listDefinitions");
keyMethodMap.setProperty(Constants.MODE_NEW, "newDefinition");
keyMethodMap.setProperty(Constants.MODE_VIEW, "listDefinitions");
keyMethodMap.setProperty("viewDefinition", "viewEscalation");
}
/**
* We override this in case the resource has been deleted ... simply ignore
* that fact.
*/
protected AppdefEntityID setResource(HttpServletRequest request, HttpServletResponse response) throws Exception {
try {
return super.setResource(request, response);
} catch (ParameterNotFoundException e) {
log.warn("No resource found.");
}
return null;
}
private void setTitle(HttpServletRequest request, Portal portal, String titleName) throws Exception {
AppdefEntityID aeid;
try {
aeid = RequestUtils.getEntityTypeId(request);
} catch (ParameterNotFoundException e) {
aeid = RequestUtils.getEntityId(request);
}
titleName = BizappUtils.replacePlatform(titleName, aeid);
portal.setName(titleName);
// if there's an alert definition available, set our second
// title parameter to its name
try {
int sessionId = RequestUtils.getSessionId(request).intValue();
AlertDefinitionValue adv = AlertDefUtil.getAlertDefinition(request, sessionId, eventsBoss);
request.setAttribute(Constants.TITLE_PARAM2_ATTR, adv.getName());
} catch (ParameterNotFoundException e) {
// it's okay
log.trace("couldn't find alert definition: " + e.getMessage());
}
}
public ActionForward newDefinition(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
setResource(request, response);
Portal portal = Portal.createPortal();
setTitle(request, portal, "alert.config.platform.edit.NewAlertDef.Title");
portal.addPortlet(new Portlet(".events.config.new"), 1);
portal.setDialog(true);
request.setAttribute(Constants.PORTAL_KEY, portal);
System.out.println("====================================================================");
System.out.println(request.getParameter("metrics"));
System.out.println(request.getAttribute("metrics"));
System.out.println("====================================================================");
return null;
}
public ActionForward editProperties(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
setResource(request, response);
Portal portal = Portal.createPortal();
setTitle(request, portal, "alert.config.platform.edit.page.Title");
portal.addPortlet(new Portlet(".events.config.edit.properties"), 1);
portal.setDialog(true);
request.setAttribute(Constants.PORTAL_KEY, portal);
return null;
}
public ActionForward editConditions(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
setResource(request, response);
Portal portal = Portal.createPortal();
setTitle(request, portal, "alert.config.platform.edit.condition.Title");
portal.addPortlet(new Portlet(".events.config.edit.conditions"), 1);
portal.setDialog(true);
request.setAttribute(Constants.PORTAL_KEY, portal);
return null;
}
public ActionForward editControlAction(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
setResource(request, response);
Portal portal = Portal.createPortal();
setTitle(request, portal, "alerts.config.platform.EditControlAction.Title");
portal.addPortlet(new Portlet(".events.config.edit.controlaction"), 1);
portal.setDialog(true);
request.setAttribute(Constants.PORTAL_KEY, portal);
return null;
}
public ActionForward editSyslogAction(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
setResource(request, response);
Portal portal = Portal.createPortal();
setTitle(request, portal, "alerts.config.platform.EditSyslogAction.Title");
portal.addPortlet(new Portlet(".events.config.edit.syslogaction"), 1);
portal.setDialog(true);
request.setAttribute(Constants.PORTAL_KEY, portal);
return null;
}
public ActionForward viewOthers(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
setResource(request, response);
Portal portal = Portal.createPortal();
setTitle(request, portal, "alert.config.platform.props.ViewDef.email.Title");
portal.addPortlet(new Portlet(".events.config.view.others"), 1);
// JW - this shouldn't be a dialog ... portal.setDialog(true);
request.setAttribute(Constants.PORTAL_KEY, portal);
return null;
}
public ActionForward viewUsers(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
setResource(request, response);
Portal portal = Portal.createPortal();
setTitle(request, portal, "alert.config.platform.props.ViewDef.users.Title");
portal.addPortlet(new Portlet(".events.config.view.users"), 1);
// JW - this shouldn't be a dialog ... portal.setDialog(true);
request.setAttribute(Constants.PORTAL_KEY, portal);
return null;
}
public ActionForward viewEscalation(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
setResource(request, response);
Portal portal = Portal.createPortal();
setTitle(request, portal, "alert.config.platform.props.ViewDef.escalation.Title");
portal.addPortlet(new Portlet(".events.config.view.escalation"), 1);
request.setAttribute(Constants.PORTAL_KEY, portal);
return null;
}
public ActionForward viewOpenNMS(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
setResource(request, response);
Portal portal = Portal.createPortal();
setTitle(request, portal, "alert.config.platform.props.ViewDef.openNMS.Title");
portal.addPortlet(new Portlet(".events.config.view.opennms"), 1);
request.setAttribute(Constants.PORTAL_KEY, portal);
return null;
}
public ActionForward monitorConfigureAlerts(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
setResource(request, response);
Portal portal = Portal.createPortal();
portal.addPortlet(new Portlet(".events.config.list"), 1);
portal.setDialog(false);
request.setAttribute(Constants.PORTAL_KEY, portal);
return null;
}
public ActionForward listDefinitions(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
AppdefEntityID aeid = setResource(request, response);
setNavMapLocation(request, mapping, Constants.ALERT_CONFIG_LOC);
// clean out the return path
SessionUtils.resetReturnPath(request.getSession());
// set the return path
try {
setReturnPath(request, mapping);
} catch (ParameterNotFoundException pne) {
log.debug(pne);
}
Portal portal = Portal.createPortal();
setTitle(request, portal, "alerts.config.platform.DefinitionList.Title");
portal.setDialog(false);
try {
RequestUtils.getStringParameter(request, Constants.APPDEF_RES_TYPE_ID);
portal.addPortlet(new Portlet(".admin.alerts.List"), 1);
} catch (ParameterNotFoundException e) {
if (aeid != null && aeid.isGroup()) {
portal.addPortlet(new Portlet(".events.group.config.list"), 1);
} else {
portal.addPortlet(new Portlet(".events.config.list"), 1);
}
}
request.setAttribute(Constants.PORTAL_KEY, portal);
return null;
}
public ActionForward addUsers(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
setResource(request, response);
Portal portal = Portal.createPortal();
setTitle(request, portal, "alerts.config.platform.AssignUsersToAlertDefinition.Title");
portal.addPortlet(new Portlet(".events.config.addusers"), 1);
portal.setDialog(false);
request.setAttribute(Constants.PORTAL_KEY, portal);
return null;
}
public ActionForward addOthers(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
setResource(request, response);
Portal portal = Portal.createPortal();
setTitle(request, portal, "alerts.config.platform.AssignOthersToAlertDefinition.Title");
portal.addPortlet(new Portlet(".events.config.addothers"), 1);
portal.setDialog(false);
request.setAttribute(Constants.PORTAL_KEY, portal);
return null;
}
/**
* This sets the return path for a ResourceAction by appending the type and
* resource id to the forward url.
*
* @param request The current controller's request.
* @param mapping The current controller's mapping that contains the input.
*
* @exception ParameterNotFoundException if the type or id are not found
* @exception ServletException If there is not input defined for this form
*/
protected void setReturnPath(HttpServletRequest request, ActionMapping mapping) throws Exception {
HashMap<String, Object> parms = new HashMap<String, Object>();
AppdefEntityID aeid = RequestUtils.getEntityId(request);
parms.put(Constants.RESOURCE_PARAM, aeid.getId());
parms.put(Constants.RESOURCE_TYPE_ID_PARAM, new Integer(aeid.getType()));
try {
Integer ad = RequestUtils.getIntParameter(request, Constants.ALERT_DEFINITION_PARAM);
parms.put(Constants.ALERT_DEFINITION_PARAM, ad);
AppdefEntityTypeID ctype = RequestUtils.getChildResourceTypeId(request);
parms.put(Constants.CHILD_RESOURCE_TYPE_ID_PARAM, ctype);
} catch (ParameterNotFoundException pnfe) {
// that's ok!
log.trace("couldn't find parameter: " + pnfe.getMessage());
}
// sets the returnPath to match the mode we're in.
String mode = request.getParameter(Constants.MODE_PARAM);
parms.put(Constants.MODE_PARAM, mode);
String returnPath = ActionUtils.findReturnPath(mapping, parms);
SessionUtils.setReturnPath(request.getSession(), returnPath);
}
}
| 14,834 | 0.675812 | 0.672914 | 341 | 42.501465 | 32.765999 | 117 | false | false | 0 | 0 | 0 | 0 | 68 | 0.009168 | 0.926686 | false | false |
5
|
e00260289d3f729a1948be7729603f7e25d7186b
| 38,517,266,741,081 |
33cd433d67488eb59a4f4d2172f26eb48893013b
|
/src/main/java/git/trufflehog/com/trufflehog/ipc/Receiver.java
|
778994282966ebc0afd80c1d045073dc758d3a44
|
[] |
no_license
|
TruffleHogProject/TruffleHog_IPC_testing
|
https://github.com/TruffleHogProject/TruffleHog_IPC_testing
|
d295fccc7e3b009264f204feca7c186b0d5bc9ab
|
41dfcd2b7ec878b72f01f1d1713afa4aa90472a9
|
refs/heads/master
| 2016-05-14T08:23:32.815000 | 2015-12-16T10:26:06 | 2015-12-16T10:26:06 | 48,097,732 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package git.trufflehog.com.trufflehog.ipc;
public interface Receiver {
InputStreamByteBuffer getBuffer();
}
|
UTF-8
|
Java
| 113 |
java
|
Receiver.java
|
Java
|
[] | null |
[] |
package git.trufflehog.com.trufflehog.ipc;
public interface Receiver {
InputStreamByteBuffer getBuffer();
}
| 113 | 0.787611 | 0.787611 | 7 | 15.142858 | 17.38167 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false |
5
|
df766fa15f03d3a3e25899723a1c20617dab8579
| 13,030,930,789,639 |
34e5a9230d1057e4584deba3d27b6847a4f04353
|
/jtwitter/jtwitter/src/main/java/com/cooksys/second/mapper/ProfileMapper.java
|
4c004cc9d8f88d8064fc5564eca6ab4886c6501a
|
[] |
no_license
|
developerjaym/second-assessment-skeleton
|
https://github.com/developerjaym/second-assessment-skeleton
|
42eef392b1fbd7148217f8753b91b06c0cebab4d
|
99b0bb5e13509dd4d03f7425d13cc9bd7c1d7ac0
|
refs/heads/master
| 2021-07-02T14:41:26.749000 | 2017-09-22T04:59:43 | 2017-09-22T04:59:43 | 104,094,387 | 0 | 0 | null | true | 2017-09-19T15:40:12 | 2017-09-19T15:40:12 | 2016-11-02T20:29:34 | 2016-11-02T21:07:21 | 6 | 0 | 0 | 0 | null | null | null |
package com.cooksys.second.mapper;
import org.mapstruct.Mapper;
import com.cooksys.second.dto.ProfileDto;
import com.cooksys.second.entity.Profile;
@Mapper(componentModel="spring")
public interface ProfileMapper {
ProfileDto toProfileDto(Profile profile);
Profile toProfile(ProfileDto profileDto);
}
|
UTF-8
|
Java
| 308 |
java
|
ProfileMapper.java
|
Java
|
[] | null |
[] |
package com.cooksys.second.mapper;
import org.mapstruct.Mapper;
import com.cooksys.second.dto.ProfileDto;
import com.cooksys.second.entity.Profile;
@Mapper(componentModel="spring")
public interface ProfileMapper {
ProfileDto toProfileDto(Profile profile);
Profile toProfile(ProfileDto profileDto);
}
| 308 | 0.808442 | 0.808442 | 14 | 21 | 18.3342 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.642857 | false | false |
1
|
fa4bdfe829fc489f967301155342b27443483348
| 6,571,299,977,189 |
aa53aa207edc295aaf1712def37d1ce3cb93c5bd
|
/src/models/PieceWorker.java
|
cde46d673d5be7c965e7cc2e3c1d83f7a337eaf2
|
[] |
no_license
|
denmind/IT5001Main
|
https://github.com/denmind/IT5001Main
|
00ecb8e36b0c60923ef5c49d790ec8df482d61a6
|
ffd6bbe302487a742a32337218169db5e5427c5a
|
refs/heads/master
| 2020-03-22T06:58:45.621000 | 2019-08-23T06:02:44 | 2019-08-23T06:02:44 | 139,670,437 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* 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 models;
import controllers.Salaries;
/**
*
* @author pc-user
*/
public class PieceWorker extends Employees implements Salaries {
private int piecesDone;
private double pieceRate;
public PieceWorker() {
}
/**
* With Middle Name*
*/
public PieceWorker(int id, String firstName, String middleName, String lastName, String gender, String job, String jobType, Double salary) {
super(id, firstName, middleName, lastName, gender, job, jobType, salary);
}
public PieceWorker(int piecesDone, double pieceRate, int id, String firstName, String middleName, String lastName, String gender, String job, String jobType, Double salary) {
super(id, firstName, middleName, lastName, gender, job, jobType, salary);
this.piecesDone = piecesDone;
this.pieceRate = pieceRate;
}
public PieceWorker(int piecesDone, double pieceRate) {
super();
this.piecesDone = piecesDone;
this.pieceRate = pieceRate;
}
public int getPiecesDone() {
return piecesDone;
}
public void setPiecesDone(int piecesDone) {
this.piecesDone = piecesDone;
}
public double getPieceRate() {
return pieceRate;
}
public void setPieceRate(double pieceRate) {
this.pieceRate = pieceRate;
}
@Override
public double computeMySalary() {
double salary;
if (pieceRate <= 0) {
setPieceRate(minimumRate);
}
if (piecesDone <= 0) {
setPiecesDone(NONE);
}
salary = getPieceRate() * getPiecesDone();
setSalary(salary);
return salary;
}
}
|
UTF-8
|
Java
| 1,858 |
java
|
PieceWorker.java
|
Java
|
[
{
"context": ";\n\nimport controllers.Salaries;\n\n/**\n *\n * @author pc-user\n */\npublic class PieceWorker extends Employees im",
"end": 258,
"score": 0.9995794892311096,
"start": 251,
"tag": "USERNAME",
"value": "pc-user"
},
{
"context": "nt id, String firstName, String middleName, String lastName, String gender, String job, String jobType, Doubl",
"end": 546,
"score": 0.51316237449646,
"start": 538,
"tag": "NAME",
"value": "lastName"
},
{
"context": "String jobType, Double salary) {\n super(id, firstName, middleName, lastName, gender, job, jobType, sala",
"end": 635,
"score": 0.6905803084373474,
"start": 626,
"tag": "NAME",
"value": "firstName"
},
{
"context": "salary) {\n super(id, firstName, middleName, lastName, gender, job, jobType, salary);\n }\n\n public",
"end": 657,
"score": 0.9695171117782593,
"start": 649,
"tag": "NAME",
"value": "lastName"
},
{
"context": "r(int piecesDone, double pieceRate, int id, String firstName, String middleName, String lastName, String gende",
"end": 778,
"score": 0.7287160158157349,
"start": 769,
"tag": "NAME",
"value": "firstName"
},
{
"context": "nt id, String firstName, String middleName, String lastName, String gender, String job, String jobType, Doubl",
"end": 814,
"score": 0.8953097462654114,
"start": 806,
"tag": "NAME",
"value": "lastName"
},
{
"context": "String jobType, Double salary) {\n super(id, firstName, middleName, lastName, gender, job, jobType, sala",
"end": 903,
"score": 0.9900886416435242,
"start": 894,
"tag": "NAME",
"value": "firstName"
},
{
"context": "salary) {\n super(id, firstName, middleName, lastName, gender, job, jobType, salary);\n this.piec",
"end": 925,
"score": 0.98853999376297,
"start": 917,
"tag": "NAME",
"value": "lastName"
}
] | null |
[] |
/*
* 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 models;
import controllers.Salaries;
/**
*
* @author pc-user
*/
public class PieceWorker extends Employees implements Salaries {
private int piecesDone;
private double pieceRate;
public PieceWorker() {
}
/**
* With Middle Name*
*/
public PieceWorker(int id, String firstName, String middleName, String lastName, String gender, String job, String jobType, Double salary) {
super(id, firstName, middleName, lastName, gender, job, jobType, salary);
}
public PieceWorker(int piecesDone, double pieceRate, int id, String firstName, String middleName, String lastName, String gender, String job, String jobType, Double salary) {
super(id, firstName, middleName, lastName, gender, job, jobType, salary);
this.piecesDone = piecesDone;
this.pieceRate = pieceRate;
}
public PieceWorker(int piecesDone, double pieceRate) {
super();
this.piecesDone = piecesDone;
this.pieceRate = pieceRate;
}
public int getPiecesDone() {
return piecesDone;
}
public void setPiecesDone(int piecesDone) {
this.piecesDone = piecesDone;
}
public double getPieceRate() {
return pieceRate;
}
public void setPieceRate(double pieceRate) {
this.pieceRate = pieceRate;
}
@Override
public double computeMySalary() {
double salary;
if (pieceRate <= 0) {
setPieceRate(minimumRate);
}
if (piecesDone <= 0) {
setPiecesDone(NONE);
}
salary = getPieceRate() * getPiecesDone();
setSalary(salary);
return salary;
}
}
| 1,858 | 0.640474 | 0.639397 | 75 | 23.76 | 31.042269 | 178 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.733333 | false | false |
1
|
1f20183dc339c4ffe4477cba3c7630b8eaf21481
| 1,030,792,162,318 |
b937082fa88a9bfce8d89e517e537f9f1e1447b3
|
/src/main/java/paul/TextQuest/gameplan/DungeonInfo.java
|
6ac7e194a62d8358619dd53616d63ddf55b35443
|
[] |
no_license
|
pauldennis2/TextQuest
|
https://github.com/pauldennis2/TextQuest
|
1d8015ee86d56b66c0ccf51d5535d19b766b39e0
|
134d992f31e99f3c15500d6c0ba9f69df18a5df6
|
refs/heads/master
| 2021-01-15T16:41:40.471000 | 2018-10-05T14:11:20 | 2018-10-05T14:11:20 | 99,717,181 | 0 | 0 | null | false | 2019-02-20T14:49:06 | 2017-08-08T17:08:20 | 2018-11-03T17:22:43 | 2019-02-20T14:49:05 | 813 | 2 | 1 | 0 |
Java
| false | null |
/**
* @author Paul Dennis
* Sep 14, 2018
*/
package paul.TextQuest.gameplan;
import java.util.ArrayList;
import java.util.List;
public class DungeonInfo {
private String fileLocation;
private List<String> prereqs;
public DungeonInfo () {
prereqs = new ArrayList<>();
}
public DungeonInfo(String name, String fileLocation) {
super();
this.fileLocation = fileLocation;
}
public String getFileLocation() {
return fileLocation;
}
public void setFileLocation(String fileLocation) {
this.fileLocation = fileLocation;
}
public List<String> getPrereqs() {
return prereqs;
}
public void setPrereqs(List<String> prereqs) {
this.prereqs = prereqs;
}
}
|
UTF-8
|
Java
| 683 |
java
|
DungeonInfo.java
|
Java
|
[
{
"context": "/**\n * @author Paul Dennis\n * Sep 14, 2018\n */\npackage paul.TextQuest.gamepl",
"end": 26,
"score": 0.9998642206192017,
"start": 15,
"tag": "NAME",
"value": "Paul Dennis"
}
] | null |
[] |
/**
* @author <NAME>
* Sep 14, 2018
*/
package paul.TextQuest.gameplan;
import java.util.ArrayList;
import java.util.List;
public class DungeonInfo {
private String fileLocation;
private List<String> prereqs;
public DungeonInfo () {
prereqs = new ArrayList<>();
}
public DungeonInfo(String name, String fileLocation) {
super();
this.fileLocation = fileLocation;
}
public String getFileLocation() {
return fileLocation;
}
public void setFileLocation(String fileLocation) {
this.fileLocation = fileLocation;
}
public List<String> getPrereqs() {
return prereqs;
}
public void setPrereqs(List<String> prereqs) {
this.prereqs = prereqs;
}
}
| 678 | 0.715959 | 0.707174 | 39 | 16.512821 | 16.340717 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.128205 | false | false |
1
|
ee3193f6a26ee7693f48d0ca0c384c7f1cc23edf
| 180,388,687,082 |
5a33fedab0b7d4018b827be77de5a57caaec689b
|
/app/src/main/java/com/esperienza/intranetmall/mobile/fragment/FragmentEnderecoFuncionario.java
|
ea119c59dd340cc812b2af859b23b4c219730baf
|
[] |
no_license
|
Andrecouto2/MyIntranet
|
https://github.com/Andrecouto2/MyIntranet
|
d289efe9553124471692dd58015c5acd1686eb4e
|
d3073ad4d61990303b5d4e375b82fa985ac7b731
|
refs/heads/master
| 2021-06-03T03:04:14.830000 | 2016-08-25T15:07:58 | 2016-08-25T15:07:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.esperienza.intranetmall.mobile.fragment;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.esperienza.intranetmall.mobile.R;
import com.esperienza.intranetmall.mobile.async.BuscarCepAsync;
import com.esperienza.intranetmall.mobile.entidade.Endereco;
import com.esperienza.intranetmall.mobile.logger.Log;
import com.esperienza.intranetmall.mobile.util.AppHelper;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import java.util.Arrays;
import java.util.List;
/**
* Created by ThinkPad on 07/12/2015.
*/
public class FragmentEnderecoFuncionario extends Fragment{
private EditText edt_cep;
private EditText edt_end;
private EditText edt_numero;
private EditText edt_complemento;
private EditText edt_bairro;
private EditText edt_municipio;
private Spinner sp_uf;
private String[] list_uf;
private ImageView imgviewcep;
private TextView txtviewerroruf;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootview = inflater.inflate(R.layout.fragment_enderecofuncionario, container, false);
FragmentDadosFuncionario.viewend=rootview;
if (getActivity().getCurrentFocus() != null) {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
}
//ScrollView scrollView = (ScrollView) rootview.findViewById(R.id.scrollViewEnderecoFnc);
//scrollView.setClipToPadding(false);
//setInsets(getActivity(), scrollView);
edt_cep = (EditText) rootview.findViewById(R.id.edt_cep);
edt_end = (EditText) rootview.findViewById(R.id.edt_endereco);
edt_numero = (EditText) rootview.findViewById(R.id.edt_num);
edt_complemento = (EditText) rootview.findViewById(R.id.edt_complemento);
edt_bairro = (EditText) rootview.findViewById(R.id.edt_bairro);
edt_municipio = (EditText) rootview.findViewById(R.id.edt_municipio);
sp_uf = (Spinner) rootview.findViewById(R.id.sp_uf_endereco);
imgviewcep = (ImageView) rootview.findViewById(R.id.imgbtn_buscar_cep);
list_uf = getResources().getStringArray(R.array.ufs);
txtviewerroruf = (TextView) rootview.findViewById(R.id.tvInvisibleErrorUf);
if(FragmentDadosFuncionario.funcionario.getStatusEnvio()>0)
{
preencheTela();
}
else
{
List<View> form_elements = rootview.getTouchables();
for (View element : form_elements){
if (element instanceof EditText){
((EditText) element).setText("");
} else if (element instanceof Spinner){
((Spinner) element).setSelection(0);
}
// and so forth...
}
}
setListener();
return rootview;
}
private void setListener()
{
// Listeners textviews
edt_cep.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
FragmentDadosFuncionario.funcionario.setCep(edt_cep.getText().toString());
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
edt_end.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
FragmentDadosFuncionario.funcionario.setEndereco(edt_end.getText().toString());
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
edt_numero.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
try{
FragmentDadosFuncionario.funcionario.setNumero(Integer.valueOf(edt_numero.getText().toString()));
}catch (Exception e)
{
Log.e("Fragment Endereço Funcionario"+getClass().toString(),"Erro conversao número");
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
edt_complemento.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
FragmentDadosFuncionario.funcionario.setComplemento(edt_complemento.getText().toString());
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
edt_bairro.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
FragmentDadosFuncionario.funcionario.setBairro(edt_bairro.getText().toString());
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
edt_municipio.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
FragmentDadosFuncionario.funcionario.setCidade(edt_municipio.getText().toString());
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
// Listeners spinners
sp_uf.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView,
View selectedItemView, int position, long id) {
FragmentDadosFuncionario.funcionario.setUf(sp_uf.getSelectedItem().toString());
if(!sp_uf.getSelectedItem().toString().equals("Selecione"))
txtviewerroruf.setError(null);
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
imgviewcep.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (AppHelper.isInternetOnline())
{
if (!edt_cep.getText().toString().equals(""))
{
getCEP(edt_cep.getText().toString().replace("-",""));
} else
{
Toast.makeText(getActivity(), "Insira o cep.", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(getActivity(), "Sem conexão com a internet.", Toast.LENGTH_SHORT).show();
}
}
});
}
public void getCEP(String cep){
new BuscarCepAsync(getActivity(),cep, new BuscarCepAsync.Action() {
@Override
public void preExecute() {
}
@Override
public void postExecute(Endereco result) {
}
@Override
public void getResult(Endereco result) {
if (result!=null){
FragmentDadosFuncionario.funcionario.setCidade(result.getMunicipio());
FragmentDadosFuncionario.funcionario.setBairro(result.getBairro());
FragmentDadosFuncionario.funcionario.setUf(result.getUf());
FragmentDadosFuncionario.funcionario.setEndereco(result.getLogradouro());
preencheTela();
}else {
Toast.makeText(getActivity(), "Cep não encontrado", Toast.LENGTH_LONG).show();
}
}
}).execute(cep);
}
public void preencheTela()
{
sp_uf.setSelection(Arrays.asList(list_uf).indexOf(FragmentDadosFuncionario.funcionario.getUf() != null&&! FragmentDadosFuncionario.funcionario.getUf().toString().equals("anyType{}")? FragmentDadosFuncionario.funcionario.getUf().toString() : "Selecione"));
edt_cep.setText(FragmentDadosFuncionario.funcionario.getCep() != null&&!FragmentDadosFuncionario.funcionario.getCep().toString().equals("anyType{}") ? FragmentDadosFuncionario.funcionario.getCep().toString() : "");
edt_end.setText(FragmentDadosFuncionario.funcionario.getEndereco() != null&&!FragmentDadosFuncionario.funcionario.getEndereco().toString().equals("anyType{}") ? FragmentDadosFuncionario.funcionario.getEndereco().toString() : "");
try{
edt_numero.setText(FragmentDadosFuncionario.funcionario.getNumero() != 0? String.valueOf(FragmentDadosFuncionario.funcionario.getNumero()) : "");
}
catch (Exception e)
{
Log.e("Fragment Endereço Funcionario","Erro conversão de número");
}
edt_bairro.setText(FragmentDadosFuncionario.funcionario.getBairro() != null&&! FragmentDadosFuncionario.funcionario.getBairro().toString().equals("anyType{}")? FragmentDadosFuncionario.funcionario.getBairro().toString() : "");
edt_complemento.setText(FragmentDadosFuncionario.funcionario.getComplemento() != null&&!FragmentDadosFuncionario.funcionario.getComplemento().toString().equals("anyType{}") ? FragmentDadosFuncionario.funcionario.getComplemento().toString() : "");
edt_municipio.setText(FragmentDadosFuncionario.funcionario.getCidade() != null&&!FragmentDadosFuncionario.funcionario.getCidade().toString().equals("anyType{}") ? FragmentDadosFuncionario.funcionario.getCidade().toString() : "");
}
public static void setInsets(Activity context, View view) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) return;
SystemBarTintManager tintManager = new SystemBarTintManager(context);
SystemBarTintManager.SystemBarConfig config = tintManager.getConfig();
view.setPadding(0, config.getPixelInsetTop(true)*2, config.getPixelInsetRight(), config.getPixelInsetBottom());
}
}
|
UTF-8
|
Java
| 11,459 |
java
|
FragmentEnderecoFuncionario.java
|
Java
|
[
{
"context": ".Arrays;\nimport java.util.List;\n\n/**\n * Created by ThinkPad on 07/12/2015.\n */\npublic class FragmentEnderecoF",
"end": 1143,
"score": 0.7802438735961914,
"start": 1135,
"tag": "USERNAME",
"value": "ThinkPad"
}
] | null |
[] |
package com.esperienza.intranetmall.mobile.fragment;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.esperienza.intranetmall.mobile.R;
import com.esperienza.intranetmall.mobile.async.BuscarCepAsync;
import com.esperienza.intranetmall.mobile.entidade.Endereco;
import com.esperienza.intranetmall.mobile.logger.Log;
import com.esperienza.intranetmall.mobile.util.AppHelper;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import java.util.Arrays;
import java.util.List;
/**
* Created by ThinkPad on 07/12/2015.
*/
public class FragmentEnderecoFuncionario extends Fragment{
private EditText edt_cep;
private EditText edt_end;
private EditText edt_numero;
private EditText edt_complemento;
private EditText edt_bairro;
private EditText edt_municipio;
private Spinner sp_uf;
private String[] list_uf;
private ImageView imgviewcep;
private TextView txtviewerroruf;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootview = inflater.inflate(R.layout.fragment_enderecofuncionario, container, false);
FragmentDadosFuncionario.viewend=rootview;
if (getActivity().getCurrentFocus() != null) {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
}
//ScrollView scrollView = (ScrollView) rootview.findViewById(R.id.scrollViewEnderecoFnc);
//scrollView.setClipToPadding(false);
//setInsets(getActivity(), scrollView);
edt_cep = (EditText) rootview.findViewById(R.id.edt_cep);
edt_end = (EditText) rootview.findViewById(R.id.edt_endereco);
edt_numero = (EditText) rootview.findViewById(R.id.edt_num);
edt_complemento = (EditText) rootview.findViewById(R.id.edt_complemento);
edt_bairro = (EditText) rootview.findViewById(R.id.edt_bairro);
edt_municipio = (EditText) rootview.findViewById(R.id.edt_municipio);
sp_uf = (Spinner) rootview.findViewById(R.id.sp_uf_endereco);
imgviewcep = (ImageView) rootview.findViewById(R.id.imgbtn_buscar_cep);
list_uf = getResources().getStringArray(R.array.ufs);
txtviewerroruf = (TextView) rootview.findViewById(R.id.tvInvisibleErrorUf);
if(FragmentDadosFuncionario.funcionario.getStatusEnvio()>0)
{
preencheTela();
}
else
{
List<View> form_elements = rootview.getTouchables();
for (View element : form_elements){
if (element instanceof EditText){
((EditText) element).setText("");
} else if (element instanceof Spinner){
((Spinner) element).setSelection(0);
}
// and so forth...
}
}
setListener();
return rootview;
}
private void setListener()
{
// Listeners textviews
edt_cep.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
FragmentDadosFuncionario.funcionario.setCep(edt_cep.getText().toString());
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
edt_end.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
FragmentDadosFuncionario.funcionario.setEndereco(edt_end.getText().toString());
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
edt_numero.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
try{
FragmentDadosFuncionario.funcionario.setNumero(Integer.valueOf(edt_numero.getText().toString()));
}catch (Exception e)
{
Log.e("Fragment Endereço Funcionario"+getClass().toString(),"Erro conversao número");
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
edt_complemento.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
FragmentDadosFuncionario.funcionario.setComplemento(edt_complemento.getText().toString());
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
edt_bairro.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
FragmentDadosFuncionario.funcionario.setBairro(edt_bairro.getText().toString());
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
edt_municipio.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
FragmentDadosFuncionario.funcionario.setCidade(edt_municipio.getText().toString());
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
// Listeners spinners
sp_uf.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView,
View selectedItemView, int position, long id) {
FragmentDadosFuncionario.funcionario.setUf(sp_uf.getSelectedItem().toString());
if(!sp_uf.getSelectedItem().toString().equals("Selecione"))
txtviewerroruf.setError(null);
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
imgviewcep.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (AppHelper.isInternetOnline())
{
if (!edt_cep.getText().toString().equals(""))
{
getCEP(edt_cep.getText().toString().replace("-",""));
} else
{
Toast.makeText(getActivity(), "Insira o cep.", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(getActivity(), "Sem conexão com a internet.", Toast.LENGTH_SHORT).show();
}
}
});
}
public void getCEP(String cep){
new BuscarCepAsync(getActivity(),cep, new BuscarCepAsync.Action() {
@Override
public void preExecute() {
}
@Override
public void postExecute(Endereco result) {
}
@Override
public void getResult(Endereco result) {
if (result!=null){
FragmentDadosFuncionario.funcionario.setCidade(result.getMunicipio());
FragmentDadosFuncionario.funcionario.setBairro(result.getBairro());
FragmentDadosFuncionario.funcionario.setUf(result.getUf());
FragmentDadosFuncionario.funcionario.setEndereco(result.getLogradouro());
preencheTela();
}else {
Toast.makeText(getActivity(), "Cep não encontrado", Toast.LENGTH_LONG).show();
}
}
}).execute(cep);
}
public void preencheTela()
{
sp_uf.setSelection(Arrays.asList(list_uf).indexOf(FragmentDadosFuncionario.funcionario.getUf() != null&&! FragmentDadosFuncionario.funcionario.getUf().toString().equals("anyType{}")? FragmentDadosFuncionario.funcionario.getUf().toString() : "Selecione"));
edt_cep.setText(FragmentDadosFuncionario.funcionario.getCep() != null&&!FragmentDadosFuncionario.funcionario.getCep().toString().equals("anyType{}") ? FragmentDadosFuncionario.funcionario.getCep().toString() : "");
edt_end.setText(FragmentDadosFuncionario.funcionario.getEndereco() != null&&!FragmentDadosFuncionario.funcionario.getEndereco().toString().equals("anyType{}") ? FragmentDadosFuncionario.funcionario.getEndereco().toString() : "");
try{
edt_numero.setText(FragmentDadosFuncionario.funcionario.getNumero() != 0? String.valueOf(FragmentDadosFuncionario.funcionario.getNumero()) : "");
}
catch (Exception e)
{
Log.e("Fragment Endereço Funcionario","Erro conversão de número");
}
edt_bairro.setText(FragmentDadosFuncionario.funcionario.getBairro() != null&&! FragmentDadosFuncionario.funcionario.getBairro().toString().equals("anyType{}")? FragmentDadosFuncionario.funcionario.getBairro().toString() : "");
edt_complemento.setText(FragmentDadosFuncionario.funcionario.getComplemento() != null&&!FragmentDadosFuncionario.funcionario.getComplemento().toString().equals("anyType{}") ? FragmentDadosFuncionario.funcionario.getComplemento().toString() : "");
edt_municipio.setText(FragmentDadosFuncionario.funcionario.getCidade() != null&&!FragmentDadosFuncionario.funcionario.getCidade().toString().equals("anyType{}") ? FragmentDadosFuncionario.funcionario.getCidade().toString() : "");
}
public static void setInsets(Activity context, View view) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) return;
SystemBarTintManager tintManager = new SystemBarTintManager(context);
SystemBarTintManager.SystemBarConfig config = tintManager.getConfig();
view.setPadding(0, config.getPixelInsetTop(true)*2, config.getPixelInsetRight(), config.getPixelInsetBottom());
}
}
| 11,459 | 0.637967 | 0.636657 | 281 | 39.754448 | 44.053513 | 263 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.576512 | false | false |
1
|
d18897fb4ab4b72e03b2c11b649b72816bf92426
| 2,362,232,014,065 |
3c149551e426a7be92052480eb5931a44effc413
|
/RongHeCaiFu/app/src/main/java/com/ayd/rhcf/ui/JyjlActivity.java
|
4691634a27f7b3839b9c13833a1170d495581ccf
|
[] |
no_license
|
captain1991/volleytest
|
https://github.com/captain1991/volleytest
|
0341cb1218dceab9f90017947c82962285f8b999
|
067ad213cadb0286d6a5433049ed61dcb8c43549
|
refs/heads/master
| 2021-01-01T05:24:46.641000 | 2016-04-21T08:14:42 | 2016-04-21T08:14:42 | 56,753,767 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.ayd.rhcf.ui;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import com.ayd.rhcf.AppConstants;
import com.ayd.rhcf.PtrCallBack;
import com.ayd.rhcf.PtrRefreshRegister;
import com.ayd.rhcf.R;
import com.ayd.rhcf.adapter.JyjlListAdapter;
import com.ayd.rhcf.view.pulltorefresh.PullToRefreshLayout;
/**
* Created by gqy on 2016/2/29.
* 交易记录t;
*/
public class JyjlActivity extends BaseActivity implements PtrCallBack {
private PullToRefreshLayout refreshLayout;
private ListView mListView;
private JyjlListAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
}
@Override
protected Activity getUmengAnalyzeContext() {
return this;
}
private void init() {
refreshLayout = (PullToRefreshLayout) findViewById(R.id.refreshLayout);
PtrRefreshRegister.regist(refreshLayout, this);
mListView = (ListView) refreshLayout.getPullableView();
adapter = new JyjlListAdapter(this);
mListView.setAdapter(adapter);
}
@Override
protected int getLayoutResId() {
return R.layout.activity_jyjl;
}
@Override
public void onRefresh() {
}
@Override
public void onLoadMore() {
}
@Override
protected void titleBarLeftClick() {
finish();
}
@Override
protected boolean isTitleBarRightVisible() {
return false;
}
@Override
protected String getTitleBarTitle() {
return getString(R.string.text_jyjl);
}
@Override
protected String[] getReqTagList() {
return new String[]{AppConstants.JYJL_REQ_TAG};
}
}
|
UTF-8
|
Java
| 1,748 |
java
|
JyjlActivity.java
|
Java
|
[
{
"context": "ltorefresh.PullToRefreshLayout;\n\n/**\n * Created by gqy on 2016/2/29.\n * 交易记录t;\n */\npublic class JyjlActi",
"end": 371,
"score": 0.9996192455291748,
"start": 368,
"tag": "USERNAME",
"value": "gqy"
}
] | null |
[] |
package com.ayd.rhcf.ui;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import com.ayd.rhcf.AppConstants;
import com.ayd.rhcf.PtrCallBack;
import com.ayd.rhcf.PtrRefreshRegister;
import com.ayd.rhcf.R;
import com.ayd.rhcf.adapter.JyjlListAdapter;
import com.ayd.rhcf.view.pulltorefresh.PullToRefreshLayout;
/**
* Created by gqy on 2016/2/29.
* 交易记录t;
*/
public class JyjlActivity extends BaseActivity implements PtrCallBack {
private PullToRefreshLayout refreshLayout;
private ListView mListView;
private JyjlListAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
}
@Override
protected Activity getUmengAnalyzeContext() {
return this;
}
private void init() {
refreshLayout = (PullToRefreshLayout) findViewById(R.id.refreshLayout);
PtrRefreshRegister.regist(refreshLayout, this);
mListView = (ListView) refreshLayout.getPullableView();
adapter = new JyjlListAdapter(this);
mListView.setAdapter(adapter);
}
@Override
protected int getLayoutResId() {
return R.layout.activity_jyjl;
}
@Override
public void onRefresh() {
}
@Override
public void onLoadMore() {
}
@Override
protected void titleBarLeftClick() {
finish();
}
@Override
protected boolean isTitleBarRightVisible() {
return false;
}
@Override
protected String getTitleBarTitle() {
return getString(R.string.text_jyjl);
}
@Override
protected String[] getReqTagList() {
return new String[]{AppConstants.JYJL_REQ_TAG};
}
}
| 1,748 | 0.682394 | 0.678366 | 76 | 21.868422 | 20.222019 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.355263 | false | false |
1
|
f0c92d13ecf0df37f390a29435f7880ae5550962
| 10,479,720,206,744 |
4708b90f1492b6796712fa430a4eb58788c1cf42
|
/NetBeansProjects/CS/CSInitialiser/src/csinitializer/InitializerFactory.java
|
49671137544b1d22b5071da3e9e832a63c1a4fe4
|
[] |
no_license
|
IgorDolgo/Nauka
|
https://github.com/IgorDolgo/Nauka
|
3897f055e056df29f53b58b3dd353f1b31a32e2a
|
34228355430ea1eb971877b4ab54a52372611ba6
|
refs/heads/master
| 2016-09-14T02:28:17.931000 | 2016-04-15T09:30:09 | 2016-04-15T09:30:09 | 56,043,790 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* 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 csinitializer;
import csinitializer.utils.CommonInitializer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* @author alex
*/
public class InitializerFactory {
private static final String CONNECTION_STRING_PATTERN = "(jdbc:[a-zA-z]*:).*";
public static CommonInitializer getInitializer(String connectionString) {
Pattern pConnectionString = Pattern.compile(CONNECTION_STRING_PATTERN);
Matcher matcher = pConnectionString.matcher(connectionString);
String prefix;
if (matcher.matches()) {
prefix = matcher.group(1);
} else {
throw new IllegalArgumentException("Invalid jdbc connection string");
}
switch (prefix.toUpperCase()) {
case "JDBC:MYSQL:":
return new CSInitializer();
case "JDBC:ORACLE:":
return new CSInitializerOracle();
case "JDBC:POSTGRESQL:":
return new CSInitializerPostgre();
default:
throw new IllegalArgumentException("Unknown or unsupported DBMS");
}
}
}
|
UTF-8
|
Java
| 1,187 |
java
|
InitializerFactory.java
|
Java
|
[
{
"context": "rt java.util.regex.Pattern;\r\n\r\n/**\r\n *\r\n * @author alex\r\n */\r\npublic class InitializerFactory {\r\n\tprivate",
"end": 355,
"score": 0.9974033832550049,
"start": 351,
"tag": "USERNAME",
"value": "alex"
}
] | null |
[] |
/*
* 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 csinitializer;
import csinitializer.utils.CommonInitializer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* @author alex
*/
public class InitializerFactory {
private static final String CONNECTION_STRING_PATTERN = "(jdbc:[a-zA-z]*:).*";
public static CommonInitializer getInitializer(String connectionString) {
Pattern pConnectionString = Pattern.compile(CONNECTION_STRING_PATTERN);
Matcher matcher = pConnectionString.matcher(connectionString);
String prefix;
if (matcher.matches()) {
prefix = matcher.group(1);
} else {
throw new IllegalArgumentException("Invalid jdbc connection string");
}
switch (prefix.toUpperCase()) {
case "JDBC:MYSQL:":
return new CSInitializer();
case "JDBC:ORACLE:":
return new CSInitializerOracle();
case "JDBC:POSTGRESQL:":
return new CSInitializerPostgre();
default:
throw new IllegalArgumentException("Unknown or unsupported DBMS");
}
}
}
| 1,187 | 0.711036 | 0.710194 | 39 | 28.435898 | 25.370884 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.794872 | false | false |
1
|
f55224b53204bf64475ff592cf8bdad0097cf544
| 23,459,111,393,974 |
94cb37e501bffc90e9b006de2c706f5bcf2a7318
|
/src/Movie.java
|
734a51aac0b242ed82d838651ae2aba7ff44c051
|
[] |
no_license
|
MahsaLayeghi/Data-Structures
|
https://github.com/MahsaLayeghi/Data-Structures
|
648c5119e6244fbba7f3bef9be7477db62025130
|
869842f0ba0328dbf1ebffc87e27b0e6bfcbd07d
|
refs/heads/master
| 2020-03-27T13:41:05.329000 | 2018-08-29T15:45:37 | 2018-08-29T15:45:37 | 141,005,404 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.util.ArrayList;
import java.util.Collections;
public class Movie
{
String name;
int year, duration;
ArrayList<String> actors;
Movie(String name, int year, int duration, ArrayList<String> actors)
{
this.name = name;
this.year = year;
this.duration = duration;
this.actors = actors;
}
boolean isEqual(String s)
{
return name.compareTo(s) == 0;
}
boolean isLess(String s)
{
return name.compareTo(s) < 0;
}
boolean isGreater(String s)
{
return name.compareTo(s) > 0;
}
void print()
{
System.out.println(name);
System.out.println(year);
System.out.println(duration);
Collections.sort(actors);
for (int i = 0; i < actors.size(); i++)
System.out.println(actors.get(i));
}
}
|
UTF-8
|
Java
| 864 |
java
|
Movie.java
|
Java
|
[] | null |
[] |
import java.util.ArrayList;
import java.util.Collections;
public class Movie
{
String name;
int year, duration;
ArrayList<String> actors;
Movie(String name, int year, int duration, ArrayList<String> actors)
{
this.name = name;
this.year = year;
this.duration = duration;
this.actors = actors;
}
boolean isEqual(String s)
{
return name.compareTo(s) == 0;
}
boolean isLess(String s)
{
return name.compareTo(s) < 0;
}
boolean isGreater(String s)
{
return name.compareTo(s) > 0;
}
void print()
{
System.out.println(name);
System.out.println(year);
System.out.println(duration);
Collections.sort(actors);
for (int i = 0; i < actors.size(); i++)
System.out.println(actors.get(i));
}
}
| 864 | 0.568287 | 0.563657 | 42 | 19.595238 | 16.898943 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.547619 | false | false |
1
|
5c5437e85e53836d92b9196f850365631857e5a3
| 32,006,096,334,438 |
7ff7d9f7902ce8e7745613c9028264233611e9ce
|
/LT_IngegneriaDelSw/eclipseWorkspace/it.unibo.system/src/it/unibo/system/IObservable.java
|
5e96ffbca880ad8e229c97b504737adffd149b3b
|
[] |
no_license
|
metaphori/uni-projects
|
https://github.com/metaphori/uni-projects
|
bca9a13204a25cee4ab778c1441cd27ba2485e4e
|
c2de0bd679037126fcc06726cf24d52944f738eb
|
refs/heads/master
| 2021-01-10T06:30:15.111000 | 2017-05-27T09:22:30 | 2017-05-27T09:22:30 | 55,056,709 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package it.unibo.system;
public interface IObservable {
public void addObserver(IObserver arg0);
}
|
UTF-8
|
Java
| 101 |
java
|
IObservable.java
|
Java
|
[] | null |
[] |
package it.unibo.system;
public interface IObservable {
public void addObserver(IObserver arg0);
}
| 101 | 0.792079 | 0.782178 | 5 | 19.200001 | 16.216042 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false |
1
|
ad79e03dd8b8b1a70b48cc26a885c558291e19dd
| 32,993,938,790,660 |
f7bb53cba36ec5880fa1f143869180764f8aff2f
|
/src/test/java/com/Maxpay/AbstractPage.java
|
fb9bce64a36c8ff95d5c4fb253415fa4c5875f13
|
[] |
no_license
|
AlexeyPaskhin/TestTaskForMaxpay
|
https://github.com/AlexeyPaskhin/TestTaskForMaxpay
|
375778f1d449c41d7404526b2bccf854b434ff99
|
6b8cd3e062e19c0f09f68abf56f907593839d6b4
|
refs/heads/master
| 2020-03-12T09:55:00.108000 | 2018-04-22T12:01:24 | 2018-04-22T12:01:24 | 130,560,806 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.Maxpay;
import com.paulhammant.ngwebdriver.NgWebDriver;
import org.openqa.selenium.*;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.util.concurrent.TimeUnit;
import static org.openqa.selenium.support.ui.ExpectedConditions.*;
public abstract class AbstractPage {
private static final String loaderLocator = "//div[@id='page-loader']";
@FindBy(xpath = loaderLocator)
WebElement loader;
protected WebDriver driver;
private NgWebDriver ngWebDriver;
WebDriverWait explWait;
JavascriptExecutor jseDriver;
public AbstractPage (WebDriver driver) {
this.driver = driver;
explWait = new WebDriverWait(driver, 10);
this.jseDriver = (JavascriptExecutor) driver;
ngWebDriver = new NgWebDriver(jseDriver);
driver.manage().timeouts().setScriptTimeout(30, TimeUnit.SECONDS);
PageFactory.initElements(driver, this);
}
public void waitForLoading() {
try { // try - на случай, если js в каком то кейсе не начал выполнятся, попытка перехода на другую страницу не произвелась
new WebDriverWait(driver, 1).until(visibilityOf(loader));
} catch (TimeoutException e) {
return;
}
explWait.until(attributeToBe(loader, "style", "display: none;"));
}
public AbstractPage waitForAngularRequestsToFinish() {
ngWebDriver.waitForAngularRequestsToFinish();
return this;
}
}
|
UTF-8
|
Java
| 1,660 |
java
|
AbstractPage.java
|
Java
|
[] | null |
[] |
package com.Maxpay;
import com.paulhammant.ngwebdriver.NgWebDriver;
import org.openqa.selenium.*;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.util.concurrent.TimeUnit;
import static org.openqa.selenium.support.ui.ExpectedConditions.*;
public abstract class AbstractPage {
private static final String loaderLocator = "//div[@id='page-loader']";
@FindBy(xpath = loaderLocator)
WebElement loader;
protected WebDriver driver;
private NgWebDriver ngWebDriver;
WebDriverWait explWait;
JavascriptExecutor jseDriver;
public AbstractPage (WebDriver driver) {
this.driver = driver;
explWait = new WebDriverWait(driver, 10);
this.jseDriver = (JavascriptExecutor) driver;
ngWebDriver = new NgWebDriver(jseDriver);
driver.manage().timeouts().setScriptTimeout(30, TimeUnit.SECONDS);
PageFactory.initElements(driver, this);
}
public void waitForLoading() {
try { // try - на случай, если js в каком то кейсе не начал выполнятся, попытка перехода на другую страницу не произвелась
new WebDriverWait(driver, 1).until(visibilityOf(loader));
} catch (TimeoutException e) {
return;
}
explWait.until(attributeToBe(loader, "style", "display: none;"));
}
public AbstractPage waitForAngularRequestsToFinish() {
ngWebDriver.waitForAngularRequestsToFinish();
return this;
}
}
| 1,660 | 0.693774 | 0.690597 | 47 | 32.489361 | 28.053043 | 136 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.723404 | false | false |
1
|
20e1b4de7a7e542a7b14170a74d745ce97ab92df
| 4,114,578,698,859 |
f883ec7c0d48efef769633256cbd8cfc9ca68a14
|
/web/src/test/java/WebCustomTest.java
|
c708476cf2d160a64e9cca77420abf31f0be2040
|
[] |
no_license
|
pallid4m/jwd-final-project
|
https://github.com/pallid4m/jwd-final-project
|
7a3c7d2ff9954e603ab5a68c5dd889706d6237ee
|
43280bcb694914a08fa4ac0c768bb49a2c66a701
|
refs/heads/master
| 2023-02-02T17:56:55.240000 | 2020-12-20T15:55:02 | 2020-12-20T15:55:02 | 300,156,139 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test;
import java.util.*;
public class WebCustomTest {
private static final Logger logger = LogManager.getLogger(WebCustomTest.class);
@Test
public void codingTest() {
String value = "123";
byte[] encode = Base64.getEncoder().encode(value.getBytes());
byte[] decode = Base64.getDecoder().decode(encode);
logger.info(value);
logger.info(new String(encode));
logger.info(new String(decode));
}
@Test
public void uuidTest() {
logger.info(UUID.randomUUID());
logger.info(UUID.fromString("1-2-3-4-5"));
}
}
|
UTF-8
|
Java
| 699 |
java
|
WebCustomTest.java
|
Java
|
[] | null |
[] |
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test;
import java.util.*;
public class WebCustomTest {
private static final Logger logger = LogManager.getLogger(WebCustomTest.class);
@Test
public void codingTest() {
String value = "123";
byte[] encode = Base64.getEncoder().encode(value.getBytes());
byte[] decode = Base64.getDecoder().decode(encode);
logger.info(value);
logger.info(new String(encode));
logger.info(new String(decode));
}
@Test
public void uuidTest() {
logger.info(UUID.randomUUID());
logger.info(UUID.fromString("1-2-3-4-5"));
}
}
| 699 | 0.649499 | 0.629471 | 25 | 26.959999 | 22.491741 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.52 | false | false |
1
|
9ecccff747c2ab9912477f73904e572908a387d1
| 2,800,318,737,487 |
a54016626d37e7baf2be2175f7bf78ac93e32ede
|
/CommonBanner/src/main/java/com/view/commonbanner/load/ImageLoadInterface.java
|
4e27700250ba099b9043ac63a5dc4a31b8507a2b
|
[] |
no_license
|
MrSimpleX/BannerDemo
|
https://github.com/MrSimpleX/BannerDemo
|
8c0e3457e0774b4a3a82369fd0467ef9bff90c47
|
aab46ccf2557bed2f40de63e905d617f46c8fbef
|
refs/heads/master
| 2020-04-15T16:06:52.096000 | 2019-01-09T09:23:16 | 2019-01-09T09:23:16 | 164,820,652 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.view.commonbanner.load;
import android.content.Context;
import android.view.View;
import java.io.Serializable;
/**
* @author MrSimpleZ
* @version V1.0
* @Title: BannerDemo
* @Package com.view.commonbanner.load
* @Description: 图片加载器
* @date 2019/1/8 14:52
*/
public interface ImageLoadInterface<T extends View> extends Serializable {
void displayImage(Context context, String url, T view);
T createView(Context context);
}
|
UTF-8
|
Java
| 460 |
java
|
ImageLoadInterface.java
|
Java
|
[
{
"context": "iew;\n\nimport java.io.Serializable;\n\n/**\n * @author MrSimpleZ\n * @version V1.0\n * @Title: BannerDemo\n * @Packag",
"end": 150,
"score": 0.9996326565742493,
"start": 141,
"tag": "USERNAME",
"value": "MrSimpleZ"
}
] | null |
[] |
package com.view.commonbanner.load;
import android.content.Context;
import android.view.View;
import java.io.Serializable;
/**
* @author MrSimpleZ
* @version V1.0
* @Title: BannerDemo
* @Package com.view.commonbanner.load
* @Description: 图片加载器
* @date 2019/1/8 14:52
*/
public interface ImageLoadInterface<T extends View> extends Serializable {
void displayImage(Context context, String url, T view);
T createView(Context context);
}
| 460 | 0.744444 | 0.717778 | 21 | 20.428572 | 19.703932 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false |
1
|
1b96378de085fc47348d444fb643727c4576e581
| 32,495,722,585,445 |
963599f6f1f376ba94cbb504e8b324bcce5de7a3
|
/sources/p042cz/msebera/android/httpclient/impl/cookie/BasicExpiresHandler.java
|
fa1ec122b994bfd2633d03873d76cc19b6063bb6
|
[] |
no_license
|
NikiHard/cuddly-pancake
|
https://github.com/NikiHard/cuddly-pancake
|
563718cb73fdc4b7b12c6233d9bf44f381dd6759
|
3a5aa80d25d12da08fd621dc3a15fbd536d0b3d4
|
refs/heads/main
| 2023-04-09T06:58:04.403000 | 2021-04-20T00:45:08 | 2021-04-20T00:45:08 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package p042cz.msebera.android.httpclient.impl.cookie;
import java.util.Date;
import p042cz.msebera.android.httpclient.client.utils.DateUtils;
import p042cz.msebera.android.httpclient.cookie.C4460SM;
import p042cz.msebera.android.httpclient.cookie.MalformedCookieException;
import p042cz.msebera.android.httpclient.cookie.SetCookie;
import p042cz.msebera.android.httpclient.util.Args;
/* renamed from: cz.msebera.android.httpclient.impl.cookie.BasicExpiresHandler */
public class BasicExpiresHandler extends AbstractCookieAttributeHandler {
private final String[] datepatterns;
public BasicExpiresHandler(String[] strArr) {
Args.notNull(strArr, "Array of date patterns");
this.datepatterns = strArr;
}
public void parse(SetCookie setCookie, String str) throws MalformedCookieException {
Args.notNull(setCookie, C4460SM.COOKIE);
if (str != null) {
Date parseDate = DateUtils.parseDate(str, this.datepatterns);
if (parseDate != null) {
setCookie.setExpiryDate(parseDate);
return;
}
throw new MalformedCookieException("Unable to parse expires attribute: " + str);
}
throw new MalformedCookieException("Missing value for expires attribute");
}
}
|
UTF-8
|
Java
| 1,294 |
java
|
BasicExpiresHandler.java
|
Java
|
[] | null |
[] |
package p042cz.msebera.android.httpclient.impl.cookie;
import java.util.Date;
import p042cz.msebera.android.httpclient.client.utils.DateUtils;
import p042cz.msebera.android.httpclient.cookie.C4460SM;
import p042cz.msebera.android.httpclient.cookie.MalformedCookieException;
import p042cz.msebera.android.httpclient.cookie.SetCookie;
import p042cz.msebera.android.httpclient.util.Args;
/* renamed from: cz.msebera.android.httpclient.impl.cookie.BasicExpiresHandler */
public class BasicExpiresHandler extends AbstractCookieAttributeHandler {
private final String[] datepatterns;
public BasicExpiresHandler(String[] strArr) {
Args.notNull(strArr, "Array of date patterns");
this.datepatterns = strArr;
}
public void parse(SetCookie setCookie, String str) throws MalformedCookieException {
Args.notNull(setCookie, C4460SM.COOKIE);
if (str != null) {
Date parseDate = DateUtils.parseDate(str, this.datepatterns);
if (parseDate != null) {
setCookie.setExpiryDate(parseDate);
return;
}
throw new MalformedCookieException("Unable to parse expires attribute: " + str);
}
throw new MalformedCookieException("Missing value for expires attribute");
}
}
| 1,294 | 0.720247 | 0.700155 | 31 | 40.741936 | 29.280586 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.645161 | false | false |
1
|
02369d4481765714a6000b922c367145f9783feb
| 22,471,268,921,017 |
e66deea4e50a7023903cd9a1d1d97b7832b3b95f
|
/src/main/java/nio/ExampleCopy.java
|
43376c63649a17c64a42cedcfc128e40ac55d29b
|
[] |
no_license
|
xwj920930/thinkingInJava
|
https://github.com/xwj920930/thinkingInJava
|
f5e6b27cfca8b4b685a9da27be9cd533b6ca68df
|
a4e791cac560916075dcaf0971aefbe59de39555
|
refs/heads/master
| 2021-07-14T04:56:18.598000 | 2020-11-11T06:03:51 | 2020-11-11T06:03:51 | 206,221,930 | 0 | 0 | null | false | 2020-10-13T15:46:55 | 2019-09-04T03:20:34 | 2020-07-16T02:40:39 | 2020-10-13T15:46:53 | 448 | 0 | 0 | 1 |
Java
| false | false |
package nio;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* @Description buffer使用实例
* @Author yuki
* @Date 2019/6/5 9:28
* @Version 1.0
**/
public class ExampleCopy {
public static void main(String[] args) throws IOException {
RandomAccessFile fileIn=new RandomAccessFile("D:\\test\\access.txt","rw");
RandomAccessFile fileOut=new RandomAccessFile("D:\\test\\access2.txt","rw");
FileChannel channelIn = fileIn.getChannel();//通道
FileChannel channelOut = fileOut.getChannel();//通道
ByteBuffer buffer=ByteBuffer.allocate(48);//缓冲区
int read = channelIn.read(buffer);//数据从通道读入缓冲
while (read != -1){//通道是否读完
buffer.flip();//反转缓冲区,将Buffer从写入模式切换到读取模式
channelOut.write(buffer);
buffer.clear();//清空,将Buffer从读取模式切换到写入模式
read=channelIn.read(buffer);//下一次数据从通道读入缓冲
}
fileIn.close();
fileOut.close();
}
}
|
UTF-8
|
Java
| 1,164 |
java
|
ExampleCopy.java
|
Java
|
[
{
"context": "hannel;\n\n/**\n * @Description buffer使用实例\n * @Author yuki\n * @Date 2019/6/5 9:28\n * @Version 1.0\n **/\npubli",
"end": 188,
"score": 0.9990212321281433,
"start": 184,
"tag": "USERNAME",
"value": "yuki"
}
] | null |
[] |
package nio;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* @Description buffer使用实例
* @Author yuki
* @Date 2019/6/5 9:28
* @Version 1.0
**/
public class ExampleCopy {
public static void main(String[] args) throws IOException {
RandomAccessFile fileIn=new RandomAccessFile("D:\\test\\access.txt","rw");
RandomAccessFile fileOut=new RandomAccessFile("D:\\test\\access2.txt","rw");
FileChannel channelIn = fileIn.getChannel();//通道
FileChannel channelOut = fileOut.getChannel();//通道
ByteBuffer buffer=ByteBuffer.allocate(48);//缓冲区
int read = channelIn.read(buffer);//数据从通道读入缓冲
while (read != -1){//通道是否读完
buffer.flip();//反转缓冲区,将Buffer从写入模式切换到读取模式
channelOut.write(buffer);
buffer.clear();//清空,将Buffer从读取模式切换到写入模式
read=channelIn.read(buffer);//下一次数据从通道读入缓冲
}
fileIn.close();
fileOut.close();
}
}
| 1,164 | 0.653922 | 0.639216 | 31 | 31.903225 | 23.396105 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.645161 | false | false |
1
|
e3e97bdbccc307c4f966dc08062cb1e90e843004
| 1,537,598,317,179 |
fe76f565fa2f154348000004bbeff19fb7020ac2
|
/app/src/main/java/com/bashar/salatreminder/FragmentSalahTime.java
|
f403d6ce14ce6f57ca393712744bb346d6583b70
|
[] |
no_license
|
bashar13/SalahReminder
|
https://github.com/bashar13/SalahReminder
|
ff6ef6b479a5996381dbd95170e27d527f666883
|
f4f3a609201c490e166452f1dd0bc78449cc458f
|
refs/heads/master
| 2021-06-16T10:31:01.815000 | 2019-07-21T22:59:15 | 2019-07-21T22:59:15 | 187,990,225 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* @author Md Khairul Bashar
* @date 8/17/2015.
*/
package com.bashar.salatreminder;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.TimePicker;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class FragmentSalahTime extends Fragment {
TextView txtCurDate, txtSunrise, textFajr, textDhur, textAsr, textMag, textEsha, timeZoneText;
ImageButton but_fajr, but_dhur, but_asr, but_mag, but_esha;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view;
setHasOptionsMenu(true);
view = inflater.inflate(R.layout.salah_time, container, false);
txtCurDate = view.findViewById(R.id.cur_date);
txtSunrise = view.findViewById(R.id.sunset_sunrise);
textFajr = view.findViewById(R.id.textFajrTime);
textDhur = view.findViewById(R.id.textDhurTime);
textAsr = view.findViewById(R.id.textAsrTime);
textMag = view.findViewById(R.id.textMagTime);
textEsha = view.findViewById(R.id.textEshaTime);
but_fajr = view.findViewById(R.id.fajrAlarm);
but_dhur = view.findViewById(R.id.dhurAlarm);
but_asr = view.findViewById(R.id.asrAlarm);
but_mag = view.findViewById(R.id.magAlarm);
but_esha = view.findViewById(R.id.eshaAlarm);
timeZoneText = view.findViewById(R.id.time_zone);
alarmButtonsOnCLickListenerMethods();
editTimeTextOnClickListenerMethods();
getSetPreferenceValues();
return view;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_salah, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.reset_time:
String title = "Reset Time", message;
if(SharedPreferencesManager.getBooleanPref(getContext(), "FAJR_EDITED", false) ||
SharedPreferencesManager.getBooleanPref(getContext(), "DHUR_EDITED", false) ||
SharedPreferencesManager.getBooleanPref(getContext(), "ASR_EDITED", false) ||
SharedPreferencesManager.getBooleanPref(getContext(), "MAG_EDITED", false) ||
SharedPreferencesManager.getBooleanPref(getContext(), "ESHA_EDITED", false)) {
message = "This will reset the prayer times according to current settings from your customized time and will also cancel the alarms. Are you sure you want to reset?";
showDialog(title, message, "No");
}
else {
message = "You have not customized any prayer time. To set prayer time manually tap on the time of your desired waqt.";
showDialog(title, message, "OK");
}
return true;
}
return false;
}
public void getCurrentDate() {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("EEEE, dd MMMM yyyy");
String formattedDate = df.format(c.getTime());
txtCurDate.setText(formattedDate);
}
public void getTime() {
String prayerTimes[] = PrayTimeManager.prayTime(getContext());
String sunrise = getResources().getString(R.string.sunrise) + ": " + prayerTimes[1]+" " + getResources().getString(R.string.sunset) + ": " + prayerTimes[4];
txtSunrise.setText(sunrise);
textFajr.setText(prayerTimes[0]);
textDhur.setText(prayerTimes[2]);
textAsr.setText(prayerTimes[3]);
textMag.setText(prayerTimes[5]);
textEsha.setText(prayerTimes[6]);
}
public void getTimePicker(final String waq)
{
//Toast.makeText(getActivity(), "Clicked", Toast.LENGTH_LONG).show();
final Calendar mcurrentTime = Calendar.getInstance();
boolean flag;
final SimpleDateFormat mSDF;
int i;
int j;
TimePickerDialog timepickerdialog;
if (SharedPreferencesManager.getIntPref(getContext(), "TIME_FORMAT", 0) == 0)
{
flag = false;
mSDF = new SimpleDateFormat("hh:mm a");
} else
{
flag = true;
mSDF = new SimpleDateFormat("HH:mm");
}
i = mcurrentTime.get(Calendar.HOUR_OF_DAY);
j = mcurrentTime.get(Calendar.MINUTE);
timepickerdialog = new TimePickerDialog(getActivity(), R.style.dialogStyle, new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker timepicker, int k, int l)
{
String time;
mcurrentTime.set(Calendar.HOUR_OF_DAY, k);
mcurrentTime.set(Calendar.MINUTE, l);
time = mSDF.format(mcurrentTime.getTime());
if (waq.equals("fajr")) {
textFajr.setText(time);
but_fajr.setImageResource(R.drawable.ic_alarm_off);
ReminderManager.cancelReminder(getContext(), 1);
SharedPreferencesManager.storeBooleanPref(getContext(), "FAJR_EDITED", true);
SharedPreferencesManager.storeStringPref(getContext(), "FAJR_EDITED_TIME", time);
}
else if (waq.equals("dhur")){
textDhur.setText(time);
but_dhur.setImageResource(R.drawable.ic_alarm_off);
ReminderManager.cancelReminder(getContext(), 2);
SharedPreferencesManager.storeBooleanPref(getContext(), "DHUR_EDITED", true);
SharedPreferencesManager.storeStringPref(getContext(), "DHUR_EDITED_TIME", time);
}
else if (waq.equals("asr")) {
textAsr.setText(time);
but_asr.setImageResource(R.drawable.ic_alarm_off);
ReminderManager.cancelReminder(getContext(), 3);
SharedPreferencesManager.storeBooleanPref(getContext(), "ASR_EDITED", true);
SharedPreferencesManager.storeStringPref(getContext(), "ASR_EDITED_TIME", time);
}
else if (waq.equals("mag")) {
textMag.setText(time);
but_mag.setImageResource(R.drawable.ic_alarm_off);
ReminderManager.cancelReminder(getContext(), 4);
SharedPreferencesManager.storeBooleanPref(getContext(), "MAG_EDITED", true);
SharedPreferencesManager.storeStringPref(getContext(), "MAG_EDITED_TIME", time);
}
else if (waq.equals("esha")) {
textEsha.setText(time);
but_esha.setImageResource(R.drawable.ic_alarm_off);
ReminderManager.cancelReminder(getContext(), 5);
SharedPreferencesManager.storeBooleanPref(getContext(), "ESHA_EDITED", true);
SharedPreferencesManager.storeStringPref(getContext(), "ESHA_EDITED_TIME", time);
}
}
}, i, j, flag);
timepickerdialog.setTitle("Select Time");
timepickerdialog.show();
}
public void getSetPreferenceValues() {
getCurrentDate();
getTime();
setEditedTime();
setAlarmIcon();
timeZoneText.setText(SharedPreferencesManager.getStringPref(getContext(), "CITY_NAME", null));
ReminderManager.cancelAllReminder(getContext());
ReminderManager.setAllReminder(getContext());
}
public void setEditedTime() {
if(SharedPreferencesManager.getBooleanPref(getContext(), "FAJR_EDITED", false))
textFajr.setText(SharedPreferencesManager.getStringPref(getContext(), "FAJR_EDITED_TIME", null));
if(SharedPreferencesManager.getBooleanPref(getContext(), "DHUR_EDITED", false))
textDhur.setText(SharedPreferencesManager.getStringPref(getContext(), "DHUR_EDITED_TIME", null));
if(SharedPreferencesManager.getBooleanPref(getContext(), "ASR_EDITED", false))
textAsr.setText(SharedPreferencesManager.getStringPref(getContext(), "ASR_EDITED_TIME", null));
if(SharedPreferencesManager.getBooleanPref(getContext(), "MAG_EDITED", false))
textMag.setText(SharedPreferencesManager.getStringPref(getContext(), "MAG_EDITED_TIME", null));
if(SharedPreferencesManager.getBooleanPref(getContext(), "ESHA_EDITED", false))
textEsha.setText(SharedPreferencesManager.getStringPref(getContext(), "ESHA_EDITED_TIME", null));
}
public void setAlarmIcon() {
if(SharedPreferencesManager.getBooleanPref(getContext(), "FAJR_ALARM", false)) {
but_fajr.setImageResource(R.drawable.ic_alarm);
String time = textFajr.getText().toString();
ReminderManager.setReminder(getContext(), 1, time, "Fajr Time");
}
else
but_fajr.setImageResource(R.drawable.ic_alarm_off);
if(SharedPreferencesManager.getBooleanPref(getContext(), "DHUR_ALARM", false)) {
but_dhur.setImageResource(R.drawable.ic_alarm);
String time = textDhur.getText().toString();
ReminderManager.setReminder(getContext(), 2, time, "Dhur Time");
}
else
but_dhur.setImageResource(R.drawable.ic_alarm_off);
if(SharedPreferencesManager.getBooleanPref(getContext(), "ASR_ALARM", false)) {
but_asr.setImageResource(R.drawable.ic_alarm);
String time = textAsr.getText().toString();
ReminderManager.setReminder(getContext(), 3, time, "Asr Time");
}
else
but_asr.setImageResource(R.drawable.ic_alarm_off);
if(SharedPreferencesManager.getBooleanPref(getContext(), "MAG_ALARM", false)) {
but_mag.setImageResource(R.drawable.ic_alarm);
String time = textMag.getText().toString();
ReminderManager.setReminder(getContext(), 4, time, "Maghrib Time");
}
else
but_mag.setImageResource(R.drawable.ic_alarm_off);
if(SharedPreferencesManager.getBooleanPref(getContext(), "ESHA_ALARM", false)) {
but_esha.setImageResource(R.drawable.ic_alarm);
String time = textEsha.getText().toString();
ReminderManager.setReminder(getContext(), 5, time, "Esha Time");
}
else
but_esha.setImageResource(R.drawable.ic_alarm_off);
}
public void showDialog(String title, String message, final String butText) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.dialogStyle);
builder.setTitle(title)
.setMessage(message)
.setCancelable(false)
.setPositiveButton(butText, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if(butText.equals("Cancel")) {
System.exit(1);
}
else
dialog.cancel();
}
});
if(butText.equals("No")) {
builder.setNegativeButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
SharedPreferencesManager.storeBooleanPref(getContext(), "FAJR_EDITED", false);
SharedPreferencesManager.storeBooleanPref(getContext(), "DHUR_EDITED", false);
SharedPreferencesManager.storeBooleanPref(getContext(), "ASR_EDITED", false);
SharedPreferencesManager.storeBooleanPref(getContext(), "MAG_EDITED", false);
SharedPreferencesManager.storeBooleanPref(getContext(), "ESHA_EDITED", false);
SharedPreferencesManager.storeBooleanPref(getContext(), "FAJR_ALARM", false );
SharedPreferencesManager.storeBooleanPref(getContext(), "DHUR_ALARM", false );
SharedPreferencesManager.storeBooleanPref(getContext(), "ASR_ALARM", false );
SharedPreferencesManager.storeBooleanPref(getContext(), "MAG_ALARM", false );
SharedPreferencesManager.storeBooleanPref(getContext(), "ESHA_ALARM", false );
ReminderManager.cancelAllReminder(getContext());
getSetPreferenceValues();
dialog.cancel();
}
});
} else if(butText.equals("Cancel")) {
builder.setNegativeButton("Enable Location", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
}
AlertDialog alert = builder.create();
alert.show();
}
private void alarmButtonsOnCLickListenerMethods() {
but_fajr.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(SharedPreferencesManager.getBooleanPref(getContext(), "FAJR_ALARM", false)) {
SharedPreferencesManager.storeBooleanPref(getContext(), "FAJR_ALARM", false);
ReminderManager.cancelReminder(getContext(), 1);
but_fajr.setImageResource(R.drawable.ic_alarm_off);
}
else {
SharedPreferencesManager.storeBooleanPref(getContext(), "FAJR_ALARM", true);
but_fajr.setImageResource(R.drawable.ic_alarm);
String time = textFajr.getText().toString();
ReminderManager.setReminder(getContext(), 1, time, "Fajr");
}
}
});
but_dhur.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(SharedPreferencesManager.getBooleanPref(getContext(), "DHUR_ALARM", false)) {
SharedPreferencesManager.storeBooleanPref(getContext(), "DHUR_ALARM", false);
ReminderManager.cancelReminder(getContext(), 2);
but_dhur.setImageResource(R.drawable.ic_alarm_off);
}
else {
SharedPreferencesManager.storeBooleanPref(getContext(), "DHUR_ALARM", true);
but_dhur.setImageResource(R.drawable.ic_alarm);
String time = textDhur.getText().toString();
ReminderManager.setReminder(getContext(), 2, time, "Dhur");
}
}
});
but_asr.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(SharedPreferencesManager.getBooleanPref(getContext(), "ASR_ALARM", false)) {
SharedPreferencesManager.storeBooleanPref(getContext(), "ASR_ALARM", false);
ReminderManager.cancelReminder(getContext(), 3);
but_asr.setImageResource(R.drawable.ic_alarm_off);
}
else {
SharedPreferencesManager.storeBooleanPref(getContext(), "ASR_ALARM", true);
but_asr.setImageResource(R.drawable.ic_alarm);
String time = textAsr.getText().toString();
ReminderManager.setReminder(getContext(), 3, time, "Asr");
}
}
});
but_mag.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (SharedPreferencesManager.getBooleanPref(getContext(), "MAG_ALARM", false)) {
SharedPreferencesManager.storeBooleanPref(getContext(), "MAG_ALARM", false);
ReminderManager.cancelReminder(getContext(), 4);
but_mag.setImageResource(R.drawable.ic_alarm_off);
} else {
SharedPreferencesManager.storeBooleanPref(getContext(), "MAG_ALARM", true);
but_mag.setImageResource(R.drawable.ic_alarm);
String time = textMag.getText().toString();
ReminderManager.setReminder(getContext(), 4, time, "Maghrib");
}
}
});
but_esha.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (SharedPreferencesManager.getBooleanPref(getContext(), "ESHA_ALARM", false)) {
SharedPreferencesManager.storeBooleanPref(getContext(), "ESHA_ALARM", false);
ReminderManager.cancelReminder(getContext(), 5);
but_esha.setImageResource(R.drawable.ic_alarm_off);
} else {
SharedPreferencesManager.storeBooleanPref(getContext(), "ESHA_ALARM", true);
but_esha.setImageResource(R.drawable.ic_alarm);
String time = textEsha.getText().toString();
ReminderManager.setReminder(getContext(), 5, time, "Esha");
}
}
});
}
private void editTimeTextOnClickListenerMethods() {
textFajr.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getTimePicker("fajr");
}
});
textDhur.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getTimePicker("dhur");
}
});
textAsr.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getTimePicker("asr");
}
});
textMag.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getTimePicker("mag");
}
});
textEsha.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getTimePicker("esha");
}
});
}
@Override
public void onResume(){
super.onResume();
getSetPreferenceValues();
}
}
|
UTF-8
|
Java
| 19,402 |
java
|
FragmentSalahTime.java
|
Java
|
[
{
"context": "/**\r\n * @author Md Khairul Bashar\r\n * @date 8/17/2015.\r\n */\r\n\r\npackage com.bashar.s",
"end": 33,
"score": 0.9997713565826416,
"start": 16,
"tag": "NAME",
"value": "Md Khairul Bashar"
},
{
"context": "inderManager.setReminder(getContext(), 5, time, \"Esha Time\");\r\n }\r\n else\r\n but",
"end": 11222,
"score": 0.6063753366470337,
"start": 11219,
"tag": "NAME",
"value": "sha"
}
] | null |
[] |
/**
* @author <NAME>
* @date 8/17/2015.
*/
package com.bashar.salatreminder;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.TimePicker;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class FragmentSalahTime extends Fragment {
TextView txtCurDate, txtSunrise, textFajr, textDhur, textAsr, textMag, textEsha, timeZoneText;
ImageButton but_fajr, but_dhur, but_asr, but_mag, but_esha;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view;
setHasOptionsMenu(true);
view = inflater.inflate(R.layout.salah_time, container, false);
txtCurDate = view.findViewById(R.id.cur_date);
txtSunrise = view.findViewById(R.id.sunset_sunrise);
textFajr = view.findViewById(R.id.textFajrTime);
textDhur = view.findViewById(R.id.textDhurTime);
textAsr = view.findViewById(R.id.textAsrTime);
textMag = view.findViewById(R.id.textMagTime);
textEsha = view.findViewById(R.id.textEshaTime);
but_fajr = view.findViewById(R.id.fajrAlarm);
but_dhur = view.findViewById(R.id.dhurAlarm);
but_asr = view.findViewById(R.id.asrAlarm);
but_mag = view.findViewById(R.id.magAlarm);
but_esha = view.findViewById(R.id.eshaAlarm);
timeZoneText = view.findViewById(R.id.time_zone);
alarmButtonsOnCLickListenerMethods();
editTimeTextOnClickListenerMethods();
getSetPreferenceValues();
return view;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_salah, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.reset_time:
String title = "Reset Time", message;
if(SharedPreferencesManager.getBooleanPref(getContext(), "FAJR_EDITED", false) ||
SharedPreferencesManager.getBooleanPref(getContext(), "DHUR_EDITED", false) ||
SharedPreferencesManager.getBooleanPref(getContext(), "ASR_EDITED", false) ||
SharedPreferencesManager.getBooleanPref(getContext(), "MAG_EDITED", false) ||
SharedPreferencesManager.getBooleanPref(getContext(), "ESHA_EDITED", false)) {
message = "This will reset the prayer times according to current settings from your customized time and will also cancel the alarms. Are you sure you want to reset?";
showDialog(title, message, "No");
}
else {
message = "You have not customized any prayer time. To set prayer time manually tap on the time of your desired waqt.";
showDialog(title, message, "OK");
}
return true;
}
return false;
}
public void getCurrentDate() {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("EEEE, dd MMMM yyyy");
String formattedDate = df.format(c.getTime());
txtCurDate.setText(formattedDate);
}
public void getTime() {
String prayerTimes[] = PrayTimeManager.prayTime(getContext());
String sunrise = getResources().getString(R.string.sunrise) + ": " + prayerTimes[1]+" " + getResources().getString(R.string.sunset) + ": " + prayerTimes[4];
txtSunrise.setText(sunrise);
textFajr.setText(prayerTimes[0]);
textDhur.setText(prayerTimes[2]);
textAsr.setText(prayerTimes[3]);
textMag.setText(prayerTimes[5]);
textEsha.setText(prayerTimes[6]);
}
public void getTimePicker(final String waq)
{
//Toast.makeText(getActivity(), "Clicked", Toast.LENGTH_LONG).show();
final Calendar mcurrentTime = Calendar.getInstance();
boolean flag;
final SimpleDateFormat mSDF;
int i;
int j;
TimePickerDialog timepickerdialog;
if (SharedPreferencesManager.getIntPref(getContext(), "TIME_FORMAT", 0) == 0)
{
flag = false;
mSDF = new SimpleDateFormat("hh:mm a");
} else
{
flag = true;
mSDF = new SimpleDateFormat("HH:mm");
}
i = mcurrentTime.get(Calendar.HOUR_OF_DAY);
j = mcurrentTime.get(Calendar.MINUTE);
timepickerdialog = new TimePickerDialog(getActivity(), R.style.dialogStyle, new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker timepicker, int k, int l)
{
String time;
mcurrentTime.set(Calendar.HOUR_OF_DAY, k);
mcurrentTime.set(Calendar.MINUTE, l);
time = mSDF.format(mcurrentTime.getTime());
if (waq.equals("fajr")) {
textFajr.setText(time);
but_fajr.setImageResource(R.drawable.ic_alarm_off);
ReminderManager.cancelReminder(getContext(), 1);
SharedPreferencesManager.storeBooleanPref(getContext(), "FAJR_EDITED", true);
SharedPreferencesManager.storeStringPref(getContext(), "FAJR_EDITED_TIME", time);
}
else if (waq.equals("dhur")){
textDhur.setText(time);
but_dhur.setImageResource(R.drawable.ic_alarm_off);
ReminderManager.cancelReminder(getContext(), 2);
SharedPreferencesManager.storeBooleanPref(getContext(), "DHUR_EDITED", true);
SharedPreferencesManager.storeStringPref(getContext(), "DHUR_EDITED_TIME", time);
}
else if (waq.equals("asr")) {
textAsr.setText(time);
but_asr.setImageResource(R.drawable.ic_alarm_off);
ReminderManager.cancelReminder(getContext(), 3);
SharedPreferencesManager.storeBooleanPref(getContext(), "ASR_EDITED", true);
SharedPreferencesManager.storeStringPref(getContext(), "ASR_EDITED_TIME", time);
}
else if (waq.equals("mag")) {
textMag.setText(time);
but_mag.setImageResource(R.drawable.ic_alarm_off);
ReminderManager.cancelReminder(getContext(), 4);
SharedPreferencesManager.storeBooleanPref(getContext(), "MAG_EDITED", true);
SharedPreferencesManager.storeStringPref(getContext(), "MAG_EDITED_TIME", time);
}
else if (waq.equals("esha")) {
textEsha.setText(time);
but_esha.setImageResource(R.drawable.ic_alarm_off);
ReminderManager.cancelReminder(getContext(), 5);
SharedPreferencesManager.storeBooleanPref(getContext(), "ESHA_EDITED", true);
SharedPreferencesManager.storeStringPref(getContext(), "ESHA_EDITED_TIME", time);
}
}
}, i, j, flag);
timepickerdialog.setTitle("Select Time");
timepickerdialog.show();
}
public void getSetPreferenceValues() {
getCurrentDate();
getTime();
setEditedTime();
setAlarmIcon();
timeZoneText.setText(SharedPreferencesManager.getStringPref(getContext(), "CITY_NAME", null));
ReminderManager.cancelAllReminder(getContext());
ReminderManager.setAllReminder(getContext());
}
public void setEditedTime() {
if(SharedPreferencesManager.getBooleanPref(getContext(), "FAJR_EDITED", false))
textFajr.setText(SharedPreferencesManager.getStringPref(getContext(), "FAJR_EDITED_TIME", null));
if(SharedPreferencesManager.getBooleanPref(getContext(), "DHUR_EDITED", false))
textDhur.setText(SharedPreferencesManager.getStringPref(getContext(), "DHUR_EDITED_TIME", null));
if(SharedPreferencesManager.getBooleanPref(getContext(), "ASR_EDITED", false))
textAsr.setText(SharedPreferencesManager.getStringPref(getContext(), "ASR_EDITED_TIME", null));
if(SharedPreferencesManager.getBooleanPref(getContext(), "MAG_EDITED", false))
textMag.setText(SharedPreferencesManager.getStringPref(getContext(), "MAG_EDITED_TIME", null));
if(SharedPreferencesManager.getBooleanPref(getContext(), "ESHA_EDITED", false))
textEsha.setText(SharedPreferencesManager.getStringPref(getContext(), "ESHA_EDITED_TIME", null));
}
public void setAlarmIcon() {
if(SharedPreferencesManager.getBooleanPref(getContext(), "FAJR_ALARM", false)) {
but_fajr.setImageResource(R.drawable.ic_alarm);
String time = textFajr.getText().toString();
ReminderManager.setReminder(getContext(), 1, time, "Fajr Time");
}
else
but_fajr.setImageResource(R.drawable.ic_alarm_off);
if(SharedPreferencesManager.getBooleanPref(getContext(), "DHUR_ALARM", false)) {
but_dhur.setImageResource(R.drawable.ic_alarm);
String time = textDhur.getText().toString();
ReminderManager.setReminder(getContext(), 2, time, "Dhur Time");
}
else
but_dhur.setImageResource(R.drawable.ic_alarm_off);
if(SharedPreferencesManager.getBooleanPref(getContext(), "ASR_ALARM", false)) {
but_asr.setImageResource(R.drawable.ic_alarm);
String time = textAsr.getText().toString();
ReminderManager.setReminder(getContext(), 3, time, "Asr Time");
}
else
but_asr.setImageResource(R.drawable.ic_alarm_off);
if(SharedPreferencesManager.getBooleanPref(getContext(), "MAG_ALARM", false)) {
but_mag.setImageResource(R.drawable.ic_alarm);
String time = textMag.getText().toString();
ReminderManager.setReminder(getContext(), 4, time, "Maghrib Time");
}
else
but_mag.setImageResource(R.drawable.ic_alarm_off);
if(SharedPreferencesManager.getBooleanPref(getContext(), "ESHA_ALARM", false)) {
but_esha.setImageResource(R.drawable.ic_alarm);
String time = textEsha.getText().toString();
ReminderManager.setReminder(getContext(), 5, time, "Esha Time");
}
else
but_esha.setImageResource(R.drawable.ic_alarm_off);
}
public void showDialog(String title, String message, final String butText) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.dialogStyle);
builder.setTitle(title)
.setMessage(message)
.setCancelable(false)
.setPositiveButton(butText, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if(butText.equals("Cancel")) {
System.exit(1);
}
else
dialog.cancel();
}
});
if(butText.equals("No")) {
builder.setNegativeButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
SharedPreferencesManager.storeBooleanPref(getContext(), "FAJR_EDITED", false);
SharedPreferencesManager.storeBooleanPref(getContext(), "DHUR_EDITED", false);
SharedPreferencesManager.storeBooleanPref(getContext(), "ASR_EDITED", false);
SharedPreferencesManager.storeBooleanPref(getContext(), "MAG_EDITED", false);
SharedPreferencesManager.storeBooleanPref(getContext(), "ESHA_EDITED", false);
SharedPreferencesManager.storeBooleanPref(getContext(), "FAJR_ALARM", false );
SharedPreferencesManager.storeBooleanPref(getContext(), "DHUR_ALARM", false );
SharedPreferencesManager.storeBooleanPref(getContext(), "ASR_ALARM", false );
SharedPreferencesManager.storeBooleanPref(getContext(), "MAG_ALARM", false );
SharedPreferencesManager.storeBooleanPref(getContext(), "ESHA_ALARM", false );
ReminderManager.cancelAllReminder(getContext());
getSetPreferenceValues();
dialog.cancel();
}
});
} else if(butText.equals("Cancel")) {
builder.setNegativeButton("Enable Location", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
}
AlertDialog alert = builder.create();
alert.show();
}
private void alarmButtonsOnCLickListenerMethods() {
but_fajr.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(SharedPreferencesManager.getBooleanPref(getContext(), "FAJR_ALARM", false)) {
SharedPreferencesManager.storeBooleanPref(getContext(), "FAJR_ALARM", false);
ReminderManager.cancelReminder(getContext(), 1);
but_fajr.setImageResource(R.drawable.ic_alarm_off);
}
else {
SharedPreferencesManager.storeBooleanPref(getContext(), "FAJR_ALARM", true);
but_fajr.setImageResource(R.drawable.ic_alarm);
String time = textFajr.getText().toString();
ReminderManager.setReminder(getContext(), 1, time, "Fajr");
}
}
});
but_dhur.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(SharedPreferencesManager.getBooleanPref(getContext(), "DHUR_ALARM", false)) {
SharedPreferencesManager.storeBooleanPref(getContext(), "DHUR_ALARM", false);
ReminderManager.cancelReminder(getContext(), 2);
but_dhur.setImageResource(R.drawable.ic_alarm_off);
}
else {
SharedPreferencesManager.storeBooleanPref(getContext(), "DHUR_ALARM", true);
but_dhur.setImageResource(R.drawable.ic_alarm);
String time = textDhur.getText().toString();
ReminderManager.setReminder(getContext(), 2, time, "Dhur");
}
}
});
but_asr.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(SharedPreferencesManager.getBooleanPref(getContext(), "ASR_ALARM", false)) {
SharedPreferencesManager.storeBooleanPref(getContext(), "ASR_ALARM", false);
ReminderManager.cancelReminder(getContext(), 3);
but_asr.setImageResource(R.drawable.ic_alarm_off);
}
else {
SharedPreferencesManager.storeBooleanPref(getContext(), "ASR_ALARM", true);
but_asr.setImageResource(R.drawable.ic_alarm);
String time = textAsr.getText().toString();
ReminderManager.setReminder(getContext(), 3, time, "Asr");
}
}
});
but_mag.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (SharedPreferencesManager.getBooleanPref(getContext(), "MAG_ALARM", false)) {
SharedPreferencesManager.storeBooleanPref(getContext(), "MAG_ALARM", false);
ReminderManager.cancelReminder(getContext(), 4);
but_mag.setImageResource(R.drawable.ic_alarm_off);
} else {
SharedPreferencesManager.storeBooleanPref(getContext(), "MAG_ALARM", true);
but_mag.setImageResource(R.drawable.ic_alarm);
String time = textMag.getText().toString();
ReminderManager.setReminder(getContext(), 4, time, "Maghrib");
}
}
});
but_esha.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (SharedPreferencesManager.getBooleanPref(getContext(), "ESHA_ALARM", false)) {
SharedPreferencesManager.storeBooleanPref(getContext(), "ESHA_ALARM", false);
ReminderManager.cancelReminder(getContext(), 5);
but_esha.setImageResource(R.drawable.ic_alarm_off);
} else {
SharedPreferencesManager.storeBooleanPref(getContext(), "ESHA_ALARM", true);
but_esha.setImageResource(R.drawable.ic_alarm);
String time = textEsha.getText().toString();
ReminderManager.setReminder(getContext(), 5, time, "Esha");
}
}
});
}
private void editTimeTextOnClickListenerMethods() {
textFajr.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getTimePicker("fajr");
}
});
textDhur.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getTimePicker("dhur");
}
});
textAsr.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getTimePicker("asr");
}
});
textMag.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getTimePicker("mag");
}
});
textEsha.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getTimePicker("esha");
}
});
}
@Override
public void onResume(){
super.onResume();
getSetPreferenceValues();
}
}
| 19,391 | 0.582723 | 0.580713 | 436 | 42.5 | 33.786331 | 186 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.961009 | false | false |
1
|
80497b9d4244ea3defa059b7d97f5eea9f3dab21
| 13,821,204,799,126 |
30c69df52e5e97dbb53bfeb3f3ba94e43ea22365
|
/AnalyticsRestServer/src/main/java/com/myapps/analytics/domain/User.java
|
dd0bdd617f828d0acc6c823865ef2b1d7a9074a4
|
[] |
no_license
|
vpedireddy/analytics
|
https://github.com/vpedireddy/analytics
|
ca294a9f98f6697ada8b481ef61ad8edce37f922
|
4e8a67d3e688fcadf3a0c907ed366a16bee96908
|
refs/heads/master
| 2020-07-14T00:06:21.585000 | 2016-10-04T11:53:32 | 2016-10-04T11:53:32 | 66,919,753 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.myapps.analytics.domain;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class User implements UserDetails, Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private int id;
private String firstName;
private String lastName;
private String username;
private String password;
private String mobile;
private int age;
private String sex;
private String email;
private Boolean isAdmin;
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id
* the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the firstName
*/
public String getFirstName() {
return firstName;
}
/**
* @param firstName
* the firstName to set
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* @return the lastName
*/
public String getLastName() {
return lastName;
}
/**
* @param lastName
* the lastName to set
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* @param username
* the username to set
*/
public void setUsername(String username) {
this.username = username;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password
* the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* @return the mobile
*/
public String getMobile() {
return mobile;
}
/**
* @param mobile
* the mobile to set
*/
public void setMobile(String mobile) {
this.mobile = mobile;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age
* the age to set
*/
public void setAge(int age) {
this.age = age;
}
/**
* @return the sex
*/
public String getSex() {
return sex;
}
/**
* @param sex
* the sex to set
*/
public void setSex(String sex) {
this.sex = sex;
}
/**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @param email
* the email to set
*/
public void setEmail(String email) {
this.email = email;
}
/**
* @return the isAdmin
*/
public Boolean isAdmin() {
return isAdmin;
}
/**
* @param isAdmin the isAdmin to set
*/
public void setAdmin(Boolean isAdmin) {
this.isAdmin = isAdmin;
}
public User(int id, String firstName, String lastName, String username, String password, String mobile, int age,
String sex, String email,Boolean isAdmin) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.username = username;
this.password = password;
this.mobile = mobile;
this.age = age;
this.sex = sex;
this.email = email;
this.isAdmin = isAdmin;
}
public User() {
}
@Override
@JsonIgnore
public Collection<? extends GrantedAuthority> getAuthorities() {
Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
SimpleGrantedAuthority authority = new SimpleGrantedAuthority(
verifyUserRole());
authorities.add(authority);
return authorities;
}
private String verifyUserRole(){
if(isAdmin() != null && isAdmin() == true){
return "ROLE_ADMIN";
}else if (isAdmin() != null && isAdmin() == false){
return "ROLE_MODERATOR";
}
else{
return "ROLE_USER";
}
}
@Override
public String getUsername() {
return getEmail();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "User [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", username=" + username
+ ", password=" + password + ", mobile=" + mobile + ", age=" + age + ", sex=" + sex + ", email=" + email
+ ", isAdmin=" + isAdmin+"]";
}
}
|
UTF-8
|
Java
| 4,668 |
java
|
User.java
|
Java
|
[
{
"context": "e;\r\n\t\tthis.lastName = lastName;\r\n\t\tthis.username = username;\r\n\t\tthis.password = password;\r\n\t\tthis.mobile = mo",
"end": 3179,
"score": 0.9995102882385254,
"start": 3171,
"tag": "USERNAME",
"value": "username"
},
{
"context": "e;\r\n\t\tthis.username = username;\r\n\t\tthis.password = password;\r\n\t\tthis.mobile = mobile;\r\n\t\tthis.age = age;\r\n\t\tt",
"end": 3208,
"score": 0.9955217838287354,
"start": 3200,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "() {\r\n\t\treturn \"User [id=\" + id + \", firstName=\" + firstName + \", lastName=\" + lastName + \", username=\" + user",
"end": 4458,
"score": 0.9196052551269531,
"start": 4449,
"tag": "NAME",
"value": "firstName"
},
{
"context": "\"User [id=\" + id + \", firstName=\" + firstName + \", lastName=\" + lastName + \", username=\" + username\r\n\t\t\t\t+ \",",
"end": 4472,
"score": 0.5892689228057861,
"start": 4464,
"tag": "NAME",
"value": "lastName"
},
{
"context": " id + \", firstName=\" + firstName + \", lastName=\" + lastName + \", username=\" + username\r\n\t\t\t\t+ \", password=\" +",
"end": 4485,
"score": 0.9829830527305603,
"start": 4477,
"tag": "NAME",
"value": "lastName"
},
{
"context": "tName + \", lastName=\" + lastName + \", username=\" + username\r\n\t\t\t\t+ \", password=\" + password + \", mobile=\" + m",
"end": 4512,
"score": 0.9978280067443848,
"start": 4504,
"tag": "USERNAME",
"value": "username"
},
{
"context": " + \", username=\" + username\r\n\t\t\t\t+ \", password=\" + password + \", mobile=\" + mobile + \", age=\" + age + \", sex=",
"end": 4544,
"score": 0.9987388849258423,
"start": 4536,
"tag": "PASSWORD",
"value": "password"
}
] | null |
[] |
package com.myapps.analytics.domain;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class User implements UserDetails, Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private int id;
private String firstName;
private String lastName;
private String username;
private String password;
private String mobile;
private int age;
private String sex;
private String email;
private Boolean isAdmin;
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id
* the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the firstName
*/
public String getFirstName() {
return firstName;
}
/**
* @param firstName
* the firstName to set
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* @return the lastName
*/
public String getLastName() {
return lastName;
}
/**
* @param lastName
* the lastName to set
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* @param username
* the username to set
*/
public void setUsername(String username) {
this.username = username;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password
* the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* @return the mobile
*/
public String getMobile() {
return mobile;
}
/**
* @param mobile
* the mobile to set
*/
public void setMobile(String mobile) {
this.mobile = mobile;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age
* the age to set
*/
public void setAge(int age) {
this.age = age;
}
/**
* @return the sex
*/
public String getSex() {
return sex;
}
/**
* @param sex
* the sex to set
*/
public void setSex(String sex) {
this.sex = sex;
}
/**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @param email
* the email to set
*/
public void setEmail(String email) {
this.email = email;
}
/**
* @return the isAdmin
*/
public Boolean isAdmin() {
return isAdmin;
}
/**
* @param isAdmin the isAdmin to set
*/
public void setAdmin(Boolean isAdmin) {
this.isAdmin = isAdmin;
}
public User(int id, String firstName, String lastName, String username, String password, String mobile, int age,
String sex, String email,Boolean isAdmin) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.username = username;
this.password = <PASSWORD>;
this.mobile = mobile;
this.age = age;
this.sex = sex;
this.email = email;
this.isAdmin = isAdmin;
}
public User() {
}
@Override
@JsonIgnore
public Collection<? extends GrantedAuthority> getAuthorities() {
Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
SimpleGrantedAuthority authority = new SimpleGrantedAuthority(
verifyUserRole());
authorities.add(authority);
return authorities;
}
private String verifyUserRole(){
if(isAdmin() != null && isAdmin() == true){
return "ROLE_ADMIN";
}else if (isAdmin() != null && isAdmin() == false){
return "ROLE_MODERATOR";
}
else{
return "ROLE_USER";
}
}
@Override
public String getUsername() {
return getEmail();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "User [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", username=" + username
+ ", password=" + <PASSWORD> + ", mobile=" + mobile + ", age=" + age + ", sex=" + sex + ", email=" + email
+ ", isAdmin=" + isAdmin+"]";
}
}
| 4,672 | 0.604542 | 0.604327 | 251 | 16.59761 | 18.722162 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.406374 | false | false |
1
|
012ac2686b58002ac581cea605faa841c7167489
| 26,396,869,062,725 |
f66a107ef0519c881e14f4a7ecd499a8d45a8f53
|
/library/src/main/java/im/toss/delegationadapter/ItemViewHolder.java
|
924dc6495a4ea79bd227fb3966a708344c61720a
|
[
"Apache-2.0"
] |
permissive
|
stargt/android-delegationadapter
|
https://github.com/stargt/android-delegationadapter
|
aa5bb2d81b10be87b63302c9e2dd0bab395ceb6a
|
cd3a59af6b249139e1ab4408bc9c1d3de7c94cf4
|
refs/heads/master
| 2020-04-28T22:56:37.193000 | 2017-08-14T12:57:10 | 2017-08-14T12:57:10 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package im.toss.delegationadapter;
import android.support.annotation.IdRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.lang.ref.WeakReference;
public class ItemViewHolder<I> extends RecyclerView.ViewHolder {
private final SparseArray<View> viewCache = new SparseArray<>();
private WeakReference<I> itemRef;
public static <I> ItemViewHolder<I> create(ViewGroup parent, @LayoutRes int layoutId) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false);
return new ItemViewHolder<I>(itemView);
}
void setItem(@Nullable I data) {
if (data != null) {
itemRef = new WeakReference<>(data);
} else {
itemRef = null;
}
}
@Nullable
public I getItem() {
if (itemRef != null) {
return itemRef.get();
}
return null;
}
private ItemViewHolder(View itemView) {
super(itemView);
}
public View getView(@IdRes int viewId) {
return getView(viewId, View.class);
}
@SuppressWarnings("unchecked, UnusedParameters")
public <T extends View> T getView(@IdRes int viewId, Class<T> viewType) {
T view = (T) viewCache.get(viewId);
if (view == null) {
view = (T) itemView.findViewById(viewId);
viewCache.put(viewId, view);
}
return view;
}
}
|
UTF-8
|
Java
| 1,506 |
java
|
ItemViewHolder.java
|
Java
|
[] | null |
[] |
package im.toss.delegationadapter;
import android.support.annotation.IdRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.lang.ref.WeakReference;
public class ItemViewHolder<I> extends RecyclerView.ViewHolder {
private final SparseArray<View> viewCache = new SparseArray<>();
private WeakReference<I> itemRef;
public static <I> ItemViewHolder<I> create(ViewGroup parent, @LayoutRes int layoutId) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false);
return new ItemViewHolder<I>(itemView);
}
void setItem(@Nullable I data) {
if (data != null) {
itemRef = new WeakReference<>(data);
} else {
itemRef = null;
}
}
@Nullable
public I getItem() {
if (itemRef != null) {
return itemRef.get();
}
return null;
}
private ItemViewHolder(View itemView) {
super(itemView);
}
public View getView(@IdRes int viewId) {
return getView(viewId, View.class);
}
@SuppressWarnings("unchecked, UnusedParameters")
public <T extends View> T getView(@IdRes int viewId, Class<T> viewType) {
T view = (T) viewCache.get(viewId);
if (view == null) {
view = (T) itemView.findViewById(viewId);
viewCache.put(viewId, view);
}
return view;
}
}
| 1,506 | 0.702523 | 0.701859 | 57 | 25.421053 | 23.206129 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.54386 | false | false |
1
|
0148fc5436c52c3ff0b91cb8c12cc686c6b5f10e
| 27,144,193,372,606 |
d6fcbf4c5fd3adac8702f5e57530329e7144efd7
|
/corejava/ch2/practice test/PT5Test14.java
|
203118b864e6fc918d8c16d4f886ffb0248617d2
|
[] |
no_license
|
prabhatsingh2408/jlc
|
https://github.com/prabhatsingh2408/jlc
|
6d46c5556a999c9a83aec869a6381bf723ee867a
|
213bf35bb25cff69bc03bb4f488723678ccfd784
|
refs/heads/master
| 2021-01-20T18:58:06.596000 | 2016-07-04T09:04:13 | 2016-07-04T09:04:13 | 62,547,129 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
class PT5Test14
{
public static void main(String str[])
{
int a=\u0041;
System.out.println(a);
}
}
|
UTF-8
|
Java
| 98 |
java
|
PT5Test14.java
|
Java
|
[] | null |
[] |
class PT5Test14
{
public static void main(String str[])
{
int a=\u0041;
System.out.println(a);
}
}
| 98 | 0.704082 | 0.632653 | 8 | 11.375 | 12.328195 | 37 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false |
1
|
16971d18adc1e7b0b5b71c71f3f37630d7a7b001
| 20,263,655,716,554 |
e619332dda84a657847557c0827035fd2422084f
|
/cloudjuri/src/main/java/br/com/cloudjuri/model/entity/ProcessoParticipanteAdvogado.java
|
3d6261e47fbb3f689e90ab7c8ae8fa2e88488385
|
[] |
no_license
|
marvanboff/cloud-juri
|
https://github.com/marvanboff/cloud-juri
|
e94bc8f5989b7ee78d7aa0ef787ce0012c77c393
|
1b2a0961a53e63b21538739ded0601fa9501ddde
|
refs/heads/master
| 2016-08-05T08:18:46.461000 | 2015-04-18T04:37:20 | 2015-04-18T04:37:20 | 32,903,697 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package br.com.cloudjuri.model.entity;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.ForeignKey;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
@SequenceGenerator(name = "SEQ_PARTICIPANTE_ADVOGADO", sequenceName = "SEQ_PARTICIPANTE_ADVOGADO")
@Entity
@Table(name = "PROCESSO_PARTICIPANTE_ADVOGADO")
public class ProcessoParticipanteAdvogado implements Auditavel {
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "SEQ_PARTICIPANTE_ADVOGADO")
private Long id;
@ManyToOne(targetEntity = ProcessoParticipante.class)
@JoinColumn(name = "ID_PARTICIPANTE", foreignKey = @ForeignKey(name = "FK_PROCESSO_PARTICIPANTE_ADVOGADO"))
private ProcessoParticipante participante;
@ManyToOne(targetEntity = Advogado.class, cascade = {CascadeType.PERSIST})
@JoinColumn(name = "ID_ADVOGADO", foreignKey = @ForeignKey(name = "FK_PARTICIPANTE_ADVOGADO"))
private Advogado advogado;
@Column(name = "DATA_ULT_ATUALIZACAO")
private Date dataUltAtualizacao;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public ProcessoParticipante getParticipante() {
return participante;
}
public void setParticipante(ProcessoParticipante participante) {
this.participante = participante;
}
public Date getDataUltAtualizacao() {
return dataUltAtualizacao;
}
public void setDataUltAtualizacao(Date dataUltAtualizacao) {
this.dataUltAtualizacao = dataUltAtualizacao;
}
public Advogado getAdvogado() {
return advogado;
}
public void setAdvogado(Advogado advogado) {
this.advogado = advogado;
}
}
|
UTF-8
|
Java
| 1,951 |
java
|
ProcessoParticipanteAdvogado.java
|
Java
|
[] | null |
[] |
package br.com.cloudjuri.model.entity;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.ForeignKey;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
@SequenceGenerator(name = "SEQ_PARTICIPANTE_ADVOGADO", sequenceName = "SEQ_PARTICIPANTE_ADVOGADO")
@Entity
@Table(name = "PROCESSO_PARTICIPANTE_ADVOGADO")
public class ProcessoParticipanteAdvogado implements Auditavel {
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "SEQ_PARTICIPANTE_ADVOGADO")
private Long id;
@ManyToOne(targetEntity = ProcessoParticipante.class)
@JoinColumn(name = "ID_PARTICIPANTE", foreignKey = @ForeignKey(name = "FK_PROCESSO_PARTICIPANTE_ADVOGADO"))
private ProcessoParticipante participante;
@ManyToOne(targetEntity = Advogado.class, cascade = {CascadeType.PERSIST})
@JoinColumn(name = "ID_ADVOGADO", foreignKey = @ForeignKey(name = "FK_PARTICIPANTE_ADVOGADO"))
private Advogado advogado;
@Column(name = "DATA_ULT_ATUALIZACAO")
private Date dataUltAtualizacao;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public ProcessoParticipante getParticipante() {
return participante;
}
public void setParticipante(ProcessoParticipante participante) {
this.participante = participante;
}
public Date getDataUltAtualizacao() {
return dataUltAtualizacao;
}
public void setDataUltAtualizacao(Date dataUltAtualizacao) {
this.dataUltAtualizacao = dataUltAtualizacao;
}
public Advogado getAdvogado() {
return advogado;
}
public void setAdvogado(Advogado advogado) {
this.advogado = advogado;
}
}
| 1,951 | 0.758073 | 0.758073 | 69 | 26.275362 | 26.688696 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.086957 | false | false |
1
|
21127bf5cfb36cbf93c6a102cb47235ceb095511
| 12,799,002,564,565 |
31bc1627743fcefb6ded06f07d41bc61853ab426
|
/openflowplugin-impl/src/main/java/org/opendaylight/openflowplugin/impl/statistics/services/PortStatsService.java
|
a4bdf4666c3577e04bd6eab1dd98bbf1daa67296
|
[] |
no_license
|
opendaylight/openflowplugin
|
https://github.com/opendaylight/openflowplugin
|
d67f2d311e812339ac977e09b1380ba22931d922
|
bc15fa6cbd453a64d08bed885f4ac3afde171613
|
refs/heads/master
| 2023-09-01T19:48:38.338000 | 2023-08-31T18:50:02 | 2023-08-31T18:50:02 | 16,362,543 | 60 | 77 | null | false | 2019-07-11T09:23:02 | 2014-01-29T23:13:36 | 2019-07-09T05:31:01 | 2019-07-09T05:30:59 | 22,446 | 46 | 62 | 1 |
Java
| false | false |
/*
* Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.openflowplugin.impl.statistics.services;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
import org.opendaylight.openflowplugin.api.openflow.device.RequestContextStack;
import org.opendaylight.openflowplugin.api.openflow.device.Xid;
import org.opendaylight.openflowplugin.api.openflow.md.util.OpenflowVersion;
import org.opendaylight.openflowplugin.impl.services.util.RequestInputUtils;
import org.opendaylight.openflowplugin.impl.statistics.services.compatibility.AbstractCompatibleStatService;
import org.opendaylight.openflowplugin.impl.statistics.services.compatibility.NodeConnectorStatisticsToNotificationTransformer;
import org.opendaylight.openflowplugin.openflow.md.util.InventoryDataServiceUtil;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReply;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestInputBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestPortStatsCaseBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.multipart.request.port.stats._case.MultipartRequestPortStatsBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.GetNodeConnectorStatisticsInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.GetNodeConnectorStatisticsOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.GetNodeConnectorStatisticsOutputBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.NodeConnectorStatisticsUpdate;
import org.opendaylight.yangtools.yang.common.Uint8;
final class PortStatsService extends AbstractCompatibleStatService<GetNodeConnectorStatisticsInput,
GetNodeConnectorStatisticsOutput,
NodeConnectorStatisticsUpdate> {
PortStatsService(final RequestContextStack requestContextStack,
final DeviceContext deviceContext,
final AtomicLong compatibilityXidSeed) {
super(requestContextStack, deviceContext, compatibilityXidSeed);
}
@Override
protected OfHeader buildRequest(final Xid xid,
final GetNodeConnectorStatisticsInput input) {
MultipartRequestPortStatsCaseBuilder caseBuilder =
new MultipartRequestPortStatsCaseBuilder();
MultipartRequestPortStatsBuilder mprPortStatsBuilder =
new MultipartRequestPortStatsBuilder();
// Set specific port
final Uint8 version = getVersion();
mprPortStatsBuilder
.setPortNo(InventoryDataServiceUtil.portNumberfromNodeConnectorId(
OpenflowVersion.get(version),
input.getNodeConnectorId()));
caseBuilder.setMultipartRequestPortStats(mprPortStatsBuilder.build());
MultipartRequestInputBuilder mprInput = RequestInputUtils
.createMultipartHeader(MultipartType.OFPMPPORTSTATS, xid.getValue(), version);
mprInput.setMultipartRequestBody(caseBuilder.build());
return mprInput.build();
}
@Override
public GetNodeConnectorStatisticsOutput buildTxCapableResult(final TransactionId emulatedTxId) {
return new GetNodeConnectorStatisticsOutputBuilder().setTransactionId(emulatedTxId).build();
}
@Override
public NodeConnectorStatisticsUpdate transformToNotification(final List<MultipartReply> result,
final TransactionId emulatedTxId) {
return NodeConnectorStatisticsToNotificationTransformer.transformToNotification(result,
getDeviceInfo(),
getOfVersion(),
emulatedTxId);
}
}
|
UTF-8
|
Java
| 4,949 |
java
|
PortStatsService.java
|
Java
|
[] | null |
[] |
/*
* Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.openflowplugin.impl.statistics.services;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
import org.opendaylight.openflowplugin.api.openflow.device.RequestContextStack;
import org.opendaylight.openflowplugin.api.openflow.device.Xid;
import org.opendaylight.openflowplugin.api.openflow.md.util.OpenflowVersion;
import org.opendaylight.openflowplugin.impl.services.util.RequestInputUtils;
import org.opendaylight.openflowplugin.impl.statistics.services.compatibility.AbstractCompatibleStatService;
import org.opendaylight.openflowplugin.impl.statistics.services.compatibility.NodeConnectorStatisticsToNotificationTransformer;
import org.opendaylight.openflowplugin.openflow.md.util.InventoryDataServiceUtil;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReply;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestInputBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestPortStatsCaseBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.multipart.request.port.stats._case.MultipartRequestPortStatsBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.GetNodeConnectorStatisticsInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.GetNodeConnectorStatisticsOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.GetNodeConnectorStatisticsOutputBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.NodeConnectorStatisticsUpdate;
import org.opendaylight.yangtools.yang.common.Uint8;
final class PortStatsService extends AbstractCompatibleStatService<GetNodeConnectorStatisticsInput,
GetNodeConnectorStatisticsOutput,
NodeConnectorStatisticsUpdate> {
PortStatsService(final RequestContextStack requestContextStack,
final DeviceContext deviceContext,
final AtomicLong compatibilityXidSeed) {
super(requestContextStack, deviceContext, compatibilityXidSeed);
}
@Override
protected OfHeader buildRequest(final Xid xid,
final GetNodeConnectorStatisticsInput input) {
MultipartRequestPortStatsCaseBuilder caseBuilder =
new MultipartRequestPortStatsCaseBuilder();
MultipartRequestPortStatsBuilder mprPortStatsBuilder =
new MultipartRequestPortStatsBuilder();
// Set specific port
final Uint8 version = getVersion();
mprPortStatsBuilder
.setPortNo(InventoryDataServiceUtil.portNumberfromNodeConnectorId(
OpenflowVersion.get(version),
input.getNodeConnectorId()));
caseBuilder.setMultipartRequestPortStats(mprPortStatsBuilder.build());
MultipartRequestInputBuilder mprInput = RequestInputUtils
.createMultipartHeader(MultipartType.OFPMPPORTSTATS, xid.getValue(), version);
mprInput.setMultipartRequestBody(caseBuilder.build());
return mprInput.build();
}
@Override
public GetNodeConnectorStatisticsOutput buildTxCapableResult(final TransactionId emulatedTxId) {
return new GetNodeConnectorStatisticsOutputBuilder().setTransactionId(emulatedTxId).build();
}
@Override
public NodeConnectorStatisticsUpdate transformToNotification(final List<MultipartReply> result,
final TransactionId emulatedTxId) {
return NodeConnectorStatisticsToNotificationTransformer.transformToNotification(result,
getDeviceInfo(),
getOfVersion(),
emulatedTxId);
}
}
| 4,949 | 0.724389 | 0.706809 | 78 | 62.448719 | 42.449261 | 190 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.641026 | false | false |
1
|
a69f40054bde75c8c20f2002569dc0bc8c021faf
| 32,100,585,602,629 |
db2478eb8537ec83645928463e4d804ef223448f
|
/self插件使用/Echarts图标行旅/auvgo-web-face/src/main/java/com/auvgo/web/face/hotel/HotelOrderController.java
|
1ad890fc51ca138e35e53a861e691878b0610ed1
|
[
"MIT"
] |
permissive
|
morehappen/test
|
https://github.com/morehappen/test
|
b2d353601d63f0950e361bc0bf082a7e83dd4862
|
bfc37e7681d0d376e075f8fd17ddf1868ae6a96a
|
refs/heads/master
| 2021-01-17T06:12:41.323000 | 2020-12-31T06:50:04 | 2020-12-31T06:50:04 | 83,147,580 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.auvgo.web.face.hotel;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.auvgo.core.contant.AirStatusContant;
import com.auvgo.core.contant.BaseStatusContant;
import com.auvgo.core.contant.HotelStatusContant;
import com.auvgo.core.utils.AuvgoResult;
import com.auvgo.core.utils.JsonUtils;
import com.auvgo.crm.api.CrmCostCenterService;
import com.auvgo.crm.api.CrmProjectService;
import com.auvgo.crm.entity.CrmCostCenter;
import com.auvgo.crm.entity.CrmEmployee;
import com.auvgo.crm.entity.CrmProject;
import com.auvgo.hotel.api.HotelOrderLogService;
import com.auvgo.hotel.api.HotelOrderService;
import com.auvgo.hotel.entity.HotelOrder;
import com.auvgo.hotel.entity.HotelOrderApprove;
import com.auvgo.hotel.entity.HotelOrderLog;
import com.auvgo.web.contant.ErrorCode;
import com.auvgo.web.face.BaseController;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
@RequestMapping("/hotel/order")
@Controller
public class HotelOrderController extends BaseController {
private String status_str="";
@Autowired
private HotelOrderService hotelOrderService;
@Autowired
private CrmCostCenterService crmCostCenterService;
@Autowired
private CrmProjectService crmProjectService;
@Autowired
private HotelOrderLogService hotelOrderLogService;
/**
* 获取酒店 历史入住人
* @param size 入住人size
* @return
*/
@RequestMapping("/ancients")
@ResponseBody
public AuvgoResult getHistoryHotelUsers(Integer size){
try {
log.info("/ancients-->request size:{}", size);
CrmEmployee user = getUser();
if(null==user|| null == user.getId()){
return AuvgoResult.build(ErrorCode.WRONG_PARAMS,ErrorCode.getMsg(ErrorCode.WRONG_PARAMS));
}
size = null == size?5:size;
List<Map<String,Object>> list = hotelOrderService.getHistoryHotelUsers(user.getId(), size);
log.info("/ancients-->reponse {}", JsonUtils.objectToJson(list));
return AuvgoResult.build(ErrorCode.SUCCESS,"success",JsonUtils.objectToJson(list));
} catch (Exception e) {
e.printStackTrace();
return AuvgoResult.build(300,"获取历史乘车人失败!!");
}
}
/**
* 条状订单详情页
*
* @param orderno
* @return
*/
@RequestMapping("/detail/{orderno}")
public String toOrderDetail(@PathVariable("orderno") String orderno) {
HotelOrder hotelOrder = hotelOrderService.getOrderByOrderNo(orderno);
Long cid = hotelOrder.getCompanyid();
//审批人
List<HotelOrderApprove> approveList = hotelOrder.getApproves();
Map<Integer, List<HotelOrderApprove>> maps = Maps.newHashMap();// 按照审批级别把里面的审批人分类
for (HotelOrderApprove approves : approveList) {
if (maps.containsKey(approves.getLevel())) {
List<HotelOrderApprove> list = maps.get(approves.getLevel());
list.add(approves);
} else {
List<HotelOrderApprove> list = Lists.newArrayList();
list.add(approves);
maps.put(approves.getLevel(), list);
}
}
// 成本中心列表
List<CrmCostCenter> costList = crmCostCenterService.getListBycid(cid);
// 获取项目
List<CrmProject> projectlist = crmProjectService.getListBycid(cid);
setAttr("costList", JsonUtils.objectToJson(costList));
setAttr("projectlist", JsonUtils.objectToJson(projectlist));
setAttr("hotelOrder", hotelOrder);
boolean selfPay = hotelOrder.getPaymentType().equals("SelfPay")? true : false;
getStateString(hotelOrder.getStatus(), hotelOrder.getApprovestatus(), hotelOrder.getPaystatus(), selfPay );
setAttr("status_str", status_str);
setAttr("approveMap", maps);
setAttr("approvestatus", hotelOrder.getApprovestatus());
return "/hotel/hotel-order-detail";
}
/**
* 取消订单{"orderno:"""}
*
* @param data
* @return
*/
@RequestMapping(value = "/cancel", method = RequestMethod.POST)
@ResponseBody
public AuvgoResult cancel(String orderNo) {
try {
if (StringUtils.isBlank(orderNo)) {
return AuvgoResult.build(ErrorCode.WRONG_PARAMS, ErrorCode.getMsg(ErrorCode.WRONG_PARAMS));
}
HotelOrder hotelOrder = hotelOrderService.getOrderByOrderNo(orderNo);
if(null !=hotelOrder && hotelOrder.getOrderfrom()== BaseStatusContant.COM_ORDER_FROM_ZUOXI_SG){
return AuvgoResult.build(ErrorCode.WRONG_PARAMS, "如需操作取消此订单,请拨打客服电话4006060011");
}
HotelOrderLog logs= new HotelOrderLog(orderNo, "web-api酒店订单取消", hotelOrder.getBookuserid(), hotelOrder.getBookusername(), "", new Date(), "客户发起取消订单请求");
hotelOrderLogService.saveOrUpdate(logs);
hotelOrderService.cancelOrder(orderNo);
//return AuvgoResult.build(ErrorCode.SUCCESS, "success", "取消成功");
log.debug("cancel request:{} ", orderNo);
return AuvgoResult.build(ErrorCode.SUCCESS, "success", "取消中");
} catch (Exception e) {
e.printStackTrace();
log.error("orderNo:{}, error:{}", orderNo, e);
return AuvgoResult.build(ErrorCode.ERROR, "发生异常", e.getMessage());
}
}
/**
* 判断酒店订单状态
* @param status
* @param approvestatus
* @param paystatus
* @param selfPay
* @return
*/
private Map<String,String> getStateString(int status, int approvestatus, int paystatus, boolean selfPay) {
Map<String,String> mapStatus = Maps.newHashMap();
status_str = "";
if (status == HotelStatusContant.HOTEL_ORDER_STATUS_CANCEL) {// 6
status_str = "已取消";
}
//如果是 已提交,待审批/无需审批,未支付 (没有调用艺龙接口之前的初始状态)
else if(status == HotelStatusContant.HOTEL_ORDER_STATUS_SUBMIT &&
(approvestatus == HotelStatusContant.COM_APPROVE_STATUS || approvestatus == HotelStatusContant.COM_APPROVE_STATUS_NO)
&& (paystatus==HotelStatusContant.HOTEL_PAY_STATUS || paystatus == HotelStatusContant.HOTEL_PAY_WEIDANBAN)){
status_str = "已提交";
//mapStatus.put("cancel", "取消");
}
//如果无需审批、或者审批通过
else if (approvestatus == HotelStatusContant.COM_APPROVE_STATUS_NO || // 3
approvestatus == HotelStatusContant.COM_APPROVE_STATUS_SUCCESS) {// 1
//审批步骤结束,进行订单状态的判断
if (selfPay) {// 现付 到店付
checkOrderState(status, paystatus,mapStatus);
} else {// 预付
checkOrderState4PrePay(status, paystatus,mapStatus);
}
}
//如果审批否决
else if (approvestatus == HotelStatusContant.COM_APPROVE_STATUS_FAIL) {// 2
status_str = "审批否决";
mapStatus.put("cancel", "取消");
//vm.setButtonState("", "", false, false);
}
// 如果是待审批(已经闭合)
else if (approvestatus == HotelStatusContant.COM_APPROVE_STATUS_WAIT) {// 5
status_str = "待审批";
mapStatus.put("cancel", "取消");
//vm.setButtonState("", "", false, true);
} else if (approvestatus == HotelStatusContant.COM_APPROVE_STATUS_ING) {// 4
//vm.setButtonState("", "", false, true);
status_str = "审批中";
mapStatus.put("cancel", "取消");
}
mapStatus.put("status_str", status_str);
return mapStatus;
}
/**
* 判断订单的状态、包括了担保状态
*/
private void checkOrderState(int status, int paystatus,Map<String,String> mapStatus) {
// 现付,担保
if (paystatus == HotelStatusContant.HOTEL_PAY_DAIDANBAO) {//等待担保4
status_str = "等待担保";
mapStatus.put("danbao", "担保");
mapStatus.put("cancel", "取消");
//vm.setButtonState("担保", "取消", true, true);
/*
现付不担保
现付担保成功
预付支付成功以后
*/
//现付不担保
//已确认
}else if(status == HotelStatusContant.HOTEL_ORDER_STATUS_QUEREN_YIQUEREN){//已确认 4
status_str = "已确认";
mapStatus.put("cancel", "取消");
}else if(paystatus == HotelStatusContant.HOTEL_PAY_STATUS_SUCCESS){ //支付成功 1
status_str = "支付成功";
mapStatus.put("cancel", "取消");
}else if (paystatus == HotelStatusContant.HOTEL_PAY_STATUS_DANBAO_ING) {//6
status_str = "担保中";
mapStatus.put("cancel", "取消");
//vm.setButtonState("", "", false, true);
} else if (status == HotelStatusContant.HOTEL_ORDER_STATUS_QUEREN) {//等待确认 2
status_str = "等待确认";
mapStatus.put("cancel", "取消");
//vm.setButtonState("", "取消", false, true);
// 现付担保失败
} else if (paystatus == HotelStatusContant.HOTEL_PAY_STATUS_DANBAO_FAIL) {//担保失败 7
status_str = "担保失败";
mapStatus.put("danbao", "重新担保");
mapStatus.put("cancel", "取消");
//vm.setButtonState("", "取消", false, true);
// 确认中
} else if (status == HotelStatusContant.HOTEL_ORDER_STATUS_QUEREN_ING) { //3
status_str = "确认中";
mapStatus.put("cancel", "取消");
//vm.setButtonState("", "取消", false, true);
//确认失败
} else if (status == HotelStatusContant.HOTEL_ORDER_STATUS_QUEREN_FAIL) {//5
status_str = "确认失败";
mapStatus.put("cancel", "取消");
//vm.setButtonState("", "取消", false, true);
//确认成功
} else if (status == HotelStatusContant.HOTEL_ORDER_STATUS_QUEREN_SUCCESS) {//8
status_str = "等待入住";
mapStatus.put("cancel", "取消");
//vm.setButtonState("", "取消", false, true);
}
}
/**
* 判断订单的状态、不包括担保状态,其实可以跟上面合并
*/
private void checkOrderState4PrePay(int status, int paystatus,Map<String,String> mapStatus) {
//确认中
if (status == HotelStatusContant.HOTEL_ORDER_STATUS_QUEREN_ING) {//3
status_str = "确认中";
mapStatus.put("cancel", "取消");
//vm.setButtonState("", "取消", false, true);
//确认失败
} else if (status == HotelStatusContant.HOTEL_ORDER_STATUS_QUEREN_FAIL) {//5
status_str = "确认失败";
mapStatus.put("cancel", "取消");
//vm.setButtonState("", "取消", false, true);
//确认成功
} else if (status == HotelStatusContant.HOTEL_ORDER_STATUS_QUEREN_SUCCESS) {//8
status_str = "等待入住";
mapStatus.put("cancel", "取消");
//vm.setButtonState("", "取消", false, true);
} else if (paystatus == HotelStatusContant.HOTEL_PAY_STATUS_DAITUIKUAN) {//8
status_str = "待退款";
// vm.setButtonState("", "", false, false);
} else if (paystatus == HotelStatusContant.HOTEL_PAY_STATUS_TUIKUAN_SUCCESS) {//9;
status_str = "退款成功";
//vm.setButtonState("", "", false, false);
} else if (paystatus == HotelStatusContant.HOTEL_PAY_STATUS_TUIKUAN_FAIL) {// 10
status_str = "退款失败";
// vm.setButtonState("", "", false, false);
//订单已提交、待支付
} else if (status == HotelStatusContant.HOTEL_ORDER_STATUS_CANCEL) {//6
status_str = "已取消";
//vm.setButtonState("", "", false, false);
} else if (status == HotelStatusContant.HOTEL_ORDER_STATUS_SUBMIT) {//7
checkPayStatus(paystatus,mapStatus);
}
}
/**
* 支付状态的判断
*/
private void checkPayStatus(int paystatus,Map<String,String> mapStatus) {
if (paystatus == HotelStatusContant.HOTEL_PAY__DAIZHIFU) {//待支付3
status_str = "待支付";
mapStatus.put("zhifu", "支付");
mapStatus.put("cancel", "取消");
//vm.setButtonState(getPayStr(), "取消", true, true);
} else if (paystatus == HotelStatusContant.HOTEL_PAY_STATUS_FAIL) {//支付失败8192
//status_str = "支付失败";
status_str = "支付中";
mapStatus.put("zhifu", "支付");
mapStatus.put("cancel", "取消");
//vm.setButtonState(getPayStr(), "取消", true, true);
} else if (paystatus == HotelStatusContant.HOTEL_PAY_STATUS_ZHIFU_ING) {//支付中4096
status_str = "支付中";
mapStatus.put("cancel", "取消");
// vm.setButtonState("", "取消", false, true);
} else if (paystatus == HotelStatusContant.HOTEL_PAY_STATUS_SUCCESS) {//支付成功1
status_str = "支付成功";
mapStatus.put("cancel", "取消");
// vm.setButtonState("", "取消", false, true);
}else if (paystatus == HotelStatusContant.HOTEL_PAY_STATUS) {//未支付 0
status_str = "未支付";
mapStatus.put("cancel", "取消");
// vm.setButtonState("", "取消", false, true);
}
}
/**
* 审批结果
* {"cid":"1","empid":"2","orderno":"MDW111841887430600","result":"Y通过N否决"
* ,"reason": "否决原因"}
*
* @param data
* @return
*/
@RequestMapping("/approvesave")
@ResponseBody
public AuvgoResult approvesave(String orderno,String result,String reason) {
try {
CrmEmployee user = getUser();
if ( StringUtils.isBlank(orderno) || StringUtils.isBlank(result)) {
return AuvgoResult.build(ErrorCode.WRONG_PARAMS, ErrorCode.getMsg(ErrorCode.WRONG_PARAMS));
}
HotelOrder order = hotelOrderService.getOrderByOrderNo(orderno);
if (null == order) {
return AuvgoResult.build(ErrorCode.ERROR, "没有获取到此订单信息");
}
Integer i=null ;
// 修改订单审批信息
if ("N".equalsIgnoreCase(result)) {
order.setStatus(HotelStatusContant.HOTEL_ORDER_STATUS_CANCEL);
// 订单的审批状态为审批否决
order.setApprovestatus(HotelStatusContant.COM_APPROVE_STATUS_FAIL);
// 前端的显示状态为订单已取消
order.setShowstatus(String.valueOf(AirStatusContant.AIR_FACE_STATUS_CANCLE));
i = hotelOrderService.updateNewOrderApprove(orderno, String.valueOf(user.getId()), HotelStatusContant.COM_APPROVE_STATUS_FAIL, reason);
return AuvgoResult.build(200, "审批否决成功");
} else {
// 更新订单审批表,发送mq
i = hotelOrderService.updateNewOrderApprove(orderno, String.valueOf(user.getId()), HotelStatusContant.COM_APPROVE_STATUS_SUCCESS, "");
}
log.info("Hotelapprovesave --->flag:{}",i);
return AuvgoResult.build(200, "审批通过成功");
} catch (Exception e) {
log.warn("Exception--->e:{}",e.getCause());
return AuvgoResult.build(300, "系统偶尔也会累,请重新提交或拨打客服电话4006060011", e.getMessage());
}
}
}
|
UTF-8
|
Java
| 15,105 |
java
|
HotelOrderController.java
|
Java
|
[] | null |
[] |
package com.auvgo.web.face.hotel;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.auvgo.core.contant.AirStatusContant;
import com.auvgo.core.contant.BaseStatusContant;
import com.auvgo.core.contant.HotelStatusContant;
import com.auvgo.core.utils.AuvgoResult;
import com.auvgo.core.utils.JsonUtils;
import com.auvgo.crm.api.CrmCostCenterService;
import com.auvgo.crm.api.CrmProjectService;
import com.auvgo.crm.entity.CrmCostCenter;
import com.auvgo.crm.entity.CrmEmployee;
import com.auvgo.crm.entity.CrmProject;
import com.auvgo.hotel.api.HotelOrderLogService;
import com.auvgo.hotel.api.HotelOrderService;
import com.auvgo.hotel.entity.HotelOrder;
import com.auvgo.hotel.entity.HotelOrderApprove;
import com.auvgo.hotel.entity.HotelOrderLog;
import com.auvgo.web.contant.ErrorCode;
import com.auvgo.web.face.BaseController;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
@RequestMapping("/hotel/order")
@Controller
public class HotelOrderController extends BaseController {
private String status_str="";
@Autowired
private HotelOrderService hotelOrderService;
@Autowired
private CrmCostCenterService crmCostCenterService;
@Autowired
private CrmProjectService crmProjectService;
@Autowired
private HotelOrderLogService hotelOrderLogService;
/**
* 获取酒店 历史入住人
* @param size 入住人size
* @return
*/
@RequestMapping("/ancients")
@ResponseBody
public AuvgoResult getHistoryHotelUsers(Integer size){
try {
log.info("/ancients-->request size:{}", size);
CrmEmployee user = getUser();
if(null==user|| null == user.getId()){
return AuvgoResult.build(ErrorCode.WRONG_PARAMS,ErrorCode.getMsg(ErrorCode.WRONG_PARAMS));
}
size = null == size?5:size;
List<Map<String,Object>> list = hotelOrderService.getHistoryHotelUsers(user.getId(), size);
log.info("/ancients-->reponse {}", JsonUtils.objectToJson(list));
return AuvgoResult.build(ErrorCode.SUCCESS,"success",JsonUtils.objectToJson(list));
} catch (Exception e) {
e.printStackTrace();
return AuvgoResult.build(300,"获取历史乘车人失败!!");
}
}
/**
* 条状订单详情页
*
* @param orderno
* @return
*/
@RequestMapping("/detail/{orderno}")
public String toOrderDetail(@PathVariable("orderno") String orderno) {
HotelOrder hotelOrder = hotelOrderService.getOrderByOrderNo(orderno);
Long cid = hotelOrder.getCompanyid();
//审批人
List<HotelOrderApprove> approveList = hotelOrder.getApproves();
Map<Integer, List<HotelOrderApprove>> maps = Maps.newHashMap();// 按照审批级别把里面的审批人分类
for (HotelOrderApprove approves : approveList) {
if (maps.containsKey(approves.getLevel())) {
List<HotelOrderApprove> list = maps.get(approves.getLevel());
list.add(approves);
} else {
List<HotelOrderApprove> list = Lists.newArrayList();
list.add(approves);
maps.put(approves.getLevel(), list);
}
}
// 成本中心列表
List<CrmCostCenter> costList = crmCostCenterService.getListBycid(cid);
// 获取项目
List<CrmProject> projectlist = crmProjectService.getListBycid(cid);
setAttr("costList", JsonUtils.objectToJson(costList));
setAttr("projectlist", JsonUtils.objectToJson(projectlist));
setAttr("hotelOrder", hotelOrder);
boolean selfPay = hotelOrder.getPaymentType().equals("SelfPay")? true : false;
getStateString(hotelOrder.getStatus(), hotelOrder.getApprovestatus(), hotelOrder.getPaystatus(), selfPay );
setAttr("status_str", status_str);
setAttr("approveMap", maps);
setAttr("approvestatus", hotelOrder.getApprovestatus());
return "/hotel/hotel-order-detail";
}
/**
* 取消订单{"orderno:"""}
*
* @param data
* @return
*/
@RequestMapping(value = "/cancel", method = RequestMethod.POST)
@ResponseBody
public AuvgoResult cancel(String orderNo) {
try {
if (StringUtils.isBlank(orderNo)) {
return AuvgoResult.build(ErrorCode.WRONG_PARAMS, ErrorCode.getMsg(ErrorCode.WRONG_PARAMS));
}
HotelOrder hotelOrder = hotelOrderService.getOrderByOrderNo(orderNo);
if(null !=hotelOrder && hotelOrder.getOrderfrom()== BaseStatusContant.COM_ORDER_FROM_ZUOXI_SG){
return AuvgoResult.build(ErrorCode.WRONG_PARAMS, "如需操作取消此订单,请拨打客服电话4006060011");
}
HotelOrderLog logs= new HotelOrderLog(orderNo, "web-api酒店订单取消", hotelOrder.getBookuserid(), hotelOrder.getBookusername(), "", new Date(), "客户发起取消订单请求");
hotelOrderLogService.saveOrUpdate(logs);
hotelOrderService.cancelOrder(orderNo);
//return AuvgoResult.build(ErrorCode.SUCCESS, "success", "取消成功");
log.debug("cancel request:{} ", orderNo);
return AuvgoResult.build(ErrorCode.SUCCESS, "success", "取消中");
} catch (Exception e) {
e.printStackTrace();
log.error("orderNo:{}, error:{}", orderNo, e);
return AuvgoResult.build(ErrorCode.ERROR, "发生异常", e.getMessage());
}
}
/**
* 判断酒店订单状态
* @param status
* @param approvestatus
* @param paystatus
* @param selfPay
* @return
*/
private Map<String,String> getStateString(int status, int approvestatus, int paystatus, boolean selfPay) {
Map<String,String> mapStatus = Maps.newHashMap();
status_str = "";
if (status == HotelStatusContant.HOTEL_ORDER_STATUS_CANCEL) {// 6
status_str = "已取消";
}
//如果是 已提交,待审批/无需审批,未支付 (没有调用艺龙接口之前的初始状态)
else if(status == HotelStatusContant.HOTEL_ORDER_STATUS_SUBMIT &&
(approvestatus == HotelStatusContant.COM_APPROVE_STATUS || approvestatus == HotelStatusContant.COM_APPROVE_STATUS_NO)
&& (paystatus==HotelStatusContant.HOTEL_PAY_STATUS || paystatus == HotelStatusContant.HOTEL_PAY_WEIDANBAN)){
status_str = "已提交";
//mapStatus.put("cancel", "取消");
}
//如果无需审批、或者审批通过
else if (approvestatus == HotelStatusContant.COM_APPROVE_STATUS_NO || // 3
approvestatus == HotelStatusContant.COM_APPROVE_STATUS_SUCCESS) {// 1
//审批步骤结束,进行订单状态的判断
if (selfPay) {// 现付 到店付
checkOrderState(status, paystatus,mapStatus);
} else {// 预付
checkOrderState4PrePay(status, paystatus,mapStatus);
}
}
//如果审批否决
else if (approvestatus == HotelStatusContant.COM_APPROVE_STATUS_FAIL) {// 2
status_str = "审批否决";
mapStatus.put("cancel", "取消");
//vm.setButtonState("", "", false, false);
}
// 如果是待审批(已经闭合)
else if (approvestatus == HotelStatusContant.COM_APPROVE_STATUS_WAIT) {// 5
status_str = "待审批";
mapStatus.put("cancel", "取消");
//vm.setButtonState("", "", false, true);
} else if (approvestatus == HotelStatusContant.COM_APPROVE_STATUS_ING) {// 4
//vm.setButtonState("", "", false, true);
status_str = "审批中";
mapStatus.put("cancel", "取消");
}
mapStatus.put("status_str", status_str);
return mapStatus;
}
/**
* 判断订单的状态、包括了担保状态
*/
private void checkOrderState(int status, int paystatus,Map<String,String> mapStatus) {
// 现付,担保
if (paystatus == HotelStatusContant.HOTEL_PAY_DAIDANBAO) {//等待担保4
status_str = "等待担保";
mapStatus.put("danbao", "担保");
mapStatus.put("cancel", "取消");
//vm.setButtonState("担保", "取消", true, true);
/*
现付不担保
现付担保成功
预付支付成功以后
*/
//现付不担保
//已确认
}else if(status == HotelStatusContant.HOTEL_ORDER_STATUS_QUEREN_YIQUEREN){//已确认 4
status_str = "已确认";
mapStatus.put("cancel", "取消");
}else if(paystatus == HotelStatusContant.HOTEL_PAY_STATUS_SUCCESS){ //支付成功 1
status_str = "支付成功";
mapStatus.put("cancel", "取消");
}else if (paystatus == HotelStatusContant.HOTEL_PAY_STATUS_DANBAO_ING) {//6
status_str = "担保中";
mapStatus.put("cancel", "取消");
//vm.setButtonState("", "", false, true);
} else if (status == HotelStatusContant.HOTEL_ORDER_STATUS_QUEREN) {//等待确认 2
status_str = "等待确认";
mapStatus.put("cancel", "取消");
//vm.setButtonState("", "取消", false, true);
// 现付担保失败
} else if (paystatus == HotelStatusContant.HOTEL_PAY_STATUS_DANBAO_FAIL) {//担保失败 7
status_str = "担保失败";
mapStatus.put("danbao", "重新担保");
mapStatus.put("cancel", "取消");
//vm.setButtonState("", "取消", false, true);
// 确认中
} else if (status == HotelStatusContant.HOTEL_ORDER_STATUS_QUEREN_ING) { //3
status_str = "确认中";
mapStatus.put("cancel", "取消");
//vm.setButtonState("", "取消", false, true);
//确认失败
} else if (status == HotelStatusContant.HOTEL_ORDER_STATUS_QUEREN_FAIL) {//5
status_str = "确认失败";
mapStatus.put("cancel", "取消");
//vm.setButtonState("", "取消", false, true);
//确认成功
} else if (status == HotelStatusContant.HOTEL_ORDER_STATUS_QUEREN_SUCCESS) {//8
status_str = "等待入住";
mapStatus.put("cancel", "取消");
//vm.setButtonState("", "取消", false, true);
}
}
/**
* 判断订单的状态、不包括担保状态,其实可以跟上面合并
*/
private void checkOrderState4PrePay(int status, int paystatus,Map<String,String> mapStatus) {
//确认中
if (status == HotelStatusContant.HOTEL_ORDER_STATUS_QUEREN_ING) {//3
status_str = "确认中";
mapStatus.put("cancel", "取消");
//vm.setButtonState("", "取消", false, true);
//确认失败
} else if (status == HotelStatusContant.HOTEL_ORDER_STATUS_QUEREN_FAIL) {//5
status_str = "确认失败";
mapStatus.put("cancel", "取消");
//vm.setButtonState("", "取消", false, true);
//确认成功
} else if (status == HotelStatusContant.HOTEL_ORDER_STATUS_QUEREN_SUCCESS) {//8
status_str = "等待入住";
mapStatus.put("cancel", "取消");
//vm.setButtonState("", "取消", false, true);
} else if (paystatus == HotelStatusContant.HOTEL_PAY_STATUS_DAITUIKUAN) {//8
status_str = "待退款";
// vm.setButtonState("", "", false, false);
} else if (paystatus == HotelStatusContant.HOTEL_PAY_STATUS_TUIKUAN_SUCCESS) {//9;
status_str = "退款成功";
//vm.setButtonState("", "", false, false);
} else if (paystatus == HotelStatusContant.HOTEL_PAY_STATUS_TUIKUAN_FAIL) {// 10
status_str = "退款失败";
// vm.setButtonState("", "", false, false);
//订单已提交、待支付
} else if (status == HotelStatusContant.HOTEL_ORDER_STATUS_CANCEL) {//6
status_str = "已取消";
//vm.setButtonState("", "", false, false);
} else if (status == HotelStatusContant.HOTEL_ORDER_STATUS_SUBMIT) {//7
checkPayStatus(paystatus,mapStatus);
}
}
/**
* 支付状态的判断
*/
private void checkPayStatus(int paystatus,Map<String,String> mapStatus) {
if (paystatus == HotelStatusContant.HOTEL_PAY__DAIZHIFU) {//待支付3
status_str = "待支付";
mapStatus.put("zhifu", "支付");
mapStatus.put("cancel", "取消");
//vm.setButtonState(getPayStr(), "取消", true, true);
} else if (paystatus == HotelStatusContant.HOTEL_PAY_STATUS_FAIL) {//支付失败8192
//status_str = "支付失败";
status_str = "支付中";
mapStatus.put("zhifu", "支付");
mapStatus.put("cancel", "取消");
//vm.setButtonState(getPayStr(), "取消", true, true);
} else if (paystatus == HotelStatusContant.HOTEL_PAY_STATUS_ZHIFU_ING) {//支付中4096
status_str = "支付中";
mapStatus.put("cancel", "取消");
// vm.setButtonState("", "取消", false, true);
} else if (paystatus == HotelStatusContant.HOTEL_PAY_STATUS_SUCCESS) {//支付成功1
status_str = "支付成功";
mapStatus.put("cancel", "取消");
// vm.setButtonState("", "取消", false, true);
}else if (paystatus == HotelStatusContant.HOTEL_PAY_STATUS) {//未支付 0
status_str = "未支付";
mapStatus.put("cancel", "取消");
// vm.setButtonState("", "取消", false, true);
}
}
/**
* 审批结果
* {"cid":"1","empid":"2","orderno":"MDW111841887430600","result":"Y通过N否决"
* ,"reason": "否决原因"}
*
* @param data
* @return
*/
@RequestMapping("/approvesave")
@ResponseBody
public AuvgoResult approvesave(String orderno,String result,String reason) {
try {
CrmEmployee user = getUser();
if ( StringUtils.isBlank(orderno) || StringUtils.isBlank(result)) {
return AuvgoResult.build(ErrorCode.WRONG_PARAMS, ErrorCode.getMsg(ErrorCode.WRONG_PARAMS));
}
HotelOrder order = hotelOrderService.getOrderByOrderNo(orderno);
if (null == order) {
return AuvgoResult.build(ErrorCode.ERROR, "没有获取到此订单信息");
}
Integer i=null ;
// 修改订单审批信息
if ("N".equalsIgnoreCase(result)) {
order.setStatus(HotelStatusContant.HOTEL_ORDER_STATUS_CANCEL);
// 订单的审批状态为审批否决
order.setApprovestatus(HotelStatusContant.COM_APPROVE_STATUS_FAIL);
// 前端的显示状态为订单已取消
order.setShowstatus(String.valueOf(AirStatusContant.AIR_FACE_STATUS_CANCLE));
i = hotelOrderService.updateNewOrderApprove(orderno, String.valueOf(user.getId()), HotelStatusContant.COM_APPROVE_STATUS_FAIL, reason);
return AuvgoResult.build(200, "审批否决成功");
} else {
// 更新订单审批表,发送mq
i = hotelOrderService.updateNewOrderApprove(orderno, String.valueOf(user.getId()), HotelStatusContant.COM_APPROVE_STATUS_SUCCESS, "");
}
log.info("Hotelapprovesave --->flag:{}",i);
return AuvgoResult.build(200, "审批通过成功");
} catch (Exception e) {
log.warn("Exception--->e:{}",e.getCause());
return AuvgoResult.build(300, "系统偶尔也会累,请重新提交或拨打客服电话4006060011", e.getMessage());
}
}
}
| 15,105 | 0.654899 | 0.648545 | 358 | 37.689945 | 28.87957 | 155 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.298883 | false | false |
1
|
0cf06f1943ac64293f92faed74ca2d76da5be027
| 28,192,165,365,989 |
00038816bd4437be38fdb8864a9266fb158ae15a
|
/src/main/java/org/thorn/code/common/security/AES.java
|
3fc1162176b1e7f940bcf4695c7fd867ecda3a50
|
[] |
no_license
|
mdouyun/thorn-commons
|
https://github.com/mdouyun/thorn-commons
|
8788336cf2619f04c5d84b97a3786dcac70d51e6
|
2a1813ead76e4f65621ff7972729cdbaac376b33
|
refs/heads/master
| 2022-07-25T15:46:54.474000 | 2020-11-06T08:31:01 | 2020-11-06T08:31:01 | 138,532,978 | 0 | 0 | null | false | 2022-07-06T19:56:08 | 2018-06-25T02:16:01 | 2020-11-06T08:46:30 | 2022-07-06T19:56:08 | 104 | 0 | 0 | 3 |
Java
| false | false |
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thorn.code.common.security;
import org.apache.commons.codec.binary.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
/**
* AES算法加解密类.
*
* @author chenyun.chris
* @since 1.0
*/
public class AES {
private static final Logger LOGGER = LoggerFactory.getLogger(AES.class);
/**
* 默认加密模式:ECB(电子密码本)
*/
private static final String DEFAULT_MODE = "ECB";
/**
* 默认对称加密填充算法
*/
private static final String DEFAULT_SYM_PADDING = "PKCS5Padding";
private static final String ALGORITHM = String.format("AES/%s/%s", DEFAULT_MODE, DEFAULT_SYM_PADDING);
/**
* AES算法对字节数组进行加密,使用模式为ECB,padding方式为PKCS5Padding。
*
* @param data
* @param key
* @return
* @throws GeneralSecurityException
*/
public static byte[] encrypt(byte[] data, String key) throws GeneralSecurityException {
SecretKey secretKey = generateKey(key);
return cipher(data, secretKey, Cipher.ENCRYPT_MODE);
}
/**
* AES算法对字节数组进行解密,使用模式为ECB,padding方式为PKCS5Padding。
*
* @param data
* @param key
* @return
* @throws GeneralSecurityException
*/
public static byte[] decrypt(byte[] data, String key) throws GeneralSecurityException {
SecretKey secretKey = generateKey(key);
return cipher(data, secretKey, Cipher.DECRYPT_MODE);
}
/**
* AES算法对字符串加密,使用模式为ECB,padding方式为PKCS5Padding。<br/>
* 对加密的字节数组做Base64编码。
*
* @param data 需要加密的字符串
* @param key 密钥
* @return 加密后的Base64字符串
* @throws GeneralSecurityException
*/
public static String encrypt(String data, String key) throws GeneralSecurityException {
// 明文作base64
byte[] bytes = StringUtils.getBytesUtf8(data);
SecretKey secretKey = generateKey(key);
byte[] encryptBytes = cipher(bytes, secretKey, Cipher.ENCRYPT_MODE);
return org.apache.commons.codec.binary.Base64.encodeBase64String(encryptBytes);
}
/**
* AES算法对字符串解密,使用模式为ECB,padding方式为PKCS5Padding。<br/>
* 需要解密的字符串必须是Base64编码后的字符串。
*
* @param data 需要解密的Base64字符串
* @param key 密钥
* @return
* @throws GeneralSecurityException
*/
public static String decrypt(String data, String key) throws GeneralSecurityException {
byte[] bytes = org.apache.commons.codec.binary.Base64.decodeBase64(data);
SecretKey secretKey = generateKey(key);
byte[] decryptBytes = cipher(bytes, secretKey, Cipher.DECRYPT_MODE);
return StringUtils.newStringUtf8(decryptBytes);
}
/**
* 通用加解密方式。
*
* @param data 原文
* @param key 密钥
* @param opMode 模式(ENCODE_MODE|DECRYPT_MODE)
* @return 加密/解密结果。字节数组形式
* @throws GeneralSecurityException 加解密出现错误时抛出
* @throws IllegalArgumentException 参数不合法时抛出
*/
private static byte[] cipher(byte[] data, Key key, int opMode)
throws GeneralSecurityException, IllegalArgumentException {
long start = System.nanoTime();
Cipher c1 = Cipher.getInstance(ALGORITHM);
c1.init(opMode, key);
byte[] result = c1.doFinal(data);
long used = System.nanoTime() - start;
if (LOGGER.isDebugEnabled()) {//
LOGGER.debug("#cipher {} {} used {} nano.",
opMode == Cipher.ENCRYPT_MODE ? "encode" : "decode", ALGORITHM, used);
}
return result;
}
/**
* AES算法128位密钥生成方法
*
* @param key 原始字符串key
* @return 满足AES算法的key
* @throws NoSuchAlgorithmException 原始密钥长度不符合要求
*/
private static SecretKey generateKey(String key) throws NoSuchAlgorithmException {
byte[] bytes = StringUtils.getBytesUtf8(key);
KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(128, new SecureRandom(bytes));
return generator.generateKey();
}
}
|
UTF-8
|
Java
| 5,273 |
java
|
AES.java
|
Java
|
[
{
"context": "ity.SecureRandom;\n\n/**\n * AES算法加解密类.\n *\n * @author chenyun.chris\n * @since 1.0\n */\npublic class AES {\n\n private",
"end": 1067,
"score": 0.9997658133506775,
"start": 1054,
"tag": "NAME",
"value": "chenyun.chris"
}
] | null |
[] |
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thorn.code.common.security;
import org.apache.commons.codec.binary.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
/**
* AES算法加解密类.
*
* @author chenyun.chris
* @since 1.0
*/
public class AES {
private static final Logger LOGGER = LoggerFactory.getLogger(AES.class);
/**
* 默认加密模式:ECB(电子密码本)
*/
private static final String DEFAULT_MODE = "ECB";
/**
* 默认对称加密填充算法
*/
private static final String DEFAULT_SYM_PADDING = "PKCS5Padding";
private static final String ALGORITHM = String.format("AES/%s/%s", DEFAULT_MODE, DEFAULT_SYM_PADDING);
/**
* AES算法对字节数组进行加密,使用模式为ECB,padding方式为PKCS5Padding。
*
* @param data
* @param key
* @return
* @throws GeneralSecurityException
*/
public static byte[] encrypt(byte[] data, String key) throws GeneralSecurityException {
SecretKey secretKey = generateKey(key);
return cipher(data, secretKey, Cipher.ENCRYPT_MODE);
}
/**
* AES算法对字节数组进行解密,使用模式为ECB,padding方式为PKCS5Padding。
*
* @param data
* @param key
* @return
* @throws GeneralSecurityException
*/
public static byte[] decrypt(byte[] data, String key) throws GeneralSecurityException {
SecretKey secretKey = generateKey(key);
return cipher(data, secretKey, Cipher.DECRYPT_MODE);
}
/**
* AES算法对字符串加密,使用模式为ECB,padding方式为PKCS5Padding。<br/>
* 对加密的字节数组做Base64编码。
*
* @param data 需要加密的字符串
* @param key 密钥
* @return 加密后的Base64字符串
* @throws GeneralSecurityException
*/
public static String encrypt(String data, String key) throws GeneralSecurityException {
// 明文作base64
byte[] bytes = StringUtils.getBytesUtf8(data);
SecretKey secretKey = generateKey(key);
byte[] encryptBytes = cipher(bytes, secretKey, Cipher.ENCRYPT_MODE);
return org.apache.commons.codec.binary.Base64.encodeBase64String(encryptBytes);
}
/**
* AES算法对字符串解密,使用模式为ECB,padding方式为PKCS5Padding。<br/>
* 需要解密的字符串必须是Base64编码后的字符串。
*
* @param data 需要解密的Base64字符串
* @param key 密钥
* @return
* @throws GeneralSecurityException
*/
public static String decrypt(String data, String key) throws GeneralSecurityException {
byte[] bytes = org.apache.commons.codec.binary.Base64.decodeBase64(data);
SecretKey secretKey = generateKey(key);
byte[] decryptBytes = cipher(bytes, secretKey, Cipher.DECRYPT_MODE);
return StringUtils.newStringUtf8(decryptBytes);
}
/**
* 通用加解密方式。
*
* @param data 原文
* @param key 密钥
* @param opMode 模式(ENCODE_MODE|DECRYPT_MODE)
* @return 加密/解密结果。字节数组形式
* @throws GeneralSecurityException 加解密出现错误时抛出
* @throws IllegalArgumentException 参数不合法时抛出
*/
private static byte[] cipher(byte[] data, Key key, int opMode)
throws GeneralSecurityException, IllegalArgumentException {
long start = System.nanoTime();
Cipher c1 = Cipher.getInstance(ALGORITHM);
c1.init(opMode, key);
byte[] result = c1.doFinal(data);
long used = System.nanoTime() - start;
if (LOGGER.isDebugEnabled()) {//
LOGGER.debug("#cipher {} {} used {} nano.",
opMode == Cipher.ENCRYPT_MODE ? "encode" : "decode", ALGORITHM, used);
}
return result;
}
/**
* AES算法128位密钥生成方法
*
* @param key 原始字符串key
* @return 满足AES算法的key
* @throws NoSuchAlgorithmException 原始密钥长度不符合要求
*/
private static SecretKey generateKey(String key) throws NoSuchAlgorithmException {
byte[] bytes = StringUtils.getBytesUtf8(key);
KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(128, new SecureRandom(bytes));
return generator.generateKey();
}
}
| 5,273 | 0.6652 | 0.654515 | 162 | 28.462963 | 27.102261 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.407407 | false | false |
1
|
14f1b394f53bab23a391f0cb91fb4e91ee9af05f
| 13,408,887,922,035 |
97e49902f7451e6bcc06ee4b94a7d683b171bd3a
|
/src/main/java/com/workflowintg/dispatcher/rest/resources/StatusResource.java
|
f33858f042fc0d85aa3cbbf26c9e1156e458ee94
|
[] |
no_license
|
emiliolalvarez/workflowintg
|
https://github.com/emiliolalvarez/workflowintg
|
d288c9ccfa31e784e12e32ac680356ef89f5332a
|
a56c42b74ef77c2c790c1ace9d1577ed466ceaae
|
refs/heads/master
| 2020-04-04T13:13:24.943000 | 2012-06-29T20:37:04 | 2012-06-29T20:37:14 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.workflowintg.dispatcher.rest.resources;
//import java.util.Date;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.apache.log4j.Logger;
import com.google.inject.Inject;
import com.myworkflow.main.Configuration;
//import com.workflowintg.dispatcher.JettyDispatcherServer;
@Path("/status")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public class StatusResource {
@Inject
private Configuration c;
private final static Logger LOGGER = Logger.getLogger(StatusResource.class);
@GET
@Produces({ MediaType.TEXT_PLAIN })
public String currentStatus() {
//JettyDispatcherServer.getRequestQueue().putMessage(""+new Date().getTime());
LOGGER.debug("Returning current status");
return "GOOD!!"+c.getString("database.driver");
}
}
|
UTF-8
|
Java
| 878 |
java
|
StatusResource.java
|
Java
|
[] | null |
[] |
package com.workflowintg.dispatcher.rest.resources;
//import java.util.Date;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.apache.log4j.Logger;
import com.google.inject.Inject;
import com.myworkflow.main.Configuration;
//import com.workflowintg.dispatcher.JettyDispatcherServer;
@Path("/status")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public class StatusResource {
@Inject
private Configuration c;
private final static Logger LOGGER = Logger.getLogger(StatusResource.class);
@GET
@Produces({ MediaType.TEXT_PLAIN })
public String currentStatus() {
//JettyDispatcherServer.getRequestQueue().putMessage(""+new Date().getTime());
LOGGER.debug("Returning current status");
return "GOOD!!"+c.getString("database.driver");
}
}
| 878 | 0.771071 | 0.769932 | 31 | 27.32258 | 22.966156 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false |
1
|
ff9d894ead5212d30292b4b9e9f1ed8606f94ca1
| 38,379,827,780,468 |
4c3dfc002bc45fa55f1f2ccdd1a6e1fb437b26b9
|
/dubbo-admin/src/test/java/com/alibaba/dubbo/registry/common/domain/PageListTest.java
|
1a4277afaedaecd52b59352d34dfaa061e2d44e8
|
[] |
permissive
|
wuwenhui0917/dubbo-ecs
|
https://github.com/wuwenhui0917/dubbo-ecs
|
8cd8122680e58111fe4a4e2e02003dbe623a17a2
|
60a739050bb5f5c877f23d2a44d45f8805a3d2d2
|
refs/heads/master
| 2022-12-08T04:28:46.110000 | 2020-06-06T09:44:27 | 2020-06-06T09:44:27 | 67,462,294 | 6 | 1 |
Apache-2.0
| true | 2019-02-21T13:45:34 | 2016-09-06T01:26:54 | 2018-09-25T14:29:44 | 2019-02-21T13:36:43 | 7,040 | 3 | 1 | 0 |
Java
| false | null |
/**
* Project: dubbo.registry.server-2.1.0-SNAPSHOT
*
* File Created at Oct 31, 2011
* $Id: PageListTest.java 181192 2012-06-21 05:05:47Z tony.chenl $
*
* Copyright 1999-2100 Alibaba.com Corporation Limited.
* All rights reserved.
*
* This software is the confidential and proprietary information of
* Alibaba Company. ("Confidential Information"). You shall not
* disclose such Confidential Information and shall use it only in
* accordance with the terms of the license agreement you entered into
* with Alibaba.com.
*/
package com.alibaba.dubbo.registry.common.domain;
import org.junit.Assert;
import org.junit.Test;
/**
* TODO Comment of PageListTest
* @author haomin.liuhm
*
*/
public class PageListTest {
@Test
public void testGetPageCount(){
//int start, int limit, int total, List<T> list
PageList<Object> pl = new PageList<Object>(0, 100, 52, null);
Assert.assertEquals(1, pl.getPageCount());
pl = new PageList<Object>(0, -100, -3, null);
Assert.assertEquals(1, pl.getPageCount());
pl = new PageList<Object>(0, 30, 100, null);
Assert.assertEquals(4, pl.getPageCount());
}
}
|
UTF-8
|
Java
| 1,198 |
java
|
PageListTest.java
|
Java
|
[
{
"context": "$Id: PageListTest.java 181192 2012-06-21 05:05:47Z tony.chenl $\n * \n * Copyright 1999-2100 Alibaba.com Corporat",
"end": 153,
"score": 0.9972509145736694,
"start": 143,
"tag": "USERNAME",
"value": "tony.chenl"
},
{
"context": "t;\n\n/**\n * TODO Comment of PageListTest\n * @author haomin.liuhm\n *\n */\npublic class PageListTest {\n\n @Test\n ",
"end": 698,
"score": 0.9449838995933533,
"start": 686,
"tag": "USERNAME",
"value": "haomin.liuhm"
}
] | null |
[] |
/**
* Project: dubbo.registry.server-2.1.0-SNAPSHOT
*
* File Created at Oct 31, 2011
* $Id: PageListTest.java 181192 2012-06-21 05:05:47Z tony.chenl $
*
* Copyright 1999-2100 Alibaba.com Corporation Limited.
* All rights reserved.
*
* This software is the confidential and proprietary information of
* Alibaba Company. ("Confidential Information"). You shall not
* disclose such Confidential Information and shall use it only in
* accordance with the terms of the license agreement you entered into
* with Alibaba.com.
*/
package com.alibaba.dubbo.registry.common.domain;
import org.junit.Assert;
import org.junit.Test;
/**
* TODO Comment of PageListTest
* @author haomin.liuhm
*
*/
public class PageListTest {
@Test
public void testGetPageCount(){
//int start, int limit, int total, List<T> list
PageList<Object> pl = new PageList<Object>(0, 100, 52, null);
Assert.assertEquals(1, pl.getPageCount());
pl = new PageList<Object>(0, -100, -3, null);
Assert.assertEquals(1, pl.getPageCount());
pl = new PageList<Object>(0, 30, 100, null);
Assert.assertEquals(4, pl.getPageCount());
}
}
| 1,198 | 0.671953 | 0.624374 | 41 | 28.219513 | 24.58585 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.609756 | false | false |
1
|
934fb37f0ac554115c91ad85a5de2ad313ef777a
| 8,495,445,325,281 |
b37d933bf233d641505dceb05d603d8371ee8d9c
|
/src/main/java/wenjalan/starbot/nli/Predictor.java
|
80ffe8a4dbf111654d340ba19f1075c2e8df3194
|
[] |
no_license
|
wenjalan/StarbotNLI
|
https://github.com/wenjalan/StarbotNLI
|
da9ad267a4069321cecf1b4b2218d93192b075d0
|
2c2bb18244a6e424c507c8e86827d46dbc5d8278
|
refs/heads/master
| 2022-03-05T10:47:00.051000 | 2020-09-01T05:56:31 | 2020-09-01T05:56:31 | 247,171,821 | 0 | 0 | null | false | 2022-02-26T01:09:18 | 2020-03-13T22:27:19 | 2020-09-01T05:56:49 | 2022-02-26T01:09:18 | 1,396 | 0 | 0 | 1 |
Java
| false | false |
package wenjalan.starbot.nli;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
// a predictor node, uses a series of corpi to predict next words
public interface Predictor {
// initializes this Predictor with a series of corpi
// corpi: the corpi to make predictions with
void init(File[] corpi) throws IOException;
// predict the next word given a List of words
// pre: at least one word (the start sentinel)
// returns: a map containing next words to their likelihoods
Map<String, Long> predictNextWord(List<String> sentence);
}
|
UTF-8
|
Java
| 609 |
java
|
Predictor.java
|
Java
|
[] | null |
[] |
package wenjalan.starbot.nli;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
// a predictor node, uses a series of corpi to predict next words
public interface Predictor {
// initializes this Predictor with a series of corpi
// corpi: the corpi to make predictions with
void init(File[] corpi) throws IOException;
// predict the next word given a List of words
// pre: at least one word (the start sentinel)
// returns: a map containing next words to their likelihoods
Map<String, Long> predictNextWord(List<String> sentence);
}
| 609 | 0.730706 | 0.730706 | 20 | 29.450001 | 23.478661 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.45 | false | false |
1
|
0cf8afbd219498010694dc7d9b2e79f392a3abb0
| 29,377,576,305,781 |
664628df46eb5771cc5a2a44011ff7ce217f5855
|
/src/main/java/com/aaa/project/system/businfo/service/BusinfoServiceImpl.java
|
fd133d5d938b284b76b8b2faa3856f0518e5a866
|
[
"MIT"
] |
permissive
|
yunjuanyunshu07/YouE-car-wash
|
https://github.com/yunjuanyunshu07/YouE-car-wash
|
017ccc72268f3d12e1aa241d2219b7dd39ad57f2
|
e7af0019bf12e7a050f27b6bd62ca2b69bc9e6d8
|
refs/heads/master
| 2020-07-08T06:45:48.797000 | 2019-08-10T06:01:09 | 2019-08-10T06:01:09 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.aaa.project.system.businfo.service;
import java.util.List;
import java.util.Map;
import com.aaa.project.system.busexamine.domain.Busexamine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.aaa.project.system.businfo.mapper.BusinfoMapper;
import com.aaa.project.system.businfo.domain.Businfo;
import com.aaa.project.system.businfo.service.IBusinfoService;
import com.aaa.common.support.Convert;
/**
* 商家 服务层实现
*
* @author teacherChen
* @date 2019-07-29
*/
@Service
public class BusinfoServiceImpl implements IBusinfoService
{
@Autowired
private BusinfoMapper businfoMapper;
/**
* 审核通过商家
*/
@Override
public int insertBus(Busexamine businfo)
{
return businfoMapper.insertBus(businfo);
}
/**
* 商家密码登录
*/
// @Override
// public List<Businfo> selepwd(Businfo businfo) {
// return businfoMapper.selepwd(businfo);
// }
/**
* 查询商家手机号码
*/
@Override
public List<Businfo> selephone(Businfo businfo) {
return businfoMapper.selphone(businfo);
}
/**
* 查询商家信息
*
* @param busId 商家ID
* @return 商家信息
*/
@Override
public Businfo selectBusinfoById(Integer busId)
{
return businfoMapper.selectBusinfoById(busId);
}
/**
* 查询商家列表
*
* @param businfo 商家信息
* @return 商家集合
*/
@Override
public List<Businfo> selectBusinfoList(Businfo businfo)
{
return businfoMapper.selectBusinfoList(businfo);
}
/**
* 新增商家
*
* @param businfo 商家信息
* @return 结果
*/
@Override
public int insertBusinfo(Businfo businfo)
{
return businfoMapper.insertBusinfo(businfo);
}
/**
* 修改商家
*
* @param businfo 商家信息
* @return 结果
*/
@Override
public int updateBusinfo(Businfo businfo)
{
return businfoMapper.updateBusinfo(businfo);
}
/**
* 删除商家对象
*
* @param ids 需要删除的数据ID
* @return 结果
*/
@Override
public int deleteBusinfoByIds(String ids)
{
return businfoMapper.deleteBusinfoByIds(Convert.toStrArray(ids));
}
/**
* 根据商家Id查询商家信息
* @param busId 需要查询的商家Id
* @return 结果
*/
public List<Map<String,Object>> selectBusInfoById(Integer busId){
return businfoMapper.selectBusInfoById(busId);
}
/**
* 查看该商家当天营业额,总共完成的订单,取消的订单数
* @param bus_name 商家名称
* @deprecated 结果
*/
@Override
public List<Map<String, Object>> selectBusDataByBusName(String bus_name) {
return businfoMapper.selectBusDataByBusName(bus_name);
}
/**
* 查询本商家所有的服务
* @param bus_id
* @return 结果
*/
public List<Map<String,Object>> selectSerByBusId(Integer bus_id){
return businfoMapper.selectSerByBusId(bus_id);
}
}
|
UTF-8
|
Java
| 2,972 |
java
|
BusinfoServiceImpl.java
|
Java
|
[
{
"context": "n.support.Convert;\n\n/**\n * 商家 服务层实现\n * \n * @author teacherChen\n * @date 2019-07-29\n */\n@Service\npublic class Bus",
"end": 524,
"score": 0.9920092225074768,
"start": 513,
"tag": "USERNAME",
"value": "teacherChen"
}
] | null |
[] |
package com.aaa.project.system.businfo.service;
import java.util.List;
import java.util.Map;
import com.aaa.project.system.busexamine.domain.Busexamine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.aaa.project.system.businfo.mapper.BusinfoMapper;
import com.aaa.project.system.businfo.domain.Businfo;
import com.aaa.project.system.businfo.service.IBusinfoService;
import com.aaa.common.support.Convert;
/**
* 商家 服务层实现
*
* @author teacherChen
* @date 2019-07-29
*/
@Service
public class BusinfoServiceImpl implements IBusinfoService
{
@Autowired
private BusinfoMapper businfoMapper;
/**
* 审核通过商家
*/
@Override
public int insertBus(Busexamine businfo)
{
return businfoMapper.insertBus(businfo);
}
/**
* 商家密码登录
*/
// @Override
// public List<Businfo> selepwd(Businfo businfo) {
// return businfoMapper.selepwd(businfo);
// }
/**
* 查询商家手机号码
*/
@Override
public List<Businfo> selephone(Businfo businfo) {
return businfoMapper.selphone(businfo);
}
/**
* 查询商家信息
*
* @param busId 商家ID
* @return 商家信息
*/
@Override
public Businfo selectBusinfoById(Integer busId)
{
return businfoMapper.selectBusinfoById(busId);
}
/**
* 查询商家列表
*
* @param businfo 商家信息
* @return 商家集合
*/
@Override
public List<Businfo> selectBusinfoList(Businfo businfo)
{
return businfoMapper.selectBusinfoList(businfo);
}
/**
* 新增商家
*
* @param businfo 商家信息
* @return 结果
*/
@Override
public int insertBusinfo(Businfo businfo)
{
return businfoMapper.insertBusinfo(businfo);
}
/**
* 修改商家
*
* @param businfo 商家信息
* @return 结果
*/
@Override
public int updateBusinfo(Businfo businfo)
{
return businfoMapper.updateBusinfo(businfo);
}
/**
* 删除商家对象
*
* @param ids 需要删除的数据ID
* @return 结果
*/
@Override
public int deleteBusinfoByIds(String ids)
{
return businfoMapper.deleteBusinfoByIds(Convert.toStrArray(ids));
}
/**
* 根据商家Id查询商家信息
* @param busId 需要查询的商家Id
* @return 结果
*/
public List<Map<String,Object>> selectBusInfoById(Integer busId){
return businfoMapper.selectBusInfoById(busId);
}
/**
* 查看该商家当天营业额,总共完成的订单,取消的订单数
* @param bus_name 商家名称
* @deprecated 结果
*/
@Override
public List<Map<String, Object>> selectBusDataByBusName(String bus_name) {
return businfoMapper.selectBusDataByBusName(bus_name);
}
/**
* 查询本商家所有的服务
* @param bus_id
* @return 结果
*/
public List<Map<String,Object>> selectSerByBusId(Integer bus_id){
return businfoMapper.selectSerByBusId(bus_id);
}
}
| 2,972 | 0.68488 | 0.681886 | 142 | 17.816902 | 19.861357 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.788732 | false | false |
1
|
89d4cad1e1ff2b733c5a4ae807d4594f942e11db
| 27,650,999,514,553 |
83eb7a965aca6a8cef409f58110d459896ac80d4
|
/phonebooklibrary/src/main/java/rabbitholesolutions/co/za/phonebooklibrary/db/DBUser.java
|
92779340cc91fbe9b59f1e8bb57a23572f6fd1bd
|
[] |
no_license
|
Roystan/phonebook
|
https://github.com/Roystan/phonebook
|
53c3a223fba9e14c22aa511cef9e9cd37e4f115e
|
a93971585f89c8ac5761998e48469c42624ce7f1
|
refs/heads/master
| 2018-09-28T20:26:17.855000 | 2018-09-14T21:04:55 | 2018-09-14T21:04:55 | 131,840,580 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package rabbitholesolutions.co.za.phonebooklibrary.db;
import android.util.Log;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import rabbitholesolutions.co.za.phonebooklibrary.Database;
import rabbitholesolutions.co.za.phonebooklibrary.dbEntry;
public class DBUser extends dbEntry {
public String keyField = "id";
public DBUser() {
this(0);
}
public DBUser(int id) {
// table name
table = "user";
super.setKeyField(this.keyField);
// declare fields
fields = new Hashtable<String, Object[]>();
// field => name default datatype
fields.put(this.keyField, new Object[]{this.keyField, "null", dataType.DB_INT});
fields.put("user_id", new Object[]{"user_id", "null", dataType.DB_INT});
fields.put("user_name", new Object[]{"user_name", "", dataType.DB_STRING});
fields.put("user_title", new Object[]{"user_title", "", dataType.DB_STRING});
fields.put("user_initial", new Object[]{"user_initial", "", dataType.DB_STRING});
fields.put("user_firstname", new Object[]{"user_firstname", "", dataType.DB_STRING});
fields.put("user_lastname", new Object[]{"user_lastname", "", dataType.DB_STRING});
fields.put("user_displayname", new Object[]{"user_displayname", "", dataType.DB_STRING});
fields.put("user_tradingname", new Object[]{"user_tradingname", "", dataType.DB_STRING});
fields.put("user_gender", new Object[]{"user_gender", "null", dataType.DB_INT});
fields.put("user_telnr", new Object[]{"user_telnr", "", dataType.DB_STRING});
fields.put("user_cellnr", new Object[]{"user_cellnr", "", dataType.DB_STRING});
fields.put("user_email", new Object[]{"user_email", "", dataType.DB_STRING});
fields.put("user_website", new Object[]{"user_website", "", dataType.DB_STRING});
fields.put("user_password", new Object[]{"user_password", "", dataType.DB_STRING});
fields.put("user_is_active", new Object[]{"user_is_active", "", dataType.DB_INT});
fields.put("user_date_added", new Object[]{"user_jobtitle", "", dataType.DB_STRING});
fields.put("user_agent", new Object[]{"user_user_agent", "", dataType.DB_STRING});
fields.put("user_ref_language", new Object[]{"user_ref_language", "", dataType.DB_INT});
fields.put("user_ref_person_type", new Object[]{"user_ref_person_type", "", dataType.DB_INT});
fields.put("user_date_login", new Object[]{"user_date_login", "", dataType.DB_STRING});
fields.put("user_date_login_previous", new Object[]{"user_date_login_previous", "", dataType.DB_STRING});
fields.put("user_retry_count", new Object[]{"user_retry_count", "", dataType.DB_STRING});
fields.put("user_retry_date", new Object[]{"user_retry_date", "null", dataType.DB_STRING});
fields.put("user_findstring", new Object[]{"user_findstring", "null", dataType.DB_STRING});
// setup content values
createDefaults();
if (id != 0) {
getFromDb(id);
}
}
public DBUser(String whereClause) {
// table name
table = "user";
super.setKeyField(this.keyField);
// declare fields
fields = new Hashtable<String, Object[]>();
// field => name default datatype
fields.put(this.keyField, new Object[]{this.keyField , "null", dataType.DB_INT});
fields.put("user_id", new Object[]{"user_id", "null", dataType.DB_INT});
fields.put("user_name", new Object[]{"user_name", "", dataType.DB_STRING});
fields.put("user_title", new Object[]{"user_title", "", dataType.DB_STRING});
fields.put("user_initial", new Object[]{"user_initial", "", dataType.DB_STRING});
fields.put("user_firstname", new Object[]{"user_firstname", "", dataType.DB_STRING});
fields.put("user_lastname", new Object[]{"user_lastname", "", dataType.DB_STRING});
fields.put("user_displayname", new Object[]{"user_displayname", "", dataType.DB_STRING});
fields.put("user_tradingname", new Object[]{"user_tradingname", "", dataType.DB_STRING});
fields.put("user_gender", new Object[]{"user_gender", "null", dataType.DB_INT});
fields.put("user_telnr", new Object[]{"user_telnr", "", dataType.DB_STRING});
fields.put("user_cellnr", new Object[]{"user_cellnr", "", dataType.DB_STRING});
fields.put("user_email", new Object[]{"user_email", "", dataType.DB_STRING});
fields.put("user_website", new Object[]{"user_website", "", dataType.DB_STRING});
fields.put("user_password", new Object[]{"user_password", "", dataType.DB_STRING});
fields.put("user_is_active", new Object[]{"user_is_active", "", dataType.DB_INT});
fields.put("user_date_added", new Object[]{"user_jobtitle", "", dataType.DB_STRING});
fields.put("user_agent", new Object[]{"user_user_agent", "", dataType.DB_STRING});
fields.put("user_ref_language", new Object[]{"user_ref_language", "", dataType.DB_INT});
fields.put("user_ref_person_type", new Object[]{"user_ref_person_type", "", dataType.DB_INT});
fields.put("user_date_login", new Object[]{"user_date_login", "", dataType.DB_STRING});
fields.put("user_date_login_previous", new Object[]{"user_date_login_previous", "", dataType.DB_STRING});
fields.put("user_retry_count", new Object[]{"user_retry_count", "", dataType.DB_STRING});
fields.put("user_retry_date", new Object[]{"user_retry_date", "null", dataType.DB_STRING});
fields.put("user_findstring", new Object[]{"user_findstring", "null", dataType.DB_STRING});
// setup content values
createDefaults();
if(!(whereClause.equals(""))){
getFromDb(whereClause);
}
}
public static HashMap<String, String> getActiveUser(String userId) {
try {
return Database.select(
"SELECT * FROM user WHERE user_id = '" + userId + "'").get(0);
} catch (Exception ex) {
return null;
}
}
public static ArrayList<HashMap<String, String>> getIndividualUsers(String type) {
try {
return Database.select(
"SELECT * FROM user");
} catch (Exception ex) {
return null;
}
}
//------------------------------------------------------------------------------------------------------------------------------------------
public static String getActiveUserId() { // active profile
return String.valueOf(Database.selectSingle("SELECT con_value FROM config where con_name = 'USER_ID'"));
}
public static HashMap<String, String> getUserAddress(String userId) {
try {
return Database.select(
"SELECT * FROM address WHERE address_ref_person = '" + userId + "'").get(0);
} catch (Exception ex) {
return null;
}
}
}
|
UTF-8
|
Java
| 8,535 |
java
|
DBUser.java
|
Java
|
[
{
"context": " extends dbEntry {\n\n public String keyField = \"id\";\n\n public DBUser() {\n this(0);\n }\n\n",
"end": 356,
"score": 0.9904832243919373,
"start": 354,
"tag": "KEY",
"value": "id"
},
{
"context": "fields.put(\"user_password\", \t\t\t\t new Object[]{\"user_password\", \"\", dataType.DB_STRING})",
"end": 5946,
"score": 0.7316487431526184,
"start": 5933,
"tag": "PASSWORD",
"value": "user_password"
}
] | null |
[] |
package rabbitholesolutions.co.za.phonebooklibrary.db;
import android.util.Log;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import rabbitholesolutions.co.za.phonebooklibrary.Database;
import rabbitholesolutions.co.za.phonebooklibrary.dbEntry;
public class DBUser extends dbEntry {
public String keyField = "id";
public DBUser() {
this(0);
}
public DBUser(int id) {
// table name
table = "user";
super.setKeyField(this.keyField);
// declare fields
fields = new Hashtable<String, Object[]>();
// field => name default datatype
fields.put(this.keyField, new Object[]{this.keyField, "null", dataType.DB_INT});
fields.put("user_id", new Object[]{"user_id", "null", dataType.DB_INT});
fields.put("user_name", new Object[]{"user_name", "", dataType.DB_STRING});
fields.put("user_title", new Object[]{"user_title", "", dataType.DB_STRING});
fields.put("user_initial", new Object[]{"user_initial", "", dataType.DB_STRING});
fields.put("user_firstname", new Object[]{"user_firstname", "", dataType.DB_STRING});
fields.put("user_lastname", new Object[]{"user_lastname", "", dataType.DB_STRING});
fields.put("user_displayname", new Object[]{"user_displayname", "", dataType.DB_STRING});
fields.put("user_tradingname", new Object[]{"user_tradingname", "", dataType.DB_STRING});
fields.put("user_gender", new Object[]{"user_gender", "null", dataType.DB_INT});
fields.put("user_telnr", new Object[]{"user_telnr", "", dataType.DB_STRING});
fields.put("user_cellnr", new Object[]{"user_cellnr", "", dataType.DB_STRING});
fields.put("user_email", new Object[]{"user_email", "", dataType.DB_STRING});
fields.put("user_website", new Object[]{"user_website", "", dataType.DB_STRING});
fields.put("user_password", new Object[]{"user_password", "", dataType.DB_STRING});
fields.put("user_is_active", new Object[]{"user_is_active", "", dataType.DB_INT});
fields.put("user_date_added", new Object[]{"user_jobtitle", "", dataType.DB_STRING});
fields.put("user_agent", new Object[]{"user_user_agent", "", dataType.DB_STRING});
fields.put("user_ref_language", new Object[]{"user_ref_language", "", dataType.DB_INT});
fields.put("user_ref_person_type", new Object[]{"user_ref_person_type", "", dataType.DB_INT});
fields.put("user_date_login", new Object[]{"user_date_login", "", dataType.DB_STRING});
fields.put("user_date_login_previous", new Object[]{"user_date_login_previous", "", dataType.DB_STRING});
fields.put("user_retry_count", new Object[]{"user_retry_count", "", dataType.DB_STRING});
fields.put("user_retry_date", new Object[]{"user_retry_date", "null", dataType.DB_STRING});
fields.put("user_findstring", new Object[]{"user_findstring", "null", dataType.DB_STRING});
// setup content values
createDefaults();
if (id != 0) {
getFromDb(id);
}
}
public DBUser(String whereClause) {
// table name
table = "user";
super.setKeyField(this.keyField);
// declare fields
fields = new Hashtable<String, Object[]>();
// field => name default datatype
fields.put(this.keyField, new Object[]{this.keyField , "null", dataType.DB_INT});
fields.put("user_id", new Object[]{"user_id", "null", dataType.DB_INT});
fields.put("user_name", new Object[]{"user_name", "", dataType.DB_STRING});
fields.put("user_title", new Object[]{"user_title", "", dataType.DB_STRING});
fields.put("user_initial", new Object[]{"user_initial", "", dataType.DB_STRING});
fields.put("user_firstname", new Object[]{"user_firstname", "", dataType.DB_STRING});
fields.put("user_lastname", new Object[]{"user_lastname", "", dataType.DB_STRING});
fields.put("user_displayname", new Object[]{"user_displayname", "", dataType.DB_STRING});
fields.put("user_tradingname", new Object[]{"user_tradingname", "", dataType.DB_STRING});
fields.put("user_gender", new Object[]{"user_gender", "null", dataType.DB_INT});
fields.put("user_telnr", new Object[]{"user_telnr", "", dataType.DB_STRING});
fields.put("user_cellnr", new Object[]{"user_cellnr", "", dataType.DB_STRING});
fields.put("user_email", new Object[]{"user_email", "", dataType.DB_STRING});
fields.put("user_website", new Object[]{"user_website", "", dataType.DB_STRING});
fields.put("user_password", new Object[]{"<PASSWORD>", "", dataType.DB_STRING});
fields.put("user_is_active", new Object[]{"user_is_active", "", dataType.DB_INT});
fields.put("user_date_added", new Object[]{"user_jobtitle", "", dataType.DB_STRING});
fields.put("user_agent", new Object[]{"user_user_agent", "", dataType.DB_STRING});
fields.put("user_ref_language", new Object[]{"user_ref_language", "", dataType.DB_INT});
fields.put("user_ref_person_type", new Object[]{"user_ref_person_type", "", dataType.DB_INT});
fields.put("user_date_login", new Object[]{"user_date_login", "", dataType.DB_STRING});
fields.put("user_date_login_previous", new Object[]{"user_date_login_previous", "", dataType.DB_STRING});
fields.put("user_retry_count", new Object[]{"user_retry_count", "", dataType.DB_STRING});
fields.put("user_retry_date", new Object[]{"user_retry_date", "null", dataType.DB_STRING});
fields.put("user_findstring", new Object[]{"user_findstring", "null", dataType.DB_STRING});
// setup content values
createDefaults();
if(!(whereClause.equals(""))){
getFromDb(whereClause);
}
}
public static HashMap<String, String> getActiveUser(String userId) {
try {
return Database.select(
"SELECT * FROM user WHERE user_id = '" + userId + "'").get(0);
} catch (Exception ex) {
return null;
}
}
public static ArrayList<HashMap<String, String>> getIndividualUsers(String type) {
try {
return Database.select(
"SELECT * FROM user");
} catch (Exception ex) {
return null;
}
}
//------------------------------------------------------------------------------------------------------------------------------------------
public static String getActiveUserId() { // active profile
return String.valueOf(Database.selectSingle("SELECT con_value FROM config where con_name = 'USER_ID'"));
}
public static HashMap<String, String> getUserAddress(String userId) {
try {
return Database.select(
"SELECT * FROM address WHERE address_ref_person = '" + userId + "'").get(0);
} catch (Exception ex) {
return null;
}
}
}
| 8,532 | 0.489162 | 0.488694 | 142 | 59.105633 | 51.072815 | 144 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.929577 | false | false |
1
|
206b613c32ef96b654509e312af466e0806ed30d
| 1,486,058,703,990 |
32ece41afb840f838918b0e9610a2ae9149db427
|
/src/A467.java
|
53a3c280a632726daafefeff41cf98cae74a3e38
|
[] |
no_license
|
michaelsam94/CF_ProblemSolving
|
https://github.com/michaelsam94/CF_ProblemSolving
|
e385bb4a5233bd564bd9e597cbfad5a3b33911d2
|
386d77f34e112a01e61e198f32549b9809296097
|
refs/heads/master
| 2021-09-04T14:49:04.363000 | 2018-01-19T16:53:11 | 2018-01-19T16:53:11 | 105,405,918 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.util.Scanner;
public class A467 {
public static void main(String[] args) {
int n;
Scanner input = new Scanner(System.in);
int[] p;
int[] c;
int res=0;
int cont=0;
n = input.nextInt();
p = new int[n];
c = new int[n];
for(int i=0;i<n;i++){
p[i] = input.nextInt();
c[i] = input.nextInt();
res = c[i] - p[i];
if(res>=2) cont++;
}
System.out.println(cont);
}
}
|
UTF-8
|
Java
| 408 |
java
|
A467.java
|
Java
|
[] | null |
[] |
import java.util.Scanner;
public class A467 {
public static void main(String[] args) {
int n;
Scanner input = new Scanner(System.in);
int[] p;
int[] c;
int res=0;
int cont=0;
n = input.nextInt();
p = new int[n];
c = new int[n];
for(int i=0;i<n;i++){
p[i] = input.nextInt();
c[i] = input.nextInt();
res = c[i] - p[i];
if(res>=2) cont++;
}
System.out.println(cont);
}
}
| 408 | 0.558824 | 0.541667 | 23 | 16.73913 | 11.51263 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.391304 | false | false |
1
|
8851d048cd6611062fd6a025b48d6e7bf4bb6a84
| 33,578,054,342,941 |
c1bbfea027038365824dedfe08c94b1b14616696
|
/snippet/pingjiao/src/com/dao/action/TongjiAction.java
|
ccfd82686d89d87fa5ff155eb1fdadf3902452e5
|
[] |
no_license
|
Zhaox98/Graduate-Design
|
https://github.com/Zhaox98/Graduate-Design
|
1e414c160d3482ce2122c8e6659ebff60391b051
|
121978db85a691e89fda04df0952fd0275740072
|
refs/heads/master
| 2022-06-19T12:21:40.094000 | 2020-05-08T05:47:27 | 2020-05-08T05:47:27 | 262,059,701 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.dao.action;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Enumeration;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.servlet.ServletUtilities;
import com.dao.bll.SimpleStatistics;
import com.dao.bll.SystemParam;
import com.dao.dal.DALBase;
import com.dao.entity.*;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class TongjiAction extends ActionSupport {
public String execute() {
HttpServletResponse response = (HttpServletResponse)ActionContext.getContext().get(org.apache.struts2.StrutsStatics.HTTP_RESPONSE);
HttpServletRequest request = (HttpServletRequest)ActionContext.getContext().get(org.apache.struts2.StrutsStatics.HTTP_REQUEST);
String actiontype = request.getParameter("actiontype");
System.out.println("actiontype=" + actiontype);
return null;
}
public void dispatchParams(HttpServletRequest request,
HttpServletResponse response) {
Enumeration params = request.getParameterNames();
while (params.hasMoreElements()) {
String paramname = params.nextElement().toString();
String value = request.getParameter(paramname);
request.setAttribute(paramname, value);
}
}
}
|
UTF-8
|
Java
| 1,418 |
java
|
TongjiAction.java
|
Java
|
[] | null |
[] |
package com.dao.action;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Enumeration;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.servlet.ServletUtilities;
import com.dao.bll.SimpleStatistics;
import com.dao.bll.SystemParam;
import com.dao.dal.DALBase;
import com.dao.entity.*;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class TongjiAction extends ActionSupport {
public String execute() {
HttpServletResponse response = (HttpServletResponse)ActionContext.getContext().get(org.apache.struts2.StrutsStatics.HTTP_RESPONSE);
HttpServletRequest request = (HttpServletRequest)ActionContext.getContext().get(org.apache.struts2.StrutsStatics.HTTP_REQUEST);
String actiontype = request.getParameter("actiontype");
System.out.println("actiontype=" + actiontype);
return null;
}
public void dispatchParams(HttpServletRequest request,
HttpServletResponse response) {
Enumeration params = request.getParameterNames();
while (params.hasMoreElements()) {
String paramname = params.nextElement().toString();
String value = request.getParameter(paramname);
request.setAttribute(paramname, value);
}
}
}
| 1,418 | 0.802539 | 0.799718 | 43 | 31.976744 | 28.990366 | 133 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.372093 | false | false |
1
|
84a1b4d2a0734edbb67d656671864e458fe420f0
| 24,421,184,062,916 |
fbcfa6167e9c4b59692ec2be491c7e11ec050ffa
|
/app/src/main/java/com/example/quickshop/RecyclerViewAdapter.java
|
f243c091c9796ebe972bac09777cc02add32814e
|
[] |
no_license
|
SushmitSingh/quickShop
|
https://github.com/SushmitSingh/quickShop
|
7e86abf331421b4e05877771d0fb134f46e2a1de
|
ff33dc80d0f901fd8a48fc771032b8cc2f7ef3f4
|
refs/heads/master
| 2023-03-31T14:40:34.653000 | 2021-07-15T22:25:39 | 2021-07-15T22:25:39 | 353,268,604 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.quickshop;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
public class RecyclerViewAdapter extends FirebaseRecyclerAdapter<RecyclerData,RecyclerViewAdapter.RecyclerViewHolder> {
Context mcontext;
/**
* Initialize a {@link RecyclerView.Adapter} that listens to a Firebase query. See
* {@link FirebaseRecyclerOptions} for configuration options.
*
* @param options
*/
public RecyclerViewAdapter(@NonNull FirebaseRecyclerOptions<RecyclerData> options) {
super(options);
}
@Override
protected void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position, @NonNull RecyclerData model) {
CharSequence title=model.getTitle();
CharSequence rate=model.getRate();
CharSequence image=model.getImg();
AppCompatActivity appCompatActivity=new AppCompatActivity();
holder.pprice.setText(model.getRate());
holder.product.setText(model.getTitle());
Glide.with(holder.img.getContext()).load(model.getImg()).into(holder.img);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent in=new Intent( v.getContext(),ProductView.class);
in.putExtra("title",title);
in.putExtra("rate",rate);
in.putExtra("image",image);
v.getContext().startActivity(in);
}
});
}
@NonNull
@Override
public RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.customgridview,parent,false);
return new RecyclerViewHolder(v);
}
public class RecyclerViewHolder extends RecyclerView.ViewHolder {
private TextView product,pprice;
private ImageView img;
public RecyclerViewHolder(@NonNull View itemView) {
super(itemView);
product = itemView.findViewById(R.id.product);
pprice = itemView.findViewById(R.id.price);
img = itemView.findViewById(R.id.imageView);
}
}
}
|
UTF-8
|
Java
| 2,679 |
java
|
RecyclerViewAdapter.java
|
Java
|
[] | null |
[] |
package com.example.quickshop;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
public class RecyclerViewAdapter extends FirebaseRecyclerAdapter<RecyclerData,RecyclerViewAdapter.RecyclerViewHolder> {
Context mcontext;
/**
* Initialize a {@link RecyclerView.Adapter} that listens to a Firebase query. See
* {@link FirebaseRecyclerOptions} for configuration options.
*
* @param options
*/
public RecyclerViewAdapter(@NonNull FirebaseRecyclerOptions<RecyclerData> options) {
super(options);
}
@Override
protected void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position, @NonNull RecyclerData model) {
CharSequence title=model.getTitle();
CharSequence rate=model.getRate();
CharSequence image=model.getImg();
AppCompatActivity appCompatActivity=new AppCompatActivity();
holder.pprice.setText(model.getRate());
holder.product.setText(model.getTitle());
Glide.with(holder.img.getContext()).load(model.getImg()).into(holder.img);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent in=new Intent( v.getContext(),ProductView.class);
in.putExtra("title",title);
in.putExtra("rate",rate);
in.putExtra("image",image);
v.getContext().startActivity(in);
}
});
}
@NonNull
@Override
public RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.customgridview,parent,false);
return new RecyclerViewHolder(v);
}
public class RecyclerViewHolder extends RecyclerView.ViewHolder {
private TextView product,pprice;
private ImageView img;
public RecyclerViewHolder(@NonNull View itemView) {
super(itemView);
product = itemView.findViewById(R.id.product);
pprice = itemView.findViewById(R.id.price);
img = itemView.findViewById(R.id.imageView);
}
}
}
| 2,679 | 0.692423 | 0.692423 | 78 | 33.358974 | 29.710991 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.628205 | false | false |
1
|
a14113f37c6b881647437303ac2d57ee51a37672
| 4,432,406,310,231 |
234f2c4dcf5356f152db2acf8ae8589ce7f17a8a
|
/src/com/java/University.java
|
247171ef43225aea2cf1891c4e989e5ee8d82a35
|
[] |
no_license
|
veeranji141/GitDemo
|
https://github.com/veeranji141/GitDemo
|
4a2dd036c2a1256631cebee0783eafc93a64e49d
|
37696d7d71993eb5caa2b493f14be49d62a5db48
|
refs/heads/master
| 2023-02-10T05:30:08.792000 | 2021-01-05T08:48:53 | 2021-01-05T08:48:53 | 326,914,773 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.java;
public interface University {
public void JNTUK();
void JNTUH();
}
|
UTF-8
|
Java
| 89 |
java
|
University.java
|
Java
|
[] | null |
[] |
package com.java;
public interface University {
public void JNTUK();
void JNTUH();
}
| 89 | 0.707865 | 0.707865 | 7 | 11.714286 | 10.739969 | 29 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.714286 | false | false |
1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.