blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 5
132
| path
stringlengths 2
382
| src_encoding
stringclasses 34
values | length_bytes
int64 9
3.8M
| score
float64 1.5
4.94
| int_score
int64 2
5
| detected_licenses
listlengths 0
142
| license_type
stringclasses 2
values | text
stringlengths 9
3.8M
| download_success
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
7f69cad997c02cd7c09771d0244559a56507ca9e
|
Java
|
whatafree/JCoffee
|
/benchmark/bigclonebenchdata_completed/10596393.java
|
UTF-8
| 3,473
| 2.78125
| 3
|
[] |
no_license
|
class c10596393 {
public static MyHelperClass Replace(String o0, String o1){ return null; }
//public MyHelperClass Replace(String o0, String o1){ return null; }
public static String BaiKe(String unknown) {
String encodeurl = "";
long sTime = System.currentTimeMillis();
long eTime;
try {
String regEx = "\\#(.+)\\#";
String searchText = "";
MyHelperClass Pattern = new MyHelperClass();
Pattern p =(Pattern)(Object) Pattern.compile(regEx);
Matcher m =(Matcher)(Object) p.matcher(unknown);
if ((boolean)(Object)m.find()) {
searchText =(String)(Object) m.group(1);
}
System.out.println("searchText : " + searchText);
MyHelperClass URLEncoder = new MyHelperClass();
encodeurl =(String)(Object) URLEncoder.encode(searchText, "UTF-8");
String url = "http://www.hudong.com/wiki/" + encodeurl;
HttpURLConnection conn = (HttpURLConnection)(HttpURLConnection)(Object) (new URL(url)).openConnection();
conn.setConnectTimeout(10000);
Parser parser = new Parser(conn);
parser.setEncoding(parser.getEncoding());
NodeFilter filtera =(NodeFilter)(Object) new TagNameFilter("DIV");
NodeList nodes =(NodeList)(Object) parser.extractAllNodesThatMatch(filtera);
String textInPage = "";
if (nodes != null) {
for (int i = 0; i < (int)(Object)nodes.size(); i++) {
Node textnode = (Node)(Node)(Object) nodes.elementAt(i);
if ("div class=\"summary\"".equals(textnode.getText())) {
String temp =(String)(Object) textnode.toPlainTextString();
textInPage += temp + "\n";
}
}
}
String s =(String)(Object) Replace(textInPage, searchText);
eTime = System.currentTimeMillis();
String time = "搜索[" + searchText + "]用时:" + (eTime - sTime) / 1000.0 + "s";
System.out.println(s);
return time + "\r\n" + s;
} catch (Exception e) {
e.printStackTrace();
return "大姨妈来了";
}
}
}
// Code below this line has been added to remove errors
class MyHelperClass {
public MyHelperClass compile(String o0){ return null; }
public MyHelperClass encode(String o0, String o1){ return null; }}
class Pattern {
public MyHelperClass matcher(String o0){ return null; }}
class Matcher {
public MyHelperClass group(int o0){ return null; }
public MyHelperClass find(){ return null; }}
class HttpURLConnection {
public MyHelperClass setConnectTimeout(int o0){ return null; }}
class URL {
URL(String o0){}
URL(){}
public MyHelperClass openConnection(){ return null; }}
class Parser {
Parser(){}
Parser(HttpURLConnection o0){}
public MyHelperClass getEncoding(){ return null; }
public MyHelperClass setEncoding(MyHelperClass o0){ return null; }
public MyHelperClass extractAllNodesThatMatch(NodeFilter o0){ return null; }}
class NodeFilter {
}
class TagNameFilter {
TagNameFilter(String o0){}
TagNameFilter(){}}
class NodeList {
public MyHelperClass size(){ return null; }
public MyHelperClass elementAt(int o0){ return null; }}
class Node {
public MyHelperClass toPlainTextString(){ return null; }
public MyHelperClass getText(){ return null; }}
| true
|
434080d56089cfa018d0b7e973e9c7f0caebc4a1
|
Java
|
geek-Xie/MyLeetCode
|
/34SearchRange(Med)/src/Solution.java
|
UTF-8
| 1,771
| 3.90625
| 4
|
[] |
no_license
|
/**
* 34. 在排序数组中查找元素的第一个和最后一个位置
*
* 给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
*
* 你的算法时间复杂度必须是O(log n) 级别。
*
* 如果数组中不存在目标值,返回[-1, -1]。
*
* 示例 1:
* 输入: nums = [5,7,7,8,8,10], target = 8
* 输出: [3,4]
*
*
* 示例2:
* 输入: nums = [5,7,7,8,8,10], target = 6
* 输出: [-1,-1]
*/
public class Solution {
public int[] searchRange(int[] nums, int target) {
int len = nums.length;
// 如果数组是空的,直接返回
if (len == 0)
return new int[]{-1, -1};
// 如果目标值比数组中最小的数值还小,直接返回
if (target < nums[0])
return new int[]{-1, -1};
// 如果目标值比数组中最大的数值还大,直接返回
if (target > nums[len - 1])
return new int[]{-1, -1};
// 前后指针同时进行遍历
int start = 0;
int end = len - 1;
while (start <= end) {
if (nums[start] != target && nums[end] != target) {
start++;
end--;
continue;
}
else if (nums[start] == target && nums[end] != target) {
end--;
continue;
}
else if (nums[start] != target && nums[end] == target) {
start++;
continue;
}
else
break;
}
// 如果查找不到,直接返回
if (start > end)
return new int[]{-1, -1};
return new int[]{start,end};
}
}
| true
|
2729a197cfdda231f560230604cd0fc4660f1a58
|
Java
|
JUNSEYOUNG/javaStudy
|
/day0929/Exam05.java
|
UHC
| 1,575
| 4.09375
| 4
|
[] |
no_license
|
// && || ) л ̸, , , Է¹
// 90 ̻̰ 90 ̸̻ ">~̰ϱ &&϶°ų?"
//б Ϸ
//б θ Ǻϴ α ۼ
import java.util.Scanner;
class Exam05
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String name;
System.out.println("л ̸ Էϼ.");
name = sc.next();
int kor, eng, math, sum; //(avg) Ÿ avgֱ
System.out.println(" Էϼ.");
kor = sc.nextInt();
System.out.println(" Էϼ.");
eng = sc.nextInt();
System.out.println(" Էϼ.");
math = sc.nextInt();
sum = kor + eng + math;
double avg; //(avg) Ǽ double
avg = (double)sum / 3; //Ǽ ijÿ()
//avg = sum / 3.0;
System.out.println("**°**");
System.out.println("̸:" + name);
System.out.println(":" + kor);
System.out.println(":" + eng);
System.out.println(":" + math);
System.out.println(":" + sum);
System.out.println(":" + avg);
if(kor >= 90 && avg >=90)
System.out.println("б Դϴ.");
else
System.out.println("б ڰ ƴմϴ.");
}
}
| true
|
55333d894ece912c07a6aa9fca4278adae261348
|
Java
|
googleapis/google-cloud-java
|
/java-kms/proto-google-cloud-kms-v1/src/main/java/com/google/cloud/kms/v1/RawEncryptResponse.java
|
UTF-8
| 90,264
| 1.84375
| 2
|
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/kms/v1/service.proto
package com.google.cloud.kms.v1;
/**
*
*
* <pre>
* Response message for
* [KeyManagementService.RawEncrypt][google.cloud.kms.v1.KeyManagementService.RawEncrypt].
* </pre>
*
* Protobuf type {@code google.cloud.kms.v1.RawEncryptResponse}
*/
public final class RawEncryptResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.kms.v1.RawEncryptResponse)
RawEncryptResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use RawEncryptResponse.newBuilder() to construct.
private RawEncryptResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private RawEncryptResponse() {
ciphertext_ = com.google.protobuf.ByteString.EMPTY;
initializationVector_ = com.google.protobuf.ByteString.EMPTY;
name_ = "";
protectionLevel_ = 0;
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new RawEncryptResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.kms.v1.KmsProto
.internal_static_google_cloud_kms_v1_RawEncryptResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.kms.v1.KmsProto
.internal_static_google_cloud_kms_v1_RawEncryptResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.kms.v1.RawEncryptResponse.class,
com.google.cloud.kms.v1.RawEncryptResponse.Builder.class);
}
public static final int CIPHERTEXT_FIELD_NUMBER = 1;
private com.google.protobuf.ByteString ciphertext_ = com.google.protobuf.ByteString.EMPTY;
/**
*
*
* <pre>
* The encrypted data. In the case of AES-GCM, the authentication tag
* is the [tag_length][google.cloud.kms.v1.RawEncryptResponse.tag_length]
* bytes at the end of this field.
* </pre>
*
* <code>bytes ciphertext = 1;</code>
*
* @return The ciphertext.
*/
@java.lang.Override
public com.google.protobuf.ByteString getCiphertext() {
return ciphertext_;
}
public static final int INITIALIZATION_VECTOR_FIELD_NUMBER = 2;
private com.google.protobuf.ByteString initializationVector_ =
com.google.protobuf.ByteString.EMPTY;
/**
*
*
* <pre>
* The initialization vector (IV) generated by the service during
* encryption. This value must be stored and provided in
* [RawDecryptRequest.initialization_vector][google.cloud.kms.v1.RawDecryptRequest.initialization_vector]
* at decryption time.
* </pre>
*
* <code>bytes initialization_vector = 2;</code>
*
* @return The initializationVector.
*/
@java.lang.Override
public com.google.protobuf.ByteString getInitializationVector() {
return initializationVector_;
}
public static final int TAG_LENGTH_FIELD_NUMBER = 3;
private int tagLength_ = 0;
/**
*
*
* <pre>
* The length of the authentication tag that is appended to
* the end of the ciphertext.
* </pre>
*
* <code>int32 tag_length = 3;</code>
*
* @return The tagLength.
*/
@java.lang.Override
public int getTagLength() {
return tagLength_;
}
public static final int CIPHERTEXT_CRC32C_FIELD_NUMBER = 4;
private com.google.protobuf.Int64Value ciphertextCrc32C_;
/**
*
*
* <pre>
* Integrity verification field. A CRC32C checksum of the returned
* [RawEncryptResponse.ciphertext][google.cloud.kms.v1.RawEncryptResponse.ciphertext].
* An integrity check of ciphertext can be performed by computing the CRC32C
* checksum of ciphertext and comparing your results to this field. Discard
* the response in case of non-matching checksum values, and perform a limited
* number of retries. A persistent mismatch may indicate an issue in your
* computation of the CRC32C checksum. Note: This field is defined as int64
* for reasons of compatibility across different languages. However, it is a
* non-negative integer, which will never exceed 2^32-1, and can be safely
* downconverted to uint32 in languages that support this type.
* </pre>
*
* <code>.google.protobuf.Int64Value ciphertext_crc32c = 4;</code>
*
* @return Whether the ciphertextCrc32c field is set.
*/
@java.lang.Override
public boolean hasCiphertextCrc32C() {
return ciphertextCrc32C_ != null;
}
/**
*
*
* <pre>
* Integrity verification field. A CRC32C checksum of the returned
* [RawEncryptResponse.ciphertext][google.cloud.kms.v1.RawEncryptResponse.ciphertext].
* An integrity check of ciphertext can be performed by computing the CRC32C
* checksum of ciphertext and comparing your results to this field. Discard
* the response in case of non-matching checksum values, and perform a limited
* number of retries. A persistent mismatch may indicate an issue in your
* computation of the CRC32C checksum. Note: This field is defined as int64
* for reasons of compatibility across different languages. However, it is a
* non-negative integer, which will never exceed 2^32-1, and can be safely
* downconverted to uint32 in languages that support this type.
* </pre>
*
* <code>.google.protobuf.Int64Value ciphertext_crc32c = 4;</code>
*
* @return The ciphertextCrc32c.
*/
@java.lang.Override
public com.google.protobuf.Int64Value getCiphertextCrc32C() {
return ciphertextCrc32C_ == null
? com.google.protobuf.Int64Value.getDefaultInstance()
: ciphertextCrc32C_;
}
/**
*
*
* <pre>
* Integrity verification field. A CRC32C checksum of the returned
* [RawEncryptResponse.ciphertext][google.cloud.kms.v1.RawEncryptResponse.ciphertext].
* An integrity check of ciphertext can be performed by computing the CRC32C
* checksum of ciphertext and comparing your results to this field. Discard
* the response in case of non-matching checksum values, and perform a limited
* number of retries. A persistent mismatch may indicate an issue in your
* computation of the CRC32C checksum. Note: This field is defined as int64
* for reasons of compatibility across different languages. However, it is a
* non-negative integer, which will never exceed 2^32-1, and can be safely
* downconverted to uint32 in languages that support this type.
* </pre>
*
* <code>.google.protobuf.Int64Value ciphertext_crc32c = 4;</code>
*/
@java.lang.Override
public com.google.protobuf.Int64ValueOrBuilder getCiphertextCrc32COrBuilder() {
return ciphertextCrc32C_ == null
? com.google.protobuf.Int64Value.getDefaultInstance()
: ciphertextCrc32C_;
}
public static final int INITIALIZATION_VECTOR_CRC32C_FIELD_NUMBER = 5;
private com.google.protobuf.Int64Value initializationVectorCrc32C_;
/**
*
*
* <pre>
* Integrity verification field. A CRC32C checksum of the returned
* [RawEncryptResponse.initialization_vector][google.cloud.kms.v1.RawEncryptResponse.initialization_vector].
* An integrity check of initialization_vector can be performed by computing
* the CRC32C checksum of initialization_vector and comparing your results to
* this field. Discard the response in case of non-matching checksum values,
* and perform a limited number of retries. A persistent mismatch may indicate
* an issue in your computation of the CRC32C checksum. Note: This field is
* defined as int64 for reasons of compatibility across different languages.
* However, it is a non-negative integer, which will never exceed 2^32-1, and
* can be safely downconverted to uint32 in languages that support this type.
* </pre>
*
* <code>.google.protobuf.Int64Value initialization_vector_crc32c = 5;</code>
*
* @return Whether the initializationVectorCrc32c field is set.
*/
@java.lang.Override
public boolean hasInitializationVectorCrc32C() {
return initializationVectorCrc32C_ != null;
}
/**
*
*
* <pre>
* Integrity verification field. A CRC32C checksum of the returned
* [RawEncryptResponse.initialization_vector][google.cloud.kms.v1.RawEncryptResponse.initialization_vector].
* An integrity check of initialization_vector can be performed by computing
* the CRC32C checksum of initialization_vector and comparing your results to
* this field. Discard the response in case of non-matching checksum values,
* and perform a limited number of retries. A persistent mismatch may indicate
* an issue in your computation of the CRC32C checksum. Note: This field is
* defined as int64 for reasons of compatibility across different languages.
* However, it is a non-negative integer, which will never exceed 2^32-1, and
* can be safely downconverted to uint32 in languages that support this type.
* </pre>
*
* <code>.google.protobuf.Int64Value initialization_vector_crc32c = 5;</code>
*
* @return The initializationVectorCrc32c.
*/
@java.lang.Override
public com.google.protobuf.Int64Value getInitializationVectorCrc32C() {
return initializationVectorCrc32C_ == null
? com.google.protobuf.Int64Value.getDefaultInstance()
: initializationVectorCrc32C_;
}
/**
*
*
* <pre>
* Integrity verification field. A CRC32C checksum of the returned
* [RawEncryptResponse.initialization_vector][google.cloud.kms.v1.RawEncryptResponse.initialization_vector].
* An integrity check of initialization_vector can be performed by computing
* the CRC32C checksum of initialization_vector and comparing your results to
* this field. Discard the response in case of non-matching checksum values,
* and perform a limited number of retries. A persistent mismatch may indicate
* an issue in your computation of the CRC32C checksum. Note: This field is
* defined as int64 for reasons of compatibility across different languages.
* However, it is a non-negative integer, which will never exceed 2^32-1, and
* can be safely downconverted to uint32 in languages that support this type.
* </pre>
*
* <code>.google.protobuf.Int64Value initialization_vector_crc32c = 5;</code>
*/
@java.lang.Override
public com.google.protobuf.Int64ValueOrBuilder getInitializationVectorCrc32COrBuilder() {
return initializationVectorCrc32C_ == null
? com.google.protobuf.Int64Value.getDefaultInstance()
: initializationVectorCrc32C_;
}
public static final int VERIFIED_PLAINTEXT_CRC32C_FIELD_NUMBER = 6;
private boolean verifiedPlaintextCrc32C_ = false;
/**
*
*
* <pre>
* Integrity verification field. A flag indicating whether
* [RawEncryptRequest.plaintext_crc32c][google.cloud.kms.v1.RawEncryptRequest.plaintext_crc32c]
* was received by
* [KeyManagementService][google.cloud.kms.v1.KeyManagementService] and used
* for the integrity verification of the plaintext. A false value of this
* field indicates either that
* [RawEncryptRequest.plaintext_crc32c][google.cloud.kms.v1.RawEncryptRequest.plaintext_crc32c]
* was left unset or that it was not delivered to
* [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. If you've
* set
* [RawEncryptRequest.plaintext_crc32c][google.cloud.kms.v1.RawEncryptRequest.plaintext_crc32c]
* but this field is still false, discard the response and perform a limited
* number of retries.
* </pre>
*
* <code>bool verified_plaintext_crc32c = 6;</code>
*
* @return The verifiedPlaintextCrc32c.
*/
@java.lang.Override
public boolean getVerifiedPlaintextCrc32C() {
return verifiedPlaintextCrc32C_;
}
public static final int VERIFIED_ADDITIONAL_AUTHENTICATED_DATA_CRC32C_FIELD_NUMBER = 7;
private boolean verifiedAdditionalAuthenticatedDataCrc32C_ = false;
/**
*
*
* <pre>
* Integrity verification field. A flag indicating whether
* [RawEncryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.RawEncryptRequest.additional_authenticated_data_crc32c]
* was received by
* [KeyManagementService][google.cloud.kms.v1.KeyManagementService] and used
* for the integrity verification of additional_authenticated_data. A false
* value of this field indicates either that //
* [RawEncryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.RawEncryptRequest.additional_authenticated_data_crc32c]
* was left unset or that it was not delivered to
* [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. If you've
* set
* [RawEncryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.RawEncryptRequest.additional_authenticated_data_crc32c]
* but this field is still false, discard the response and perform a limited
* number of retries.
* </pre>
*
* <code>bool verified_additional_authenticated_data_crc32c = 7;</code>
*
* @return The verifiedAdditionalAuthenticatedDataCrc32c.
*/
@java.lang.Override
public boolean getVerifiedAdditionalAuthenticatedDataCrc32C() {
return verifiedAdditionalAuthenticatedDataCrc32C_;
}
public static final int VERIFIED_INITIALIZATION_VECTOR_CRC32C_FIELD_NUMBER = 10;
private boolean verifiedInitializationVectorCrc32C_ = false;
/**
*
*
* <pre>
* Integrity verification field. A flag indicating whether
* [RawEncryptRequest.initialization_vector_crc32c][google.cloud.kms.v1.RawEncryptRequest.initialization_vector_crc32c]
* was received by
* [KeyManagementService][google.cloud.kms.v1.KeyManagementService] and used
* for the integrity verification of initialization_vector. A false value of
* this field indicates either that
* [RawEncryptRequest.initialization_vector_crc32c][google.cloud.kms.v1.RawEncryptRequest.initialization_vector_crc32c]
* was left unset or that it was not delivered to
* [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. If you've
* set
* [RawEncryptRequest.initialization_vector_crc32c][google.cloud.kms.v1.RawEncryptRequest.initialization_vector_crc32c]
* but this field is still false, discard the response and perform a limited
* number of retries.
* </pre>
*
* <code>bool verified_initialization_vector_crc32c = 10;</code>
*
* @return The verifiedInitializationVectorCrc32c.
*/
@java.lang.Override
public boolean getVerifiedInitializationVectorCrc32C() {
return verifiedInitializationVectorCrc32C_;
}
public static final int NAME_FIELD_NUMBER = 8;
@SuppressWarnings("serial")
private volatile java.lang.Object name_ = "";
/**
*
*
* <pre>
* The resource name of the
* [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] used in
* encryption. Check this field to verify that the intended resource was used
* for encryption.
* </pre>
*
* <code>string name = 8;</code>
*
* @return The name.
*/
@java.lang.Override
public java.lang.String getName() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
}
}
/**
*
*
* <pre>
* The resource name of the
* [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] used in
* encryption. Check this field to verify that the intended resource was used
* for encryption.
* </pre>
*
* <code>string name = 8;</code>
*
* @return The bytes for name.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PROTECTION_LEVEL_FIELD_NUMBER = 9;
private int protectionLevel_ = 0;
/**
*
*
* <pre>
* The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] of the
* [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] used in
* encryption.
* </pre>
*
* <code>.google.cloud.kms.v1.ProtectionLevel protection_level = 9;</code>
*
* @return The enum numeric value on the wire for protectionLevel.
*/
@java.lang.Override
public int getProtectionLevelValue() {
return protectionLevel_;
}
/**
*
*
* <pre>
* The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] of the
* [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] used in
* encryption.
* </pre>
*
* <code>.google.cloud.kms.v1.ProtectionLevel protection_level = 9;</code>
*
* @return The protectionLevel.
*/
@java.lang.Override
public com.google.cloud.kms.v1.ProtectionLevel getProtectionLevel() {
com.google.cloud.kms.v1.ProtectionLevel result =
com.google.cloud.kms.v1.ProtectionLevel.forNumber(protectionLevel_);
return result == null ? com.google.cloud.kms.v1.ProtectionLevel.UNRECOGNIZED : result;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!ciphertext_.isEmpty()) {
output.writeBytes(1, ciphertext_);
}
if (!initializationVector_.isEmpty()) {
output.writeBytes(2, initializationVector_);
}
if (tagLength_ != 0) {
output.writeInt32(3, tagLength_);
}
if (ciphertextCrc32C_ != null) {
output.writeMessage(4, getCiphertextCrc32C());
}
if (initializationVectorCrc32C_ != null) {
output.writeMessage(5, getInitializationVectorCrc32C());
}
if (verifiedPlaintextCrc32C_ != false) {
output.writeBool(6, verifiedPlaintextCrc32C_);
}
if (verifiedAdditionalAuthenticatedDataCrc32C_ != false) {
output.writeBool(7, verifiedAdditionalAuthenticatedDataCrc32C_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 8, name_);
}
if (protectionLevel_
!= com.google.cloud.kms.v1.ProtectionLevel.PROTECTION_LEVEL_UNSPECIFIED.getNumber()) {
output.writeEnum(9, protectionLevel_);
}
if (verifiedInitializationVectorCrc32C_ != false) {
output.writeBool(10, verifiedInitializationVectorCrc32C_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!ciphertext_.isEmpty()) {
size += com.google.protobuf.CodedOutputStream.computeBytesSize(1, ciphertext_);
}
if (!initializationVector_.isEmpty()) {
size += com.google.protobuf.CodedOutputStream.computeBytesSize(2, initializationVector_);
}
if (tagLength_ != 0) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(3, tagLength_);
}
if (ciphertextCrc32C_ != null) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(4, getCiphertextCrc32C());
}
if (initializationVectorCrc32C_ != null) {
size +=
com.google.protobuf.CodedOutputStream.computeMessageSize(
5, getInitializationVectorCrc32C());
}
if (verifiedPlaintextCrc32C_ != false) {
size += com.google.protobuf.CodedOutputStream.computeBoolSize(6, verifiedPlaintextCrc32C_);
}
if (verifiedAdditionalAuthenticatedDataCrc32C_ != false) {
size +=
com.google.protobuf.CodedOutputStream.computeBoolSize(
7, verifiedAdditionalAuthenticatedDataCrc32C_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(8, name_);
}
if (protectionLevel_
!= com.google.cloud.kms.v1.ProtectionLevel.PROTECTION_LEVEL_UNSPECIFIED.getNumber()) {
size += com.google.protobuf.CodedOutputStream.computeEnumSize(9, protectionLevel_);
}
if (verifiedInitializationVectorCrc32C_ != false) {
size +=
com.google.protobuf.CodedOutputStream.computeBoolSize(
10, verifiedInitializationVectorCrc32C_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.kms.v1.RawEncryptResponse)) {
return super.equals(obj);
}
com.google.cloud.kms.v1.RawEncryptResponse other =
(com.google.cloud.kms.v1.RawEncryptResponse) obj;
if (!getCiphertext().equals(other.getCiphertext())) return false;
if (!getInitializationVector().equals(other.getInitializationVector())) return false;
if (getTagLength() != other.getTagLength()) return false;
if (hasCiphertextCrc32C() != other.hasCiphertextCrc32C()) return false;
if (hasCiphertextCrc32C()) {
if (!getCiphertextCrc32C().equals(other.getCiphertextCrc32C())) return false;
}
if (hasInitializationVectorCrc32C() != other.hasInitializationVectorCrc32C()) return false;
if (hasInitializationVectorCrc32C()) {
if (!getInitializationVectorCrc32C().equals(other.getInitializationVectorCrc32C()))
return false;
}
if (getVerifiedPlaintextCrc32C() != other.getVerifiedPlaintextCrc32C()) return false;
if (getVerifiedAdditionalAuthenticatedDataCrc32C()
!= other.getVerifiedAdditionalAuthenticatedDataCrc32C()) return false;
if (getVerifiedInitializationVectorCrc32C() != other.getVerifiedInitializationVectorCrc32C())
return false;
if (!getName().equals(other.getName())) return false;
if (protectionLevel_ != other.protectionLevel_) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + CIPHERTEXT_FIELD_NUMBER;
hash = (53 * hash) + getCiphertext().hashCode();
hash = (37 * hash) + INITIALIZATION_VECTOR_FIELD_NUMBER;
hash = (53 * hash) + getInitializationVector().hashCode();
hash = (37 * hash) + TAG_LENGTH_FIELD_NUMBER;
hash = (53 * hash) + getTagLength();
if (hasCiphertextCrc32C()) {
hash = (37 * hash) + CIPHERTEXT_CRC32C_FIELD_NUMBER;
hash = (53 * hash) + getCiphertextCrc32C().hashCode();
}
if (hasInitializationVectorCrc32C()) {
hash = (37 * hash) + INITIALIZATION_VECTOR_CRC32C_FIELD_NUMBER;
hash = (53 * hash) + getInitializationVectorCrc32C().hashCode();
}
hash = (37 * hash) + VERIFIED_PLAINTEXT_CRC32C_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getVerifiedPlaintextCrc32C());
hash = (37 * hash) + VERIFIED_ADDITIONAL_AUTHENTICATED_DATA_CRC32C_FIELD_NUMBER;
hash =
(53 * hash)
+ com.google.protobuf.Internal.hashBoolean(
getVerifiedAdditionalAuthenticatedDataCrc32C());
hash = (37 * hash) + VERIFIED_INITIALIZATION_VECTOR_CRC32C_FIELD_NUMBER;
hash =
(53 * hash)
+ com.google.protobuf.Internal.hashBoolean(getVerifiedInitializationVectorCrc32C());
hash = (37 * hash) + NAME_FIELD_NUMBER;
hash = (53 * hash) + getName().hashCode();
hash = (37 * hash) + PROTECTION_LEVEL_FIELD_NUMBER;
hash = (53 * hash) + protectionLevel_;
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.kms.v1.RawEncryptResponse parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.kms.v1.RawEncryptResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.kms.v1.RawEncryptResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.kms.v1.RawEncryptResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.kms.v1.RawEncryptResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.kms.v1.RawEncryptResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.kms.v1.RawEncryptResponse parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.kms.v1.RawEncryptResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.kms.v1.RawEncryptResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.kms.v1.RawEncryptResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.kms.v1.RawEncryptResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.kms.v1.RawEncryptResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.kms.v1.RawEncryptResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Response message for
* [KeyManagementService.RawEncrypt][google.cloud.kms.v1.KeyManagementService.RawEncrypt].
* </pre>
*
* Protobuf type {@code google.cloud.kms.v1.RawEncryptResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.kms.v1.RawEncryptResponse)
com.google.cloud.kms.v1.RawEncryptResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.kms.v1.KmsProto
.internal_static_google_cloud_kms_v1_RawEncryptResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.kms.v1.KmsProto
.internal_static_google_cloud_kms_v1_RawEncryptResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.kms.v1.RawEncryptResponse.class,
com.google.cloud.kms.v1.RawEncryptResponse.Builder.class);
}
// Construct using com.google.cloud.kms.v1.RawEncryptResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
ciphertext_ = com.google.protobuf.ByteString.EMPTY;
initializationVector_ = com.google.protobuf.ByteString.EMPTY;
tagLength_ = 0;
ciphertextCrc32C_ = null;
if (ciphertextCrc32CBuilder_ != null) {
ciphertextCrc32CBuilder_.dispose();
ciphertextCrc32CBuilder_ = null;
}
initializationVectorCrc32C_ = null;
if (initializationVectorCrc32CBuilder_ != null) {
initializationVectorCrc32CBuilder_.dispose();
initializationVectorCrc32CBuilder_ = null;
}
verifiedPlaintextCrc32C_ = false;
verifiedAdditionalAuthenticatedDataCrc32C_ = false;
verifiedInitializationVectorCrc32C_ = false;
name_ = "";
protectionLevel_ = 0;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.kms.v1.KmsProto
.internal_static_google_cloud_kms_v1_RawEncryptResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.kms.v1.RawEncryptResponse getDefaultInstanceForType() {
return com.google.cloud.kms.v1.RawEncryptResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.kms.v1.RawEncryptResponse build() {
com.google.cloud.kms.v1.RawEncryptResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.kms.v1.RawEncryptResponse buildPartial() {
com.google.cloud.kms.v1.RawEncryptResponse result =
new com.google.cloud.kms.v1.RawEncryptResponse(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.kms.v1.RawEncryptResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.ciphertext_ = ciphertext_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.initializationVector_ = initializationVector_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.tagLength_ = tagLength_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.ciphertextCrc32C_ =
ciphertextCrc32CBuilder_ == null ? ciphertextCrc32C_ : ciphertextCrc32CBuilder_.build();
}
if (((from_bitField0_ & 0x00000010) != 0)) {
result.initializationVectorCrc32C_ =
initializationVectorCrc32CBuilder_ == null
? initializationVectorCrc32C_
: initializationVectorCrc32CBuilder_.build();
}
if (((from_bitField0_ & 0x00000020) != 0)) {
result.verifiedPlaintextCrc32C_ = verifiedPlaintextCrc32C_;
}
if (((from_bitField0_ & 0x00000040) != 0)) {
result.verifiedAdditionalAuthenticatedDataCrc32C_ =
verifiedAdditionalAuthenticatedDataCrc32C_;
}
if (((from_bitField0_ & 0x00000080) != 0)) {
result.verifiedInitializationVectorCrc32C_ = verifiedInitializationVectorCrc32C_;
}
if (((from_bitField0_ & 0x00000100) != 0)) {
result.name_ = name_;
}
if (((from_bitField0_ & 0x00000200) != 0)) {
result.protectionLevel_ = protectionLevel_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.kms.v1.RawEncryptResponse) {
return mergeFrom((com.google.cloud.kms.v1.RawEncryptResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.kms.v1.RawEncryptResponse other) {
if (other == com.google.cloud.kms.v1.RawEncryptResponse.getDefaultInstance()) return this;
if (other.getCiphertext() != com.google.protobuf.ByteString.EMPTY) {
setCiphertext(other.getCiphertext());
}
if (other.getInitializationVector() != com.google.protobuf.ByteString.EMPTY) {
setInitializationVector(other.getInitializationVector());
}
if (other.getTagLength() != 0) {
setTagLength(other.getTagLength());
}
if (other.hasCiphertextCrc32C()) {
mergeCiphertextCrc32C(other.getCiphertextCrc32C());
}
if (other.hasInitializationVectorCrc32C()) {
mergeInitializationVectorCrc32C(other.getInitializationVectorCrc32C());
}
if (other.getVerifiedPlaintextCrc32C() != false) {
setVerifiedPlaintextCrc32C(other.getVerifiedPlaintextCrc32C());
}
if (other.getVerifiedAdditionalAuthenticatedDataCrc32C() != false) {
setVerifiedAdditionalAuthenticatedDataCrc32C(
other.getVerifiedAdditionalAuthenticatedDataCrc32C());
}
if (other.getVerifiedInitializationVectorCrc32C() != false) {
setVerifiedInitializationVectorCrc32C(other.getVerifiedInitializationVectorCrc32C());
}
if (!other.getName().isEmpty()) {
name_ = other.name_;
bitField0_ |= 0x00000100;
onChanged();
}
if (other.protectionLevel_ != 0) {
setProtectionLevelValue(other.getProtectionLevelValue());
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
ciphertext_ = input.readBytes();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
initializationVector_ = input.readBytes();
bitField0_ |= 0x00000002;
break;
} // case 18
case 24:
{
tagLength_ = input.readInt32();
bitField0_ |= 0x00000004;
break;
} // case 24
case 34:
{
input.readMessage(
getCiphertextCrc32CFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000008;
break;
} // case 34
case 42:
{
input.readMessage(
getInitializationVectorCrc32CFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000010;
break;
} // case 42
case 48:
{
verifiedPlaintextCrc32C_ = input.readBool();
bitField0_ |= 0x00000020;
break;
} // case 48
case 56:
{
verifiedAdditionalAuthenticatedDataCrc32C_ = input.readBool();
bitField0_ |= 0x00000040;
break;
} // case 56
case 66:
{
name_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000100;
break;
} // case 66
case 72:
{
protectionLevel_ = input.readEnum();
bitField0_ |= 0x00000200;
break;
} // case 72
case 80:
{
verifiedInitializationVectorCrc32C_ = input.readBool();
bitField0_ |= 0x00000080;
break;
} // case 80
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private com.google.protobuf.ByteString ciphertext_ = com.google.protobuf.ByteString.EMPTY;
/**
*
*
* <pre>
* The encrypted data. In the case of AES-GCM, the authentication tag
* is the [tag_length][google.cloud.kms.v1.RawEncryptResponse.tag_length]
* bytes at the end of this field.
* </pre>
*
* <code>bytes ciphertext = 1;</code>
*
* @return The ciphertext.
*/
@java.lang.Override
public com.google.protobuf.ByteString getCiphertext() {
return ciphertext_;
}
/**
*
*
* <pre>
* The encrypted data. In the case of AES-GCM, the authentication tag
* is the [tag_length][google.cloud.kms.v1.RawEncryptResponse.tag_length]
* bytes at the end of this field.
* </pre>
*
* <code>bytes ciphertext = 1;</code>
*
* @param value The ciphertext to set.
* @return This builder for chaining.
*/
public Builder setCiphertext(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
ciphertext_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The encrypted data. In the case of AES-GCM, the authentication tag
* is the [tag_length][google.cloud.kms.v1.RawEncryptResponse.tag_length]
* bytes at the end of this field.
* </pre>
*
* <code>bytes ciphertext = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearCiphertext() {
bitField0_ = (bitField0_ & ~0x00000001);
ciphertext_ = getDefaultInstance().getCiphertext();
onChanged();
return this;
}
private com.google.protobuf.ByteString initializationVector_ =
com.google.protobuf.ByteString.EMPTY;
/**
*
*
* <pre>
* The initialization vector (IV) generated by the service during
* encryption. This value must be stored and provided in
* [RawDecryptRequest.initialization_vector][google.cloud.kms.v1.RawDecryptRequest.initialization_vector]
* at decryption time.
* </pre>
*
* <code>bytes initialization_vector = 2;</code>
*
* @return The initializationVector.
*/
@java.lang.Override
public com.google.protobuf.ByteString getInitializationVector() {
return initializationVector_;
}
/**
*
*
* <pre>
* The initialization vector (IV) generated by the service during
* encryption. This value must be stored and provided in
* [RawDecryptRequest.initialization_vector][google.cloud.kms.v1.RawDecryptRequest.initialization_vector]
* at decryption time.
* </pre>
*
* <code>bytes initialization_vector = 2;</code>
*
* @param value The initializationVector to set.
* @return This builder for chaining.
*/
public Builder setInitializationVector(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
initializationVector_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The initialization vector (IV) generated by the service during
* encryption. This value must be stored and provided in
* [RawDecryptRequest.initialization_vector][google.cloud.kms.v1.RawDecryptRequest.initialization_vector]
* at decryption time.
* </pre>
*
* <code>bytes initialization_vector = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearInitializationVector() {
bitField0_ = (bitField0_ & ~0x00000002);
initializationVector_ = getDefaultInstance().getInitializationVector();
onChanged();
return this;
}
private int tagLength_;
/**
*
*
* <pre>
* The length of the authentication tag that is appended to
* the end of the ciphertext.
* </pre>
*
* <code>int32 tag_length = 3;</code>
*
* @return The tagLength.
*/
@java.lang.Override
public int getTagLength() {
return tagLength_;
}
/**
*
*
* <pre>
* The length of the authentication tag that is appended to
* the end of the ciphertext.
* </pre>
*
* <code>int32 tag_length = 3;</code>
*
* @param value The tagLength to set.
* @return This builder for chaining.
*/
public Builder setTagLength(int value) {
tagLength_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* The length of the authentication tag that is appended to
* the end of the ciphertext.
* </pre>
*
* <code>int32 tag_length = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearTagLength() {
bitField0_ = (bitField0_ & ~0x00000004);
tagLength_ = 0;
onChanged();
return this;
}
private com.google.protobuf.Int64Value ciphertextCrc32C_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Int64Value,
com.google.protobuf.Int64Value.Builder,
com.google.protobuf.Int64ValueOrBuilder>
ciphertextCrc32CBuilder_;
/**
*
*
* <pre>
* Integrity verification field. A CRC32C checksum of the returned
* [RawEncryptResponse.ciphertext][google.cloud.kms.v1.RawEncryptResponse.ciphertext].
* An integrity check of ciphertext can be performed by computing the CRC32C
* checksum of ciphertext and comparing your results to this field. Discard
* the response in case of non-matching checksum values, and perform a limited
* number of retries. A persistent mismatch may indicate an issue in your
* computation of the CRC32C checksum. Note: This field is defined as int64
* for reasons of compatibility across different languages. However, it is a
* non-negative integer, which will never exceed 2^32-1, and can be safely
* downconverted to uint32 in languages that support this type.
* </pre>
*
* <code>.google.protobuf.Int64Value ciphertext_crc32c = 4;</code>
*
* @return Whether the ciphertextCrc32c field is set.
*/
public boolean hasCiphertextCrc32C() {
return ((bitField0_ & 0x00000008) != 0);
}
/**
*
*
* <pre>
* Integrity verification field. A CRC32C checksum of the returned
* [RawEncryptResponse.ciphertext][google.cloud.kms.v1.RawEncryptResponse.ciphertext].
* An integrity check of ciphertext can be performed by computing the CRC32C
* checksum of ciphertext and comparing your results to this field. Discard
* the response in case of non-matching checksum values, and perform a limited
* number of retries. A persistent mismatch may indicate an issue in your
* computation of the CRC32C checksum. Note: This field is defined as int64
* for reasons of compatibility across different languages. However, it is a
* non-negative integer, which will never exceed 2^32-1, and can be safely
* downconverted to uint32 in languages that support this type.
* </pre>
*
* <code>.google.protobuf.Int64Value ciphertext_crc32c = 4;</code>
*
* @return The ciphertextCrc32c.
*/
public com.google.protobuf.Int64Value getCiphertextCrc32C() {
if (ciphertextCrc32CBuilder_ == null) {
return ciphertextCrc32C_ == null
? com.google.protobuf.Int64Value.getDefaultInstance()
: ciphertextCrc32C_;
} else {
return ciphertextCrc32CBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Integrity verification field. A CRC32C checksum of the returned
* [RawEncryptResponse.ciphertext][google.cloud.kms.v1.RawEncryptResponse.ciphertext].
* An integrity check of ciphertext can be performed by computing the CRC32C
* checksum of ciphertext and comparing your results to this field. Discard
* the response in case of non-matching checksum values, and perform a limited
* number of retries. A persistent mismatch may indicate an issue in your
* computation of the CRC32C checksum. Note: This field is defined as int64
* for reasons of compatibility across different languages. However, it is a
* non-negative integer, which will never exceed 2^32-1, and can be safely
* downconverted to uint32 in languages that support this type.
* </pre>
*
* <code>.google.protobuf.Int64Value ciphertext_crc32c = 4;</code>
*/
public Builder setCiphertextCrc32C(com.google.protobuf.Int64Value value) {
if (ciphertextCrc32CBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ciphertextCrc32C_ = value;
} else {
ciphertextCrc32CBuilder_.setMessage(value);
}
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* Integrity verification field. A CRC32C checksum of the returned
* [RawEncryptResponse.ciphertext][google.cloud.kms.v1.RawEncryptResponse.ciphertext].
* An integrity check of ciphertext can be performed by computing the CRC32C
* checksum of ciphertext and comparing your results to this field. Discard
* the response in case of non-matching checksum values, and perform a limited
* number of retries. A persistent mismatch may indicate an issue in your
* computation of the CRC32C checksum. Note: This field is defined as int64
* for reasons of compatibility across different languages. However, it is a
* non-negative integer, which will never exceed 2^32-1, and can be safely
* downconverted to uint32 in languages that support this type.
* </pre>
*
* <code>.google.protobuf.Int64Value ciphertext_crc32c = 4;</code>
*/
public Builder setCiphertextCrc32C(com.google.protobuf.Int64Value.Builder builderForValue) {
if (ciphertextCrc32CBuilder_ == null) {
ciphertextCrc32C_ = builderForValue.build();
} else {
ciphertextCrc32CBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* Integrity verification field. A CRC32C checksum of the returned
* [RawEncryptResponse.ciphertext][google.cloud.kms.v1.RawEncryptResponse.ciphertext].
* An integrity check of ciphertext can be performed by computing the CRC32C
* checksum of ciphertext and comparing your results to this field. Discard
* the response in case of non-matching checksum values, and perform a limited
* number of retries. A persistent mismatch may indicate an issue in your
* computation of the CRC32C checksum. Note: This field is defined as int64
* for reasons of compatibility across different languages. However, it is a
* non-negative integer, which will never exceed 2^32-1, and can be safely
* downconverted to uint32 in languages that support this type.
* </pre>
*
* <code>.google.protobuf.Int64Value ciphertext_crc32c = 4;</code>
*/
public Builder mergeCiphertextCrc32C(com.google.protobuf.Int64Value value) {
if (ciphertextCrc32CBuilder_ == null) {
if (((bitField0_ & 0x00000008) != 0)
&& ciphertextCrc32C_ != null
&& ciphertextCrc32C_ != com.google.protobuf.Int64Value.getDefaultInstance()) {
getCiphertextCrc32CBuilder().mergeFrom(value);
} else {
ciphertextCrc32C_ = value;
}
} else {
ciphertextCrc32CBuilder_.mergeFrom(value);
}
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* Integrity verification field. A CRC32C checksum of the returned
* [RawEncryptResponse.ciphertext][google.cloud.kms.v1.RawEncryptResponse.ciphertext].
* An integrity check of ciphertext can be performed by computing the CRC32C
* checksum of ciphertext and comparing your results to this field. Discard
* the response in case of non-matching checksum values, and perform a limited
* number of retries. A persistent mismatch may indicate an issue in your
* computation of the CRC32C checksum. Note: This field is defined as int64
* for reasons of compatibility across different languages. However, it is a
* non-negative integer, which will never exceed 2^32-1, and can be safely
* downconverted to uint32 in languages that support this type.
* </pre>
*
* <code>.google.protobuf.Int64Value ciphertext_crc32c = 4;</code>
*/
public Builder clearCiphertextCrc32C() {
bitField0_ = (bitField0_ & ~0x00000008);
ciphertextCrc32C_ = null;
if (ciphertextCrc32CBuilder_ != null) {
ciphertextCrc32CBuilder_.dispose();
ciphertextCrc32CBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Integrity verification field. A CRC32C checksum of the returned
* [RawEncryptResponse.ciphertext][google.cloud.kms.v1.RawEncryptResponse.ciphertext].
* An integrity check of ciphertext can be performed by computing the CRC32C
* checksum of ciphertext and comparing your results to this field. Discard
* the response in case of non-matching checksum values, and perform a limited
* number of retries. A persistent mismatch may indicate an issue in your
* computation of the CRC32C checksum. Note: This field is defined as int64
* for reasons of compatibility across different languages. However, it is a
* non-negative integer, which will never exceed 2^32-1, and can be safely
* downconverted to uint32 in languages that support this type.
* </pre>
*
* <code>.google.protobuf.Int64Value ciphertext_crc32c = 4;</code>
*/
public com.google.protobuf.Int64Value.Builder getCiphertextCrc32CBuilder() {
bitField0_ |= 0x00000008;
onChanged();
return getCiphertextCrc32CFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Integrity verification field. A CRC32C checksum of the returned
* [RawEncryptResponse.ciphertext][google.cloud.kms.v1.RawEncryptResponse.ciphertext].
* An integrity check of ciphertext can be performed by computing the CRC32C
* checksum of ciphertext and comparing your results to this field. Discard
* the response in case of non-matching checksum values, and perform a limited
* number of retries. A persistent mismatch may indicate an issue in your
* computation of the CRC32C checksum. Note: This field is defined as int64
* for reasons of compatibility across different languages. However, it is a
* non-negative integer, which will never exceed 2^32-1, and can be safely
* downconverted to uint32 in languages that support this type.
* </pre>
*
* <code>.google.protobuf.Int64Value ciphertext_crc32c = 4;</code>
*/
public com.google.protobuf.Int64ValueOrBuilder getCiphertextCrc32COrBuilder() {
if (ciphertextCrc32CBuilder_ != null) {
return ciphertextCrc32CBuilder_.getMessageOrBuilder();
} else {
return ciphertextCrc32C_ == null
? com.google.protobuf.Int64Value.getDefaultInstance()
: ciphertextCrc32C_;
}
}
/**
*
*
* <pre>
* Integrity verification field. A CRC32C checksum of the returned
* [RawEncryptResponse.ciphertext][google.cloud.kms.v1.RawEncryptResponse.ciphertext].
* An integrity check of ciphertext can be performed by computing the CRC32C
* checksum of ciphertext and comparing your results to this field. Discard
* the response in case of non-matching checksum values, and perform a limited
* number of retries. A persistent mismatch may indicate an issue in your
* computation of the CRC32C checksum. Note: This field is defined as int64
* for reasons of compatibility across different languages. However, it is a
* non-negative integer, which will never exceed 2^32-1, and can be safely
* downconverted to uint32 in languages that support this type.
* </pre>
*
* <code>.google.protobuf.Int64Value ciphertext_crc32c = 4;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Int64Value,
com.google.protobuf.Int64Value.Builder,
com.google.protobuf.Int64ValueOrBuilder>
getCiphertextCrc32CFieldBuilder() {
if (ciphertextCrc32CBuilder_ == null) {
ciphertextCrc32CBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Int64Value,
com.google.protobuf.Int64Value.Builder,
com.google.protobuf.Int64ValueOrBuilder>(
getCiphertextCrc32C(), getParentForChildren(), isClean());
ciphertextCrc32C_ = null;
}
return ciphertextCrc32CBuilder_;
}
private com.google.protobuf.Int64Value initializationVectorCrc32C_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Int64Value,
com.google.protobuf.Int64Value.Builder,
com.google.protobuf.Int64ValueOrBuilder>
initializationVectorCrc32CBuilder_;
/**
*
*
* <pre>
* Integrity verification field. A CRC32C checksum of the returned
* [RawEncryptResponse.initialization_vector][google.cloud.kms.v1.RawEncryptResponse.initialization_vector].
* An integrity check of initialization_vector can be performed by computing
* the CRC32C checksum of initialization_vector and comparing your results to
* this field. Discard the response in case of non-matching checksum values,
* and perform a limited number of retries. A persistent mismatch may indicate
* an issue in your computation of the CRC32C checksum. Note: This field is
* defined as int64 for reasons of compatibility across different languages.
* However, it is a non-negative integer, which will never exceed 2^32-1, and
* can be safely downconverted to uint32 in languages that support this type.
* </pre>
*
* <code>.google.protobuf.Int64Value initialization_vector_crc32c = 5;</code>
*
* @return Whether the initializationVectorCrc32c field is set.
*/
public boolean hasInitializationVectorCrc32C() {
return ((bitField0_ & 0x00000010) != 0);
}
/**
*
*
* <pre>
* Integrity verification field. A CRC32C checksum of the returned
* [RawEncryptResponse.initialization_vector][google.cloud.kms.v1.RawEncryptResponse.initialization_vector].
* An integrity check of initialization_vector can be performed by computing
* the CRC32C checksum of initialization_vector and comparing your results to
* this field. Discard the response in case of non-matching checksum values,
* and perform a limited number of retries. A persistent mismatch may indicate
* an issue in your computation of the CRC32C checksum. Note: This field is
* defined as int64 for reasons of compatibility across different languages.
* However, it is a non-negative integer, which will never exceed 2^32-1, and
* can be safely downconverted to uint32 in languages that support this type.
* </pre>
*
* <code>.google.protobuf.Int64Value initialization_vector_crc32c = 5;</code>
*
* @return The initializationVectorCrc32c.
*/
public com.google.protobuf.Int64Value getInitializationVectorCrc32C() {
if (initializationVectorCrc32CBuilder_ == null) {
return initializationVectorCrc32C_ == null
? com.google.protobuf.Int64Value.getDefaultInstance()
: initializationVectorCrc32C_;
} else {
return initializationVectorCrc32CBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Integrity verification field. A CRC32C checksum of the returned
* [RawEncryptResponse.initialization_vector][google.cloud.kms.v1.RawEncryptResponse.initialization_vector].
* An integrity check of initialization_vector can be performed by computing
* the CRC32C checksum of initialization_vector and comparing your results to
* this field. Discard the response in case of non-matching checksum values,
* and perform a limited number of retries. A persistent mismatch may indicate
* an issue in your computation of the CRC32C checksum. Note: This field is
* defined as int64 for reasons of compatibility across different languages.
* However, it is a non-negative integer, which will never exceed 2^32-1, and
* can be safely downconverted to uint32 in languages that support this type.
* </pre>
*
* <code>.google.protobuf.Int64Value initialization_vector_crc32c = 5;</code>
*/
public Builder setInitializationVectorCrc32C(com.google.protobuf.Int64Value value) {
if (initializationVectorCrc32CBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
initializationVectorCrc32C_ = value;
} else {
initializationVectorCrc32CBuilder_.setMessage(value);
}
bitField0_ |= 0x00000010;
onChanged();
return this;
}
/**
*
*
* <pre>
* Integrity verification field. A CRC32C checksum of the returned
* [RawEncryptResponse.initialization_vector][google.cloud.kms.v1.RawEncryptResponse.initialization_vector].
* An integrity check of initialization_vector can be performed by computing
* the CRC32C checksum of initialization_vector and comparing your results to
* this field. Discard the response in case of non-matching checksum values,
* and perform a limited number of retries. A persistent mismatch may indicate
* an issue in your computation of the CRC32C checksum. Note: This field is
* defined as int64 for reasons of compatibility across different languages.
* However, it is a non-negative integer, which will never exceed 2^32-1, and
* can be safely downconverted to uint32 in languages that support this type.
* </pre>
*
* <code>.google.protobuf.Int64Value initialization_vector_crc32c = 5;</code>
*/
public Builder setInitializationVectorCrc32C(
com.google.protobuf.Int64Value.Builder builderForValue) {
if (initializationVectorCrc32CBuilder_ == null) {
initializationVectorCrc32C_ = builderForValue.build();
} else {
initializationVectorCrc32CBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000010;
onChanged();
return this;
}
/**
*
*
* <pre>
* Integrity verification field. A CRC32C checksum of the returned
* [RawEncryptResponse.initialization_vector][google.cloud.kms.v1.RawEncryptResponse.initialization_vector].
* An integrity check of initialization_vector can be performed by computing
* the CRC32C checksum of initialization_vector and comparing your results to
* this field. Discard the response in case of non-matching checksum values,
* and perform a limited number of retries. A persistent mismatch may indicate
* an issue in your computation of the CRC32C checksum. Note: This field is
* defined as int64 for reasons of compatibility across different languages.
* However, it is a non-negative integer, which will never exceed 2^32-1, and
* can be safely downconverted to uint32 in languages that support this type.
* </pre>
*
* <code>.google.protobuf.Int64Value initialization_vector_crc32c = 5;</code>
*/
public Builder mergeInitializationVectorCrc32C(com.google.protobuf.Int64Value value) {
if (initializationVectorCrc32CBuilder_ == null) {
if (((bitField0_ & 0x00000010) != 0)
&& initializationVectorCrc32C_ != null
&& initializationVectorCrc32C_ != com.google.protobuf.Int64Value.getDefaultInstance()) {
getInitializationVectorCrc32CBuilder().mergeFrom(value);
} else {
initializationVectorCrc32C_ = value;
}
} else {
initializationVectorCrc32CBuilder_.mergeFrom(value);
}
bitField0_ |= 0x00000010;
onChanged();
return this;
}
/**
*
*
* <pre>
* Integrity verification field. A CRC32C checksum of the returned
* [RawEncryptResponse.initialization_vector][google.cloud.kms.v1.RawEncryptResponse.initialization_vector].
* An integrity check of initialization_vector can be performed by computing
* the CRC32C checksum of initialization_vector and comparing your results to
* this field. Discard the response in case of non-matching checksum values,
* and perform a limited number of retries. A persistent mismatch may indicate
* an issue in your computation of the CRC32C checksum. Note: This field is
* defined as int64 for reasons of compatibility across different languages.
* However, it is a non-negative integer, which will never exceed 2^32-1, and
* can be safely downconverted to uint32 in languages that support this type.
* </pre>
*
* <code>.google.protobuf.Int64Value initialization_vector_crc32c = 5;</code>
*/
public Builder clearInitializationVectorCrc32C() {
bitField0_ = (bitField0_ & ~0x00000010);
initializationVectorCrc32C_ = null;
if (initializationVectorCrc32CBuilder_ != null) {
initializationVectorCrc32CBuilder_.dispose();
initializationVectorCrc32CBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Integrity verification field. A CRC32C checksum of the returned
* [RawEncryptResponse.initialization_vector][google.cloud.kms.v1.RawEncryptResponse.initialization_vector].
* An integrity check of initialization_vector can be performed by computing
* the CRC32C checksum of initialization_vector and comparing your results to
* this field. Discard the response in case of non-matching checksum values,
* and perform a limited number of retries. A persistent mismatch may indicate
* an issue in your computation of the CRC32C checksum. Note: This field is
* defined as int64 for reasons of compatibility across different languages.
* However, it is a non-negative integer, which will never exceed 2^32-1, and
* can be safely downconverted to uint32 in languages that support this type.
* </pre>
*
* <code>.google.protobuf.Int64Value initialization_vector_crc32c = 5;</code>
*/
public com.google.protobuf.Int64Value.Builder getInitializationVectorCrc32CBuilder() {
bitField0_ |= 0x00000010;
onChanged();
return getInitializationVectorCrc32CFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Integrity verification field. A CRC32C checksum of the returned
* [RawEncryptResponse.initialization_vector][google.cloud.kms.v1.RawEncryptResponse.initialization_vector].
* An integrity check of initialization_vector can be performed by computing
* the CRC32C checksum of initialization_vector and comparing your results to
* this field. Discard the response in case of non-matching checksum values,
* and perform a limited number of retries. A persistent mismatch may indicate
* an issue in your computation of the CRC32C checksum. Note: This field is
* defined as int64 for reasons of compatibility across different languages.
* However, it is a non-negative integer, which will never exceed 2^32-1, and
* can be safely downconverted to uint32 in languages that support this type.
* </pre>
*
* <code>.google.protobuf.Int64Value initialization_vector_crc32c = 5;</code>
*/
public com.google.protobuf.Int64ValueOrBuilder getInitializationVectorCrc32COrBuilder() {
if (initializationVectorCrc32CBuilder_ != null) {
return initializationVectorCrc32CBuilder_.getMessageOrBuilder();
} else {
return initializationVectorCrc32C_ == null
? com.google.protobuf.Int64Value.getDefaultInstance()
: initializationVectorCrc32C_;
}
}
/**
*
*
* <pre>
* Integrity verification field. A CRC32C checksum of the returned
* [RawEncryptResponse.initialization_vector][google.cloud.kms.v1.RawEncryptResponse.initialization_vector].
* An integrity check of initialization_vector can be performed by computing
* the CRC32C checksum of initialization_vector and comparing your results to
* this field. Discard the response in case of non-matching checksum values,
* and perform a limited number of retries. A persistent mismatch may indicate
* an issue in your computation of the CRC32C checksum. Note: This field is
* defined as int64 for reasons of compatibility across different languages.
* However, it is a non-negative integer, which will never exceed 2^32-1, and
* can be safely downconverted to uint32 in languages that support this type.
* </pre>
*
* <code>.google.protobuf.Int64Value initialization_vector_crc32c = 5;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Int64Value,
com.google.protobuf.Int64Value.Builder,
com.google.protobuf.Int64ValueOrBuilder>
getInitializationVectorCrc32CFieldBuilder() {
if (initializationVectorCrc32CBuilder_ == null) {
initializationVectorCrc32CBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Int64Value,
com.google.protobuf.Int64Value.Builder,
com.google.protobuf.Int64ValueOrBuilder>(
getInitializationVectorCrc32C(), getParentForChildren(), isClean());
initializationVectorCrc32C_ = null;
}
return initializationVectorCrc32CBuilder_;
}
private boolean verifiedPlaintextCrc32C_;
/**
*
*
* <pre>
* Integrity verification field. A flag indicating whether
* [RawEncryptRequest.plaintext_crc32c][google.cloud.kms.v1.RawEncryptRequest.plaintext_crc32c]
* was received by
* [KeyManagementService][google.cloud.kms.v1.KeyManagementService] and used
* for the integrity verification of the plaintext. A false value of this
* field indicates either that
* [RawEncryptRequest.plaintext_crc32c][google.cloud.kms.v1.RawEncryptRequest.plaintext_crc32c]
* was left unset or that it was not delivered to
* [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. If you've
* set
* [RawEncryptRequest.plaintext_crc32c][google.cloud.kms.v1.RawEncryptRequest.plaintext_crc32c]
* but this field is still false, discard the response and perform a limited
* number of retries.
* </pre>
*
* <code>bool verified_plaintext_crc32c = 6;</code>
*
* @return The verifiedPlaintextCrc32c.
*/
@java.lang.Override
public boolean getVerifiedPlaintextCrc32C() {
return verifiedPlaintextCrc32C_;
}
/**
*
*
* <pre>
* Integrity verification field. A flag indicating whether
* [RawEncryptRequest.plaintext_crc32c][google.cloud.kms.v1.RawEncryptRequest.plaintext_crc32c]
* was received by
* [KeyManagementService][google.cloud.kms.v1.KeyManagementService] and used
* for the integrity verification of the plaintext. A false value of this
* field indicates either that
* [RawEncryptRequest.plaintext_crc32c][google.cloud.kms.v1.RawEncryptRequest.plaintext_crc32c]
* was left unset or that it was not delivered to
* [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. If you've
* set
* [RawEncryptRequest.plaintext_crc32c][google.cloud.kms.v1.RawEncryptRequest.plaintext_crc32c]
* but this field is still false, discard the response and perform a limited
* number of retries.
* </pre>
*
* <code>bool verified_plaintext_crc32c = 6;</code>
*
* @param value The verifiedPlaintextCrc32c to set.
* @return This builder for chaining.
*/
public Builder setVerifiedPlaintextCrc32C(boolean value) {
verifiedPlaintextCrc32C_ = value;
bitField0_ |= 0x00000020;
onChanged();
return this;
}
/**
*
*
* <pre>
* Integrity verification field. A flag indicating whether
* [RawEncryptRequest.plaintext_crc32c][google.cloud.kms.v1.RawEncryptRequest.plaintext_crc32c]
* was received by
* [KeyManagementService][google.cloud.kms.v1.KeyManagementService] and used
* for the integrity verification of the plaintext. A false value of this
* field indicates either that
* [RawEncryptRequest.plaintext_crc32c][google.cloud.kms.v1.RawEncryptRequest.plaintext_crc32c]
* was left unset or that it was not delivered to
* [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. If you've
* set
* [RawEncryptRequest.plaintext_crc32c][google.cloud.kms.v1.RawEncryptRequest.plaintext_crc32c]
* but this field is still false, discard the response and perform a limited
* number of retries.
* </pre>
*
* <code>bool verified_plaintext_crc32c = 6;</code>
*
* @return This builder for chaining.
*/
public Builder clearVerifiedPlaintextCrc32C() {
bitField0_ = (bitField0_ & ~0x00000020);
verifiedPlaintextCrc32C_ = false;
onChanged();
return this;
}
private boolean verifiedAdditionalAuthenticatedDataCrc32C_;
/**
*
*
* <pre>
* Integrity verification field. A flag indicating whether
* [RawEncryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.RawEncryptRequest.additional_authenticated_data_crc32c]
* was received by
* [KeyManagementService][google.cloud.kms.v1.KeyManagementService] and used
* for the integrity verification of additional_authenticated_data. A false
* value of this field indicates either that //
* [RawEncryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.RawEncryptRequest.additional_authenticated_data_crc32c]
* was left unset or that it was not delivered to
* [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. If you've
* set
* [RawEncryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.RawEncryptRequest.additional_authenticated_data_crc32c]
* but this field is still false, discard the response and perform a limited
* number of retries.
* </pre>
*
* <code>bool verified_additional_authenticated_data_crc32c = 7;</code>
*
* @return The verifiedAdditionalAuthenticatedDataCrc32c.
*/
@java.lang.Override
public boolean getVerifiedAdditionalAuthenticatedDataCrc32C() {
return verifiedAdditionalAuthenticatedDataCrc32C_;
}
/**
*
*
* <pre>
* Integrity verification field. A flag indicating whether
* [RawEncryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.RawEncryptRequest.additional_authenticated_data_crc32c]
* was received by
* [KeyManagementService][google.cloud.kms.v1.KeyManagementService] and used
* for the integrity verification of additional_authenticated_data. A false
* value of this field indicates either that //
* [RawEncryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.RawEncryptRequest.additional_authenticated_data_crc32c]
* was left unset or that it was not delivered to
* [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. If you've
* set
* [RawEncryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.RawEncryptRequest.additional_authenticated_data_crc32c]
* but this field is still false, discard the response and perform a limited
* number of retries.
* </pre>
*
* <code>bool verified_additional_authenticated_data_crc32c = 7;</code>
*
* @param value The verifiedAdditionalAuthenticatedDataCrc32c to set.
* @return This builder for chaining.
*/
public Builder setVerifiedAdditionalAuthenticatedDataCrc32C(boolean value) {
verifiedAdditionalAuthenticatedDataCrc32C_ = value;
bitField0_ |= 0x00000040;
onChanged();
return this;
}
/**
*
*
* <pre>
* Integrity verification field. A flag indicating whether
* [RawEncryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.RawEncryptRequest.additional_authenticated_data_crc32c]
* was received by
* [KeyManagementService][google.cloud.kms.v1.KeyManagementService] and used
* for the integrity verification of additional_authenticated_data. A false
* value of this field indicates either that //
* [RawEncryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.RawEncryptRequest.additional_authenticated_data_crc32c]
* was left unset or that it was not delivered to
* [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. If you've
* set
* [RawEncryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.RawEncryptRequest.additional_authenticated_data_crc32c]
* but this field is still false, discard the response and perform a limited
* number of retries.
* </pre>
*
* <code>bool verified_additional_authenticated_data_crc32c = 7;</code>
*
* @return This builder for chaining.
*/
public Builder clearVerifiedAdditionalAuthenticatedDataCrc32C() {
bitField0_ = (bitField0_ & ~0x00000040);
verifiedAdditionalAuthenticatedDataCrc32C_ = false;
onChanged();
return this;
}
private boolean verifiedInitializationVectorCrc32C_;
/**
*
*
* <pre>
* Integrity verification field. A flag indicating whether
* [RawEncryptRequest.initialization_vector_crc32c][google.cloud.kms.v1.RawEncryptRequest.initialization_vector_crc32c]
* was received by
* [KeyManagementService][google.cloud.kms.v1.KeyManagementService] and used
* for the integrity verification of initialization_vector. A false value of
* this field indicates either that
* [RawEncryptRequest.initialization_vector_crc32c][google.cloud.kms.v1.RawEncryptRequest.initialization_vector_crc32c]
* was left unset or that it was not delivered to
* [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. If you've
* set
* [RawEncryptRequest.initialization_vector_crc32c][google.cloud.kms.v1.RawEncryptRequest.initialization_vector_crc32c]
* but this field is still false, discard the response and perform a limited
* number of retries.
* </pre>
*
* <code>bool verified_initialization_vector_crc32c = 10;</code>
*
* @return The verifiedInitializationVectorCrc32c.
*/
@java.lang.Override
public boolean getVerifiedInitializationVectorCrc32C() {
return verifiedInitializationVectorCrc32C_;
}
/**
*
*
* <pre>
* Integrity verification field. A flag indicating whether
* [RawEncryptRequest.initialization_vector_crc32c][google.cloud.kms.v1.RawEncryptRequest.initialization_vector_crc32c]
* was received by
* [KeyManagementService][google.cloud.kms.v1.KeyManagementService] and used
* for the integrity verification of initialization_vector. A false value of
* this field indicates either that
* [RawEncryptRequest.initialization_vector_crc32c][google.cloud.kms.v1.RawEncryptRequest.initialization_vector_crc32c]
* was left unset or that it was not delivered to
* [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. If you've
* set
* [RawEncryptRequest.initialization_vector_crc32c][google.cloud.kms.v1.RawEncryptRequest.initialization_vector_crc32c]
* but this field is still false, discard the response and perform a limited
* number of retries.
* </pre>
*
* <code>bool verified_initialization_vector_crc32c = 10;</code>
*
* @param value The verifiedInitializationVectorCrc32c to set.
* @return This builder for chaining.
*/
public Builder setVerifiedInitializationVectorCrc32C(boolean value) {
verifiedInitializationVectorCrc32C_ = value;
bitField0_ |= 0x00000080;
onChanged();
return this;
}
/**
*
*
* <pre>
* Integrity verification field. A flag indicating whether
* [RawEncryptRequest.initialization_vector_crc32c][google.cloud.kms.v1.RawEncryptRequest.initialization_vector_crc32c]
* was received by
* [KeyManagementService][google.cloud.kms.v1.KeyManagementService] and used
* for the integrity verification of initialization_vector. A false value of
* this field indicates either that
* [RawEncryptRequest.initialization_vector_crc32c][google.cloud.kms.v1.RawEncryptRequest.initialization_vector_crc32c]
* was left unset or that it was not delivered to
* [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. If you've
* set
* [RawEncryptRequest.initialization_vector_crc32c][google.cloud.kms.v1.RawEncryptRequest.initialization_vector_crc32c]
* but this field is still false, discard the response and perform a limited
* number of retries.
* </pre>
*
* <code>bool verified_initialization_vector_crc32c = 10;</code>
*
* @return This builder for chaining.
*/
public Builder clearVerifiedInitializationVectorCrc32C() {
bitField0_ = (bitField0_ & ~0x00000080);
verifiedInitializationVectorCrc32C_ = false;
onChanged();
return this;
}
private java.lang.Object name_ = "";
/**
*
*
* <pre>
* The resource name of the
* [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] used in
* encryption. Check this field to verify that the intended resource was used
* for encryption.
* </pre>
*
* <code>string name = 8;</code>
*
* @return The name.
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The resource name of the
* [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] used in
* encryption. Check this field to verify that the intended resource was used
* for encryption.
* </pre>
*
* <code>string name = 8;</code>
*
* @return The bytes for name.
*/
public com.google.protobuf.ByteString getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The resource name of the
* [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] used in
* encryption. Check this field to verify that the intended resource was used
* for encryption.
* </pre>
*
* <code>string name = 8;</code>
*
* @param value The name to set.
* @return This builder for chaining.
*/
public Builder setName(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
name_ = value;
bitField0_ |= 0x00000100;
onChanged();
return this;
}
/**
*
*
* <pre>
* The resource name of the
* [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] used in
* encryption. Check this field to verify that the intended resource was used
* for encryption.
* </pre>
*
* <code>string name = 8;</code>
*
* @return This builder for chaining.
*/
public Builder clearName() {
name_ = getDefaultInstance().getName();
bitField0_ = (bitField0_ & ~0x00000100);
onChanged();
return this;
}
/**
*
*
* <pre>
* The resource name of the
* [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] used in
* encryption. Check this field to verify that the intended resource was used
* for encryption.
* </pre>
*
* <code>string name = 8;</code>
*
* @param value The bytes for name to set.
* @return This builder for chaining.
*/
public Builder setNameBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
name_ = value;
bitField0_ |= 0x00000100;
onChanged();
return this;
}
private int protectionLevel_ = 0;
/**
*
*
* <pre>
* The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] of the
* [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] used in
* encryption.
* </pre>
*
* <code>.google.cloud.kms.v1.ProtectionLevel protection_level = 9;</code>
*
* @return The enum numeric value on the wire for protectionLevel.
*/
@java.lang.Override
public int getProtectionLevelValue() {
return protectionLevel_;
}
/**
*
*
* <pre>
* The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] of the
* [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] used in
* encryption.
* </pre>
*
* <code>.google.cloud.kms.v1.ProtectionLevel protection_level = 9;</code>
*
* @param value The enum numeric value on the wire for protectionLevel to set.
* @return This builder for chaining.
*/
public Builder setProtectionLevelValue(int value) {
protectionLevel_ = value;
bitField0_ |= 0x00000200;
onChanged();
return this;
}
/**
*
*
* <pre>
* The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] of the
* [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] used in
* encryption.
* </pre>
*
* <code>.google.cloud.kms.v1.ProtectionLevel protection_level = 9;</code>
*
* @return The protectionLevel.
*/
@java.lang.Override
public com.google.cloud.kms.v1.ProtectionLevel getProtectionLevel() {
com.google.cloud.kms.v1.ProtectionLevel result =
com.google.cloud.kms.v1.ProtectionLevel.forNumber(protectionLevel_);
return result == null ? com.google.cloud.kms.v1.ProtectionLevel.UNRECOGNIZED : result;
}
/**
*
*
* <pre>
* The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] of the
* [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] used in
* encryption.
* </pre>
*
* <code>.google.cloud.kms.v1.ProtectionLevel protection_level = 9;</code>
*
* @param value The protectionLevel to set.
* @return This builder for chaining.
*/
public Builder setProtectionLevel(com.google.cloud.kms.v1.ProtectionLevel value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000200;
protectionLevel_ = value.getNumber();
onChanged();
return this;
}
/**
*
*
* <pre>
* The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] of the
* [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] used in
* encryption.
* </pre>
*
* <code>.google.cloud.kms.v1.ProtectionLevel protection_level = 9;</code>
*
* @return This builder for chaining.
*/
public Builder clearProtectionLevel() {
bitField0_ = (bitField0_ & ~0x00000200);
protectionLevel_ = 0;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.kms.v1.RawEncryptResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.kms.v1.RawEncryptResponse)
private static final com.google.cloud.kms.v1.RawEncryptResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.kms.v1.RawEncryptResponse();
}
public static com.google.cloud.kms.v1.RawEncryptResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<RawEncryptResponse> PARSER =
new com.google.protobuf.AbstractParser<RawEncryptResponse>() {
@java.lang.Override
public RawEncryptResponse parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<RawEncryptResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<RawEncryptResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.kms.v1.RawEncryptResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| true
|
c8c28e29732a9b795af08960c98f99672f842440
|
Java
|
xrealm/tiktok-src
|
/sources/com/p280ss/android/ugc/aweme/profile/edit/C35758f.java
|
UTF-8
| 531
| 1.898438
| 2
|
[] |
no_license
|
package com.p280ss.android.ugc.aweme.profile.edit;
/* renamed from: com.ss.android.ugc.aweme.profile.edit.f */
final /* synthetic */ class C35758f implements Runnable {
/* renamed from: a */
private final InstagramPresenter f93726a;
/* renamed from: b */
private final String f93727b;
C35758f(InstagramPresenter instagramPresenter, String str) {
this.f93726a = instagramPresenter;
this.f93727b = str;
}
public final void run() {
this.f93726a.mo90605a(this.f93727b);
}
}
| true
|
c90b7b3875fb4ed7efe50d59db34859545f6baea
|
Java
|
JosePatricio/heavy-cargo-management-system
|
/PROYECTOS/TAS-ON-WEB/tas_on_web/tas-on-web-services/src/main/java/ec/net/redcode/tas/on/rest/processor/PublicServiceProcessor.java
|
UTF-8
| 9,282
| 1.96875
| 2
|
[] |
no_license
|
package ec.net.redcode.tas.on.rest.processor;
import ec.net.redcode.tas.on.common.Constant;
import ec.net.redcode.tas.on.common.MethodConstant;
import ec.net.redcode.tas.on.common.dto.Company;
import ec.net.redcode.tas.on.common.exception.TasOnException;
import ec.net.redcode.tas.on.persistence.entities.*;
import ec.net.redcode.tas.on.rest.bean.CommonBean;
import ec.net.redcode.tas.on.rest.dto.Solicitud;
import ec.net.redcode.tas.on.rest.dto.Solicitudes;
import lombok.extern.log4j.Log4j;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.component.cxf.common.message.CxfConstants;
import org.apache.cxf.message.MessageContentsList;
import org.codehaus.jackson.map.ObjectMapper;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Log4j
public class PublicServiceProcessor extends CommonBean implements Processor {
@Override
public void process(Exchange exchange) throws Exception {
MessageContentsList messageList = exchange.getIn().getBody(MessageContentsList.class);
String operationName = exchange.getIn().getHeader(CxfConstants.OPERATION_NAME, String.class);
switch (operationName) {
case MethodConstant.LOCALIDAD_ALL_BY_PADRE:
int idLocalidadPadre = Integer.valueOf(messageList.get(0).toString());
int estado = Integer.valueOf(messageList.get(1).toString());
List<Localidad> localidads = getLocalidadByPadre(idLocalidadPadre, estado);
exchange.getIn().setBody(response(localidads));
break;
case MethodConstant.CATALOGO_ITEM_ALL_BY_CATALOGO:
int idCatalogo = exchange.getIn().getBody(Integer.class);
List<CatalogoItem> catalogoItems = getCatalogoItemByCatalogo(idCatalogo);
exchange.getIn().setBody(response(catalogoItems));
break;
case MethodConstant.CATALOGO_ITEM_READ:
int idCatalogoItem = exchange.getIn().getBody(Integer.class);
CatalogoItem catalogoItem = readCatalogo(idCatalogoItem);
exchange.getIn().setBody(response(catalogoItem));
break;
case MethodConstant.PUBLIC_CREATE_EMPRESA_CLIENTE:
Map<String, Object> data = exchange.getIn().getBody(Map.class);
Map<String, String> mapResponse = new HashMap<>();
try{
createEmpresaCliente(data);
mapResponse.put("response", Constant.RESPONSE_OK);
mapResponse.put("responseMessage", "Usuario creado correctamente");
exchange.getIn().setBody(response(mapResponse));
ObjectMapper mapper = new ObjectMapper();
Usuario usuario = mapper.convertValue( data.get("cliente"), Usuario.class);
exchange.getIn().setHeader("idDocumento", usuario.getUsuarioIdDocumento());
if (usuario.getUsuarioPrincipal())
exchange.getIn().setHeader("email", Boolean.TRUE);
else
exchange.getIn().setHeader("email", Boolean.FALSE);
}catch (TasOnException e){
mapResponse.put("response", Constant.RESPONSE_ERROR);
mapResponse.put("responseMessage", e.getDeveloperMessage());
exchange.getIn().setBody(response(mapResponse));
exchange.setProperty(Exchange.ROUTE_STOP, Boolean.TRUE);
}
break;
case MethodConstant.CLIENT_GET_CLIENTE_BY_TIPO:
int tipoCliente = exchange.getIn().getBody(Integer.class);
List<Company> clientesByTipo = getAllClienteByTipo(tipoCliente);
exchange.getIn().setBody(response(clientesByTipo));
break;
case MethodConstant.USUARIO_CREATE:
Usuario usuarioCreate = exchange.getIn().getBody(Usuario.class);
usuarioCreate.setUsuarioPrincipal(Boolean.FALSE);
usuarioCreate.setUsuarioEstado(Constant.USER_PENDING);
createUsuario(usuarioCreate);
Map<String, String> responseCreate = new HashMap<>();
responseCreate.put("response", Constant.RESPONSE_OK);
responseCreate.put("responseMessage", "Usuario creado correctamente");
exchange.getIn().setBody(response(responseCreate));
exchange.getIn().setHeader("idDocumento", usuarioCreate.getUsuarioIdDocumento());
if (usuarioCreate.getUsuarioPrincipal())
exchange.getIn().setHeader("email", Boolean.TRUE);
else
exchange.getIn().setHeader("email", Boolean.FALSE);
break;
case MethodConstant.USUARIO_BY_USERNAME:
String username = exchange.getIn().getBody(String.class);
Usuario usuarioss = getUsarioByUsername(username);
setMessageToResponse(usuarioss, exchange, "Usuario no existe");
break;
case MethodConstant.USUARIO_BY_EMAIL:
String email = exchange.getIn().getBody(String.class);
Usuario usuarioEmail = getUsuarioByEmail(email);
setMessageToResponse(usuarioEmail, exchange, "Usuario no existe");
break;
case MethodConstant.CLIENT_READ:
String ruc = exchange.getIn().getBody(String.class);
Cliente clienteRead = readCliente(ruc);
setMessageToResponse(clienteRead, exchange, "Empresa no existe");
break;
case MethodConstant.CLIENT_TRANSPORTE_READ:
String rucEmpresaTransporte = exchange.getIn().getBody(String.class);
Cliente clienteTransporteRead = readCliente(rucEmpresaTransporte);
if(clienteTransporteRead != null && clienteTransporteRead.getClienteTipoCliente() != Constant.CLIENTE_EMPRESA_TRANSPORTISTA &&
clienteTransporteRead.getClienteTipoCliente() != Constant.CLIENTE_EMPRESA_TRANSPORTISTA_INDEPENDIENTE &&
clienteTransporteRead.getClienteTipoCliente() != Constant.CLIENTE_EMPRESA_TRANSPORTISTA_ENVIOS)
clienteTransporteRead = null;
setMessageToResponse(clienteTransporteRead, exchange, "Empresa no existe");
break;
case MethodConstant.USUARIO_READ:
Usuario usuarioRead = readUsuario(exchange.getIn().getBody(String.class));
setMessageToResponse(usuarioRead, exchange, "Usuario no existe");
break;
case MethodConstant.SOLICITUD_ALL_SOLICITUDES:
int estadossss = exchange.getIn().getBody(Integer.class);
List<Solicitudes> solicitudss = getSolicitudesEnvio(estadossss, Constant.PUBLIC_USER);
exchange.getIn().setBody(response(solicitudss));
break;
case MethodConstant.SOLICITUD_SOLICITUD:
String idSolicitud = exchange.getIn().getBody(String.class);
Solicitud solicitud = getSolicitud(idSolicitud, null);
exchange.getIn().setBody(response(solicitud));
break;
case MethodConstant.VEHICULO_PLACA:
String placa = exchange.getIn().getBody(String.class);
Vehiculo vehiculoPlaca = getVehiculoByPlaca(placa);
exchange.getIn().setBody(response(vehiculoPlaca));
break;
case MethodConstant.USUARIO_RESTABLECER:
String correo = messageList.get(0).toString();
String identificador = messageList.get(1).toString();
Map<String, String> response = new HashMap<>();
try{
validarCambioPassword(identificador, correo);
response.put("response", Constant.RESPONSE_OK);
response.put("responseMessage", "Se enviará a su correo los datos de recuperación");
exchange.getIn().setBody(response(response));
exchange.getIn().setHeader("idDocumento", identificador);
}catch (TasOnException e){
response.put("response", Constant.RESPONSE_ERROR);
response.put("responseMessage", e.getDeveloperMessage());
exchange.getIn().setBody(response(response));
exchange.setProperty(Exchange.ROUTE_STOP, Boolean.TRUE);
}
break;
case MethodConstant.GET_HOME:
exchange.getIn().setBody(response(getEstadisticaHome()));
break;
}
}
//Permite devolver el objeto de la consulta
private void setMessageToResponse(Object object, Exchange exchange, String message){
if (object == null){
Map<String, String> errors = new HashMap<>();
errors.put("response", Constant.RESPONSE_ERROR);
errors.put("responseMessage", message);
exchange.getIn().setBody(response(errors));
}else {
exchange.getIn().setBody(response(object));
}
}
}
| true
|
2689234e96d80ccb7c22b6bb8c59681f05226b1c
|
Java
|
Anber2/Home_Plus
|
/app/src/main/java/com/mawaqaa/homepluskw_new/data/ConstructionInnerData.java
|
UTF-8
| 1,702
| 2.328125
| 2
|
[] |
no_license
|
package com.mawaqaa.homepluskw_new.data;
/**
* Created by JijoCJ on 11/14/2016.
*/
public class ConstructionInnerData {
private String id;
private String name;
private String averageRating;
private String personsRated;
private String profilePhotoUrl;
private String location;
public ConstructionInnerData(String id, String name, String averageRating, String personsRated, String profilePhotoUrl, String location){
this.id = id;
this.name = name;
this.averageRating = averageRating;
this.personsRated = personsRated;
this.profilePhotoUrl = profilePhotoUrl;
this.location = location;
}
public String getAverageRating() {
return averageRating;
}
public void setAverageRating(String averageRating) {
this.averageRating = averageRating;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPersonsRated() {
return personsRated;
}
public void setPersonsRated(String personsRated) {
this.personsRated = personsRated;
}
public String getProfilePhotoUrl() {
return profilePhotoUrl;
}
public void setProfilePhotoUrl(String profilePhotoUrl) {
this.profilePhotoUrl = profilePhotoUrl;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
| true
|
1fe35ad0769470a6759a41bc7b74be62a90b2b94
|
Java
|
hyperledger/besu
|
/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/results/NetworkResult.java
|
UTF-8
| 1,643
| 2.171875
| 2
|
[
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] |
permissive
|
/*
* Copyright ConsenSys AG.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.ethereum.api.jsonrpc.internal.results;
import java.net.SocketAddress;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonPropertyOrder({"localAddress", "remoteAddress"})
public class NetworkResult {
private final String localAddress;
private final String remoteAddress;
public NetworkResult(final SocketAddress localAddress, final SocketAddress remoteAddress) {
this.localAddress = removeTrailingSlash(localAddress.toString());
this.remoteAddress = removeTrailingSlash(remoteAddress.toString());
}
@JsonGetter(value = "localAddress")
public String getLocalAddress() {
return localAddress;
}
@JsonGetter(value = "remoteAddress")
public String getRemoteAddress() {
return remoteAddress;
}
private String removeTrailingSlash(final String address) {
if (address != null && address.startsWith("/")) {
return address.substring(1);
} else {
return address;
}
}
}
| true
|
84ef5a5c88c96763ef8c8722ca334388699601c4
|
Java
|
XClouded/avp
|
/.svn/pristine/84/84ef5a5c88c96763ef8c8722ca334388699601c4.svn-base
|
UTF-8
| 1,777
| 2.375
| 2
|
[] |
no_license
|
package com.lvsint.abp.markettype.factory;
import com.lvsint.abp.MarketType;
import uk.co.abp.MarketTypeStyle;
import com.lvsint.abp.markettype.MarketTypeInstance;
import com.lvsint.abp.markettype.Period;
import com.lvsint.abp.markettype.bean.MethodOfDismissalModel;
import com.lvsint.abp.markettype.processor.MethodOfDismissalProcessor;
import com.lvsint.abp.markettype.processor.Processor;
/**
* Factory used for the cricket market type 'Method of Dismissal'
*
* @author Juan Salamanca
*
*/
public class MethodOfDismissalMarketTypeFactory extends SimpleMarketTypeFactory {
private Processor processor;
public MethodOfDismissalMarketTypeFactory() {
super();
processor = new MethodOfDismissalProcessor();
processor.setResulter(super.getProcessor().getResulter());
}
@Override
public Processor getProcessor() {
return processor;
}
@Override
public MarketTypeInstance makeMarketTypeInstance(MarketType marketType, Period period, long opponentId) {
MarketTypeInstance marketTypeInstance = new MarketTypeInstance(marketType, period, opponentId);
marketTypeInstance.setSelectionModel(new MethodOfDismissalModel());
marketTypeInstance.setSelectionModel2(new MethodOfDismissalModel());
marketTypeInstance.setCandidateModel(new MethodOfDismissalModel());
marketTypeInstance.setCandidateModel2(new MethodOfDismissalModel());
return marketTypeInstance;
}
@Override
public MarketTypeUIFactory getUIFactory() {
return new MethodOfDismissalMarketTypeUIFactory();
}
@Override
public MarketTypeStyle getStyle(MarketType marketType) {
return MarketTypeStyle.PROPOSITION;
}
}
| true
|
5d4cbf0906a760f554bac625f5b065dd128cddc3
|
Java
|
pujianggh/my-APPEChuang_tianyuanhao
|
/src/com/echuang/tianyuanhao/model/CornerModel.java
|
UTF-8
| 1,075
| 2.46875
| 2
|
[] |
no_license
|
package com.echuang.tianyuanhao.model;
/**
* 数据配置
*
* @ClassName: TopCornerModel
* @Description: TODO
* @author 蒲江
* @date 2016-9-1 上午11:35:58
*/
public class CornerModel {
private String content = "";
private String id = "";
private int flag = 0;// 标记升序或者降序 默认0:降序 1:升序
public CornerModel(String content, String id) {
super();
this.content = content;
this.id = id;
}
public CornerModel(String content, String id, int flag) {
super();
this.content = content;
this.id = id;
this.flag = flag;
}
public CornerModel(String content) {
super();
this.content = content;
}
public String getContent() {
return content;
}
public CornerModel setContent(String content) {
this.content = content;
return this;
}
public String getId() {
return id;
}
public CornerModel setId(String id) {
this.id = id;
return this;
}
public int getFlag() {
return flag;
}
public void setFlag(int flag) {
this.flag = flag;
}
}
| true
|
b496aa7ce1bdf0d02ebfb8cca467929b27b8933b
|
Java
|
RohanNagar/lightning
|
/application/src/main/java/com/sanction/lightning/authentication/LightningAuthenticator.java
|
UTF-8
| 941
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
package com.sanction.lightning.authentication;
import com.sanction.lightning.LightningConfiguration;
import io.dropwizard.auth.AuthenticationException;
import io.dropwizard.auth.Authenticator;
import io.dropwizard.auth.basic.BasicCredentials;
import java.util.List;
import java.util.Optional;
public class LightningAuthenticator implements Authenticator<BasicCredentials, Key> {
private final List<Key> allKeys;
public LightningAuthenticator(LightningConfiguration config) {
this.allKeys = config.getApprovedKeys();
}
@Override
public Optional<Key> authenticate(BasicCredentials credentials) throws AuthenticationException {
// Construct a key from incoming credentials
Key key = new Key(credentials.getUsername(), credentials.getPassword());
// Check if that key exists in the list of approved keys
if (!allKeys.contains(key)) {
return Optional.empty();
}
return Optional.of(key);
}
}
| true
|
0df37e9749d2c4aac04dd7aa6122389645b455e2
|
Java
|
klausklemens/sudoku-chimp
|
/SudokuField.java
|
UTF-8
| 2,793
| 3.125
| 3
|
[] |
no_license
|
import java.util.Iterator;
import java.util.Random;
import java.util.Scanner;
public class SudokuField {
private Pice[][] field;
private Scanner input;
public SudokuField() {
this.input = new Scanner(System.in);
this.field = new Pice[9][9];
Random rng = new Random();
for (int row = 0; row < this.field.length; row++) {
for (int column = 0; column < this.field.length; column++) {
this.field[column][row] = new Pice(rng.nextInt(9) + 1, false);
}
}
this.tmpMarker();
}
private void tmpMarker() {
for (int row = 0; row < this.field.length; row++) {
for (int column = 0; column < this.field.length; column++) {
Coordinate originCoord = new Coordinate(column, row);
Pice originPice = this.getPice(originCoord);
for (SudokuIterType iterationType : SudokuIterType.values()) {
if (originPice.isMarked()) {
break;
}
Iterator pices = this.getIterator(iterationType, originCoord);
int c = 0;
while (pices.hasNext()) {
Pice pNow = (Pice) pices.next();
if (originPice.equals(pNow)) {
c += 1;
}
}
if (c >= 2) {
originPice.setMarked(true);
}
}
}
}
}
public void readInput() {
String s = this.input.nextLine().toUpperCase();
String[] coordString = s.split(":")[0].split(",");
int[] coord = {Integer.parseInt(coordString[0]), Integer.parseInt(coordString[1])};
this.field[coord[0]][coord[1]].setNumber(Integer.parseInt(s.split(":")[1]));
for (int row = 0; row < this.field.length; row++) {
for (int column = 0; column < this.field.length; column++) {
this.field[column][row].setMarked(false);
}
}
this.tmpMarker();
}
public Pice getPice(Coordinate c) {
return field[c.getColumn()][c.getRow()];
}
@Override
public String toString() {
String divider = "+---+---+---+\n";
String s = divider;
for (int row = 0; row < this.field.length; row++) {
for (int column = 0; column < this.field.length; column++) {
if (column % 3 == 0) {
s += "|";
}
s += this.field[column][row];
}
s += "|\n";
if (row % 3 == 2) {
s += divider;
}
}
return s;
}
public Iterator getIterator(SudokuIterType iteratorType, Coordinate origin) {
return new SudokuFieldIterator(iteratorType, origin);
}
private class SudokuFieldIterator implements Iterator {
private int iterator = 0;
private SudokuIterType iteratorType;
private Coordinate origin;
public SudokuFieldIterator(SudokuIterType iteratorType, Coordinate origin) {
this.iteratorType = iteratorType;
this.origin = origin;
}
public boolean hasNext() {
return this.iterator < 9;
}
public Pice next() {
Coordinate c = this.iteratorType.next(this.origin, this.iterator);
this.iterator += 1;
return getPice(c);
}
}
}
| true
|
a8350461a4335a298e30825106636977fc130b49
|
Java
|
boosty-jp/backend
|
/src/main/java/jp/boosty/backend/domain/service/datafetchers/UserDataFetcher.java
|
UTF-8
| 5,895
| 2.109375
| 2
|
[] |
no_license
|
package jp.boosty.backend.domain.service.datafetchers;
import jp.boosty.backend.application.converter.requester.RequesterConverter;
import jp.boosty.backend.application.converter.user.AccountResponseConverter;
import jp.boosty.backend.application.converter.user.UserInputConverter;
import jp.boosty.backend.application.converter.user.UserResponseConverter;
import jp.boosty.backend.application.datamodel.request.user.Requester;
import jp.boosty.backend.application.datamodel.response.mutation.CreateResponse;
import jp.boosty.backend.application.datamodel.response.query.user.SalesLinkResponse;
import jp.boosty.backend.domain.service.user.UserMutationService;
import jp.boosty.backend.domain.service.user.UserQueryService;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.stream.Collectors;
import jp.boosty.backend.application.converter.user.OrderHistoryResponseConverter;
import jp.boosty.backend.application.datamodel.response.query.user.OrderHistoriesResponse;
import jp.boosty.backend.infrastructure.datamodel.user.OrderHistoriesEntity;
import graphql.schema.DataFetcher;
@Component
public class UserDataFetcher {
private final UserQueryService userQueryService;
private final UserMutationService userMutationService;
private final RequesterConverter requesterConverter;
public UserDataFetcher(
UserQueryService userQueryService,
UserMutationService userMutationService,
RequesterConverter requesterConverter) {
this.userQueryService = userQueryService;
this.userMutationService = userMutationService;
this.requesterConverter = requesterConverter;
}
///////////////////////////////
/////////// Query //////////
///////////////////////////////
public DataFetcher userDataFetcher() {
return dataFetchingEnvironment -> {
String userId = dataFetchingEnvironment.getArgument("userId");
return UserResponseConverter.toUserResponse(userQueryService.findUser(userId));
};
}
public DataFetcher accountDataFetcher() {
return dataFetchingEnvironment -> {
Requester requester = requesterConverter.toRequester(dataFetchingEnvironment);
return AccountResponseConverter.toAccountResponse(userQueryService.findAccount(requester));
};
}
public DataFetcher canSaleDataFetcher() {
return dataFetchingEnvironment -> {
Requester requester = requesterConverter.toRequester(dataFetchingEnvironment);
return userQueryService.canSale(requester);
};
}
public DataFetcher salesLinkDataFetcher() {
return dataFetchingEnvironment -> {
Requester requester = requesterConverter.toRequester(dataFetchingEnvironment);
return SalesLinkResponse.builder().url(userQueryService.findSalesLink(requester)).build();
};
}
public DataFetcher orderHistoriesDataFetcher() {
return dataFetchingEnvironment -> {
Requester requester = requesterConverter.toRequester(dataFetchingEnvironment);
int page = dataFetchingEnvironment.getArgument("page");
OrderHistoriesEntity orderHistoriesEntity = userQueryService.findOrderHistories(page, requester);
return OrderHistoriesResponse.builder()
.orderHistories(orderHistoriesEntity.getOrderHistoryEntityList()
.stream()
.map(o -> OrderHistoryResponseConverter.toOrderHistoryResponse(
o))
.collect(Collectors.toList()))
.sumCount(orderHistoriesEntity.getSumCount())
.build();
};
}
///////////////////////////////
///////// Mutations /////////
///////////////////////////////
public DataFetcher createUserDataFetcher() {
return dataFetchingEnvironment -> {
Map<String, Object> userInputMap = dataFetchingEnvironment.getArgument("user");
Requester requester = requesterConverter.toRequester(dataFetchingEnvironment);
String displayName = dataFetchingEnvironment.getArgument("displayName");
String imageUrl = dataFetchingEnvironment.getArgument("imageUrl");
userMutationService.createUser(displayName, imageUrl, requester);
return CreateResponse.builder().id(requester.getUserId()).build();
};
}
public DataFetcher updateUserDataFetcher() {
return dataFetchingEnvironment -> {
Map<String, Object> userInputMap = dataFetchingEnvironment.getArgument("user");
Requester requester = requesterConverter.toRequester(dataFetchingEnvironment);
userMutationService.updateUser(UserInputConverter.toUserInput(userInputMap), requester);
return true;
};
}
public DataFetcher deleteUserDataFetcher() {
return dataFetchingEnvironment -> {
Requester requester = requesterConverter.toRequester(dataFetchingEnvironment);
userMutationService.deleteUser(requester);
return true;
};
}
public DataFetcher registerStripeDataFetcher() {
return dataFetchingEnvironment -> {
Requester requester = requesterConverter.toRequester(dataFetchingEnvironment);
String userId = dataFetchingEnvironment.getArgument("userId");
String code = dataFetchingEnvironment.getArgument("code");
userMutationService.registerStripe(userId, code, requester);
return true;
};
}
}
| true
|
d19738303bdffea8cbc3bae35bdd46d7ae7197b8
|
Java
|
wuchen1234/bom
|
/src/main/java/zhth/bom/management/bom/service/serivceImpl/BomMaterialItemServiceImpl.java
|
UTF-8
| 2,581
| 2.203125
| 2
|
[] |
no_license
|
package zhth.bom.management.bom.service.serivceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import zhth.bom.management.bom.domian.BomMaterialItem;
import zhth.bom.management.bom.domian.BuildingTable;
import zhth.bom.management.bom.repository.BomMaterialItemRepository;
import zhth.bom.management.bom.service.BomMaterialItemService;
import zhth.bom.management.bom.util.change.Serial;
import zhth.bom.management.bom.util.common.IMBomResponse;
import java.util.Date;
import java.util.List;
@Service
public class BomMaterialItemServiceImpl implements BomMaterialItemService{
private BuildingTableServiceImpl buildingTableService;
private BomMaterialItemRepository bomMaterialItemRepository;
@Autowired
public BomMaterialItemServiceImpl(BuildingTableServiceImpl buildingTableService, BomMaterialItemRepository bomMaterialItemRepository) {
this.buildingTableService = buildingTableService;
this.bomMaterialItemRepository = bomMaterialItemRepository;
}
@Override
@Transactional()
public IMBomResponse<BomMaterialItem> save(BomMaterialItem bomMaterialItem) {
BuildingTable buildingTable=bomMaterialItem.getBuildingTable();
BuildingTable buildingTable1=buildingTableService.save(buildingTable);
bomMaterialItem.setBmiTime(new Date());
bomMaterialItem.setSerialNum(Serial.serialNumber());
bomMaterialItem.setBuildingTable(buildingTable1);
BomMaterialItem bomMaterial=bomMaterialItemRepository.save(bomMaterialItem);
return IMBomResponse.build(bomMaterial);
}
@Override
public void insertbomMaterial(String model, Integer num, String serialNum, String remark, String biaoming) {
bomMaterialItemRepository.insertbomMaterial(model,num,serialNum,remark,biaoming);
}
@Override
public List<BomMaterialItem> findAll() {
return bomMaterialItemRepository.findAll();
}
@Override
public List<BomMaterialItem> findByBmiPerson(String name) {
return bomMaterialItemRepository.findByBmiPerson(name);
}
@Override
public List<BomMaterialItem> findByBmiExplain(String BmiExplain) {
return bomMaterialItemRepository.findByBmiExplain(BmiExplain);
}
@Override
public List<BomMaterialItem> findByBmiExplainAndAndBmiPerson(String BmExplain, String bmiPerson) {
return bomMaterialItemRepository.findByBmiExplainAndAndBmiPerson(BmExplain,bmiPerson);
}
}
| true
|
317bb5f4492b1b4b23d4f2aea1e3642ce08f93ca
|
Java
|
AraiNylaz/origins-forge
|
/src/main/java/io/github/apace100/origins/power/Powers.java
|
UTF-8
| 12,072
| 1.515625
| 2
|
[
"MIT"
] |
permissive
|
package io.github.apace100.origins.power;
import java.util.HashMap;
import java.util.UUID;
import java.util.stream.Stream;
import io.github.apace100.origins.OriginsMod;
import io.github.apace100.origins.api.RegisterPowerIMC;
import io.github.apace100.origins.power.bird.HighBedPower;
import io.github.apace100.origins.power.bird.JumpBoostPower;
import io.github.apace100.origins.power.bird.SlowFallPower;
import io.github.apace100.origins.power.cat.NoFallDamagePower;
import io.github.apace100.origins.power.cat.ScareCreepersPower;
import io.github.apace100.origins.power.cat.WeakStoneBreakingPower;
import io.github.apace100.origins.power.common.HurtfulWaterPower;
import io.github.apace100.origins.power.common.MultiplyPotionDurationPower;
import io.github.apace100.origins.power.creeper.ExplosionPower;
import io.github.apace100.origins.power.creeper.GunpowderResourcePower;
import io.github.apace100.origins.power.ender.ThrowEnderPearlPower;
import io.github.apace100.origins.power.fire.FireImmunityPower;
import io.github.apace100.origins.power.fire.NoMeleeDamagePower;
import io.github.apace100.origins.power.fire.ThrowFireballPower;
import io.github.apace100.origins.power.fish.WaterBreathingPower;
import io.github.apace100.origins.power.fish.WaterDiggingPower;
import io.github.apace100.origins.power.fish.WaterVisionPower;
import io.github.apace100.origins.power.golem.BadSunVisionPower;
import io.github.apace100.origins.power.golem.ExtraInventoryPower;
import io.github.apace100.origins.power.phantom.BurnInDaylightPower;
import io.github.apace100.origins.power.phantom.ColorblindPower;
import io.github.apace100.origins.power.phantom.InvisibilityPower;
import io.github.apace100.origins.power.phantom.LifestealPower;
import io.github.apace100.origins.power.phantom.NoAttacksPower;
import io.github.apace100.origins.power.spider.ClimbPower;
import io.github.apace100.origins.power.spider.CobwebImmunityPower;
import io.github.apace100.origins.power.spider.CobwebPower;
import io.github.apace100.origins.power.spider.InflictPoisonPower;
import io.github.apace100.origins.power.tree.BurnForeverPower;
import io.github.apace100.origins.power.tree.ComposterPower;
import io.github.apace100.origins.power.tree.LogBreakHurtPower;
import io.github.apace100.origins.power.tree.SunFoodPower;
import io.github.apace100.origins.power.tree.XPMultiplierPower;
import io.github.apace100.tags.ModItemTags;
import net.minecraft.block.Blocks;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.entity.ai.attributes.AttributeModifier.Operation;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Items;
import net.minecraft.potion.Effects;
import net.minecraft.tags.FluidTags;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.InterModComms;
public class Powers {
private static HashMap<ResourceLocation, Power> REGISTRY = new HashMap<>();
public static Power INVULNERABILITY = register(new InvulnerabilityPower(OriginsMod.MODID + ":invulnerability").setHidden());
// Common
public static Power POTION_EFFICIENCY = register(new MultiplyPotionDurationPower(OriginsMod.MODID + ":potion_efficiency", 2));
// Fish
public static Power WATER_BREATHING = register(new WaterBreathingPower(OriginsMod.MODID + ":water_breathing"));
public static Power WATER_VISION = register(new WaterVisionPower(OriginsMod.MODID + ":water_vision"));
public static Power WATER_DIGGING = register(new WaterDiggingPower(OriginsMod.MODID + ":water_digging"));
private static UUID WATER_SPEED_MOD = UUID.fromString("02632AF3-B6E8-481E-9E21-F481F6EC14FE");
public static Power WATER_SPEED = register(new AttributeModifierPower(OriginsMod.MODID + ":water_speed").addAttributeModifier(LivingEntity.SWIM_SPEED, new AttributeModifier(WATER_SPEED_MOD, "Water speed from power", 0.7, Operation.MULTIPLY_TOTAL)));
// Fire
public static Power THROW_FIREBALL = register(new ThrowFireballPower(OriginsMod.MODID + ":throw_fireball"));
public static Power FIRE_IMMUNITY = register(new FireImmunityPower(OriginsMod.MODID + ":fire_immunity"));
public static Power NO_RANGED = register(new PreventItemUsePower(OriginsMod.MODID + ":no_ranged", ModItemTags.RANGED_WEAPONS));
public static Power HURTFUL_WATER_POWER = register(new HurtfulWaterPower(OriginsMod.MODID + ":hurtful_water"));
public static Power NO_MELEE_DAMAGE = register(new NoMeleeDamagePower(OriginsMod.MODID + ":no_melee_damage"));
// Ender
public static Power THROW_ENDER_PEARL = register(new ThrowEnderPearlPower(OriginsMod.MODID + ":throw_ender_pearl"));
public static Power NO_PUMPKIN_PIE = register(new PreventItemUsePower(OriginsMod.MODID + ":no_pumpkin_pie", Items.PUMPKIN_PIE));
// Bird
public static Power JUMP_BOOST = register(new JumpBoostPower(OriginsMod.MODID + ":jump_boost", 1.5F).addCondition(PlayerEntity::isSprinting));
private static UUID RUN_BOOST_MOD = UUID.fromString("F4C56C55-D5F1-4BC1-B661-A0409DE255A5");
public static Power RUN_BOOST = register(new AttributeModifierPower(OriginsMod.MODID + ":run_boost").addAttributeModifier(SharedMonsterAttributes.MOVEMENT_SPEED, new AttributeModifier(RUN_BOOST_MOD, "Move speed from power", 0.1, Operation.MULTIPLY_BASE)));
public static Power SLOW_FALL = register(new SlowFallPower(OriginsMod.MODID + ":slow_fall", 0.1));
public static Power VEGETARIAN = register(new PreventItemUsePower(OriginsMod.MODID + ":vegetarian", ModItemTags.MEAT));
public static Power HIGH_BED = register(new HighBedPower(OriginsMod.MODID + ":high_bed"));
// Phantom
public static InvisibilityPower INVISIBILITY = (InvisibilityPower)register(new InvisibilityPower(OriginsMod.MODID + ":invisibility"));
public static Power NO_ATTACKS = register(new NoAttacksPower(OriginsMod.MODID + ":no_attacks"));
public static Power BURN_IN_DAYLIGHT = register(new BurnInDaylightPower(OriginsMod.MODID + ":burn_in_daylight").addCondition(pe -> !INVISIBILITY.isInvisible(pe)));
public static Power LIFESTEAL = register(new LifestealPower(OriginsMod.MODID + ":lifesteal", 0.5F));
public static Power COLORBLIND = register(new ColorblindPower(OriginsMod.MODID + ":colorblind"));
public static Power NIGHT_VISION = register(new PotionPower(OriginsMod.MODID + ":night_vision", Effects.NIGHT_VISION).addCondition(pe -> pe.areEyesInFluid(FluidTags.WATER)));
public static Power NO_FOOD_REGEN = register(new Power(OriginsMod.MODID + ":no_food_regen"));
// Spider
public static Power CLIMBING = register(new ClimbPower(OriginsMod.MODID + ":climbing"));
public static Power ONLY_MEAT = register(new PreventItemUsePower(OriginsMod.MODID + ":only_meat", stack -> stack.isFood() && !stack.getItem().isIn(ModItemTags.MEAT)));
public static Power NO_CAKE = register(new PreventBlockUsePower(OriginsMod.MODID + ":no_cake", Blocks.CAKE).setHidden());
public static Power POISON_DAMAGE = register(new VenomPower(OriginsMod.MODID + ":poison_damage", 1F, 1F));
public static Power POISON_IMMUNITY = register(new PotionImmunityPower(OriginsMod.MODID + ":poison_immunity", Effects.POISON));
public static Power SPIDERWEB = register(new CobwebPower(OriginsMod.MODID + ":spiderweb"));
private static UUID LESS_HP_MOD = UUID.fromString("D0CD8CE6-8C53-4407-B78C-8816E8707688");
public static Power LESS_HP = register(new AttributeModifierPower(OriginsMod.MODID + ":less_hp").addAttributeModifier(SharedMonsterAttributes.MAX_HEALTH, new AttributeModifier(LESS_HP_MOD, "Less hp from power", -4, Operation.ADDITION)));
// Rock
public static Power BAD_SUN_VISION = register(new BadSunVisionPower(OriginsMod.MODID + ":bad_sun_vision"));
private static UUID NATURAL_ARMOR_MOD = UUID.fromString("66BDFE9A-D467-4F44-8FB2-7EA8483C3303");
public static Power NATURAL_ARMOR = register(new AttributeModifierPower(OriginsMod.MODID + ":natural_armor").addAttributeModifier(SharedMonsterAttributes.ARMOR, new AttributeModifier(NATURAL_ARMOR_MOD, "More armor from power", 10, Operation.ADDITION)));
private static UUID SLOWNESS_MOD = UUID.fromString("96DC9F7F-8C1B-419F-895C-1301604AF047");
public static Power SLOWNESS = register(new AttributeModifierPower(OriginsMod.MODID + ":slowness").addAttributeModifier(SharedMonsterAttributes.MOVEMENT_SPEED, new AttributeModifier(SLOWNESS_MOD, "Speed penalty from power", -0.3, Operation.MULTIPLY_BASE)).addCondition(player -> player.getFoodStats().getFoodLevel() < 16));
public static Power NO_SHIELD = register(new PreventItemUsePower(OriginsMod.MODID + ":no_shield", Items.SHIELD));
public static Power EXTRA_INVENTORY = register(new ExtraInventoryPower(OriginsMod.MODID + ":extra_inventory"));
// Tree
public static Power BURN_FOREVER = register(new BurnForeverPower(OriginsMod.MODID + ":burn_forever"));
public static Power HURT_ON_LOG_BREAK = register(new LogBreakHurtPower(OriginsMod.MODID + ":hurt_on_log_break"));
public static Power LUCKY_COMPOSTER = register(new ComposterPower(OriginsMod.MODID + ":lucky_composter"));
public static Power MORE_XP = register(new XPMultiplierPower(OriginsMod.MODID + ":more_xp", 1.8F));
public static Power PHOTOSYNTHESIS = register(new SunFoodPower(OriginsMod.MODID + ":photosynthesis"));
// Cat
public static Power SCARE_CREEPERS = register(new ScareCreepersPower(OriginsMod.MODID + ":scare_creepers"));
public static Power NO_FALL_DAMAGE = register(new NoFallDamagePower(OriginsMod.MODID + ":no_fall_damage"));
private static UUID NINE_LIVES_MOD = UUID.fromString("A0AE00AB-DD41-4D28-BD70-3F6FA3B6B19B");
public static Power NINE_LIVES = register(new AttributeModifierPower(OriginsMod.MODID + ":nine_lives").addAttributeModifier(SharedMonsterAttributes.MAX_HEALTH, new AttributeModifier(NINE_LIVES_MOD, "Less hp from power", -2, Operation.ADDITION)));
public static Power WEAK_STONE_BREAKING = register(new WeakStoneBreakingPower(OriginsMod.MODID + ":weak_stone_breaking"));
// Creeper
public static ResourcePower GUNPOWDER_RESOURCE = (ResourcePower) register(new GunpowderResourcePower(OriginsMod.MODID + ":gunpowder_resource"));
public static Power EXPLOSION = register(new ExplosionPower(OriginsMod.MODID + ":explosion"));
// Unused or Not Functional
public static Power COBWEB_IMMUNITY = register(new CobwebImmunityPower(OriginsMod.MODID + ":cobweb_immunity").setHidden());
public static Power TP_IN_WATER = register(new TeleportingWaterPower(OriginsMod.MODID + ":tp_in_water"));
public static Power INFLICT_POISON = register(new InflictPoisonPower(OriginsMod.MODID + ":inflict_poison"));
public static Power NO_MILK = register(new PreventItemUsePower(OriginsMod.MODID + ":no_milk", Items.MILK_BUCKET).setHidden());
public static Power register(Power power) {
ResourceLocation registryName = power.getRegistryName();
if(registryName == null) {
throw new IllegalArgumentException("Someone tried to register a Power without registry name.");
}
if(REGISTRY.containsKey(registryName)) {
throw new IllegalArgumentException("A Power with registry name " + registryName.toString() + " is already registered.");
}
REGISTRY.put(registryName, power);
return power;
}
public static Power getByName(String registryName) {
return getByResourceLocation(new ResourceLocation(registryName));
}
public static Power getByResourceLocation(ResourceLocation location) {
if(!REGISTRY.containsKey(location)) {
throw new IllegalArgumentException("Tried to get Power by location at location " + location.toString() + ", but there is none.");
}
return REGISTRY.get(location);
}
public static void processRegistryIMC(Stream<InterModComms.IMCMessage> stream) {
stream.filter(msg -> msg.getMessageSupplier().get() instanceof RegisterPowerIMC)
.map(msg -> (RegisterPowerIMC)msg.getMessageSupplier().get())
.forEach(Powers::registerPowerFromIMC);
}
private static void registerPowerFromIMC(RegisterPowerIMC imc) {
try {
register(imc.getPower());
} catch(IllegalArgumentException e) {
System.err.println("Failing to register power from IMC: " + e.getMessage());
}
}
}
| true
|
3260df4a3748c60add4d3d77febbd4dd0b44a7a4
|
Java
|
FabrizzioRuiz/java-practice
|
/src/main/java/java8/lambda/EjemploFunction.java
|
UTF-8
| 990
| 3.53125
| 4
|
[] |
no_license
|
package java8.lambda;
import java.util.Locale;
import java.util.function.BiFunction;
import java.util.function.Function;
public class EjemploFunction {
public static void main(String[] args) {
Function<String, String> f1 = param -> "Hola que tal " + param;
String resultado = f1.apply("Fabrizzio");
System.out.println(resultado);
Function<String, String> f2 = String::toUpperCase; // param -> param.toUpperCase();
System.out.println(f2.apply("hola"));
BiFunction<String, String, String> f3 = (a, b) -> a.toUpperCase().concat(b.toUpperCase());
String r2 = f3.apply("fabri", "ruiz");
System.out.println(r2);
BiFunction<String, String, Integer> f4 = String::compareTo; // (a, b) -> a.compareTo(b);
System.out.println(f4.apply("fabri", "fabri2"));
BiFunction<String, String, String> f5 = String::concat; // (a, b) -> a.concat(b);
System.out.println(f5.apply("fabri", "fabri2"));
}
}
| true
|
77c7a80ba47e1575bdd878227736fe9505b61aea
|
Java
|
GabrielVicente-GT/HojaDeTrabajoNo.2
|
/Version 1/Main.java
|
UTF-8
| 1,067
| 3.125
| 3
|
[] |
no_license
|
public class Main {
public static void main(String[] args){
Calculadora calculator = new Calculadora();
lector a = new lector();
String operation = a.archivo("cerrito.txt");
String[] SplitOperation;
SplitOperation = operation.split(" ");
for (int i = 0; i < SplitOperation.length; i++){
if(SplitOperation[i].equals("*") || SplitOperation[i].equals("-") || SplitOperation[i].equals("+") || SplitOperation[i].equals("/")){
int operadorB = calculator.pila.pop();
int operadorA = calculator.pila.pop();
int nuevo = calculator.calculo(operadorA, operadorB,SplitOperation[i]);
calculator.pila.push(nuevo);
}else{
int num = Integer.parseInt(SplitOperation[i]);
calculator.pila.push(num);
}
}
for (int i = 0; i< calculator.pila.size();i++){
System.out.println(" Resultado final");
System.out.println(calculator.pila.peek());
}
}
}
| true
|
5c645955def080790d0158087e2ee0ea0ef8ffa8
|
Java
|
sanopi/my-atcoder-log
|
/abc2/abc27/abc270/ABC270C.java
|
UTF-8
| 2,513
| 3.375
| 3
|
[] |
no_license
|
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ABC270C {
private static List<Integer>[] tree;
private static int x;
private static int y;
public static void main(String[] args) {
int n = nextInt();
x = nextInt()-1;
y = nextInt()-1;
tree = new List[n];
for (int i = 0; i < n; i++) {
tree[i] = new ArrayList<>();
}
for (int i = 0; i < n - 1; i++) {
int u = nextInt()-1;
int v = nextInt()-1;
tree[u].add(v);
tree[v].add(u);
}
List<Integer> result = dfs(y, -1);
for (Integer integer : result) {
out.print(integer+1 + " ");
}
out.println();
out.flush();
}
private static List<Integer> dfs(int current, int prev) {
if (current == x) {
ArrayList<Integer> res = new ArrayList<>();
res.add(x);
return res;
}
for (Integer next : tree[current]) {
if (prev == next) continue;
List<Integer> result = dfs(next, current);
if (result.size() > 0) {
result.add(current);
return result;
}
}
return List.of();
}
static PrintWriter out = new PrintWriter(System.out);
static Scanner scanner = new Scanner(System.in);
static String next() { return scanner.next(); }
static int nextInt() {
int res = 0;
char[] chars = next().toCharArray();
boolean minus = chars[0] == '-';
int start = minus?1:0;
for (int i = start; i < chars.length; i++) {
res = res*10 + (chars[i]-'0');
}
return minus?-res:res;
}
static long nextLong() {
long res = 0;
char[] chars = next().toCharArray();
boolean minus = chars[0] == '-';
int start = minus?1:0;
for (int i = start; i < chars.length; i++) {
res = res*10 + (chars[i]-'0');
}
return minus?-res:res;
}
static double nextDouble() { return Double.parseDouble(next()); }
static int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; i++) { array[i] = nextInt(); }
return array;
}
static long[] nextLongArray(int n) {
long[] array = new long[n];
for (int i = 0; i < n; i++) { array[i] = nextLong(); }
return array;
}
}
| true
|
9dcf0b7df55efbcc83dde01313bdd7936d9064d6
|
Java
|
kgabbasova/java-learner
|
/Simple/src/PascalTriangle.java
|
UTF-8
| 1,475
| 3.53125
| 4
|
[] |
no_license
|
import java.util.ArrayList;
public class PascalTriangle {
public static void printPascalTriangleWithArr(int n) {
//create rows
int[][] triangleMatrix = new int[n][];
//initialize
for (int i = 0; i < n; i++) {
triangleMatrix[i] = new int[i + 1];
for (int j = 0; j <= i; j++) {
if (j == 0 || j == i) {
triangleMatrix[i][j] = 1;
} else {
triangleMatrix[i][j] = triangleMatrix[i - 1][j - 1] + triangleMatrix[i - 1][j];
}
}
}
int maxLength = String.valueOf(triangleMatrix[n - 1][n / 2]).length();
int maxSpace = (int) (maxLength * n + n-1);
int [] lineLenght = new int[n];
for (int i=1; i<= n; i++) {
lineLenght[i-1] = (int) (maxLength * i + i-1);
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < (maxSpace-lineLenght[i])/2; j++) {
System.out.print(" ");
}
for (int j = 0; j <= i; j++) {
System.out.print(String.format("%" + maxLength + "d", triangleMatrix[i][j]) + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
printPascalTriangleWithArr(9);
}
}
/*
1. треугольник Паскаля
1.1 Через массивы
1.2 Через формулу каждого элемента
1.3 Красиво вывести
*/
| true
|
3795566c814f483f1e0b808b57384169cf29ea77
|
Java
|
RoyKiran/Cost-to-Go-Android-App
|
/Cost-based-navigation/Cost-to-Go/app/src/main/java/com/bakmaps/cost_to_go/maps/HttpURLs.java
|
UTF-8
| 509
| 1.695313
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.bakmaps.cost_to_go.maps;
import java.util.TreeMap;
/**
* Created by WORK with FUN on 03-02-2016.
*/
public class HttpURLs {
private String url="https://maps.googleapis.com/maps/api/";
private String API_KEY = "" ;
/* void getDistance(TreeMap<>){
*//** URL:- https://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC|Seattle&destinations=San+Francisco|
Victoria+BC&mode=transit&transit_mode=train&key=YOUR_API_KEY
**//*
}*/
}
| true
|
2c4661a0eec0743232a0e035a9bc2ee57164c735
|
Java
|
VitalyOrochko/EpamCourses
|
/task1/src/com/epam/geometry/exception/PointCreateException.java
|
UTF-8
| 602
| 2.234375
| 2
|
[] |
no_license
|
package com.epam.geometry.exception;
public class PointCreateException extends Exception {
public PointCreateException() {
}
public PointCreateException(String message) {
super(message);
}
public PointCreateException(String message, Throwable cause) {
super(message, cause);
}
public PointCreateException(Throwable cause) {
super(cause);
}
public PointCreateException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
| true
|
764073b88ac94d366712ed7f426294a6f33d52f1
|
Java
|
mhp13345/MemberManagementSystem
|
/src/com/rjjs/member/dao/BaseDao.java
|
UTF-8
| 759
| 2.53125
| 3
|
[] |
no_license
|
package com.rjjs.member.dao;
import java.sql.*;
public class BaseDao {
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String url = "jdbc:sqlserver://localhost:1433;DatabaseName=member";
String user = "sa";
String pwd = "123456";
public Connection getConn() {
Connection conn = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, user, pwd);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public void closeAll(Connection conn, Statement stmt) {
try {
if (conn != null) {
conn.close();
}
if (stmt != null) {
stmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
| true
|
a46c054f9807269cc11248cfe6f81feeffa35c69
|
Java
|
RongChoii/kakaopay
|
/src/main/java/com/kakaopay/finance/util/FileReaderUtil.java
|
UTF-8
| 934
| 2.515625
| 3
|
[] |
no_license
|
package com.kakaopay.finance.util;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class FileReaderUtil {
public static List<String> getCsvfileInfo(String path){
List<String> result = new ArrayList<>();
try{
// BufferedReader br = new BufferedReader(new FileReader(new File(path)));
//// Charset.forName("UTF-8");
// Charset.forName("EUC-KR");
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path), "EUC-KR"));
String line ;
while((line = br.readLine()) != null)
result.add(line);
if(br != null){
br.close();
}
return result;
} catch(Exception e){
e.printStackTrace();
}
return null;
}
}
| true
|
61d29ff619b46c05441f6f2ff2d82f869804f7ee
|
Java
|
AJAX-UP/ajax_project
|
/configclient2/src/main/java/com/configclient2/configclient2/unitl/ConfigUtils.java
|
UTF-8
| 571
| 1.601563
| 2
|
[] |
no_license
|
package com.configclient2.configclient2.unitl;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* @author guangjiechen
* @createDate 2019/7/22 10:33
*/
public class ConfigUtils {
@Configuration
public static class Config {
@Bean
@LoadBalanced
public static RestTemplate restTemplate() {
return new RestTemplate();
}
}
}
| true
|
8bbe190b21f1cb61a43679e4fcf59359190c51cd
|
Java
|
FarhadShariatzadeh/RecursivePolynomials
|
/src/main/java/RecursivePolynomialStatements/IPolynomial.java
|
UTF-8
| 2,219
| 3.84375
| 4
|
[] |
no_license
|
package RecursivePolynomialStatements;
public interface IPolynomial {
/**
* A method addTerm, that takes a term (have a coefficient and a power), and
* adds the resulting term to the polynomial
* @param coefficient adding coefficient to the polynomial
* @param power adding power to the polynomial
* @return new IPolynomial with the new term
* @throws PolynomialException an exception when the coefficient is zero
*/
IPolynomial addTerm(Integer coefficient, Integer power) throws PolynomialException;
/**
* A method removeTerm, that takes a power, and removes any and all terms in the
* polynomial with that power.
* @param power - is the deleting power
* @return new IPolynomial with the remove term
* @throws PolynomialException an exception when the the Polynomial is empty
*/
IPolynomial removeTerm(Integer power) throws PolynomialException;
/**
* A method getDegree, that returns the degree of the polynomial
* @return - the degree of the polynomial
* @throws PolynomialException an exception when the the Polynomial is empty
*/
Integer getDegree() throws PolynomialException;
/**
* A method getCoefficient, that takes a power, and returns the coefficient for the
* term with that power.
* @param power the power of coefficient
* @return the coefficient for the power
* @throws PolynomialException an exception when the the Polynomial is empty
*/
Integer getCoefficient(Integer power) throws PolynomialException;
/**
* A method isSame, that takes another ConsPolynomial object and returns True if they
* are the same, False otherwise.
* @param object - polynomial object to compare
* @return - True if they are same and false otherwise
*/
Boolean isSame(IPolynomial object) throws PolynomialException;
/**
* A method add, that takes another ConsPolynomial object, and returns the polynomial
* obtained by adding the two polynomials.
* @param object - adding polynomial object
* @return the polynomial obtained by adding two polynomial
* @throws PolynomialException an exception when the the Polynomial is empty
*/
IPolynomial add(IPolynomial object) throws PolynomialException;
}
| true
|
6405ee82820a2f2858386f47a84e982eadcc65a9
|
Java
|
maxiaobu1999/malong_service
|
/src/test/java/com/norman/TestMovie.java
|
UTF-8
| 3,717
| 2.265625
| 2
|
[] |
no_license
|
package com.norman;
import com.norman.moive.repository.IMovieDao;
import com.norman.moive.repository.IPlayAddressDao;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import java.io.InputStream;
public class TestMovie {
private InputStream in;
private SqlSessionFactory factory;
private SqlSession session;
private IMovieDao mMovieDao;
private IPlayAddressDao mPlayAddressDao;
@Before
public void init() throws Exception {
in = Resources.getResourceAsStream("SqlMapConfig.xml");
factory = new SqlSessionFactoryBuilder().build(in);
session = factory.openSession();
mMovieDao = session.getMapper(IMovieDao.class);
mPlayAddressDao = session.getMapper(IPlayAddressDao.class);
}
@After
public void destroy() throws Exception {
session.commit();
session.close();
in.close();
}
// /**
// * 查找全部
// */
// @Test
// public void testFindAll() {
// List<Movie> movieList = mMovieDao.findAll();
// int i = 0;
// for (Movie movie : movieList) {
// System.out.println(i+"++++"+movie.getName());
// i++;
// }
// }
//
// @Test
// public void testFindByName() {
// List<Movie> byName = mMovieDao.findByName("牙狼:红莲之月");
// System.out.println(byName.toString());
// }
//
// /**
// * 根据ID查课程
// */
// @Test
// public void testFindById() {
// Movie movie = mMovieDao.findById(1);
// System.out.println(movie.toString());
// }
//
//
// /**
// * 根据类别查询影片
// * 国产动漫
// * 日韩动漫
// * 欧美动漫
// * 港台动漫
// * 海外动漫
// */
// @Test
// public void testFindByType() {
// List<Movie> movieList = mMovieDao.findByType("国产动漫");
// for (Movie movie : movieList) {
// System.out.println("++"+movie.toString());
// }
// }
//
// @Test
// public void testFindAddressByMovieId() {
// List<PlayAddress> playAddressList = mPlayAddressDao.findByMovieId(1);
// for (PlayAddress playAddress : playAddressList) {
// System.out.println(playAddress.toString());
//
// }
// }
//// /**
//// * 根据courseID查课程
//// */
//// @Test
//// public void testFindByCourseID() {
//// List<Course> list = mCourseDao.findByCourseId(123);
//// System.out.println(list);
//// }
////
//// /**
//// * 修改课程
//// */
//// @Test
//// public void testUpdate() {
//// Course course = new Course();
//// course.setCourseId(123);
//// course.setTitle("mybatis annotation update");
//// course.setImgUrl("北京市海淀区");
//// course.setCourseProfile("男");
//// course.setTime(String.valueOf(new Date()));
////
//// mCourseDao.updateCourse(course);
//// }
//// @Test
//// public void testFindTotal(){
//// int total = userDao.findTotalUser();
//// System.out.println(total);
//// }
//
//
////
//// @Test
//// public void testDelete(){
//// userDao.deleteUser(51);
//// }
////
//
////
////
//// @Test
//// public void testFindByName(){
////// List<User> users = userDao.findUserByName("%mybatis%");
//// List<User> users = userDao.findUserByName("mybatis");
//// for(User user : users){
//// System.out.println(user);
//// }
//// }
////
}
| true
|
c4726e27c47bb60c4d379bc717c100431dd745fb
|
Java
|
jsdumas/java-training
|
/java-best-of/src/main/java/io/jsd/training/designpattern/book/chap1/voyages/VolLuxe.java
|
UTF-8
| 204
| 2.34375
| 2
|
[] |
no_license
|
package io.jsd.training.designpattern.book.chap1.voyages;
public class VolLuxe implements PartieVoyageLuxe {
public void affiche() {
System.out.println("Vol en première classe");
}
}
| true
|
5c2ebb0e12806dc3b3a4cbc007ebcef8d0f6bac4
|
Java
|
cuiods/DataRepository
|
/Homework1/src/main/java/com/cuiods/datamining/h1/filter/AccountFilter.java
|
UTF-8
| 818
| 2.25
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.cuiods.datamining.h1.filter;
import com.cuiods.datamining.h1.rules.AccountDateRule;
import com.cuiods.datamining.h1.rules.FrequencyEnumRule;
import com.cuiods.datamining.h1.rules.IdRule;
import com.cuiods.datamining.h1.rules.Rule;
import java.util.ArrayList;
import java.util.List;
public class AccountFilter extends CsvFilter {
@Override
String getCsvName() {
return "account";
}
@Override
List<Rule> getRules() {
List<Rule> rules = new ArrayList<Rule>(4);
rules.add(new IdRule());
rules.add(new IdRule());
rules.add(new FrequencyEnumRule());
rules.add(new AccountDateRule());
return rules;
}
@Override
String[] getHeaders() {
return new String[]{"account_id","district_id","frequency","date"};
}
}
| true
|
ca6c94bbfb15b9ca7b8b4111d997cc83a9b27de4
|
Java
|
thalissonoliveira/estrutdados20201
|
/src/br/edu/fadam/estruturadedados/aula2/Funcionario.java
|
UTF-8
| 378
| 2.5
| 2
|
[] |
no_license
|
package br.edu.fadam.estruturadedados.aula2;
public class Funcionario implements Pagavel {
private String nome;
private String numeroDocumento;
private double salarioBase;
public double calculaSalario(){
return 0.0;
}
public double getSalarioBase() {
return salarioBase;
}
public void setSalarioBase (double salarioBase) {
this.salarioBase = salarioBase;
}
}
| true
|
d54f63c9c0dbba138ad9051e79c0d8fe2f608d07
|
Java
|
xiyionxiong/framwork
|
/src/com/flyong/others/applet/BasicApplet.java
|
UTF-8
| 1,123
| 3
| 3
|
[] |
no_license
|
package com.flyong.others.applet;
import java.applet.*;
import java.awt.*;
/**
* Applet的基础框架。
*
*
*
*/
public class BasicApplet extends Applet {
/**
*
*/
private static final long serialVersionUID = 3363561144082703501L;
// This method is called once by the browser when it starts the applet.
// 浏览器第一次启动这个applet时被调用一次
public void init() {
}
// This method is called whenever the page containing this applet is made
// visible.
// 当包含这个applet的页面可见时,被调用
public void start() {
}
// This method is called whenever the page containing this applet is not
// visible.
// 当包含这个applet的页面不可见时被调用
public void stop() {
}
// This method is called once when the browser destroys this applet.
// 当浏览器销毁这个applet时被调用
public void destroy() {
}
// This method is called whenever this applet needs to repaint itself.
// 当applet需要自己重画时被调用
public void paint(Graphics g) {
}
}
| true
|
a63dd8c004c39bc3429ac9bc4c5332b136d276af
|
Java
|
MateuszHupa/Online_Voting
|
/Backend/src/main/java/com/wybory/pai/models/DatesOfVoting.java
|
UTF-8
| 736
| 2.359375
| 2
|
[] |
no_license
|
package com.wybory.pai.models;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import javax.persistence.*;
import java.util.Date;
@Entity
@Table(name = "DATES_OF_VOTING")
@EnableAutoConfiguration
public class DatesOfVoting{
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Integer id;
@Temporal(TemporalType.TIMESTAMP)
private Date dateOfVoting;
public Integer getId(){
return id;
}
public void setId(Integer id){
this.id = id;
}
public Date getDateOfVoting(){
return dateOfVoting;
}
public void setDateOfVoting(Date dateOfVoting){
this.dateOfVoting = dateOfVoting;
}
}
| true
|
a3a8c6306bdb3613ebf03b33d1a064a867bb53ee
|
Java
|
VinnyLin72/MKS22X
|
/07/Merge.java
|
UTF-8
| 805
| 3.34375
| 3
|
[] |
no_license
|
import java.util.*;
import java.io.*;
public class Merge {
public static void mergesort(int[] data) {
int[] temp = new int[data.length];
msort(data, temp, 0, data.length - 1);
}
public static void msort(int[] data, int[] temp, int lo, int hi) {
if (lo < hi){
for (int i = lo; i < hi + 1; i ++){
temp[i] = data[i];
}
msort(temp, data, lo, (lo + hi) / 2);
msort(temp, data, (lo + hi) / 2 + 1, hi);
merge(data, temp, lo, (lo + hi) / 2, (lo + hi) / 2 + 1, hi);
}
}
public static void merge(int[] data, int[] temp, int lo, int hi, int lo1, int hi1) {
for (int i = lo; i < hi1 + 1; i ++){
if (lo < hi + 1 && (lo1 > hi1 || temp[lo] < temp[lo1])){
data[i] = temp[lo];
lo ++;
}
else {
data[i] = temp[lo1];
lo1 ++;
}
}
}
}
| true
|
fa736f83e59ec46b868d965af349ab5f29d3e697
|
Java
|
bhanu2308/Training
|
/Training/src/stringbased/CharArrayToString.java
|
UTF-8
| 359
| 3.03125
| 3
|
[] |
no_license
|
package stringbased;
public class CharArrayToString {
public static void main(String args[])
{
char[] chars = {'T', 'e', 'c', 'h', 'i', 'e', ' ',
'D', 'e', 'l', 'i', 'g', 'h', 't'};
StringBuilder sb = new StringBuilder();
for (char ch: chars) {
sb.append(ch);
}
String string = sb.toString();
System.out.println(string);
}
}
| true
|
d1b260513c7a28934cfccb5565afd47460a7216e
|
Java
|
CrumblingAway/School-Projects
|
/OOP (Java)/ex5/filesprocessing/filters/Filter.java
|
UTF-8
| 312
| 2.859375
| 3
|
[] |
no_license
|
package filesprocessing.filters;
import java.io.File;
/**
* Interface for all filters
*/
public interface Filter
{
/**
* Run the filter on the requested file
* @param file file
* @return true if file meets the filter's requirement, otherwise false
*/
boolean filter(File file);
}
| true
|
cd6d1f1451f7471588da24d3acb4d9b22e2ffe8c
|
Java
|
mahdiazizProjects/InstaStars
|
/src/com/robin/instastars/classes/Search.java
|
UTF-8
| 1,225
| 2.765625
| 3
|
[] |
no_license
|
package com.robin.instastars.classes;
import java.util.ArrayList;
public class Search {
private String keyword;
private boolean result;
private ArrayList<Actor_Class>actors;
public ArrayList<Actor_Class> getActors() {
return actors;
}
public void setActors(ArrayList<Actor_Class> actors) {
this.actors = actors;
}
public boolean isResult() {
return result;
}
public void setResult(boolean result) {
this.result = result;
}
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
public ArrayList<Actor_Class> getindexofsearch(int indexofsearchfile)
{
ArrayList<Actor_Class> actors=new ArrayList<Actor_Class>();
for(int ii=0;ii<this.actors.size();ii++)
{
if(this.actors.get(ii).getFName().contains(keyword)||this.actors.get(ii).getLName().contains(keyword))
actors.add(this.actors.get(ii));
}
return actors;
}
public ArrayList<Actor_Class> getindexofsearchall(ArrayList<Actor_Class>allactors)
{
for(int ii=0;ii<this.actors.size();ii++)
{
if(this.actors.get(ii).getFName().contains(keyword)||this.actors.get(ii).getLName().contains(keyword))
allactors.add(this.actors.get(ii));
}
return allactors;
}
}
| true
|
2cd8707ed8aa6d4c6f9d70335cd9babf81fecbd1
|
Java
|
SergySanJj/MultitaskingManager
|
/MultitaskingManager/src/com/university/StrFunc.java
|
UTF-8
| 803
| 3.109375
| 3
|
[] |
no_license
|
package com.university;
import static java.lang.Character.*;
public class StrFunc {
public static String getFirstNumber(String str) {
StringBuilder res = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
if (isDigit(str.charAt(i)) || str.charAt(i) == '.' || str.charAt(i) == '-' || isLetter(str.charAt(i)))
res.append(str.charAt(i));
}
return res.toString();
}
public static String[] parseNumValues(String str) {
String[] values = str.split(" ");
for (int i = 0; i < values.length; i++) {
values[i] = getFirstNumber(values[i]);
}
return values;
}
public static String parseFunctionWithoutCopyLabel(String str) {
return str.replaceAll("copy", "");
}
}
| true
|
923fd46dddfbbd6f06196fd87c43e7296bb5cb27
|
Java
|
rafadmlima/RegistroPresenca
|
/app/src/main/java/com/example/rafael/registropresenca/dao/RegistroDao.java
|
UTF-8
| 3,849
| 2.59375
| 3
|
[] |
no_license
|
package com.example.rafael.registropresenca.dao;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.example.rafael.registropresenca.model.Registro;
import com.example.rafael.registropresenca.util.DBHelper;
import java.util.ArrayList;
import java.util.List;
/**
* Created by RAFAEL on 12/08/2017.
*/
public class RegistroDao {
RegistroDao dao;
private Registro registro;
private SQLiteDatabase db;
private DBHelper helper;
Cursor cursor;
private String sql = "CREATE TABLE IF NOT EXISTS REGISTRO ( " +
"_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, " +
"EMPRESA VARCHAR(14)," +
"COLABORADOR VARCHAR(11), " +
"DATA VARCHAR(10)," +
"DATA_REUNIAO VARCHAR(10)," +
"OPERACAO VARCHAR(1)," +
"MOTIVO VARCHAR (255), " +
"HORARIO VARCHAR(8)," +
"STATUS VARCHAR(1), " +
"TRABALHADO VARCHAR(8)," +
"COORDENADAS VARCHAR(20)," +
"TT_TRABALHADO VARCHAR(8)," +
"); ";
//instancia um objeto da classe DBHelper no construtor
public RegistroDao(Context contexto){
dao = new RegistroDao();
helper = new DBHelper(contexto, sql, "registro");
}
public RegistroDao() {
}
//insert
public long inserir(Registro registro){
long rowid = 0;
ContentValues valores = new ContentValues();
//valores.put("id", 1);
valores.put("empresa", registro.getEmpresa());
valores.put("colaborador", registro.getColaborador());
valores.put("data",registro.getData());
valores.put("data_reuniao", registro.getData_reuniao());
valores.put("operacao", registro.getOperacao());
valores.put("motivo", registro.getMotivo());
valores.put("horario", registro.getHorario());
valores.put("status", registro.getStatus());
valores.put("trabalhado", registro.getTrabalhado());
valores.put("coordenadas", registro.getCoordenadas());
valores.put("ttTrabalhado", registro.getTtTrabalhado());
db = helper.getWritableDatabase();
try {
rowid = db.insert(DBHelper.TABLE, null, valores);
}catch (Exception e) {
System.out.println(e.getMessage());;
}
return rowid;
}
//select
public List<Registro> selecionarTodos() {
List<Registro> lista = new ArrayList<Registro>();
db = helper.getReadableDatabase();
cursor = db.query(DBHelper.TABLE,
new String[] {"id, empresa, colaborador, data, data_reuniao", "operacao", "motivo", "horario", "status", "trabalhado", "coordenadas", "ttTrabalhado"}, null, null, null, null, "id");
cursor.moveToFirst();
while (! cursor.isAfterLast()) {
registro = new Registro(cursor.getLong(0),
cursor.getLong(1),
cursor.getLong(2),
cursor.getString(3),
cursor.getString(4),
cursor.getString(5),
cursor.getString(6),
cursor.getString(7),
cursor.getString(8),
cursor.getString(9),
cursor.getString(10),
cursor.getString(11) );
lista.add(registro);
cursor.moveToNext();
}
cursor.close();
helper.close();
return lista;
}
}
| true
|
ff2bc67cc6344748f2b03a73d857b63251fe04ce
|
Java
|
qmwu2000/frameworks
|
/type-converter/src/test/java/org/unidal/converter/TypeUtilTest.java
|
UTF-8
| 1,315
| 2.328125
| 2
|
[] |
no_license
|
package org.unidal.converter;
import org.unidal.converter.TypeUtil;
import junit.framework.TestCase;
public class TypeUtilTest extends TestCase {
public void testUserDefinedClass() {
assertEquals(false, TypeUtil.isUserDefinedClass(int.class));
assertEquals(false, TypeUtil.isUserDefinedClass(Integer.class));
assertEquals(false, TypeUtil.isUserDefinedClass(String.class));
assertEquals(true, TypeUtil.isUserDefinedClass(getClass()));
}
public void testWrapClass() {
assertEquals(Boolean.class, TypeUtil.getWrapClass(boolean.class));
assertEquals(Byte.class, TypeUtil.getWrapClass(byte.class));
assertEquals(Character.class, TypeUtil.getWrapClass(char.class));
assertEquals(Short.class, TypeUtil.getWrapClass(short.class));
assertEquals(Integer.class, TypeUtil.getWrapClass(int.class));
assertEquals(Long.class, TypeUtil.getWrapClass(long.class));
assertEquals(Float.class, TypeUtil.getWrapClass(float.class));
assertEquals(Double.class, TypeUtil.getWrapClass(Double.class));
assertEquals(Integer.class, TypeUtil.getWrapClass(Integer.TYPE));
assertEquals(Integer.class, TypeUtil.getWrapClass(Integer.class));
assertEquals(String.class, TypeUtil.getWrapClass(String.class));
}
}
| true
|
c312d9901fcf0e47bf2838d3dc6f7031473fa63a
|
Java
|
AugGroup/AugSystem
|
/aug-db/src/main/java/com/aug/db/services/LoginServiceImpl.java
|
UTF-8
| 1,161
| 2.359375
| 2
|
[] |
no_license
|
package com.aug.db.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.aug.db.dto.LoginDTO;
import com.aug.db.entities.Login;
import com.aug.db.repositories.LoginRepository;
@Service(value = "loginService")
@Transactional
public class LoginServiceImpl implements LoginService{
@Autowired
private LoginRepository loginRepository;
@Override
public void create(Login login) {
loginRepository.insert(login);
}
@Override
public Login findById(Integer id) {
return loginRepository.findById(id);
}
@Override
public void update(Login login) {
loginRepository.update(login);
}
@Override
public void deleteById(Integer id) {
loginRepository.deleteById(id);
}
@Override
public void delete(Login login) {
loginRepository.delete(login);
}
@Override
public List<Login> findAll() {
return loginRepository.findAll();
}
@Override
public LoginDTO findByUserName(String userName) {
LoginDTO logins = loginRepository.findByUserName(userName);
return logins;
}
}
| true
|
832fe7cfc49299aac0c86e90bf87bff957bb7cc3
|
Java
|
Wangyuf/JAVA-01
|
/Week_04/lesson7/src/main/java/com/example/lesson7/Method8.java
|
UTF-8
| 1,207
| 3.171875
| 3
|
[] |
no_license
|
package com.example.lesson7;
import com.example.lesson7.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicReference;
/**
* @program: lesson7 Method7.java
* @description: 在 main 函数启动一个新线程,运行一个方法,拿到这个方法的返回值后,退出主线程
* @author: cc
* @create: 2021-02-07 00:15
*/
@Slf4j
public class Method8 {
/**
* 使用CountDownLatch返回
*
* @param args
*/
public static void main(String[] args) throws InterruptedException {
final BlockingDeque<String> blockingDeque = new LinkedBlockingDeque<>(10);
ExecutorService executorService = Executors.newFixedThreadPool(2);
CountDownLatch latch = new CountDownLatch(10);
for (int i = 0; i < 10; i++) {
int k = i;
executorService.execute(() -> {
blockingDeque.push("当前" + k);
latch.countDown();
log.info("wait 1s");
CommonUtil.sleep(1000L);
});
}
latch.await();
executorService.shutdown();
log.info("结束{}", blockingDeque);
}
}
| true
|
3edfe24009ccce791b0ab9c37940772f1263319b
|
Java
|
climbtop/EC_PAYMENT
|
/src/com/trendy/ow/portal/payment/bean/PayItemBean.java
|
UTF-8
| 2,332
| 1.914063
| 2
|
[] |
no_license
|
package com.trendy.ow.portal.payment.bean;
import java.sql.Timestamp;
public class PayItemBean {
private int payItemId = 0;
private int payId = 0;
private int companyId = 0;
private int channelId = 0;
private String payNumber = "";
private String currency = "";
private double payAmount = 0;
private String ipAddress = "";
private Timestamp payTime = null;
private String payStatus = "";
private int status = 0;
private Timestamp createTime = null;
private Timestamp modifyTime = null;
public int getPayItemId() {
return payItemId;
}
public void setPayItemId(int payItemId) {
this.payItemId = payItemId;
}
public int getPayId() {
return payId;
}
public void setPayId(int payId) {
this.payId = payId;
}
public int getCompanyId() {
return companyId;
}
public void setCompanyId(int companyId) {
this.companyId = companyId;
}
public int getChannelId() {
return channelId;
}
public void setChannelId(int channelId) {
this.channelId = channelId;
}
public String getPayNumber() {
return payNumber;
}
public void setPayNumber(String payNumber) {
this.payNumber = payNumber;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public double getPayAmount() {
return payAmount;
}
public void setPayAmount(double payAmount) {
this.payAmount = payAmount;
}
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public Timestamp getPayTime() {
return payTime;
}
public void setPayTime(Timestamp payTime) {
this.payTime = payTime;
}
public String getPayStatus() {
return payStatus;
}
public void setPayStatus(String payStatus) {
this.payStatus = payStatus;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public Timestamp getCreateTime() {
return createTime;
}
public void setCreateTime(Timestamp createTime) {
this.createTime = createTime;
}
public Timestamp getModifyTime() {
return modifyTime;
}
public void setModifyTime(Timestamp modifyTime) {
this.modifyTime = modifyTime;
}
}
| true
|
ffbf4550aa2e1744116ed93900be2286c9054c89
|
Java
|
lichuandi/springboot2021
|
/src/main/java/com/lichuandi/springboot2021/controller/TestController.java
|
UTF-8
| 804
| 2.203125
| 2
|
[] |
no_license
|
package com.lichuandi.springboot2021.controller;
import com.lichuandi.springboot2021.configBean.ConfigBean;
import com.lichuandi.springboot2021.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Auther digege
* @Date 2021/4/22
* @Description:com.lichuandi.springboot2021.controller version:1
*/
@RestController
@EnableConfigurationProperties({ConfigBean.class, User.class})
public class TestController {
@Autowired
User user;
@RequestMapping(value = "/user")
public String user(){
return user.getName()+"-"+user.getAge();
}
}
| true
|
b2cf60a6d2eef30e4c38169ea9d2b77b2e8609fb
|
Java
|
luosen26/CustomerInformationManage
|
/src/com/luosen/demo/dao/PhoneDao.java
|
UTF-8
| 445
| 2.09375
| 2
|
[] |
no_license
|
package com.luosen.demo.dao;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.luosen.demo.domain.Phone;
public interface PhoneDao {
public List<Phone> find(@Param("u_id")int u_id,@Param("p_id")int p_id,@Param("p_name")String p_name);
public Phone findByName(@Param("u_id")int u_id,@Param("p_name")String p_name);
public int create(Phone phone);
public int modify(Phone phone);
public int remove(int p_id);
}
| true
|
42a56706ad9a1a0d3b12971c6716f632c4d43100
|
Java
|
michaelmccabe/vaadin-spring-projects
|
/coins/src/main/java/com/mic/springvaadin/dao/impl/CoinsDaoImpl.java
|
UTF-8
| 848
| 2.1875
| 2
|
[] |
no_license
|
package com.mic.springvaadin.dao.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mic.springvaadin.dao.CoinsDao;
import com.mic.springvaadin.dao.model.Coin;
import com.mic.springvaadin.dao.model.CoinRepository;
@Service
public class CoinsDaoImpl implements CoinsDao {
@Autowired
private CoinRepository repository;
@Override
public List<Coin> getCoins() {
return (List<Coin>) repository.findAll();
}
@Override
public void saveCoin(Coin coin) {
repository.save(coin);
}
public void setRepository(CoinRepository repository) {
this.repository = repository;
}
@Override
public void removeCoin(Coin coin) {
repository.delete(coin);
}
@Override
public Coin getCoin(Integer id) {
return repository.findOne(id);
}
}
| true
|
919986068ec90c8672794f644628f634f2800a58
|
Java
|
alexlimatds/rlAPI
|
/src/test/java/org/rlapi/StateActionValueTableTest.java
|
UTF-8
| 4,351
| 2.75
| 3
|
[
"Apache-2.0"
] |
permissive
|
package org.rlapi;
import java.util.List;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
/**
*
* @author Alexandre
*/
public class StateActionValueTableTest {
@Test
public void testGetStates(){
ActionValueTableInMemory table = new ActionValueTableInMemory();
String stateA = "A";
String stateB = "B";
table.putValue(stateA, "action", 3.0);
table.putValue(stateB, "action", 8.0);
Set<String> states = table.getStates();
Assert.assertTrue(states.contains(stateA));
Assert.assertTrue(states.contains(stateB));
}
@Test
public void testGetValue(){
ActionValueTableInMemory table = new ActionValueTableInMemory();
String stateA = "s1";
String stateB = "s2";
String actionA = "a1";
Double actionAValue = 5.0;
String actionB = "a2";
Double actionBValue = 7.0;
String actionC = "a3";
Double actionCValue = 1.0;
table.putValue(stateA, actionA, actionAValue);
table.putValue(stateA, actionB, actionBValue);
table.putValue(stateB, actionC, actionCValue);
Assert.assertEquals(actionAValue, table.getValue(stateA, actionA), 0.0001);
Assert.assertEquals(actionBValue, table.getValue(stateA, actionB), 0.0001);
Assert.assertEquals(actionCValue, table.getValue(stateB, actionC), 0.0001);
}
@Test
public void testGetActions_1(){
ActionValueTableInMemory table = new ActionValueTableInMemory();
String stateA = "s1";
String stateB = "s2";
String actionA = "a1";
String actionB = "a2";
String actionC = "a3";
table.putValue(stateA, actionA, 5.0);
table.putValue(stateA, actionB, 7.0);
table.putValue(stateB, actionA, 9.0);
table.putValue(stateB, actionC, 1.0);
Set<String> stateAActions = table.getActions(stateA);
Assert.assertEquals(2, stateAActions.size());
Assert.assertTrue(stateAActions.contains(actionA));
Assert.assertTrue(stateAActions.contains(actionB));
Set<String> stateABctions = table.getActions(stateB);
Assert.assertEquals(2, stateABctions.size());
Assert.assertTrue(stateABctions.contains(actionA));
Assert.assertTrue(stateABctions.contains(actionC));
}
@Test
public void testGetActions_2(){
ActionValueTableInMemory table = new ActionValueTableInMemory();
Set<String> stateAActions = table.getActions("state");
Assert.assertNotNull(stateAActions);
Assert.assertTrue(stateAActions.isEmpty());
}
@Test
public void testGetBestActions_1(){
ActionValueTableInMemory table = new ActionValueTableInMemory();
table.putValue("s1", "a1", 3.0);
table.putValue("s1", "a2", 8.0);
List<String> maxActions = table.getBestActions("s1");
Assert.assertEquals(1, maxActions.size());
Assert.assertTrue(maxActions.contains("a2"));
}
@Test
public void testGetBestActions_2(){
ActionValueTableInMemory table = new ActionValueTableInMemory();
table.putValue("s1", "a1", 8.0);
table.putValue("s1", "a2", 2.0);
table.putValue("s1", "a3", 8.0);
List<String> maxActions = table.getBestActions("s1");
Assert.assertEquals(2, maxActions.size());
Assert.assertTrue(maxActions.contains("a1"));
Assert.assertTrue(maxActions.contains("a3"));
}
@Test
public void testGetBestActions_3(){
ActionValueTableInMemory table = new ActionValueTableInMemory();
table.putValue("s1", "a1", 8.0);
table.putValue("s1", "a2", 2.0);
List<String> maxActions = table.getBestActions("s2");
Assert.assertTrue(maxActions.isEmpty());
}
@Test
public void testPutValue_1(){
//Tests an update
ActionValueTableInMemory table = new ActionValueTableInMemory();
table.putValue("s1", "a1", 8.0);
table.putValue("s1", "a2", 2.0);
table.putValue("s1", "a1", 7.0);
Assert.assertEquals(7.0, table.getValue("s1", "a1"), 0.00001);
}
}
| true
|
2e9726ca8a4548f71bb078ed01524d6473f5971f
|
Java
|
ronnnnnn/happy-help
|
/src/main/java/com/zyfz/dao/RoleResourceMapper.java
|
UTF-8
| 245
| 1.65625
| 2
|
[] |
no_license
|
package com.zyfz.dao;
import com.zyfz.domain.RoleResourceKey;
public interface RoleResourceMapper {
int deleteByPrimaryKey(RoleResourceKey key);
int insert(RoleResourceKey record);
int insertSelective(RoleResourceKey record);
}
| true
|
1bcd8780eccd2befa069ad2e52bffbfc7d5bddda
|
Java
|
narusas/sinsege
|
/AceAuction/src2/net/narusas/si/auction/converters/건물현황_층형Converter.java
|
UTF-8
| 830
| 2.671875
| 3
|
[] |
no_license
|
/*
*
*/
package net.narusas.si.auction.converters;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
// TODO: Auto-generated Javadoc
/**
* The Class 건물현황_층형Converter.
*/
public class 건물현황_층형Converter {
/** The p. */
static Pattern p = Pattern.compile("(\\d+\\s*층)");
/** The p2. */
static Pattern p2 = Pattern.compile("\\s+([^\\s]+층)");
/**
* Convert.
*
* @param floor the floor
*
* @return the string
*/
public static String convert(String floor) {
if (floor == null) {
return "";
}
floor = floor.replaceAll("지상", "");
floor = floor.replaceAll("지층", "지하층");
Matcher m = p2.matcher(floor);
if (m.find()) {
return floor.substring(m.start()).trim();
}
return floor.trim();
}
}
| true
|
e98954002cf12782dfb4761ced35ec8d6e4a98c3
|
Java
|
Xinhuix/SpringCloud
|
/SpringCloud-visionvera/visionvera-operation/src/main/java/com/visionvera/util/MysqlJdbc.java
|
UTF-8
| 2,326
| 2.734375
| 3
|
[] |
no_license
|
package com.visionvera.util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
public class MysqlJdbc {
Connection con = null; // 定义一个MYSQL链接对象
String driver;
String url;
String user;
String pwd;
public MysqlJdbc() {
Properties prop = new Properties();
// String path = (getPath() + "properties/jdbc.properties").replaceAll("%20", " ");
String path = "/properties/jdbc.properties";
InputStream in = this.getClass().getResourceAsStream(path);
try {
prop.load(in);
driver = prop.getProperty("mysql.driver").trim();
url = prop.getProperty("mysql.url").trim();
user = prop.getProperty("mysql.username").trim();
pwd = prop.getProperty("mysql.password").trim();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public int open() throws SQLException {
try {
Class.forName(driver).newInstance();
con = (Connection) DriverManager.getConnection(url, user, pwd); // 链接本地MYSQL
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return 0;
}
public int close() {
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
public List<String> getResults(String sql) {
List<String> list = new ArrayList<String>();
Statement stmt; // 创建声明
try {
stmt = (Statement) con.createStatement();
ResultSet selectRes = stmt.executeQuery(sql);
while (selectRes.next()) { // 循环输出结果集
list.add(selectRes.getString(1));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
@SuppressWarnings("unused")
private String getPath() {
// 取得根目录路径
String rootPath = getClass().getResource("/").getFile().toString();
return rootPath.substring(1);
}
}
| true
|
c3146b0b7ad40e4105fbb8198ef54c419281c3de
|
Java
|
Teratech2018/Teratech
|
/keren-erp/core-components/service-components/service-impl/src/main/java/com/core/views/KabanRecordRSImpl.java
|
UTF-8
| 1,107
| 1.96875
| 2
|
[] |
no_license
|
package com.core.views;
import javax.ws.rs.Path;
import com.bekosoftware.genericmanagerlayer.core.ifaces.GenericManager;
import com.megatimgroup.generic.jax.rs.layer.annot.Manager;
import com.megatimgroup.generic.jax.rs.layer.impl.AbstractGenericService;
/**
* Classe d'implementation du Web Service JAX-RS
* @since Tue Aug 14 12:34:06 GMT+01:00 2018
*
*/
@Path("/kabanrecord")
public class KabanRecordRSImpl
extends AbstractGenericService<KabanRecord, Long>
implements KabanRecordRS
{
/**
* On injecte un Gestionnaire d'entites
*
*/
@Manager(application = "kerencore", name = "KabanRecordManagerImpl", interf = KabanRecordManagerRemote.class)
protected KabanRecordManagerRemote manager;
public KabanRecordRSImpl() {
super();
}
/**
* Methode permettant de retourner le gestionnaire d'entites
*
*/
@Override
public GenericManager<KabanRecord, Long> getManager() {
return manager;
}
public String getModuleName() {
return ("kerencore");
}
}
| true
|
0b6d86c41d940baecf985a20513731eac87d08d5
|
Java
|
nguyendinhduc/FirstProjectVMO
|
/src/com/vmodev/hieplnc/first/MyArray.java
|
UTF-8
| 3,507
| 3.578125
| 4
|
[] |
no_license
|
package com.vmodev.hieplnc.first;
import java.lang.annotation.Target;
import java.util.ArrayList;
import java.lang.Math;
import java.util.Arrays;
public class MyArray {
//============================================//
// variable
ArrayList<Integer> array = null;
//=============================================//
// constructor
public MyArray(ArrayList<Integer> array){
this.array = array;
}
//=============================================//
// method
public boolean isPrimeNumber(Integer n){
int max = (int) Math.sqrt(Double.valueOf(n));
for(int i = 2; i <= max; i++){
if(n % i == 0) return false;
}
return true;
}
public void getPrimeNumber(){
System.out.println("Prime Number: ");
for(Integer i : array){
if(isPrimeNumber(i)) System.out.println(i);
}
}
public void subArrayIncrease(){
System.out.println("Get increase sub array:");
int size = array.size();
int min = array.get(0);
int count = 0;
for(int i = 0; i < size; i++){
if(array.get(i) <= min){
System.out.println("\nSub array " + count + " :");
count++;
}
min = array.get(i);
System.out.print(array.get(i));
System.out.print(" ");
}
}
public void subArrayIncSteadily(){
System.out.println("Get increase steadily sub array:");
int size = array.size();
int min = array.get(0);
int hop = 0;
int count = 0;
for(int i = 0; i < size; i++){
if(hop == 0){
hop = array.get(i) - min;
}
if(array.get(i) - min != hop || hop <= 0){
System.out.println("\nSub array " + count + " :");
count++;
hop = 0;
}
min = array.get(i);
System.out.print(array.get(i));
System.out.print(" ");
}
}
private int sumArray(ArrayList<Integer> temp){
int result = 0;
for(Integer i : temp){
result += i;
}
return result;
}
private void displayArray(ArrayList<Integer> temp){
System.out.println("Array List: ");
for(Integer i : temp){
System.out.print(i.toString() + " ");
}
System.out.println("");
}
private void rcsArray(int pos, int num, ArrayList<Integer> temp, int target){
int size = array.size();
for(int i = pos; i < size; i++){
if(num == 0){
if(sumArray(temp) + array.get(i) == target) {
ArrayList<Integer> finalArray = new ArrayList(temp);
finalArray.add(array.get(i));
displayArray(finalArray);
}
} else{
ArrayList<Integer> conArray = new ArrayList(temp);
conArray.add(array.get(i));
rcsArray(i + 1, num - 1, conArray, target);
}
}
}
public void listHasSumEqual(int M){
int size = array.size();
for(int i = 0; i < size; i++) {
rcsArray(0, i, new ArrayList<Integer>(), M);
}
}
public static void main(String[] args){
ArrayList<Integer> arrayList = new ArrayList<Integer>(Arrays.asList(1,2,4,5,7,4,6,8));
MyArray obj = new MyArray(arrayList);
obj.listHasSumEqual(9);
}
}
| true
|
d468bc4a19ab17822d6bacf858906320ad0aa3ee
|
Java
|
LadyToledo/Pacman-2.0
|
/Juego.java
|
UTF-8
| 9,157
| 2.390625
| 2
|
[] |
no_license
|
/**
*
*/
package pacman;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;
/**
* @author Lady Toledo
*
*/
public class Juego extends JPanel implements ComponentesDeJuego,Constantes,ActionListener{
private Timer timer; // tengo bloqueado lo que lo usa en tablero, solo lo ocupa juego
private Pacman a;
private Tablero b;
private Fantasmas c;
private Niveles e;
private Image ii;
private int pacanimdir = 1; //1
private final int pacanimdelay = 2; //2
private final int pacmananimcount = 4; //4
private int pacanimcount = pacanimdelay;
public boolean ingame = false;
public boolean dying = false; //moribundo
public int currentspeed = 3; //3, velocidad actual
public int nrofghosts = 6;
public int pacmananimpos = 0; //0
public Dimension d;
public Color mazecolor;
public int pacsleft, score;
public int reqdx, reqdy, viewdx, viewdy;
public int pacmanx, pacmany, pacmandx, pacmandy;
public int[] dx, dy;
public short[] screendata;
public int[] ghostx, ghosty, ghostdx, ghostdy, ghostspeed;
public Image ghost;
public Image pacman1, pacman2up, pacman2left, pacman2right, pacman2down;
public Image pacman3up, pacman3down, pacman3left, pacman3right;
public Image pacman4up, pacman4down, pacman4left, pacman4right;
public void loadImages() {
ghost = new ImageIcon(getClass().getResource("../images/ghost.gif")).getImage();
pacman1 = new ImageIcon(getClass().getResource("../images/pacman.gif")).getImage();
pacman2up = new ImageIcon(getClass().getResource("../images/up1.gif")).getImage();
pacman3up = new ImageIcon(getClass().getResource("../images/up2.gif")).getImage();
pacman4up = new ImageIcon(getClass().getResource("../images/up3.gif")).getImage();
pacman2down = new ImageIcon(getClass().getResource("../images/down1.gif")).getImage();
pacman3down = new ImageIcon(getClass().getResource("../images/down2.gif")).getImage();
pacman4down = new ImageIcon(getClass().getResource("../images/down3.gif")).getImage();
pacman2left = new ImageIcon(getClass().getResource("../images/left1.gif")).getImage();
pacman3left = new ImageIcon(getClass().getResource("../images/left2.gif")).getImage();
pacman4left = new ImageIcon(getClass().getResource("../images/left3.gif")).getImage();
pacman2right = new ImageIcon(getClass().getResource("../images/right1.gif")).getImage();
pacman3right = new ImageIcon(getClass().getResource("../images/right2.gif")).getImage();
pacman4right = new ImageIcon(getClass().getResource("../images/right3.gif")).getImage();
}
public Juego() {
loadImages();
initVariables();
addKeyListener(new TAdapter());
setFocusable(true);
setBackground(Color.BLACK);
setDoubleBuffered(true);
}
@Override
public void addNotify() {
super.addNotify();
juegoInicial();
}
//showIntroScreen -> mostrar pantalla de introduccion
public void showIntroScreen(Graphics2D g2d) {
g2d.setColor(new Color(0, 32, 48));
g2d.fillRect(50, scrsize / 2 - 30, scrsize - 100, 50);
// g2d.fillRect(50, scrsize / 2 - 30, scrsize - 100, 50);
g2d.setColor(Color.white);
g2d.drawRect(50, scrsize / 2 - 30, scrsize - 100, 50);
String x = "Presiona X para empezar.";
Font small = new Font("Helvetica", Font.BOLD, 15);
FontMetrics metr = this.getFontMetrics(small);
g2d.setColor(Color.white);
g2d.setFont(small);
g2d.drawString(x, (scrsize - metr.stringWidth(x)) / 2, scrsize / 2);
}
@Override
public void tablero() {
}
private void initVariables() {
screendata = new short[nrofblocks * nrofblocks];
mazecolor = new Color(0, 0, 255); //color laberinto
d = new Dimension(400, 400); //no paso nada
ghostx = new int[maxghosts];
ghostdx = new int[maxghosts];
ghosty = new int[maxghosts];
ghostdy = new int[maxghosts];
ghostspeed = new int[maxghosts];
dx = new int[4]; //4
dy = new int[4]; //4
timer = new Timer(40, this);
timer.start();
}
public void playGame (Graphics2D g2d) {
a=new Pacman();
c=new Fantasmas();
if (dying) {
death();
} else {
a.movePacman();
a.drawPacman(g2d);
c.moveGhosts(g2d);
checkMaze();
}
}
//comprobar laberinto
private void checkMaze() {
short i = 0;
boolean finished = true;
while (i < nrofblocks * nrofblocks && finished) {
if ((screendata[i] & 48) != 0) {
finished = false;
}
i++;
}
if (finished) {
score += 50;
if (nrofghosts < maxghosts) {
nrofghosts++;
}
if (currentspeed < maxspeed) {
currentspeed++;
}
nivelDeInicio();
}
}
private void death() {//murio
pacsleft--;
if (pacsleft == 0) {
ingame = false;
}
continuarNivel();
}
@Override
public void niveles() {
}
@Override
public void pacman() {
}
@Override
public void fantasmas() {
}
@Override
public void juegoInicial() { //init game
pacsleft = 3; //3, vidas
score = 0; //puntaje inicial
nivelDeInicio();
nrofghosts = 3; //numero de fantasmas
currentspeed = 3; //velocidad actual
}
@Override
public void nivelDeInicio() {
e=new Niveles();
e.initLevel();
}
@Override
public void continuarNivel() {
e=new Niveles();
e.continueLevel();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
public void doDrawing(Graphics g) {
b=new Tablero();
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.black);
g2d.fillRect(0, 0, d.width, d.height); //ocupan dimension dx
b.drawMaze(g2d);
b.drawScore(g2d);
doAnim();
if (ingame) {
playGame(g2d);
} else {
showIntroScreen(g2d);
}
g2d.drawImage(ii, 5, 5, this);
Toolkit.getDefaultToolkit().sync();
g2d.dispose();
}
private void doAnim() {
pacanimcount--;
if (pacanimcount <= 0) {
pacanimcount = pacanimdelay;
pacmananimpos = pacmananimpos + pacanimdir;
if (pacmananimpos == (pacmananimcount - 1) || pacmananimpos == 0) {
pacanimdir = -pacanimdir;
}
}
}
/**teclas que controlan el juego */
class TAdapter extends KeyAdapter {
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (ingame) {
if (key == KeyEvent.VK_LEFT) {
reqdx = -1;
reqdy = 0;
} else if (key == KeyEvent.VK_RIGHT) {
reqdx = 1;
reqdy = 0;
} else if (key == KeyEvent.VK_UP) {
reqdx = 0;
reqdy = -1;
} else if (key == KeyEvent.VK_DOWN) {
reqdx = 0;
reqdy = 1;
// pensar si dejar esto
}/** else if (key == KeyEvent.VK_ESCAPE && timer.isRunning()) {
ingame = false;
} else if (key == KeyEvent.VK_PAUSE) {
if (timer.isRunning()) {
timer.stop();
} else {
timer.start();
}
}*/
/**letra con la que empieza el juego*/
} else {
if (key == 'x' || key == 'X') {
ingame = true;
juegoInicial();
}
}
}
//no se para que sirve
@Override
public void keyReleased(KeyEvent e) {
/*
int key = e.getKeyCode();
if (key == Event.LEFT || key == Event.RIGHT
|| key == Event.UP || key == Event.DOWN) {
reqdx = 0;
reqdy = 0;
}*/
}
}
@Override
public void actionPerformed(ActionEvent e) {
repaint();
}
}
| true
|
cf6172677fb94969c2d612d1f90512e1edf1e81d
|
Java
|
zoluu/Round-Up-For-Savings
|
/RoundUpTest.java
|
UTF-8
| 6,390
| 3.21875
| 3
|
[] |
no_license
|
package com.starlingbank;
import org.junit.Test;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.NoSuchElementException;
import static org.junit.Assert.*;
public class RoundUpTest {
/**
* Tests whether findRoundUp finds the correct round up
*/
@Test
public void testOne() {
int expected = WeeklySavings.findRoundUp(BigInteger.valueOf(573)).intValue();
int actual = BigInteger.valueOf(27).intValue();
assertEquals(expected, actual);
}
/**
* Tests whether findRoundUp finds the correct round up
*/
@Test
public void testTwo() {
int expected = WeeklySavings.findRoundUp(BigInteger.valueOf(6689)).intValue();
int actual = BigInteger.valueOf(11).intValue();
assertEquals(expected, actual);
}
/**
* Tests and makes sure a value of 0 throws IllegalArgumentException if passed through findRoundUp
*/
@Test(expected = IllegalArgumentException.class)
public void testThree() {
int expected = WeeklySavings.findRoundUp(BigInteger.valueOf(0)).intValue();
int actual = BigInteger.valueOf(0).intValue();
assertEquals(expected, actual);
}
/**
* Tests what happens when a negative value is passed through findRoundUp
*/
@Test(expected = IllegalArgumentException.class)
public void testFour() {
WeeklySavings.findRoundUp(BigInteger.valueOf(-50));
}
/**
* Tests what happens when null is passed through findRoundUp
*/
@Test(expected = NullPointerException.class)
public void testFive() {
WeeklySavings.findRoundUp(null);
}
/**
* Tests what happens when there is nothing to round up in findRoundUp
*/
@Test
public void testSix() {
int expected = WeeklySavings.findRoundUp(BigInteger.valueOf(500)).intValue();
int actual = BigInteger.valueOf(0).intValue();
assertEquals(expected, actual);
}
/**
* Tests whether the check for today is in the current week
*/
@Test
public void testSeven() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String timeNow = sdf.format(cal.getTime());
boolean expected = WeeklySavings.isDateInCurrentWeek(timeNow);
assertTrue(expected);
}
/**
* Tests whether the check for last weeks date is in the current week
*/
@Test
public void testEight() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
cal.add(Calendar.DATE,-7);
String timeLastWeek = sdf.format(cal.getTime());
boolean expected = WeeklySavings.isDateInCurrentWeek(timeLastWeek);
assertFalse(expected);
}
/**
* Tests what happens when null is passed through isDateInCurrentWeek
*/
@Test(expected = NullPointerException.class)
public void testNine() {
WeeklySavings.isDateInCurrentWeek(null);
}
/**
* Creates a list of transactions to test the getWeeklyRoundUps
*/
@Test
public void testTen() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String timeNow = sdf.format(cal.getTime());
List<Transaction> transactionList = new ArrayList<>();
Transaction transaction = new Transaction("test1","OUT","SETTLED", BigInteger.valueOf(539));
transaction.setSettlementTime(timeNow);
transactionList.add(transaction);
transaction = new Transaction("test2","OUT","SETTLED", BigInteger.valueOf(7789));
transaction.setSettlementTime(timeNow);
transactionList.add(transaction);
transaction = new Transaction("test3","IN","SETTLED", BigInteger.valueOf(455));
transaction.setSettlementTime(timeNow);
transactionList.add(transaction);
BigInteger expected = WeeklySavings.getWeeklyRoundUps(transactionList);
BigInteger actual = BigInteger.valueOf(72);
assertEquals(expected, actual);
}
/**
* Creates a list of transactions to test the getWeeklyRoundUps when the values don't need to be rounded up
*/
@Test
public void testEleven() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String timeNow = sdf.format(cal.getTime());
List<Transaction> transactionList = new ArrayList<>();
Transaction transaction = new Transaction("test1","OUT","SETTLED", BigInteger.valueOf(500));
transaction.setSettlementTime(timeNow);
transactionList.add(transaction);
transaction = new Transaction("test2","OUT","SETTLED", BigInteger.valueOf(4000));
transaction.setSettlementTime(timeNow);
BigInteger expected = WeeklySavings.getWeeklyRoundUps(transactionList);
BigInteger actual = BigInteger.valueOf(0);
assertEquals(expected, actual);
}
/**
* Creates a list of transactions to test the getWeeklyRoundUps when there are no transactions made this week
*/
@Test (expected = NoSuchElementException.class)
public void testTwelve() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
cal.add(Calendar.DATE,-7);
String timeLastWeek = sdf.format(cal.getTime());
List<Transaction> transactionList = new ArrayList<>();
Transaction transaction = new Transaction("test1","OUT","SETTLED", BigInteger.valueOf(4000));
transaction.setSettlementTime(timeLastWeek);
transactionList.add(transaction);
transaction = new Transaction("test2","OUT","SETTLED", BigInteger.valueOf(500));
transaction.setSettlementTime(timeLastWeek);
BigInteger expected = WeeklySavings.getWeeklyRoundUps(transactionList);
BigInteger actual = BigInteger.valueOf(0);
assertEquals(expected, actual);
}
}
| true
|
a3472bcca88d0b9d432386b773630b7d7806e445
|
Java
|
M-andra/NETGURU
|
/src/test/java/Tests/Login2test.java
|
UTF-8
| 796
| 1.992188
| 2
|
[] |
no_license
|
package Tests;
import Base.BaseTest;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
public class Login2test extends BaseTest {
@Test
public void Login2(){
//test will validate correct email address and incorrect password will not be accepted and user will be prompted
WebElement AcceptCookies = driver.findElement(By.cssSelector("#onetrust-accept-btn-handler"));
AcceptCookies.click();
WebElement InsertEmail = driver.findElement(By.id("ul-email"));
InsertEmail.sendKeys("andinrsk@gmail.com");
WebElement InsertPass = driver.findElement(By.id("ul-password"));
InsertPass.sendKeys("TestNetguru1");
WebElement Login = driver.findElement(By.id("ul-login"));
Login.click();
}
}
| true
|
ea393861e55f8ddb2d9b2f2d6b142dc51968aef4
|
Java
|
milanmanvar/CNAndroidApp-Milan
|
/CNAndroidApp/src/main/java/com/thecn/app/activities/post/PostActivity.java
|
UTF-8
| 7,026
| 2.375
| 2
|
[] |
no_license
|
package com.thecn.app.activities.post;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import com.thecn.app.AppSession;
import com.thecn.app.R;
import com.thecn.app.activities.navigation.NavigationActivity;
import com.thecn.app.models.content.Post;
import com.thecn.app.stores.PostStore;
import com.thecn.app.stores.StoreUtil;
import com.thecn.app.tools.CallbackManager;
/**
* Shows a single post and its reflections (through {@link com.thecn.app.activities.post.PostFragment}
*/
public class PostActivity extends NavigationActivity {
private Post mPost;
//fragment manager keys
private static final String mLoadPostFragmentTag = "load_post";
public static final String FRAGMENT_BUNDLE_KEY = "pr_fragment";
private DataGrabber mDataGrabber;
/**
* Begin loading if savedInstanceState is null, otherwise get instance of DataGrabber.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setActionBarAndTitle("Post");
if (savedInstanceState == null) {
String postId;
try {
mPost = (Post) getIntent().getSerializableExtra("post");
postId = mPost.getId();
if (postId == null) {
throw new NullPointerException();
}
} catch (NullPointerException e) {
onLoadingError();
return;
}
mDataGrabber = DataGrabber.getInstance(postId);
getSupportFragmentManager().beginTransaction()
.add(mDataGrabber, mLoadPostFragmentTag)
.commit();
} else {
mDataGrabber =
(DataGrabber) getSupportFragmentManager().findFragmentByTag(mLoadPostFragmentTag);
if (!mDataGrabber.loading) {
mPost = (Post) savedInstanceState.getSerializable("post");
}
hideProgressBar();
}
}
/**
* Loads post data for the PostActivity
*/
public static class DataGrabber extends Fragment {
public boolean loading = false;
private CallbackManager<DataGrabber> manager;
//tag for the id of the post
public static final String ID_KEY = "id_key";
/**
* Sets up this fragment with its arguments.
* @param id id of the post to load
* @return new instance of this class
*/
public static DataGrabber getInstance(String id) {
Bundle args = new Bundle();
args.putString(ID_KEY, id);
DataGrabber grabber = new DataGrabber();
grabber.setArguments(args);
return grabber;
}
/**
* Set up and begin loading
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
manager = new CallbackManager<>();
loading = true;
String id = getArguments().getString(ID_KEY);
PostStore.getPostById(id,PostStore.taskId, new Callback(manager));
}
@Override
public void onResume() {
super.onResume();
manager.resume(this);
}
@Override
public void onPause() {
manager.pause();
super.onPause();
}
/**
* Used to make decisions when a network call returns.
*/
private static class Callback extends CallbackManager.NetworkCallback<DataGrabber> {
public Callback(CallbackManager<DataGrabber> grabber) {
super(grabber);
}
@Override
public void onResumeWithResponse(DataGrabber object) {
Post post = PostStore.getData(response);
PostActivity a = (PostActivity) object.getActivity();
if (post != null) {
a.onSuccess(post);
} else {
a.onLoadingError();
}
}
@Override
public void onResumeWithError(DataGrabber object) {
StoreUtil.showExceptionMessage(error);
object.getActivity().finish();
}
}
}
public DataGrabber getDataGrabber() {
return mDataGrabber;
}
/**
* Called when a network call returns successfully
* @param post the post to be displayed
*/
private void onSuccess(Post post) {
if (post == null) {
onLoadingError();
return;
}
setPost(post);
hideProgressBar();
//whether or not to show the soft keyboard for reflection input
boolean textFocus = getIntent().getBooleanExtra("textFocus", false);
//add a new PostFragment
Fragment fragment = PostFragment.newInstance(post, textFocus);
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, fragment, PostActivity.FRAGMENT_BUNDLE_KEY)
.commit();
getDataGrabber().loading = false;
}
/**
* Finish activity if there is a problem loading.
*/
private void onLoadingError() {
AppSession.showDataLoadError("post");
finish();
}
/**
* Gets the post of this activity
* @return the post associated with this activity
*/
public Post getPost() {
return mPost;
}
/**
* Sets the post for this activity
* @param post the post to associate with this activity
*/
public void setPost(Post post) {
mPost = post;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("post", mPost);
}
/**
* Make sure that duplicate post activities are not opened.
* If the same post, bring up the soft keyboard if requested.
* @param post the post to check
* @param textFocus whether to bring up the soft keyboard for reflection entry.
*/
@Override
public void openPostPage(Post post, boolean textFocus) {
// override to prevent another reflections page from opening
if (post.getId().equals(mPost.getId())) {
if (textFocus) {
try {
PostFragment fragment =
(PostFragment) getSupportFragmentManager()
.findFragmentByTag(FRAGMENT_BUNDLE_KEY);
fragment.focusReflectionTextBox(true);
} catch (NullPointerException e) {
// something went wrong
} catch (ClassCastException e) {
// something went wrong
}
} else {
closeNotificationDrawer();
}
} else {
super.openPostPage(post, textFocus);
}
}
}
| true
|
ff8a5fba8aade1fca7b947ae47af9ccca8855a87
|
Java
|
Jaludi/restapp
|
/app/src/main/java/com/example/android/restapp/restPack/ResultAdapter.java
|
UTF-8
| 2,038
| 2.46875
| 2
|
[] |
no_license
|
package com.example.android.restapp.restPack;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.example.android.restapp.R;
import java.util.ArrayList;
/**
* Created by Android on 6/7/2017.
*/
public class ResultAdapter extends BaseAdapter {
private ArrayList<ContactClass> contacts;
private Context context;
public ResultAdapter(ArrayList<ContactClass> results, Context context) {
this.contacts = results;
this.context = context;
}
@Override
public int getCount() {
return contacts.size();
}
@Override
public Object getItem(int position) {
return contacts.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.listitem, parent, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
}else{
viewHolder = (ViewHolder) convertView.getTag();
}
ContactClass currentResult = (ContactClass) getItem(position);
viewHolder.resultName.setText(currentResult.getName());
viewHolder.resultLocation.setText(currentResult.getLocation());
viewHolder.resultEmail.setText(currentResult.getEmail());
return convertView;
}
private class ViewHolder{
TextView resultName;
TextView resultEmail;
TextView resultLocation;
public ViewHolder(View view){
resultName = (TextView) view.findViewById(R.id.tv_name);
resultEmail = (TextView) view.findViewById(R.id.tv_email);
resultLocation = (TextView) view.findViewById(R.id.tv_location);
}
}
}
| true
|
645ef384c08cf76f3a5697ca3424b0b4277e33be
|
Java
|
1792507768/etl-visual
|
/code/model/com/iisquare/jwframe/service/ResourceService.java
|
UTF-8
| 5,660
| 2
| 2
|
[] |
no_license
|
package com.iisquare.jwframe.service;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.web.context.WebApplicationContext;
import com.iisquare.jwframe.Configuration;
import com.iisquare.jwframe.dao.RelationDao;
import com.iisquare.jwframe.dao.ResourceDao;
import com.iisquare.jwframe.dao.UserDao;
import com.iisquare.jwframe.mvc.ServiceBase;
import com.iisquare.jwframe.utils.DPUtil;
import com.iisquare.jwframe.utils.ServiceUtil;
@Service
@Scope("prototype")
public class ResourceService extends ServiceBase {
@Autowired
protected WebApplicationContext webApplicationContext;
@Autowired
protected Configuration configuration;
public Map<String, String> getStatusMap() {
Map<String, String> map = new LinkedHashMap<String, String>();
map.put("-1", "全部允许");
map.put("0", "全部阻止");
map.put("1", "正常验证");
return map;
}
public Set<Object> getIdSetByRoleIds(Object[] roleIdArray) {
if(DPUtil.empty(roleIdArray)) return new HashSet<>();
RelationDao dao = webApplicationContext.getBean(RelationDao.class);
List<Map<String, Object>> list = dao.where("type='role_resource' and aid in ("
+ DPUtil.implode(",", DPUtil.arrayToIntegerArray(roleIdArray)) + ")", new HashMap<>()).all();
return ServiceUtil.getFieldValues(list, "bid");
}
public Map<Object, Object> search(Map<String, Object> map, String orderBy, int page, int pageSize) {
StringBuilder condition = new StringBuilder("1=1");
Map<String, Object> params = new HashMap<String, Object>();
Object name = map.get("name");
if(!DPUtil.empty(name)) {
condition.append(" and name like :name");
params.put(":name", "%" + name + "%");
}
Object module = map.get("module");
if(!DPUtil.empty(module)) {
condition.append(" and module = :module");
params.put(":module", module);
}
Object controller = map.get("controller");
if(!DPUtil.empty(controller)) {
condition.append(" and controller = :controller");
params.put(":controller", controller);
}
Object action = map.get("action");
if(!DPUtil.empty(action)) {
condition.append(" and action = :action");
params.put(":action", action);
}
Object operation = map.get("operation");
if(!DPUtil.empty(operation)) {
condition.append(" and operation = :operation");
params.put(":operation", operation);
}
Object status = map.get("status");
if(null != status && !"".equals(status)) {
condition.append(" and status = :status");
params.put(":status", status);
}
Object description = map.get("description");
if(!DPUtil.empty(description)) {
condition.append(" and description like :description");
params.put(":description", "%" + description + "%");
}
Object timeStart = map.get("timeStart");
if(!DPUtil.empty(timeStart)) {
condition.append(" and update_time >= :timeStart");
params.put(":timeStart", DPUtil.dateTimeToMillis(timeStart, configuration.getDateTimeFormat()));
}
Object timeEnd = map.get("timeEnd");
if(!DPUtil.empty(timeEnd)) {
condition.append(" and update_time <= :timeEnd");
params.put(":timeEnd", DPUtil.dateTimeToMillis(timeEnd, configuration.getDateTimeFormat()));
}
ResourceDao dao = webApplicationContext.getBean(ResourceDao.class);
int total = dao.where(condition.toString(), params).count().intValue();
List<Map<String, Object>> rows;
if(-1 == pageSize) {
rows = dao.orderBy(orderBy).all();
} else {
rows = dao.orderBy(orderBy).page(page, pageSize).all();
}
rows = ServiceUtil.fillFields(rows, new String[]{"status"}, new Map<?, ?>[]{getStatusMap()}, null);
UserDao userDao = webApplicationContext.getBean(UserDao.class);
rows = ServiceUtil.fillRelations(rows, userDao,
new String[]{"create_uid", "update_uid"}, new String[]{"id", "username", "name"}, null);
return DPUtil.buildMap(new String[]{"total", "rows"}, new Object[]{total, rows});
}
public Map<String, Object> getInfo(Object id) {
ResourceDao dao = webApplicationContext.getBean(ResourceDao.class);
return dao.where("id = :id", ":id", id).one();
}
public Map<String, Object> getInfoByRouter(
Integer exceptId, String module, String controller, String action, String operation) {
if(null == exceptId) exceptId = 0;
ResourceDao dao = webApplicationContext.getBean(ResourceDao.class);
return dao.where("id!=:id and module=:module and controller=:controller and action=:action and operation=:operation",
":id", exceptId, ":module", module, ":controller", controller, ":action", action, ":operation", operation).one();
}
public int insert(Map<String, Object> data) {
if(DPUtil.empty(data.get("id"))) data.remove("id");
ResourceDao dao = webApplicationContext.getBean(ResourceDao.class);
return dao.insert(data).intValue();
}
public int update(Map<String, Object> data) {
ResourceDao dao = webApplicationContext.getBean(ResourceDao.class);
return dao.where("id = :id", ":id", data.get("id")).update(data).intValue();
}
public int delete(Object ...ids) {
if(DPUtil.empty(ids)) return -1;
ResourceDao dao = webApplicationContext.getBean(ResourceDao.class);
int count = dao.where("parent_id in ("
+ DPUtil.implode(",", DPUtil.arrayToIntegerArray(ids)) + ")", new HashMap<>()).count().intValue();
if(count > 0) return -2;
return dao.where("id in ("
+ DPUtil.implode(",", DPUtil.arrayToIntegerArray(ids)) + ")", new HashMap<>()).delete().intValue();
}
}
| true
|
27a15b7c98ba676b3864ce2b3a14d2b5d17d0789
|
Java
|
rohitravishankar/Year-1
|
/CSCI-605/HomeWork9/NoBlockingIO.java
|
UTF-8
| 5,225
| 3.671875
| 4
|
[] |
no_license
|
package HomeWork9;
/*
* NoBlockingIO.java
*
* Version: NoBlockingIO.java, v 1.0 2017/04/11
*
* Revisions:
* Revision 1.0 2017/04/11 08:07:05
* Initial Revision
*
*/
import java.io.*;
/**
* This class demonstrates the understanding of Thread Synchronization
*
* @author Rohit Ravishankar
* @author Parinitha Nagaraja
*
*/
public class NoBlockingIO extends Thread{
//Divide the reads based on number of threads
public static final int NUMBER_OF_THREADS = 4;
//Total even/odd count
static long totalEven = 0;
static long totalOdd = 0;
//Static object on which the block is synchronized
static Object object = new Object();
//Buffer 1 on which all the calculation happens
static byte[] finalBuffer;
//To ensure the output is sequential
static int readCount = 0;
//Creating an array of threads
NoBlockingIO threads[] = new NoBlockingIO[NUMBER_OF_THREADS];
//To mark a thread id
int id;
//Thread buffered reader
BufferedReader brr = null;
//Individual buffer for each thread
byte[] buffer;
//To have the path of the data file
static String filePath = "";
//BufferedReader object from the input
BufferedReader in;
//Each buffer size
static int bufferSize;
public NoBlockingIO() {
}
public NoBlockingIO( int id, byte[] buffer , BufferedReader in ) {
this.id = id;
this.buffer = buffer;
this.brr = in;
}
public NoBlockingIO( BufferedReader br ) {
this.in = br;
}
/**
* Initiate the process of reading
*
* @param filePath File path to read
* @param finalBuffer Buffer from the input
*
* @return No value returned
*/
public void read( String filePath ) throws IOException {
//File object with argument as a filePath
File file = new File( filePath );
//Calculating length to decide which part should each thread take
int size = (int) file.length();
this.filePath = filePath;
//Calculate the buffer size
bufferSize = size/NUMBER_OF_THREADS;
//Create a buffer for a thread
byte[] inbuffer = new byte[bufferSize];
//Allowing the final buffer to be available globally
finalBuffer = new byte[bufferSize];
//The first thread read should be blocking
threads[0] = new NoBlockingIO( 0, inbuffer , in );
threads[0].start();
}
/**
* Simulation of no blocking IO
*
* @return No value returned
*/
public void run() {
//The thread is reading
try {
read1( id );
} catch (IOException e1) {
e1.printStackTrace();
}
//If the first thread, spawn multiple threads
if (id == 0) {
for ( int i = 1; i < NUMBER_OF_THREADS; i++) {
byte[] inbuffer = new byte[bufferSize];
threads[i] = new NoBlockingIO( i, inbuffer , brr );
threads[i].start();
}
}
//Synchronized on object for processing the data sequentially
synchronized ( object ) {
//Describes the thread which has finished reading
System.out.println( id + " has finished reading. ");
//To ensure that the thread data is processed sequentially
while ( readCount != id ) {
System.out.println( id + " is waiting to process the data. ");
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//To ensure that the thread data is processed sequentially
if( readCount == id ) {
System.out.println( id + " is being processed.");
System.arraycopy( this.buffer , 0, finalBuffer, 0, this.buffer.length );
++readCount;
countEvenOdd( finalBuffer );
object.notifyAll();
}
//If all the threads have been processed print the result
if( readCount == NUMBER_OF_THREADS ) {
//Print the result
System.out.println( "even: " + totalEven );
System.out.println( "odd: " + totalOdd );
double result = (double) totalOdd/totalEven;
System.out.println( "odd/even: " + result );
}
}
}
/**
* Read different parts of the file from threads
*
* @param id Thread number
*
* @return No return value
*
* @throws IOException If file is not found
*/
public void read1( int id ) throws IOException {
RandomAccessFile randomFile = new RandomAccessFile( filePath, "r");
long offset = bufferSize * id;
randomFile.seek( offset );
try {
randomFile.read( buffer );
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* To count even/odd occurances within input file
*
* @param inputBuffer The input buffer to calculate even/odd digits
*
* @return No returned value
*/
private void countEvenOdd( byte[] inputBuffer ) {
//Convert input buffer into a string of characters
String characters = new String( inputBuffer );
//Iterating over the entire length of the string
for( int i = 0; i < characters.length(); i++ ) {
char character = characters.charAt(i);
//Check if the character encountered is a digit or not
if( Character.isDigit( character ) ) {
int digit = Integer.parseInt(String.valueOf( character ));
if ( digit == 0 || digit % 2 == 0 )
++totalEven;
else
++totalOdd;
}
}
System.out.println("EVEN COUNT: " + " thread id: " + id + " count: " + totalEven );
System.out.println("ODD COUNT: " + " thread id: " + id + " " + totalOdd );
}
}
| true
|
b1a5f4232203ad2b73c5f35866ed5e13d841e8ff
|
Java
|
aQuaNice/ClientMaster
|
/src/main/java/com/andana/Model/MenuHeader.java
|
UTF-8
| 1,364
| 2.15625
| 2
|
[] |
no_license
|
package com.andana.Model;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name = "tbm_h_menu")
public class MenuHeader {
private Long id;
private String desc;
private String url;
private String icon;
private int stat;
// private Set<MenuDetail> menuDetail;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public int getStat() {
return stat;
}
public void setStat(int stat) {
this.stat = stat;
}
// @OneToMany(mappedBy = "menuHeader", cascade = CascadeType.ALL, fetch=FetchType.LAZY)
// public Set<MenuDetail> getMenuDetail() {
// return menuDetail;
// }
// public void setMenuDetail(Set<MenuDetail> menuDetail) {
// this.menuDetail = menuDetail;
// }
}
| true
|
6846ba98779b2f492a3e61f34098cb8378b8fcc6
|
Java
|
Tio304/12prog
|
/src/pkg12prog/calculator.java
|
UTF-8
| 3,833
| 3.25
| 3
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pkg12prog;
import java.util.Scanner;
import static pkg12prog.Main.hitung;
/**
*
* @author H4NS
*/
public class calculator {
public static int Plus(int a , int b){
int c = a + b;
return c;
}
public static int Minus(int a, int b){
int c = a-b;
return c;
}
public static int Mixed(int a , int b){
int c = a*b;
return c;
}
public static double Divide(double a , double b){
double c = a / b;
return c;
}
public static int Lefted(int a, int b ){
if (a>b){
System.out.println("hasil Sisa Bagi Adlah : "+ (a%b));
}else if (a<b){
System.out.println("Hasil tidak ditemukan");
System.out.println("\n************************");
}
return 0;
}
public static void main(String[]args)
{System.out.println("=========================================== PROGRAM CALCULATOR ===========================================");
Scanner input = new Scanner(System.in);
int x;
int bill;
System.out.println("\n============= Masukkan angka ynag Plus di Inginkan =============");
bill = input.nextInt();
System.out.println("\n ===========Masukkan angka Plus ynag di Inginkan ==========" );
int bil2 =input.nextInt();
x = Plus(bill,bil2);
System.out.println("Hasil : " +x + " Hasil Plus");
System.out.println("\n******************************");
int a;
System.out.println("\n ========== Masukkan angka Minus ynag di Inginkan =========== ");
int bil3 =input.nextInt();
System.out.println("\n ========= Masukkan angka Minus ynag di Inginkan =========");
int bil4 = input.nextInt();
a = Minus(bil3,bil4);
System.out.println("Hasil : " + a+ " Hasil Minus");
System.out.println("\n********************************");
int b;
System.out.println("\n ============= Masukkan angka Mixed ynag di Inginkan =============" );
int bil5=input.nextInt();
System.out.println("\n ============ Masukkan angka Mixed ynag di Inginkan ============" );
int bil6= input.nextInt();
b = Mixed(bil5,bil6);
System.out.println("HAsil : " + b+ " Hasil Mixed");
System.out.println("\n********************************");
double c ;
System.out.println("\n ============== Masukkan angka Divided ynag di Inginkan ============" );
double bil7=input.nextInt();
System.out.println("\n ============= Masukkan angka Divided ynag di Inginkan ===========" );
double bil8=input.nextInt();
c = Divide(bil7,bil8);
System.out.println("Hasil : " + c+ " Hasil Divide");
System.out.println("\n***********************************************");
int d;
System.out.println("\n =========== Masukkan angka Lefted ynag di Inginkan ==========" );
int bil9=input.nextInt();
System.out.println("\n ============== Masukkan angka Lefted ynag di Inginkan ================ " );
int bil0 =input.nextInt();
d = Lefted(bil9,bil0);
System.out.println("***************************************");
}
}
| true
|
ea8d4b7ede9efba79244a2d79563a9e48bc2b015
|
Java
|
apache/sirona
|
/plugins/hazelcast/agent/src/main/java/org/apache/sirona/plugin/hazelcast/agent/HazelcastGaugeFactory.java
|
UTF-8
| 3,208
| 2.078125
| 2
|
[
"BSD-3-Clause",
"MIT",
"Apache-2.0",
"CC-BY-3.0",
"LicenseRef-scancode-proprietary-license"
] |
permissive
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.sirona.plugin.hazelcast.agent;
import com.hazelcast.core.HazelcastInstance;
import org.apache.sirona.configuration.Configuration;
import org.apache.sirona.configuration.ioc.Destroying;
import org.apache.sirona.configuration.ioc.IoCs;
import org.apache.sirona.gauges.Gauge;
import org.apache.sirona.gauges.GaugeFactory;
import org.apache.sirona.plugin.hazelcast.agent.gauge.HazelcastMembersGauge;
import org.apache.sirona.plugin.hazelcast.agent.gauge.HazelcastPartitionsGauge;
import org.apache.sirona.plugin.hazelcast.agent.instance.HazelcastClientFactory;
import org.apache.sirona.plugin.hazelcast.agent.instance.HazelcastMemberFactory;
import java.util.Collection;
import java.util.LinkedList;
public class HazelcastGaugeFactory implements GaugeFactory {
@Override
public Gauge[] gauges() {
final String instances = Configuration.getProperty(Configuration.CONFIG_PROPERTY_PREFIX + "hazelcast.clusters", "");
if (instances.isEmpty()) {
return null;
}
final Collection<Gauge> gauges = new LinkedList<Gauge>();
for (final String instance : instances.split(",")) {
final String trimmed = instance.trim();
final HazelcastInstance hzInstance;
final String prefix = Configuration.CONFIG_PROPERTY_PREFIX + "hazelcast." + trimmed + ".";
if (Configuration.is(prefix + "client", true)) {
hzInstance = HazelcastClientFactory.newClient(prefix);
} else {
hzInstance = HazelcastMemberFactory.newMember(trimmed, prefix);
}
IoCs.processInstance(new DestroyInstance(hzInstance)); // ensure to shutdown
addGauges(gauges, trimmed, hzInstance);
}
return gauges.toArray(new Gauge[gauges.size()]);
}
private void addGauges(final Collection<Gauge> gauges, final String name, final HazelcastInstance hzInstance) {
gauges.add(new HazelcastMembersGauge(name, hzInstance));
gauges.add(new HazelcastPartitionsGauge(name, hzInstance));
}
private static class DestroyInstance {
private final HazelcastInstance instance;
public DestroyInstance(final HazelcastInstance instance) {
this.instance = instance;
}
@Destroying
public void destroy() {
instance.getLifecycleService().shutdown();
}
}
}
| true
|
af917e2eed630eca6835bf053136d07f509cb8b6
|
Java
|
radufurculesteanu/JavaDocs
|
/JDBC/Code/JDBCApp/src/main/java/ro/teamnet/zth/api/em/EmployeeManager.java
|
UTF-8
| 2,347
| 2.78125
| 3
|
[] |
no_license
|
package ro.teamnet.zth.api.em;
import ro.teamnet.zth.api.database.DBManager;
import ro.teamnet.zth.appl.domain.Employee;
import javax.swing.plaf.nimbus.State;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Radu.Furculesteanu on 7/14/2017.
*/
public class EmployeeManager {
public List<Employee> findEmpByDept(Class<Employee> employeeClass, String string)
{
try
{
Connection con = DBManager.getConnection();
String tableName = EntityUtils.getTableName(employeeClass);
List<ColumnInfo> columnList = EntityUtils.getColumns(employeeClass);
String sql = new String("select * from " + tableName + " where department_id in (select department_id from " +
"departments where lower(department_name) like '%" + string + "%')");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
ArrayList<Employee> employeeList = new ArrayList<Employee>();
while(rs.next())
{
Employee emp = employeeClass.newInstance();
for (ColumnInfo column : columnList)
{
Field field = emp.getClass().getDeclaredField(column.getColumnName());
field.setAccessible(true);
field.set(emp,EntityUtils.castFromSqlType(rs.getObject(column.getDbColumnName()),field.getType()));
}
employeeList.add(emp);
}
return employeeList;
}
catch (SQLException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
EmployeeManager employeeManager = new EmployeeManager();
List<Employee> employeeList = employeeManager.findEmpByDept(Employee.class,"co");
for (Employee employee : employeeList) {
System.out.println(employee);
}
}
}
| true
|
40e204ca22fd40d78c5ccc4844b3ab6404e36bf7
|
Java
|
thushear/solr1
|
/src/org/apache/solr/request/SimpleFacets.java
|
UTF-8
| 10,650
| 1.96875
| 2
|
[] |
no_license
|
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.solr.request;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TermEnum;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.search.*;
import org.apache.solr.core.SolrCore;
import org.apache.solr.core.SolrException;
import org.apache.solr.request.SolrParams;
import org.apache.solr.schema.IndexSchema;
import org.apache.solr.schema.FieldType;
import org.apache.solr.schema.SchemaField;
import org.apache.solr.schema.BoolField;
import org.apache.solr.search.*;
import org.apache.solr.util.NamedList;
import org.apache.solr.util.BoundedTreeSet;
import java.io.IOException;
import java.util.*;
/**
* A class that generates simple Facet information for a request.
*
* More advanced facet implementations may compose or subclass this class
* to leverage any of it's functionality.
*/
public class SimpleFacets {
/** The main set of documents all facet counts should be relative to */
protected DocSet docs;
/** Configuration params behavior should be driven by */
protected SolrParams params;
/** Searcher to use for all calculations */
protected SolrIndexSearcher searcher;
public SimpleFacets(SolrIndexSearcher searcher,
DocSet docs,
SolrParams params) {
this.searcher = searcher;
this.docs = docs;
this.params = params;
}
/**
* Looks at various Params to determing if any simple Facet Constraint count
* computations are desired.
*
* @see #getFacetQueryCounts
* @see #getFacetFieldCounts
* @see SolrParams#FACET
* @return a NamedList of Facet Count info or null
*/
public NamedList getFacetCounts() {
// if someone called this method, benefit of the doubt: assume true
if (!params.getBool(params.FACET,true))
return null;
NamedList res = new NamedList();
try {
res.add("facet_queries", getFacetQueryCounts());
res.add("facet_fields", getFacetFieldCounts());
} catch (Exception e) {
SolrException.logOnce(SolrCore.log, "Exception during facet counts", e);
res.add("exception", SolrException.toStr(e));
}
return res;
}
/**
* Returns a list of facet counts for each of the facet queries
* specified in the params
*
* @see SolrParams#FACET_QUERY
*/
public NamedList getFacetQueryCounts() throws IOException,ParseException {
NamedList res = new NamedList();
/* Ignore SolrParams.DF - could have init param facet.query assuming
* the schema default with query param DF intented to only affect Q.
* If user doesn't want schema default for facet.query, they should be
* explicit.
*/
SolrQueryParser qp = new SolrQueryParser(searcher.getSchema(),null);
String[] facetQs = params.getParams(SolrParams.FACET_QUERY);
if (null != facetQs && 0 != facetQs.length) {
for (String q : facetQs) {
res.add(q, searcher.numDocs(qp.parse(q), docs));
}
}
return res;
}
public NamedList getTermCounts(String field) throws IOException {
int limit = params.getFieldInt(field, params.FACET_LIMIT, 100);
boolean zeros = params.getFieldBool(field, params.FACET_ZEROS, true);
boolean missing = params.getFieldBool(field, params.FACET_MISSING, false);
NamedList counts;
SchemaField sf = searcher.getSchema().getField(field);
FieldType ft = sf.getType();
if (sf.multiValued() || ft.isTokenized() || ft instanceof BoolField) {
// Always use filters for booleans... we know the number of values is very small.
counts = getFacetTermEnumCounts(searcher,docs,field,limit,zeros,missing);
} else {
// TODO: future logic could use filters instead of the fieldcache if
// the number of terms in the field is small enough.
counts = getFieldCacheCounts(searcher, docs, field, limit, zeros, missing);
}
return counts;
}
/**
* Returns a list of value constraints and the associated facet counts
* for each facet field specified in the params.
*
* @see SolrParams#FACET_FIELD
* @see #getFieldMissingCount
* @see #getFacetTermEnumCounts
*/
public NamedList getFacetFieldCounts()
throws IOException {
NamedList res = new NamedList();
String[] facetFs = params.getParams(SolrParams.FACET_FIELD);
if (null != facetFs) {
for (String f : facetFs) {
res.add(f, getTermCounts(f));
}
}
return res;
}
/**
* Returns a count of the documents in the set which do not have any
* terms for for the specified field.
*
* @see SolrParams#FACET_MISSING
*/
public static int getFieldMissingCount(SolrIndexSearcher searcher, DocSet docs, String fieldName)
throws IOException {
DocSet hasVal = searcher.getDocSet
(new ConstantScoreRangeQuery(fieldName, null, null, false, false));
return docs.andNotSize(hasVal);
}
/**
* Use the Lucene FieldCache to get counts for each unique field value in <code>docs</code>.
* The field must have at most one indexed token per document.
*/
public static NamedList getFieldCacheCounts(SolrIndexSearcher searcher, DocSet docs, String fieldName, int limit, boolean zeros, boolean missing) throws IOException {
// TODO: If the number of terms is high compared to docs.size(), and zeros==false,
// we should use an alternate strategy to avoid
// 1) creating another huge int[] for the counts
// 2) looping over that huge int[] looking for the rare non-zeros.
//
// Yet another variation: if docs.size() is small and termvectors are stored,
// then use them instead of the FieldCache.
//
FieldCache.StringIndex si = FieldCache.DEFAULT.getStringIndex(searcher.getReader(), fieldName);
int[] count = new int[si.lookup.length];
DocIterator iter = docs.iterator();
while (iter.hasNext()) {
count[si.order[iter.nextDoc()]]++;
}
FieldType ft = searcher.getSchema().getFieldType(fieldName);
NamedList res = new NamedList();
// IDEA: we could also maintain a count of "other"... everything that fell outside
// of the top 'N'
BoundedTreeSet<CountPair<String,Integer>> queue=null;
if (limit>=0) {
// TODO: compare performance of BoundedTreeSet compare against priority queue?
queue = new BoundedTreeSet<CountPair<String,Integer>>(limit);
}
int min=-1; // the smallest value in the top 'N' values
for (int i=1; i<count.length; i++) {
int c = count[i];
if (c==0 && !zeros) continue;
if (limit<0) {
res.add(ft.indexedToReadable(si.lookup[i]), c);
} else if (c>min) {
// NOTE: we use c>min rather than c>=min as an optimization because we are going in
// index order, so we already know that the keys are ordered. This can be very
// important if a lot of the counts are repeated (like zero counts would be).
queue.add(new CountPair<String,Integer>(ft.indexedToReadable(si.lookup[i]), c));
if (queue.size()>=limit) min=queue.last().val;
}
}
if (limit>=0) {
for (CountPair<String,Integer> p : queue) {
res.add(p.key, p.val);
}
}
if (missing) res.add(null, count[0]);
return res;
}
/**
* Returns a list of terms in the specified field along with the
* corrisponding count of documents in the set that match that constraint.
* This method uses the FilterCache to get the intersection count between <code>docs</code>
* and the DocSet for each term in the filter.
*
* @see SolrParams#FACET_LIMIT
* @see SolrParams#FACET_ZEROS
* @see SolrParams#FACET_MISSING
*/
public NamedList getFacetTermEnumCounts(SolrIndexSearcher searcher, DocSet docs, String field, int limit, boolean zeros, boolean missing)
throws IOException {
/* :TODO: potential optimization...
* cache the Terms with the highest docFreq and try them first
* don't enum if we get our max from them
*/
IndexSchema schema = searcher.getSchema();
IndexReader r = searcher.getReader();
FieldType ft = schema.getFieldType(field);
Set<CountPair<String,Integer>> counts
= new HashSet<CountPair<String,Integer>>();
if (0 <= limit) {
counts = new BoundedTreeSet<CountPair<String,Integer>>(limit);
}
TermEnum te = r.terms(new Term(field,""));
do {
Term t = te.term();
if (null == t || ! t.field().equals(field))
break;
if (0 < te.docFreq()) { /* all docs may be deleted */
int count = searcher.numDocs(new TermQuery(t),
docs);
if (zeros || 0 < count)
counts.add(new CountPair<String,Integer>
(t.text(), count));
}
} while (te.next());
NamedList res = new NamedList();
for (CountPair<String,Integer> p : counts) {
res.add(ft.indexedToReadable(p.key), p.val);
}
if (missing) {
res.add(null, getFieldMissingCount(searcher,docs,field));
}
return res;
}
/**
* A simple key=>val pair whose natural order is such that
* <b>higher</b> vals come before lower vals.
* In case of tie vals, then <b>lower</b> keys come before higher keys.
*/
public static class CountPair<K extends Comparable<? super K>, V extends Comparable<? super V>>
implements Comparable<CountPair<K,V>> {
public CountPair(K k, V v) {
key = k; val = v;
}
public K key;
public V val;
public int hashCode() {
return key.hashCode() ^ val.hashCode();
}
public boolean equals(Object o) {
return (o instanceof CountPair)
&& (0 == this.compareTo((CountPair<K,V>) o));
}
public int compareTo(CountPair<K,V> o) {
int vc = o.val.compareTo(val);
return (0 != vc ? vc : key.compareTo(o.key));
}
}
}
| true
|
8857640d4d01defd4b983fa948a8506efe888f2b
|
Java
|
rdayton/stockparser
|
/src/test/java/pages/StockPage.java
|
UTF-8
| 4,898
| 2.671875
| 3
|
[] |
no_license
|
package pages;
import cucumber.api.java.an.E;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import tests.TestRunner;
public class StockPage {
private String url;
private static WebDriver driver;
private Double currentPrice;
private final String STOCK_URL = "https://finance.yahoo.com/";
private Double highestPrice;
private Double lowestPrice;
private Double earningsPerShare;
private String symbol;
private WebElement searchBox;
public StockPage(String symbol) {
this.symbol = symbol;
this.driver = TestRunner.driver;
}
public void openBrowser(){
//driver = new ChromeDriver();
driver.manage().window().maximize();
}
public void goToHomePage(){
driver.get(STOCK_URL);
}
public String getUrl(){
return driver.getCurrentUrl();
}
public String getSymbol(){
return symbol;
}
public void searchForStock(){
final String searchSelector = "#fin-srch-assist > input";
WebElement searchBox = new WebDriverWait(driver, 15)
.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(searchSelector)));
searchBox.sendKeys(symbol);
//prevent search from starting before all keys are entered
//TODO: Find better way to wait for exact text
WebDriverWait keysEntered = new WebDriverWait(driver, 10);
keysEntered.until(ExpectedConditions.textToBePresentInElementValue( By.cssSelector(searchSelector), symbol));
searchBox.submit();
}
public void setCurrentPrice(){
final String priceXpath = "//*[@id=\"quote-header-info\"]/div[3]/div[1]/div/span[1]";
WebElement price = new WebDriverWait(driver, 10)
.until(ExpectedConditions.presenceOfElementLocated(By.xpath(priceXpath)));
//data can briefly appear as N/A, so wait until it is not N/A to get the current price
WebDriverWait waitForData = new WebDriverWait(driver, 5);
//use xpath because element may have been replaced in the DOM when it was updated
waitForData.until(ExpectedConditions.not(ExpectedConditions.textToBePresentInElementLocated(By.xpath(priceXpath), "N/A")));
currentPrice = Double.parseDouble(price.getText().replaceAll(",", ""));
}
public Double getCurrentPrice(){
return currentPrice;
}
public void setHighAndLowForYear(){
final String priceRangeXpath = "//*[@id=\"quote-summary\"]/div[1]/table/tbody/tr[6]/td[2]";
WebElement priceRangeElement = new WebDriverWait(driver, 10)
.until(ExpectedConditions.presenceOfElementLocated(By.xpath(priceRangeXpath)));
//data can briefly appear as N/A, so wait until it is not N/A to get the current price
WebDriverWait waitForData = new WebDriverWait(driver, 5);
//use xpath because element may have been replaced in the DOM when it was updated
waitForData.until(ExpectedConditions.not(ExpectedConditions.textToBePresentInElementLocated(By.xpath(priceRangeXpath), "N/A")));
String prices = priceRangeElement.getText();
int mid = prices.indexOf("-");
lowestPrice = Double.parseDouble(prices.substring(0, mid-1).replaceAll(",", ""));
highestPrice = Double.parseDouble(prices.substring(mid+1, prices.length()).replaceAll(",", ""));
}
public Double getHigh(){
return highestPrice;
}
public Double getLow(){
return lowestPrice;
}
public Integer calculatePercentBelowHigh(){
int percent = (int) Math.rint((highestPrice-currentPrice) / highestPrice * 100);
//percent.intValue();
return percent;
}
public Integer calculatePercentAboveLow(){
int percent = (int) Math.rint((currentPrice-lowestPrice) / lowestPrice * 100);
return percent;
}
public Double setEarningsPerShare(){
final String epsXpath = "//*[@id=\"quote-summary\"]/div[2]/table/tbody/tr[4]/td[2]/span";
WebElement epsElement = new WebDriverWait(driver,10)
.until(ExpectedConditions.presenceOfElementLocated(
By.xpath("//*[@id=\"quote-summary\"]/div[2]/table/tbody/tr[4]/td[2]/span")));
//data can briefly appear as N/A, so wait until it is not N/A to get the current price
WebDriverWait waitForData = new WebDriverWait(driver, 5);
//use xpath because element may have been replaced in the DOM when it was updated
waitForData.until(ExpectedConditions.not(ExpectedConditions.textToBePresentInElementLocated(By.xpath(epsXpath), "N/A")));
earningsPerShare = Double.parseDouble(epsElement.getText());
return earningsPerShare;
}
public Double getEarningsPerShare(){
return earningsPerShare;
}
}
| true
|
011046656095f17f6e5e92b30f4214fb2778850a
|
Java
|
onyas/leetcode
|
/src/main/java/com/onyas/leetcode/P027RemoveElement.java
|
UTF-8
| 593
| 3.375
| 3
|
[] |
no_license
|
package com.onyas.leetcode;
/**
* Given an array and a value, remove all instances of that value in place and return the new length.
* The order of elements can be changed. It doesn't matter what you leave beyond the new length.
* <p/>
* Created by IntelliJ IDEA
* User: zhenglinlin
* Date: 15/11/5
* Time: 上午10:22
*/
public class P027RemoveElement {
public int removeElement(int[] nums, int val) {
int j=0;
for(int i=0;i<nums.length;i++){
if(nums[i]!=val){
nums[j++] = nums[i];
}
}
return j;
}
}
| true
|
6a5d13ab77430accfd395163a0969d3416982656
|
Java
|
reggiej/TA_ICE_Dlittle
|
/ta_ice/lib/toplink-src/oracle/toplink/ox/mappings/nullpolicy/IsSetNullPolicy.java
|
UTF-8
| 7,145
| 2.140625
| 2
|
[] |
no_license
|
// Copyright (c) 1998, 2007, Oracle. All rights reserved.
package oracle.toplink.ox.mappings.nullpolicy;
import java.lang.reflect.Method;
import oracle.toplink.internal.ox.NillableNodeValue;
import oracle.toplink.internal.ox.NodeValue;
import oracle.toplink.internal.ox.NullCapableValue;
import oracle.toplink.internal.ox.OptionalNodeValue;
import oracle.toplink.internal.ox.XPathFragment;
import oracle.toplink.internal.ox.XPathNode;
import oracle.toplink.internal.security.PrivilegedGetMethod;
import oracle.toplink.internal.security.PrivilegedMethodInvoker;
import oracle.toplink.ox.NamespaceResolver;
import oracle.toplink.ox.XMLConstants;
import oracle.toplink.ox.XMLField;
import oracle.toplink.ox.record.MarshalRecord;
import oracle.toplink.ox.record.XMLRecord;
import oracle.toplink.sessions.Session;
/**
* PUBLIC:
* <b>Description</b>:
* This null policy allows for various configurations of isSet behavior to be set.<br>
* Marshal:<br>
* The boolean value of the isSet() state of a node will determine whether a node will be written out
* for a null value.
* Unmarshal:<br>
*
* <p><b>The following instance fields can be set</b>:<ul>
* <li>isSetMethodName: </li>
* <li>isSetParameterTypes: </li>
* <li>isSetParameters: </li>
* </ul>
* <p>
* <b>Usage</b>:<br>
* <ul>
* <li> Set to a non-null value</li><br/>IsSet==true, value=value
* <li> Not set</li><br/>isSet=false, value=null
* <li> Set to null value </li><br/>isSet=true, value=null
* <li> Set to default value </li><br/>isSet=false, value=default
* </ul>
*
* @see oracle.toplink.internal.ox.NullCapableValue
* @since Oracle TopLink 11<i>g</i> Release 1 (11.1.1)
*/
public class IsSetNullPolicy extends AbstractNullPolicy {
private static final Class[] PARAMETER_TYPES = {};
private static final Object[] PARAMETERS = {};
private String isSetMethodName;
private Class[] isSetParameterTypes = PARAMETER_TYPES;
private Object[] isSetParameters = PARAMETERS;
/**
* Default Constructor
* Set the IsSetPerformedForAbsentNode to false to enable the other 2 flags
* isNullRepresentedByEmptyNode and isNullRepresentedByXsiNil
*/
public IsSetNullPolicy() {
super();
isSetPerformedForAbsentNode = false;
}
/**
* Specific Constructor to set the name for checking the isSet state of the mapping
* @param anIsSetMethodName
*/
public IsSetNullPolicy(String anIsSetMethodName) {
this();
setIsSetMethodName(anIsSetMethodName);
}
/**
* Specific Constructor to set both the Marshal enum and the Unmarshal flags.
* @param anIsSetMethodName
* @param bIsNullRepresentedByEmptyNode
* @param bIsNullRepresentedByXsiNil
* @param aMarshalNullRepresentation
*/
public IsSetNullPolicy(String anIsSetMethodName, //
boolean bIsNullRepresentedByEmptyNode, boolean bIsNullRepresentedByXsiNil, //
XMLNullRepresentationType aMarshalNullRepresentation) {
this(anIsSetMethodName);
setNullRepresentedByEmptyNode(bIsNullRepresentedByEmptyNode);
setNullRepresentedByXsiNil(bIsNullRepresentedByXsiNil);
setMarshalNullRepresentation(aMarshalNullRepresentation);
}
public boolean directMarshal(XPathFragment xPathFragment, MarshalRecord marshalRecord, //
Object object, Session session, NamespaceResolver namespaceResolver) {
// Do nothing when the value is not set or we are marshaling as ABSENT_NODE (optional)
if(!isSet(object)) {
return false;
} else {
return super.directMarshal(xPathFragment, marshalRecord, object, session, namespaceResolver);
}
}
public boolean compositeObjectMarshal(XPathFragment xPathFragment, MarshalRecord marshalRecord, //
Object object, Session session, NamespaceResolver namespaceResolver) {
// Do nothing when the value is not set or we are marshaling as ABSENT_NODE (optional)
if(!isSet(object)) {
return false;
} else {
return super.compositeObjectMarshal(xPathFragment, marshalRecord, object, session, namespaceResolver);
}
}
public boolean compositeObjectMarshal(XMLRecord record, Object object, XMLField field) {
if(!isSet(object)) {
return false;
} else {
return super.compositeObjectMarshal(record, object, field);
}
}
public void xPathNode(XPathNode xPathNode, NullCapableValue nullCapableValue) {
// isset optional only
if(!(isNullRepresentedByXsiNil() || getMarshalNullRepresentation().equals(XMLNullRepresentationType.XSI_NIL))) {
if(xPathNode.getXPathFragment().isAttribute()) {
return;
}
}
// get the parent above the text() node
XPathNode parentNode = xPathNode.getParent();
// isset nillable only
if(isNullRepresentedByXsiNil() || getMarshalNullRepresentation().equals(XMLNullRepresentationType.XSI_NIL)) {
XPathFragment xPathFragment = new XPathFragment();
xPathFragment.setXPath('@' + XMLConstants.SCHEMA_NIL_ATTRIBUTE);
xPathFragment.setNamespaceURI(XMLConstants.SCHEMA_INSTANCE_URL);
NodeValue aNodeValue = new NillableNodeValue(nullCapableValue);
parentNode.addChild(xPathFragment, aNodeValue, null);
} else {
NodeValue aNodeValue = new OptionalNodeValue(nullCapableValue);
parentNode.setNodeValue(aNodeValue);
}
}
/**
* INTERNAL:
* Indicates if a null value has been set or not.
* @param object
* @return boolean (isSet status)
*/
private boolean isSet(Object object) {
Boolean isSet;
try {
Class objectClass = object.getClass();
PrivilegedGetMethod privilegedGetMethod = new PrivilegedGetMethod(objectClass, getIsSetMethodName(), getIsSetParameterTypes(), false);
Method isSetMethod = (Method) privilegedGetMethod.run();
PrivilegedMethodInvoker privilegedMethodInvoker = new PrivilegedMethodInvoker(isSetMethod, object, isSetParameters);
isSet = (Boolean) privilegedMethodInvoker.run();
} catch(Exception e) {
throw new RuntimeException(e);
}
return isSet.booleanValue();
}
/**
*
* @return
*/
public String getIsSetMethodName() {
return isSetMethodName;
}
/**
*
* @param isSetMethodName
*/
public void setIsSetMethodName(String anIsSetMethodName) {
isSetMethodName = anIsSetMethodName;
}
/**
*
* @return
*/
public Class[] getIsSetParameterTypes() {
return isSetParameterTypes;
}
/**
*
* @param parameterTypes
*/
public void setIsSetParameterTypes(Class[] parameterTypes) {
isSetParameterTypes = parameterTypes;
}
/**
*
* @return
*/
public Object[] getIsSetParameters() {
return isSetParameters;
}
/**
*
* @param parameters
*/
public void setIsSetParameters(Object[] parameters) {
isSetParameters = parameters;
}
}
| true
|
82edc2f00ede8112cd8dc8207cdf08dadfe31302
|
Java
|
easy-develop/core-utils
|
/src/test/java/com/easy/core/utils/StringsUtilTest.java
|
UTF-8
| 385
| 2.28125
| 2
|
[
"MIT"
] |
permissive
|
package com.easy.core.utils;
import org.junit.Test;
import static org.junit.Assert.*;
public class StringsUtilTest {
@Test
public void canNormalizeWhitespace(){
String text = "This contains some whitespaces ";
assertEquals("Cannot normalize whitespaces", "This contains some whitespaces", StringsUtil.getWhitespaceNormalized(text));
}
}
| true
|
bc0daa8b11deab59ce780f3bef511717541565e6
|
Java
|
livinglh/leetcode_record
|
/src/笔试题/广联达7_29/Main.java
|
UTF-8
| 649
| 2.953125
| 3
|
[] |
no_license
|
package 笔试题.广联达7_29;
import java.util.PriorityQueue;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int x = sc.nextInt();
PriorityQueue<Integer> minheap = new PriorityQueue<>();
for (int i = 0; i < n; i++) {
minheap.offer(sc.nextInt());
}
for (int i = 0; i < m; i++) {
int curmin = minheap.poll();
curmin += x;
minheap.offer(curmin);
}
System.out.println(minheap.peek());
}
}
| true
|
95831c120209ecd73252ab475e25d3e76ed307c8
|
Java
|
chenmingang/dubbo-tx
|
/txTest11/src/test/java/tx/ProviderServiceTest.java
|
UTF-8
| 1,400
| 2.25
| 2
|
[] |
no_license
|
package tx;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created by zeal on 17-8-8.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:/META-INF/spring/*.xml")
public class ProviderServiceTest {
@Autowired
ProviderService providerService;
private static ExecutorService threadPool = Executors.newFixedThreadPool(10);
@Test
public void te(){
// providerService.hello("s");
for (int i = 1; i <= 20; i++) {
final int index = i;
threadPool.execute(new Runnable() {
@Override
public void run() {
String threadName = Thread.currentThread().getName();
System.out.println("线程:" + threadName + ",正在执行第" + index + "个任务");
try {
long time = index * 500;
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
}
| true
|
c07d7d8e5b85432f5e18893e837c89d18aab84ad
|
Java
|
dzy-713/ssm-demo
|
/src/main/java/com/rl/mes/pojo/PickData.java
|
UTF-8
| 669
| 2.125
| 2
|
[] |
no_license
|
package com.rl.mes.pojo;
/**
*/
public class PickData {
private static final long serialVersionUID = 1L;
/**
* 类型
*/
String type;
/**
* 条码
*/
String barcode;
/**
* 汇总数量
*/
Integer qty;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getBarcode() {
return barcode;
}
public void setBarcode(String barcode) {
this.barcode = barcode;
}
public Integer getQty() {
return qty;
}
public void setQty(Integer qty) {
this.qty = qty;
}
}
| true
|
04f8d16670a4b6fef08eadcfe8b34af2c15f2a18
|
Java
|
thatnerd2/Algorithms-Data-Structures
|
/algos/src/dp/MaxValueContigSeq.java
|
UTF-8
| 981
| 4
| 4
|
[] |
no_license
|
package dp;
public class MaxValueContigSeq {
public static void main (String [] args) {
/*
* Problem: Find subsequence of consecutive numbers that have maximized sum
*
* Success!
*/
int[] in = {1, 2, 3, 5, 6, 7};
int ans = solve(in);
System.out.println("Answer: " + ans);
}
public static int solve (int[] set) {
int[] states = new int[set.length];
/* Init states to be just the number in set, sequence of 1 */
for (int i = 0; i < states.length; i++) {
states[i] = set[i];
}
for (int i = 0; i < states.length; i++) {
for (int j = 0; j < i; j++) {
if (set[i] - set[j] == 1 && states[j] + set[i] > states[i]) {
states[i] = states[j] + set[i];
System.out.println("Set states[" + i + "] to " + states[i]);
}
}
}
return maxOf(states);
}
public static int maxOf (int[] a) {
int max = 0;
for (int b : a ) {
max = Math.max(b, max);
}
return max;
}
}
| true
|
ca784645210da86d207b65fd1b08306c7e3ce9d9
|
Java
|
CrackerCat/XiaomiFramework
|
/mi2s_securitycenter_miui12/src/main/java/androidx/appcompat/app/C0084f.java
|
UTF-8
| 776
| 1.828125
| 2
|
[] |
no_license
|
package androidx.appcompat.app;
import android.view.View;
/* renamed from: androidx.appcompat.app.f reason: case insensitive filesystem */
class C0084f implements Runnable {
/* renamed from: a reason: collision with root package name */
final /* synthetic */ View f300a;
/* renamed from: b reason: collision with root package name */
final /* synthetic */ View f301b;
/* renamed from: c reason: collision with root package name */
final /* synthetic */ AlertController f302c;
C0084f(AlertController alertController, View view, View view2) {
this.f302c = alertController;
this.f300a = view;
this.f301b = view2;
}
public void run() {
AlertController.a(this.f302c.g, this.f300a, this.f301b);
}
}
| true
|
0d120fd90cb17ff14fc06fa61042ee03fcc0d3a8
|
Java
|
seamus-zou/ideal-flume
|
/src/main/java/com/ideal/flume/io/BucketWriter.java
|
UTF-8
| 13,580
| 2.21875
| 2
|
[] |
no_license
|
package com.ideal.flume.io;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import com.google.common.base.Throwables;
import com.ideal.flume.clients.CollectClient;
import com.ideal.flume.tools.HostnameUtils;
import com.ideal.flume.tools.PidUtils;
import org.apache.flume.Event;
import org.apache.flume.FlumeException;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class BucketWriter {
private static final Logger LOG = LoggerFactory.getLogger(BucketWriter.class);
/**
* 用以确保打开文件时的线程安全。HADOOP在某些时候是非线程安全的.
*/
private static final Object staticLock = new Object();
private final YeeFileWriter redcamWriter;
private long rollInterval;
private final long rollSize;
private final long rollLine;
private final long batchSize;
private final CompressionCodec codeC;
private final ScheduledExecutorService timedRollerPool;
private long processLines;
private long processBytes;
private final CollectClient fileClient;
private volatile String tempPath;
private volatile String filePath;
private volatile String fileName;
private volatile String inUseSuffix;
private volatile String fileSuffix;
private volatile String bucketPath;
private volatile String targetPath;
private volatile AtomicLong bytesCounter = new AtomicLong(0L);
private AtomicReference<ScheduledFuture<Void>> timedRollFuture;
private final WriterCallback onCloseCallback;
private final String onCloseCallbackPath;
/**
* 有文件句柄打开着,由synchronized方法保证同步性.
*/
private volatile boolean isOpen;
/**
* 当前对象是否关闭,文件超时关闭时同时标记对象已关闭,需重新实例化,由synchronized方法保证同步性.
*/
protected volatile boolean closed;
/**
* 文件处理过程中(写入、关闭)是否有异常发生,如有,不做rename处理,由synchronized方法保证同步性.
*/
private volatile boolean sthError;
private long lastAppendTime = -1L;
private final boolean useTimestamp;
/**
* 构造器.
*
* @param fileClient fileClient
* @param redcamWriter redcamWriter
* @param rollInterval 回滚间隔(秒)
* @param rollSize 回滚字节
* @param rollLine 回滚行数
* @param batchSize batchSize
* @param tempPath 临时目录
* @param filePath 最终目录
* @param fileName 文件名前缀
* @param inUseSuffix 临时后缀
* @param fileSuffix 最终后缀
* @param codeC 压缩格式
* @param timedRollerPool 线程池
* @param onCloseCallback 关闭时的回调函数
* @param onCloseCallbackPath 回调函数参数
*/
public BucketWriter(CollectClient fileClient, YeeFileWriter redcamWriter, long rollInterval,
long rollSize, long rollLine, long batchSize, String tempPath, String filePath,
String fileName, String inUseSuffix, String fileSuffix, CompressionCodec codeC,
ScheduledExecutorService timedRollerPool, WriterCallback onCloseCallback,
String onCloseCallbackPath, boolean useTimestamp) {
this.rollInterval = rollInterval;
this.rollSize = rollSize;
this.rollLine = rollLine;
this.batchSize = batchSize;
this.tempPath = tempPath;
this.filePath = filePath;
this.fileName = fileName;
this.inUseSuffix = inUseSuffix;
this.fileSuffix = fileSuffix;
this.codeC = codeC;
this.redcamWriter = redcamWriter;
this.timedRollerPool = timedRollerPool;
this.onCloseCallback = onCloseCallback;
this.onCloseCallbackPath = onCloseCallbackPath;
this.useTimestamp = useTimestamp;
this.fileClient = fileClient;
isOpen = false;
closed = false;
sthError = false;
}
/**
* Clear the class counters.
*/
private void resetCounters() {
processLines = 0;
processBytes = 0;
bytesCounter.set(0L);
}
/**
* open() is called by append().
*/
private void open() throws IOException, InterruptedException {
if (null == tempPath || null == filePath || null == redcamWriter) {
throw new IOException("Invalid file settings");
}
synchronized (staticLock) {
try {
//定义文件名格式:数据命名_yyyyMMdd_HHmmss_采集机hostname_进程号
String signName =new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date())+"_"+HostnameUtils.getHostname()+"_"+PidUtils.PID+"_"+Thread.currentThread().getId();
String fullFileName =useTimestamp ? (fileName + signName) : fileName;
if (fileSuffix != null && fileSuffix.length() > 0) {
fullFileName += fileSuffix;
LOG.info("fullFileName fileSuffix : " + fullFileName);
} else if (codeC != null) {
fullFileName += codeC.getDefaultExtension();
}
bucketPath = tempPath + fullFileName + inUseSuffix;
targetPath = filePath + fullFileName;
LOG.info("Creating " + bucketPath);
if (codeC == null) {
redcamWriter.open(bucketPath);
} else {
redcamWriter.open(bucketPath, codeC);
}
} catch (Exception ex) {
if (ex instanceof IOException) {
throw (IOException) ex;
} else {
throw Throwables.propagate(ex);
}
}
}
resetCounters();
// if time-based rolling is enabled, schedule the roll
if (rollInterval > 0) {
// 如果rollInterval大于100万,则关闭间隔是相对的,相对于最后写入时间;否则是绝对的
final AtomicBoolean relativeInterval = new AtomicBoolean(false);
if (rollInterval > 1000000) {
relativeInterval.set(true);
rollInterval = rollInterval % 1000000;
}
Callable<Void> action = new Callable<Void>() {
public Void call() throws Exception {
LOG.debug("Rolling file ({}): Roll scheduled after {} sec elapsed.", bucketPath,
rollInterval);
try {
if (relativeInterval.get()) {
if (System.currentTimeMillis() - lastAppendTime >= rollInterval
* 1000L) {
close(true);
}
} else {
close(true);
}
} catch (Throwable th) {
sthError = true;
LOG.error("Unexpected error", th);
}
return null;
}
};
timedRollFuture = new AtomicReference<ScheduledFuture<Void>>(
timedRollerPool.schedule(action, rollInterval, TimeUnit.SECONDS));
}
isOpen = true;
sthError = false;
}
/**
* 关闭文件.
*
* @throws Exception 执行异常时抛出
* @throws InterruptedException 执行异常时抛出
*/
public synchronized void close() throws Exception, InterruptedException {
close(false);
}
/**
* 关闭文件.
*
* @param callCloseCallback 是否需要关闭writer
* @throws Exception 执行异常时抛出
* @throws InterruptedException 执行异常时抛出
*/
public synchronized void close(boolean callCloseCallback)
throws Exception, InterruptedException {
boolean failedToClose = false;
LOG.info("Closing {}", bucketPath);
if (isOpen) {
try {
LOG.info("Close tries incremented");
redcamWriter.close();
} catch (IOException ex) {
LOG.warn("failed to close() HDFSWriter for file (" + bucketPath
+ "). Exception follows.", ex);
failedToClose = true;
sthError = true;
}
isOpen = false;
} else {
failedToClose = true;
LOG.info("HDFSWriter is already closed: {}", bucketPath);
}
// 定时关闭文件线程也会到此
if (timedRollFuture.get() != null && !timedRollFuture.get().isDone()) {
timedRollFuture.get().cancel(false); // for 定时关闭文件线程,所以不要cancel掉自己
timedRollFuture.set(null);
}
// 没有正常关闭就不要重命名,让文件永远呆在临时目录
if (bucketPath != null && fileClient != null && !failedToClose) {
renameBucket(bucketPath, targetPath, fileClient);
}
if (callCloseCallback) {
runCloseAction();
closed = true;
}
}
/**
* 把输出流中的数据flush出去.
*
* @throws Exception 流flush异常
* @throws InterruptedException 同步执行异常
*/
public synchronized void flush() throws Exception, InterruptedException {
if (!isBatchComplete()) {
redcamWriter.flush();
bytesCounter.set(0L);
}
}
private void runCloseAction() {
try {
if (onCloseCallback != null) {
onCloseCallback.run(onCloseCallbackPath);
}
} catch (Throwable th) {
LOG.error("Unexpected error", th);
}
}
/**
* 写入数据.
*
* @param event 一行数据的
* @param combinedSize 如果做过批量提交,表示合并的event个数
* @throws Exception 执行异常时抛出
* @throws InterruptedException 执行异常时抛出
*/
public synchronized void append(final Event event, int combinedSize)
throws Exception, InterruptedException {
// 文件超时被关闭了,重新打开,计数器重置
if (!isOpen) {
if (closed) {
throw new FlumeException(
"This bucket writer was closed and this handle is thus no longer valid");
}
open();
}
// 文件是否需要回滚
if (shouldRotate()) {
close();
open();
}
// 写入数据
try {
redcamWriter.append(event);
lastAppendTime = System.currentTimeMillis();
} catch (IOException ex) {
sthError = true;
LOG.warn("Caught IOException writing to HDFSWriter ({}). Closing file (" + bucketPath
+ ") and rethrowing exception.", ex.getMessage());
try {
close(true);
} catch (IOException e2) {
LOG.warn("Caught IOException while closing file (" + bucketPath
+ "). Exception follows.", e2);
}
throw ex;
}
// update statistics
processBytes += event.getBody().length;
processLines += combinedSize;
if (bytesCounter.addAndGet(event.getBody().length) >= batchSize) {
flush();
}
}
/**
* 文件是否需要回滚.
*/
private boolean shouldRotate() {
if (rollLine > 0 && rollLine <= processLines) {
LOG.debug("rolling: rollCount: {}, events: {}", rollLine, processLines);
return true;
}
if (rollSize > 0 && rollSize <= processBytes) {
LOG.debug("rolling: rollSize: {}, bytes: {}", rollSize, processBytes);
return true;
}
return false;
}
private void renameBucket(String bucketPath, String targetPath, final CollectClient fs)
throws Exception, InterruptedException {
if (sthError) {
LOG.info("something is wrong before rename, do nothing here.");
return;
}
if (bucketPath.equals(targetPath)) {
return;
}
if (fs.exists(bucketPath)) {
LOG.info("Renaming " + bucketPath + " to " + targetPath);
LOG.info("rename result: " + fs.rename(bucketPath, targetPath));
}
}
@Override
public String toString() {
return "[ " + this.getClass().getSimpleName() + " targetPath = " + targetPath
+ ", bucketPath = " + bucketPath + " ]";
}
private boolean isBatchComplete() {
return bytesCounter.get() == 0;
}
}
| true
|
3ce5d4838555b9c4871351d428b3b5be38f3e82c
|
Java
|
tomeks86/c0dility-training
|
/test/edu/tseidler/countingelements/MaxCountersTest.java
|
UTF-8
| 808
| 2.453125
| 2
|
[] |
no_license
|
package edu.tseidler.countingelements;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertArrayEquals;
@RunWith(JUnitParamsRunner.class)
public class MaxCountersTest {
private MaxCounters maxCounters = new MaxCounters();
@Test
@Parameters
public void solutionMaxCounterProblem(int N, int[] A, int[] result) {
assertArrayEquals(result, maxCounters.solution(5, A));
}
public Object[] parametersForSolutionMaxCounterProblem() {
return new Object[] {
new Object[] {5, new int[] {3, 4, 4, 6, 1, 4, 4}, new int[] {3, 2, 2, 4, 2}},
new Object[] {5, new int[] {1, 1, 1, 1, 1, 1, 1}, new int[] {7, 0, 0, 0, 0}}
};
}
}
| true
|
a9d065cfe8ebd574ab1116152ab3fe0a5d4b1d71
|
Java
|
yuki-mtmr/myApp
|
/src/main/java/com/example/myApp/dao/UserSkillMapper.java
|
UTF-8
| 318
| 1.96875
| 2
|
[] |
no_license
|
package com.example.myApp.dao;
import com.example.myApp.model.UserSkill;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface UserSkillMapper {
List<UserSkill> selectAllSkillByUser(int user_id);
int insert(UserSkill userSkill);
int update(UserSkill userSkill);
}
| true
|
cc988e1b6bb2f5a3b554da0ddd34b96622b4f648
|
Java
|
ITFakultetet/JavaGrunnkurs
|
/Scanner/src/no/itfakultetet/java/TripPlanner.java
|
UTF-8
| 2,602
| 3.5
| 4
|
[] |
no_license
|
package no.itfakultetet.java;
import java.util.Scanner;
public class TripPlanner {
public static void main(String[] args) {
intro();
budget();
time();
}
public static void intro() {
Scanner input = new Scanner(System.in);
System.out.println("Velkommen til ferieplanleggeren!");
System.out.print("Hva er navnet ditt? ");
String nameOfPlanner = input.nextLine();
System.out.print("Hyggelig å treffe deg, " + nameOfPlanner + ". Hvor vil du reise? ");
String travellingDestination = input.nextLine();
System.out.println("Flott! Reise til " + travellingDestination + " høres ut som en fin tur");
System.out.println("*****\n");
}
public static void budget() {
Scanner input = new Scanner(System.in);
System.out.print("Hvor mange dager bil du være borte? ");
int noOfDays = input.nextInt();
System.out.print("Hvor mye, i NOK, planlegger du å bruke? ");
double amountOfMoney = input.nextDouble();
System.out.print("Hva er trebokstavskoden for valutaen til stdet du reiser til? ");
String symbolOfCurrency = input.next();
System.out.print("Hvor mange " + symbolOfCurrency + " er det i 1 NOK? ");
double multipleFactor = input.nextDouble();
System.out.println();
System.out.println("Hvis du er borte i " + noOfDays + " dager, er det det samme som " + noOfDays * 24 + " timer, eller " + noOfDays * 24 * 60 + " minutter");
System.out.println("Hvis du bruker " + (int) amountOfMoney + " NOK, kan du bruke " + (double) Math.round((amountOfMoney / noOfDays) * 100) / 100 + " NOK per dag");
System.out.println("Ditt totale budsjett i " + symbolOfCurrency + " er " + amountOfMoney * multipleFactor + " " + symbolOfCurrency + ", som blir " + (double) Math.round((amountOfMoney * multipleFactor / noOfDays) * 100) / 100 + " " + symbolOfCurrency+" per dag");
System.out.println("*****\n");
}
public static void time() {
Scanner input = new Scanner(System.in);
System.out.print("Hva er tidsforskjellen, i timer, mellom hjemstedet ditt og destinasjonen? (sett minus foran hvis det er bakover i tid) ");
int differenceOfTime = input.nextInt();
System.out.println("Det betyr at når det er midnatt hjemme, vil klokken være " + (24 + differenceOfTime) % 24 + ":00 på destinasjonsstedet,\nog når kl. er 12 på dagen hjemme, vil den være " + (12 + differenceOfTime) + ":00 på destinasjonsstedet");
System.out.println("*****\n");
}
}
| true
|
e76c1c8ff91ba15ccfd559bb4cd76dd9849334d4
|
Java
|
unnch/spell-sat
|
/spell/branches/1.5/spel-dev/org.python.pydev/src_completions/org/python/pydev/editor/codecompletion/PyCodeCompletionInitializer.java
|
UTF-8
| 2,058
| 1.8125
| 2
|
[] |
no_license
|
/*
* Created on 20/08/2005
*/
package org.python.pydev.editor.codecompletion;
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.core.runtime.preferences.DefaultScope;
import org.osgi.service.prefs.Preferences;
import org.python.pydev.logging.PyLoggingPreferencesPage;
import org.python.pydev.plugin.PydevPlugin;
public class PyCodeCompletionInitializer extends AbstractPreferenceInitializer{
@Override
public void initializeDefaultPreferences() {
Preferences node = new DefaultScope().getNode(PydevPlugin.DEFAULT_PYDEV_SCOPE);
node.putBoolean(PyCodeCompletionPreferencesPage.USE_CODECOMPLETION, PyCodeCompletionPreferencesPage.DEFAULT_USE_CODECOMPLETION);
node.putInt(PyCodeCompletionPreferencesPage.ATTEMPTS_CODECOMPLETION, PyCodeCompletionPreferencesPage.DEFAULT_ATTEMPTS_CODECOMPLETION);
node.putBoolean(PyCodeCompletionPreferencesPage.AUTOCOMPLETE_ON_DOT, PyCodeCompletionPreferencesPage.DEFAULT_AUTOCOMPLETE_ON_DOT);
node.putBoolean(PyCodeCompletionPreferencesPage.AUTOCOMPLETE_ON_ALL_ASCII_CHARS, PyCodeCompletionPreferencesPage.DEFAULT_AUTOCOMPLETE_ON_ALL_ASCII_CHARS);
node.putBoolean(PyCodeCompletionPreferencesPage.USE_AUTOCOMPLETE, PyCodeCompletionPreferencesPage.DEFAULT_USE_AUTOCOMPLETE);
node.putInt(PyCodeCompletionPreferencesPage.AUTOCOMPLETE_DELAY, PyCodeCompletionPreferencesPage.DEFAULT_AUTOCOMPLETE_DELAY);
node.putBoolean(PyCodeCompletionPreferencesPage.AUTOCOMPLETE_ON_PAR, PyCodeCompletionPreferencesPage.DEFAULT_AUTOCOMPLETE_ON_PAR);
node.putInt(PyCodeCompletionPreferencesPage.ARGUMENTS_DEEP_ANALYSIS_N_CHARS, PyCodeCompletionPreferencesPage.DEFAULT_ARGUMENTS_DEEP_ANALYSIS_N_CHARS);
node.putBoolean(PyLoggingPreferencesPage.DEBUG_CODE_COMPLETION, PyLoggingPreferencesPage.DEFAULT_DEBUG_CODE_COMPLETION);
node.putBoolean(PyLoggingPreferencesPage.DEBUG_ANALYSIS_REQUESTS, PyLoggingPreferencesPage.DEFAULT_DEBUG_ANALYSIS_REQUESTS);
}
}
| true
|
e89d138f7c5c2c15945a932eb2f9b37d6a2f61bd
|
Java
|
JaneMoskalenko/CourseProjectApp
|
/app/src/main/java/com/example/admin/courseproject/Model/image/ImageManager.java
|
UTF-8
| 3,137
| 2.3125
| 2
|
[] |
no_license
|
package com.example.admin.courseproject.Model.image;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ImageManager {
private File outputDir;
private static final String FOLDER_NAME_FOR_PICTURES = "sPikcher";
private static final String DATE_FORMAT_FOR_NAMING_PICTURES = "yyyyMMDD_HHmmss";
private static final String TAG = ImageManager.class.getSimpleName();
private Context mContext;
public ImageManager(Context context) {
mContext = context;
}
private File getPhotoDirectory(){
outputDir = null;
String externalStorageState = Environment.getExternalStorageState();
Log.i(TAG, " externalStorageState " + externalStorageState);
if (externalStorageState.equals(Environment.MEDIA_MOUNTED)){
File pictureDir = getDefaultPicturesDirectory();
outputDir = new File (pictureDir, FOLDER_NAME_FOR_PICTURES);
checkOutputDirectoryExistance();
}
return outputDir;
}
private void checkOutputDirectoryExistance() {
if (!outputDir.exists()){
if (!outputDir.mkdirs()) {
/*TODO MAKE Logging or exeption*/
/* Toast.makeText(this, "Failed creating directory: "
+ outputDir.getAbsolutePath(), Toast.LENGTH_LONG).show();*/
outputDir = null;
}
}
}
private File getDefaultPicturesDirectory() {
return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
}
public Uri generateTimeStampPhotoFileUri(){
Uri photoFileUri = null;
File outputDir = getPhotoDirectory();
if (outputDir != null) {
String timeStamp = new SimpleDateFormat(DATE_FORMAT_FOR_NAMING_PICTURES).format(new Date());
String photoFileName = "IMG_"+ timeStamp + ".jpg";
File photoFile = new File(outputDir, photoFileName);
photoFileUri = Uri.fromFile(photoFile);
}
return photoFileUri;
}
public Bitmap getSelectedBitmap(Intent data) {
Uri photoFileUri = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = mContext.getContentResolver().query(photoFileUri,
filePathColumn, null, null, null);
assert cursor != null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String imgDecodableString = cursor.getString(columnIndex);
cursor.close();
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inScaled = true;
bitmapOptions.inSampleSize = 4;
//bitmapOptions.inDensity =
return BitmapFactory.decodeFile(imgDecodableString, bitmapOptions);
}
}
| true
|
ef26c086e5ce2d45112c6cca95a44f944f113854
|
Java
|
Rita-Bernstein/Gensokyo
|
/src/main/java/Gensokyo/cards/UrbanLegend/Kunekune.java
|
UTF-8
| 1,608
| 2.28125
| 2
|
[] |
no_license
|
package Gensokyo.cards.UrbanLegend;
import Gensokyo.GensokyoMod;
import Gensokyo.powers.act1.LunacyPower;
import Gensokyo.tags.Tags;
import com.megacrit.cardcrawl.actions.AbstractGameAction;
import com.megacrit.cardcrawl.actions.common.ApplyPowerAction;
import com.megacrit.cardcrawl.characters.AbstractPlayer;
import com.megacrit.cardcrawl.dungeons.AbstractDungeon;
import com.megacrit.cardcrawl.monsters.AbstractMonster;
import static Gensokyo.GensokyoMod.makeCardPath;
public class Kunekune extends AbstractUrbanLegendCard {
public static final String ID = GensokyoMod.makeID(Kunekune.class.getSimpleName());
public static final String IMG = makeCardPath("Kunekune.png");
private static final CardRarity RARITY = CardRarity.SPECIAL;
private static final CardTarget TARGET = CardTarget.ENEMY;
private static final CardType TYPE = CardType.SKILL;
private static final int COST = 3;
private static final int DEBUFF = 2;
public Kunekune() {
super(ID, IMG, COST, TYPE, RARITY, TARGET);
magicNumber = baseMagicNumber = DEBUFF;
exhaust = true;
isEthereal = true;
tags.add(Tags.URBAN_LEGEND);
}
@Override
public void use(AbstractPlayer p, AbstractMonster m) {
AbstractDungeon.actionManager.addToBottom(new ApplyPowerAction(m, p, new LunacyPower(m, this.magicNumber), this.magicNumber, AbstractGameAction.AttackEffect.NONE));
}
@Override
public void upgrade() {
if (!upgraded) {
upgradeName();
isEthereal = false;
initializeDescription();
}
}
}
| true
|
a4b052745211172034f688f05f5a894273532d13
|
Java
|
AnupKumarPanwar/RightFlick
|
/app/src/main/java/com/rightflick/dating/social/FullScreenImage.java
|
UTF-8
| 1,328
| 1.945313
| 2
|
[] |
no_license
|
package com.rightflick.dating.social;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import com.jsibbold.zoomage.ZoomageView;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
public class FullScreenImage extends AppCompatActivity {
ZoomageView imageView;
ImageView imageBackground;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_full_screen_image);
imageView = (ZoomageView) findViewById(R.id.imageView);
imageBackground = (ImageView) findViewById(R.id.imageBackground);
String url = getIntent().getExtras().getString("url");
// imageView.setImage("https://instagram.fixc1-2.fna.fbcdn.net/vp/b710693e4dc4cb443b6fb743d2501f7c/5C35DA0C/t51.2885-15/sh0.08/e35/s640x640/31941457_1031025983720679_1139431025215012864_n.jpg");
Picasso.get().load(url).into(imageView);
Picasso.get().load(url).into(imageBackground);
}
}
| true
|
bfd6d313775afc6b088c09372393f3f42b18ee10
|
Java
|
yankaic/Paxos
|
/src/messages/TableLine.java
|
UTF-8
| 1,040
| 2.46875
| 2
|
[] |
no_license
|
package messages;
import com.google.gson.Gson;
import java.io.Serializable;
import jdk.nashorn.internal.parser.JSONParser;
import jdk.nashorn.internal.runtime.JSONFunctions;
/**
*
* @author Yan Kaic
*/
public class TableLine implements Serializable {
protected String target;
protected String link;
protected int distance;
public TableLine(String target, String link, int distance) {
this.target = target;
this.link = link;
this.distance = distance;
}
public String getTarget() {
return target;
}
public String getLink() {
return link;
}
public int getDistance() {
return distance;
}
public boolean isDirect() {
return target.equals(link);
}
public void update(String link, int distance) {
this.link = link;
this.distance = distance;
}
public static void load(String string){
}
@Override
public String toString() {
return '[' + target + ", " + link + ", " + distance + ']';
}
}
| true
|
d5caa0ac1e8f2f77dc850967108ddc777f99bc53
|
Java
|
gogym/gogym-oss
|
/commonModule/src/main/java/pres/gogym/common/Constants.java
|
UTF-8
| 1,352
| 1.617188
| 2
|
[] |
no_license
|
package pres.gogym.common;
public class Constants {
// 上传头像大小
public static final int UPLOAD_HEAD_PORTRAIT_SIZE = 2097152;
// token有效时间
public static final int TOKEN_VALID_TIME = 48 * 60 * 60 * 1000;// 48小时
public static final int TOKEN_REDIS_TIME = 2 * 60 * 60;// 24小时(单位:s)
// 推送URL
public static final String PUSH_URL = "http://localhost:8089/PushServer/pushMessage/pushMsg";
public static final String apiKey = "1dfd23456";
public static final String secretKey = "dfdf654321";
// 一级缓存消息最大数量,超过放到二级缓存
public static final int LEVEL_1_CACHE_MESSAGE_COUNT = 1000;
// 一级缓存消息超时时间,10分钟
public static final long LEVEL_1_CACHE_MESSAGE_TIMEINTERVAL = 10 * 60 * 1000;
// 二级缓存消息超时时间,24个小时
public static final long LEVEL_2_CACHE_MESSAGE_TIMEINTERVAL = 24 * 60 * 60 * 1000;
// 消息重发有效时间
public static final long RESEND_MESSAGE_TIME = 90 * 1000;
// UDP连接保留时间
public static final long UDP_SOCKET_TIMEINTERVAL = 1000 * 60 * 5;
// 协议标识
public final static String identify = "ys";
// 协议版本
public final static String version = "1.0";
// 群聊前缀
public final static String REDIS_CHAT_GROUP = "redis_chat_group_";
}
| true
|
99b565015bd58fa2e8340268086338916579502d
|
Java
|
lfallo1/ScheduleGenerator
|
/src/com/lancefallon/schedulegenerator/service/AnalyzerService.java
|
UTF-8
| 559
| 2.640625
| 3
|
[] |
no_license
|
package com.lancefallon.schedulegenerator.service;
import com.lancefallon.schedulegenerator.model.Team;
public class AnalyzerService {
public double getGameRating(Team team1, Team team2){
double rating = 0.0;
rating += team1.getPreviousSeasonWins() + team2.getPreviousSeasonWins();
if(team1.getDivision().equals(team2.getDivision())){
rating = rating + rating * 0.1;
}
rating = rating + rating * (team1.getMadePlayoffs() && team1.getMadePlayoffs() ? .4 : team1.getMadePlayoffs() || team2.getMadePlayoffs() ? .15 : 0);
return rating;
}
}
| true
|
53de2393e7dee495ec793355874c9d218a4b7ce7
|
Java
|
ds21h/LightControl
|
/app/src/main/java/jb/light/control/ManageSwitchListAdapter.java
|
UTF-8
| 3,858
| 2.21875
| 2
|
[] |
no_license
|
package jb.light.control;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
/**
* Created by Jan on 18-9-2015.
*/
public class ManageSwitchListAdapter extends ArrayAdapter<Switch> {
private List<Switch> mSwitches;
private int mLayout;
private Context mContext;
ManageSwitchListAdapter(Context pContext, int pLayout, List<Switch> pSwitches) {
super(pContext, pLayout, pSwitches);
mLayout = pLayout;
mContext = pContext;
mSwitches = pSwitches;
}
@Override
public @NonNull View getView(int pPos, View pView, @NonNull ViewGroup pGroup) {
View lRow;
SwitchListHandle lHandle;
Object lTag = null;
boolean lRecycle;
if (pView == null) {
lRecycle = false;
} else {
lTag = pView.getTag();
lRecycle = lTag instanceof SwitchListHandle;
}
if (lRecycle) {
lHandle = (SwitchListHandle)lTag;
lRow = pView;
} else {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
lRow = inflater.inflate(mLayout, pGroup, false);
lHandle = new SwitchListHandle();
lHandle.xTxtName = lRow.findViewById(R.id.txtName);
lHandle.xTxtType = lRow.findViewById(R.id.txtType);
lHandle.xChkActive = lRow.findViewById(R.id.chkActive);
lHandle.xTxtGroup = lRow.findViewById(R.id.txtGroup);
lHandle.xTxtPoint = lRow.findViewById(R.id.txtPoint);
lHandle.xTxtIP = lRow.findViewById(R.id.txtIP);
lHandle.xTxtPause = lRow.findViewById(R.id.txtPause);
lHandle.xLyoFM = lRow.findViewById((R.id.lyoFM));
lHandle.xLyoIot = lRow.findViewById((R.id.lyoIot));
lHandle.xParHide = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0);
lHandle.xParShow = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lRow.setTag(lHandle);
}
sSetItem(lHandle, pPos);
return lRow;
}
private void sSetItem(SwitchListHandle pHandle, int pPos) {
pHandle.xSwitch = mSwitches.get(pPos);
pHandle.xTxtName.setText(pHandle.xSwitch.xName());
pHandle.xTxtType.setText(pHandle.xSwitch.xType());
pHandle.xChkActive.setChecked(pHandle.xSwitch.xActive());
if (pHandle.xSwitch.xType().equals("esp")){
pHandle.xLyoFM.setLayoutParams(pHandle.xParHide);
pHandle.xLyoIot.setLayoutParams(pHandle.xParShow);
pHandle.xTxtIP.setText(pHandle.xSwitch.xIP());
pHandle.xTxtGroup.setText("");
pHandle.xTxtPoint.setText("");
} else {
pHandle.xLyoFM.setLayoutParams(pHandle.xParShow);
pHandle.xLyoIot.setLayoutParams(pHandle.xParHide);
pHandle.xTxtIP.setText("");
pHandle.xTxtGroup.setText(pHandle.xSwitch.xGroup());
pHandle.xTxtPoint.setText(pHandle.xSwitch.xPoint());
}
pHandle.xTxtPause.setText(String.valueOf(pHandle.xSwitch.xPause()));
}
static class SwitchListHandle{
Switch xSwitch;
TextView xTxtName;
TextView xTxtType;
CheckBox xChkActive;
TextView xTxtGroup;
TextView xTxtPoint;
TextView xTxtIP;
TextView xTxtPause;
LinearLayout xLyoFM;
LinearLayout xLyoIot;
LinearLayout.LayoutParams xParHide;
LinearLayout.LayoutParams xParShow;
}
}
| true
|
ff761c74bff83188d872e3672d129ccf4937bbd4
|
Java
|
hkj141421/StudyDemo
|
/SSMDemo/src/main/java/com/knight/Dao/XHostSummaryByFileIoTypeMapper.java
|
UTF-8
| 2,355
| 1.742188
| 2
|
[] |
no_license
|
package com.knight.Dao;
import com.knight.Bean.XHostSummaryByFileIoType;
import com.knight.Bean.XHostSummaryByFileIoTypeExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface XHostSummaryByFileIoTypeMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table x$host_summary_by_file_io_type
*
* @mbg.generated Sat Dec 28 12:31:56 CST 2019
*/
long countByExample(XHostSummaryByFileIoTypeExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table x$host_summary_by_file_io_type
*
* @mbg.generated Sat Dec 28 12:31:56 CST 2019
*/
int deleteByExample(XHostSummaryByFileIoTypeExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table x$host_summary_by_file_io_type
*
* @mbg.generated Sat Dec 28 12:31:56 CST 2019
*/
int insert(XHostSummaryByFileIoType record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table x$host_summary_by_file_io_type
*
* @mbg.generated Sat Dec 28 12:31:56 CST 2019
*/
int insertSelective(XHostSummaryByFileIoType record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table x$host_summary_by_file_io_type
*
* @mbg.generated Sat Dec 28 12:31:56 CST 2019
*/
List<XHostSummaryByFileIoType> selectByExample(XHostSummaryByFileIoTypeExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table x$host_summary_by_file_io_type
*
* @mbg.generated Sat Dec 28 12:31:56 CST 2019
*/
int updateByExampleSelective(@Param("record") XHostSummaryByFileIoType record, @Param("example") XHostSummaryByFileIoTypeExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table x$host_summary_by_file_io_type
*
* @mbg.generated Sat Dec 28 12:31:56 CST 2019
*/
int updateByExample(@Param("record") XHostSummaryByFileIoType record, @Param("example") XHostSummaryByFileIoTypeExample example);
}
| true
|
acdc45166e921bf7dbcd61ad2a9a54f0b5a057c6
|
Java
|
SaharHany/EventHubUser
|
/EventHubUser/app/src/main/java/com/iti/eventhubuser/screens/loginscreen/fragments/ForgetPasswordFragment.java
|
UTF-8
| 599
| 1.8125
| 2
|
[] |
no_license
|
package com.iti.eventhubuser.screens.loginscreen.fragments;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.fragment.app.Fragment;
import com.iti.eventhubuser.R;
public class ForgetPasswordFragment extends Fragment {
public ForgetPasswordFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_forget_password, container, false);
}
}
| true
|
7259eac68606af6a0d6e01bf2678a95d8b93c8b9
|
Java
|
vacaly/Alink
|
/core/src/main/java/com/alibaba/alink/pipeline/feature/ScorecardModel.java
|
UTF-8
| 675
| 1.773438
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.alibaba.alink.pipeline.feature;
import org.apache.flink.ml.api.misc.param.Params;
import com.alibaba.alink.common.annotation.NameCn;
import com.alibaba.alink.operator.common.finance.ScorecardModelMapper;
import com.alibaba.alink.params.finance.ScorecardPredictParams;
import com.alibaba.alink.pipeline.MapModel;
@NameCn("评分卡模型")
public class ScorecardModel extends MapModel <ScorecardModel>
implements ScorecardPredictParams <ScorecardModel> {
private static final long serialVersionUID = -6327950527201298541L;
public ScorecardModel() {
this(null);
}
public ScorecardModel(Params params) {
super(ScorecardModelMapper::new, params);
}
}
| true
|
c15df68c8d6b7e5bcdb8868fc718fa0adb381b20
|
Java
|
YaqianQi/Algorithm-and-Data-Structure
|
/Java/Math/_5343_ConstructTargetArrayWithMultipleSums.java
|
UTF-8
| 1,088
| 3.625
| 4
|
[] |
no_license
|
import java.util.*;
public class _5343_ConstructTargetArrayWithMultipleSums {
public boolean isPossible(int[] target) {
PriorityQueue<Integer> q = new PriorityQueue<>((a,b)->(b-a));
int sum = 0;
int n = target.length;
for (int num : target) {
q.offer(num);
sum+= num;
}
while(sum > n) {
int val = q.poll();
int temp = val - (sum - val);
if (temp < 1) {return false;}
q.offer(temp);
sum -= (val - temp);
}
return sum == n;
}
public boolean isPossible2(int[] target) {
Arrays.sort(target);
int sum = 0;
int n = target.length;
for (int num : target) {
sum+= num;
}
while(sum > n) {
int val = target[n-1];
int temp = val - (sum - val);
if (temp < 1) {return false;}
target[n-1] = temp;
sum -= (val - temp);
Arrays.sort(target);
}
return sum == n;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] target = {9,3,5};
_5343_ConstructTargetArrayWithMultipleSums cs = new _5343_ConstructTargetArrayWithMultipleSums ();
System.out.println(cs.isPossible2(target));
}
}
| true
|
2c9a1861b60a3e1d87d1e5d2b08f184dbd266612
|
Java
|
smoenssen/MyGroceryList
|
/app/src/main/java/com/smoftware/mygrocerylist/EditCategoryListActivity.java
|
UTF-8
| 12,625
| 2.09375
| 2
|
[] |
no_license
|
package com.smoftware.mygrocerylist;
import android.app.Dialog;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class EditCategoryListActivity extends AppCompatActivity implements AddCategoryFragment.IOnAddCategoryDialogListener {
FloatingActionButton fab;
EditCategoryListAdapter editCategoryListAdapter = null;
MenuItem menuIcon = null;
long selectedCatId = 0;
long listId = 0;
String Title;
String comingFrom;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.icon_list_add);
Title = getIntent().getStringExtra("Title");
setTitle(Title);
listId = getIntent().getLongExtra("ListId", 0);
comingFrom = getIntent().getStringExtra("ComingFrom");
editCategoryListAdapter = new EditCategoryListAdapter(this, listId);
final ListView editCategoryListView = (ListView)findViewById(R.id.iconListViewAdd);
editCategoryListView.setAdapter(editCategoryListAdapter);
TextView emptyListView = (TextView) findViewById(R.id.emptyListViewAdd);
emptyListView.setText(R.string.no_grocery_categories);
editCategoryListView.setEmptyView(emptyListView);
this.fab = (FloatingActionButton)findViewById(R.id.fab_add);
this.fab.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(R.color.colorFab)));
this.fab.setRippleColor(getResources().getColor(R.color.colorFabRipple));
this.fab.show();
showFabWithAnimation(fab, 300);
fab.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (fab != null) {
DisplayAddCategoryDialog("");
}
}
});
editCategoryListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// srm - in order for this to fire I needed to set android:focusable="false" for the items in the layout file
selectedCatId = editCategoryListView.getAdapter().getItemId(position);
Intent myIntent = new Intent(getBaseContext(), EditGroceryItemListActivity.class);
myIntent.putExtra("CatId", selectedCatId);
myIntent.putExtra("ListId", listId);
startActivityForResult(myIntent, 0);
}
});
editCategoryListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
// prompt to confirm deletion
final long catId = editCategoryListView.getAdapter().getItemId(position);
final String catName = (String)editCategoryListView.getAdapter().getItem(position);
AlertDialog.Builder alert = new AlertDialog.Builder(EditCategoryListActivity.this);
alert.setTitle("Modify Category");
if (listId == 0) {
// the main category table will be affected!
alert.setMessage("Would you like to edit or delete " + catName + "? If you choose to delete, " +
"the category will be permanently deleted from ALL lists.");
alert.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
AlertDialog.Builder confirm = new AlertDialog.Builder(EditCategoryListActivity.this);
confirm.setTitle("Delete Category");
confirm.setMessage("Are you sure you want to permanently delete " + catName + " from the database?");
confirm.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
editCategoryListAdapter.DeleteCategory((int)catId);
Toast.makeText(getBaseContext(), String.format("%s deleted", catName), Toast.LENGTH_SHORT).show();
}
});
confirm.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// do nothing
}
});
Dialog dialog2 = confirm.create();
dialog2.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
dialog2.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
dialog2.show();
}
});
}
else
{
alert.setMessage("Would you like to edit or remove " + catName + "? If you choose to remove, " +
"the category will be removed from just this list.");
alert.setPositiveButton("Remove", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
editCategoryListAdapter.RemoveCategory((int) catId, listId);
Toast.makeText(getBaseContext(), String.format("%s removed", catName), Toast.LENGTH_SHORT).show();
}
});
}
alert.setNeutralButton("Edit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
DisplayAddCategoryDialog((String) catName);
Toast.makeText(getBaseContext(), String.format("%s updated", catName), Toast.LENGTH_SHORT).show();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// do nothing
}
});
Dialog dialog = alert.create();
dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
dialog.show();
return true;
}
});
}
public static void showFabWithAnimation(final FloatingActionButton fab, final int delay) {
fab.hide();
fab.setScaleX(0.0F);
fab.setScaleY(0.0F);
fab.setAlpha(0.0F);
fab.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
fab.getViewTreeObserver().removeOnPreDrawListener(this);
fab.postDelayed(new Runnable() {
@Override
public void run() {
fab.show();
}
}, delay);
return true;
}
});
}
public void OnSomethingModified()
{
runOnUiThread(new Runnable() {
@Override
public void run() {
if (menuIcon != null)
menuIcon.getIcon().setTint(getResources().getColor(R.color.LightGreen));
}
});
}
@Override
public void onAttachedToWindow()
{
super.onAttachedToWindow();
getWindow().setTitle(Title);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.options_menu_edit_category, menu);
menuIcon = menu.findItem(R.id.action_done);
menuIcon.getIcon().setTint(getResources().getColor(R.color.White));
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
finish();
return true;
case R.id.action_done:
Intent myIntent = new Intent(this, CreateListActivity.class);
if (comingFrom != null && comingFrom.equals("GoShoppingActivity")) {
startActivity(myIntent);
}
else {
setResult(RESULT_OK, myIntent);
}
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onBackPressed()
{
// make sure changes are reflected if hardware back button is pressed
Intent myIntent = new Intent(this, CreateListActivity.class);
setResult(RESULT_OK, myIntent);
finish();
}
public void DisplayAddCategoryDialog(String catName)
{
FragmentTransaction ft = getFragmentManager().beginTransaction();
// Remove fragment else it will crash as it is already added to backstack
Fragment prev = getFragmentManager().findFragmentByTag("AddCategoryFragment");
if (prev != null)
{
ft.remove(prev);
}
ft.addToBackStack(null);
// Create and show the dialog.
Bundle args = new Bundle();
args.putString("name", catName);
AddCategoryFragment newFragment = AddCategoryFragment.newInstance(args);
newFragment.show(ft, "AddCategoryFragment");
}
public void OnAddCategoryDialogListener(String newText, String oldText)
{
if (newText.equals(""))
{
DisplayAddCategoryAlert("Add Category", "Category cannot be empty.");
}
else
{
if (oldText.equals(""))
{
// adding new category
if (editCategoryListAdapter.AddCategory(listId, newText, "ic_view_list_white_24dp", 1) == 0)
{
String text = String.format("\'%s\' category already exists.", newText);
DisplayAddCategoryAlert("Add Category", text);
}
}
else
{
// editing a category
editCategoryListAdapter.EditCategory(oldText, newText);
}
}
}
void DisplayAddCategoryAlert(String title, String text)
{
AlertDialog.Builder alert = new AlertDialog.Builder(EditCategoryListActivity.this);
alert.setTitle(title);
alert.setMessage(text);
alert.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
DisplayAddCategoryDialog("");
}
});
Dialog dialog = alert.create();
dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
dialog.show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK)
{
switch (requestCode)
{
case 0:
// refresh checkbox
editCategoryListAdapter.SetCheckBasedOnSelectedGroceryItems((int)selectedCatId);
break;
default:
break;
}
}
}
}
| true
|
fd151ded52dda4fe322cc20ac03ff4a6b9f9b87f
|
Java
|
yqhuang1/VideoApplication
|
/app/src/main/java/com/li/videoapplication/utils/HttpUtils.java
|
UTF-8
| 45,974
| 1.953125
| 2
|
[] |
no_license
|
package com.li.videoapplication.utils;
import android.content.Context;
import android.util.Log;
import com.li.videoapplication.activity.ExApplication;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.File;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
/**
* Created by li on 2014/9/22.
*/
public class HttpUtils {
public static String BASE_URL = "http://apps.ifeimo.com/home";
// public static String BASE_URL="http://192.168.28.9/sysj_php/home";
// public static final String BASE_URL="http://nw.sysj.com/home";
/**
* 自动获取礼包详情
*
* @param id
* @return
*/
public static String getAutoGift(String id, String member_id) {
return BASE_URL + "/member/PackageInfo.html?id=" + id + "&member_id=" + member_id;
}
// 上传封面接口
public static final String getuploadVideoCoverImage(String videoKey) {
return "http://apps.ifeimo.com/home/video/uploadPicQiniu.html?videokey="
+ videoKey;
}
/**
* 我的礼包列表
*
* @param page
* @return
*/
public static String getMyGift(String page) {
return BASE_URL + "/member/getMyPackageList.html?member_id=" + ExApplication.MEMBER_ID + "&page=" + page;
}
/**
* 我的消息列表
*
* @param type_id 1表示系统消息,2视频消息(含空间信息)
* @param member_id
* @param page
* @return
*/
public static String getMyMessage(String type_id, String member_id, String page) {
return BASE_URL + "/member/msgList.html?type_id=" + type_id + "&member_id=" + member_id + "&page=" + page;
}
/**
* 刷新token
*
* @return
*/
public static final String refreshToken() {
return "https://openapi.youku.com/v2/oauth2/token";
}
/**
* 取消收藏
*
* @param ids
* @return
*/
public static String cancelCollect(String ids) {
return BASE_URL + "/video/cancelCollect.html";
}
/**
* 上传视频信息
*
* @return
*/
public static final String postVideoInfo() {
return BASE_URL + "/video/publishVideo.html";
}
/**
* 单条视频基本信息
*
* @return
*/
public static final String youkuVideoInfo(String id) {
return "https://openapi.youku.com/v2/videos/show_basic.json?client_id=" + ExApplication.id + "&video_id=" + id;
}
/**
* 第三方登陆
*
* @return
*/
public static final String getOtherLogin() {
return BASE_URL + "/member/login.html";
}
/**
* 手机号登录
*
* @return
*/
public static final String getPhoneLogin(String phoneNum) {
return BASE_URL + "/member/login.html?key=" + phoneNum;
}
/**
* 获取用户资料
*
* @param id
* @return
*/
public static final String getUserDetailInfo(String id, String member_id) {
return BASE_URL + "/member/detailNew.html?id=" + id + "&member_id=" + member_id;
}
/**
* 修改用户资料
*
* @return
*/
public static final String getUpdateInfo() {
return BASE_URL + "/member/finishMemberInfo.html";
}
/**
* 获取(热门)游戏列表
*
* @return
*/
public static final String getHotGame() {
return BASE_URL + "/game/hotGame.html";
}
/**
* 获取大神列表
*
* @return
*/
public static final String getMasterListUrl(String page, String member_id) {
return BASE_URL + "/topic/topicList.html?page=" + page + "&member_id=" + member_id;
}
/**
* 关注玩家
*
* @param fans_id 关注者id
* @param befocus_id 被关注者id
* @return
*/
public static final String submitFocusUrl(String fans_id, String befocus_id) {
return BASE_URL + "/member/attention.html?id=" + fans_id + "&member_id=" + befocus_id;
}
/**
* 加入游戏圈接口
*
* @param group_id
* @param member_id
* @return
*/
public static final String joinGameCircleUrl(String group_id, String member_id) {
return BASE_URL + "/game/attention.html?group_id=" + group_id + "&member_id=" + member_id;
}
/**
* 大神关注
*
* @param fans_id
* @param master_id
* @return
*/
public static final String masterFocusUrl(String fans_id, String master_id) {
return BASE_URL + "/topic/subscribe.html?member_id=" + fans_id + "&id=" + master_id;
}
/**
* 版本验证升级
*
* @return
*/
public static final String getUpdateUrl() {
return BASE_URL + "/index/updateVersion.html?build=";
}
/**
* 收藏视屏
*
* @param member_id
* @param id
* @return
*/
public static final String getCollectVideo(String id, String member_id) {
return BASE_URL + "/video/collect.html?id=" + id + "&member_id=" + member_id;
}
/**
* 取消收藏视频
*
* @param member_id
* @param id
* @return
*/
public static final String getCancelCollectVideo(String id, String member_id) {
return BASE_URL + "/video/cancelCollect.html?id=" + id + "&member_id=" + member_id;
}
/**
* 收藏赛事
*
* @param member_id
* @param match_id
* @return
*/
public static final String submitCollectMatch(String member_id, String match_id) {
return BASE_URL + "/member/matchLike.html?match_id=" + match_id + "&member_id=" + member_id;
}
/**
* 赛事收藏状态
*
* @param member_id
* @param match_id
* @return
*/
public static final String getMatchStateUrl(String member_id, String match_id) {
return BASE_URL + "/member/matchMark.html?match_id=" + match_id + "&member_id=" + member_id;
}
/**
* 赛事评论
*
* @param member_id
* @param match_id
* @param content
* @return
*/
public static final String getMatchReviewUrl(String member_id, String match_id, String content) {
return BASE_URL + "/member/matchReview.html?match_id=" + match_id + "&member_id=" + member_id + "&content=" + content;
}
/**
* 会员收藏列表
*
* @param id
* @param page
* @return
*/
public static final String getCollectVideoList(String id, String page) {
return BASE_URL + "/member/collectVideoList.html?member_id=" + id + "&page=" + page;
}
/**
* 上传头像
*
* @param id
* @return
*/
public static final String getuploadAvatar(String id) {
return BASE_URL + "/member/uploadAvatar.html?id=" + id;
}
/**
* 游戏类型(分类)列表
*
* @return
*/
public static final String getGameTypeList() {
return BASE_URL + "/game/typeList.html";
}
/**
* 游戏圈子类型接口
*
* @return
*/
public static final String getGameCircleTypeUrl() {
return BASE_URL + "/game/groupType.html";
}
/**
* 游戏圈子列表接口
*
* @param type_id
* @param member_id
* @return
*/
public static final String getGameCircleGameUrl(String page, String type_id, String member_id) {
return BASE_URL + "/game/groupList.html?type_id=" + type_id + "&member_id=" + member_id + "&page=" + page;
}
/**
* 游戏圈子详情
*
* @param group_id
* @param member_id
* @param type_name 圈子类型名
* @return
*/
public static final String getGameCircleInfoUrl(String group_id, String member_id, String type_name) {
return BASE_URL + "/game/groupDetail.html?group_id=" + group_id + "&member_id=" + member_id + "&type_name=" + type_name;
}
/**
* 小编荐
*
* @return
*/
public static final String getShowPointList(String page) {
return BASE_URL + "/recommend/editorRecommend.html?page=" + page;
}
/**
* 用户上传视频列表(云端视频)
*
* @param page
* @return
*/
public static final String getColudVideoUrl(String page) {
return BASE_URL + "/video/authorVideoList.html?page=" + page + "&member_id=" + ExApplication.MEMBER_ID;
}
/**
* 返回视界专栏视频二级列表
*
* @return
*/
public static final String getHomeColumnListUrl(String page, String mark) {
return BASE_URL + "/recommend/topicList.html?page=" + page + "&mark=" + mark;
}
/**
* 下载量统计接口
*
* @param game_id
* @return
*/
public static final String getSubmitDownloadCountUrl(String game_id) {
return BASE_URL + "/game/downloadNum.html?id=" + game_id;
}
/**
* 根据提交的类型获取视频列表
*
* @param page
* @param type_id
* @return
*/
public static final String getRecommendList(String page, String type_id, String type) {
// return BASE_URL+"/video/recommendList.html?page="+page+"&type_id="+type_id;
return BASE_URL + "/video/list.html?page=" + page + "&sort=" + type + "&type_id=" + type_id;
}
/**
* 更多热门视频、精彩推荐
*
* @param page
* @param type
* @return
*/
public static final String getRecommendVideoList(String page, String type, String flag) {
if (flag.equals("home")) {
return BASE_URL + "/video/homeDaily.html?page=" + page + "&sort=" + type;
} else {
return BASE_URL + "/video/likeVideoList.html?member_id=" + ExApplication.MEMBER_ID + "&page=" + page + "&sort=" + type;
}
}
/**
* 首页热门分类更多
*
* @param name
* @param page
* @param type
* @return
*/
public static final String getMoreHomeHotList(String name, String page, String type) {
return BASE_URL + "/search/searchVideo.html?name=" + name + "&sort=" + type + "&page=" + page;
}
/**
* 游戏圈子视频列表接口
*
* @param group_id
* @param member_id
* @param page
* @return
*/
public static final String getGameCircleVideoListUrl(String group_id, String member_id, String page) {
return BASE_URL + "/game/groupVideoList.html?group_id=" + group_id + "&member_id=" + member_id + "&page=" + page;
}
/**
* 用户上传(视频)列表
*
* @param page
* @param member_id
* @return
*/
public static final String getUploadListUrl(String page, String member_id) {
return BASE_URL + "/Video/authorVideoList.html?member_id=" + member_id + "&page=" + page;
}
/**
* 视频类型列表
*
* @return
*/
public static final String getVideoTypeList() {
return BASE_URL + "/video/typeList.html";
}
/**
* 领取礼包
*
* @param member_id
* @param id
* @return
*/
public static final String getGiftUrl(String member_id, String id) {
return BASE_URL + "/member/claimPackage.html?member_id=" + member_id + "&id=" + id;
}
/**
* 提交(二级)评论 接口
* V1.1.6
*
* @return
*/
public static final String submitCommentUrl() {
return BASE_URL + "/video/doComment116.html";
}
/**
* 个人空间评论
*
* @return
*/
public static final String submitPersonCommentUrl() {
return BASE_URL + "/member/memberReview.html";
}
/**
* 圈子评论接口
*
* @return
*/
public static final String submitGameCircleCommentUrl() {
return BASE_URL + "/game/groupReview.html";
}
/**
* 视频下载次数统计
*
* @param id
* @return
*/
public static final String getDownLoadUrl(String id) {
return BASE_URL + "/video/downLoad.html?id=" + id;
}
/**
* 视频点赞
*
* @param id
* @return
*/
public static final String getVedioFlowerUrl(String id, String member_id) {
return BASE_URL + "/video/flower.html?id=" + id + "&member_id=" + member_id;
}
/**
* 取消视频点赞
*
* @param id
* @return
*/
public static final String getVedioCancelFlowerUrl(String id, String member_id) {
return BASE_URL + "/video/cancelFlower.html?id=" + id + "&member_id=" + member_id;
}
/**
* 大神点赞接口
*
* @param id 玩家id
* @param member_id 大神ID
* @return
*/
public static final String submitMasterPriseUrl(String id, String member_id) {
return BASE_URL + "/member/like.html?id=" + id + "&member_id=" + member_id;
}
/**
* 大神关注接口
*
* @param id
* @param member_id
* @return
*/
public static final String submitMasterFocusUrl(String id, String member_id) {
return BASE_URL + "/member/attention.html?id=" + id + "&member_id=" + member_id;
}
/**
* 视频评论点赞
*
* @param comment_id 点赞对象的评论id
* @param member_id 点赞对象的玩家id
* @return
*/
public static String getCommentPriseUrl(String comment_id, String member_id) {
return BASE_URL + "/video/commentLike.html?comment_id=" + comment_id + "&member_id=" + member_id;
}
/**
* 游戏圈子评论点赞接口
*
* @param review_id
* @param member_id
* @return
*/
public static String getGameCirclePriseUrl(String review_id, String member_id) {
return BASE_URL + "/game/reviewLike.html?review_id=" + review_id + "&member_id=" + member_id;
}
/**
* 个人留言评论点赞
*
* @param comment_id
* @param member_id
* @return
*/
public static String getPersonCommentPriseUrl(String comment_id, String member_id) {
return BASE_URL + "/member/reviewLike.html?id=" + comment_id + "&member_id=" + member_id;
}
/**
* 获取关键字
* <p>
* v1.1.4接口
*
* @return
*/
public static final String getKeyWordUrlByPage() {
return BASE_URL + "/search/keyWordList.html?page=1";
}
/**
* 获取关键字
* <p>
* v1.1.5接口
*
* @return
*/
public static final String getKeyWordUrlByNum() {
return BASE_URL + "/search/keyWordListNew.html?num=9";
}
/**
* 用户登录的路径
*
* @param key 手机号
* @return
*/
public static final String getLoginUrl(String key, String password) {
return BASE_URL + "/member/loginNew.html?key=" + key + "&password=" + password;
}
/**
* 用户注册路径
*
* @param key 手机号或邮箱
* @return
*/
public static final String getRegisterUrl(String key, String password) {
return BASE_URL + "/member/registerNew.html?key=" + key + "&password=" + password + "&origin=a_sysj";
}
/**
* 直接修改密码
*
* @param uid 用户id
* @param oldpwd 原密码
* @param newpwd 新密码
* @return
*/
public static final String directModifyPsdUrl(String uid, String oldpwd, String newpwd) {
return BASE_URL + "/member/pwdModify?uid=" + uid + "&oldpwd=" + oldpwd + "&newpwd=" + newpwd;
}
/**
* 验证修改密码
*
* @param uid
* @param newpwd
* @return
*/
public static String verifyModifyPsdUrl(String uid, String newpwd) {
return BASE_URL + "/member/pwdForget?uid=" + uid + "&newpwd=" + newpwd;
}
/**
* 邮箱找回密码
*
* @param email
* @return
*/
public static String findPassWordUrl(String email) {
return BASE_URL + "/member/findForEmail?email=" + email;
}
/**
* 视频搜索的地址
*
* @param key
* @param type
* @param page
* @return
*/
public static final String getSearchVideoUrl(String key, String type, String page) {
return BASE_URL + "/search/searchVideo.html?name=" + key + "&sort=" + type + "&page=" + page;
}
/**
* 获取搜索联想词地址
*
* @return
*/
public static final String getSearchKeyWord() {
return BASE_URL + "/search/associate.html";
}
public static final String getGameCircleSearchKey(String keyWord) {
return BASE_URL + "/search/groupSearch.html?keyWord=" + keyWord;
}
/**
* 商务合作的路径
*
* @return
*/
public static final String getBussinessUrl() {
return BASE_URL + "/index/business.html";
}
/**
* 返回默认礼包列表
*
* @param page
* @return
*/
public static final String getPackageList(String memerId, String page) {
if (memerId.equals("")) {
return BASE_URL + "/member/packageList.html?page=" + page;
} else {
return BASE_URL + "/member/packageList.html?page=" + page + "&member_id=" + memerId;
}
}
/**
* 返回默认任务列表
* <p>
* V1.1.4
*
* @return
*/
public static final String getTaskList(String page) {
if (!ExApplication.MEMBER_ID.equals("")) {
return BASE_URL + "/member/taskListNew.html?page=" + page + "&member_id=" + ExApplication.MEMBER_ID;
}
return BASE_URL + "/member/taskListNew.html?page=" + page;
}
/**
* 返回默认任务列表
* <p>
* V1.1.5,新增接受任务
*
* @return
*/
public static final String getTaskList115(String page) {
if (!ExApplication.MEMBER_ID.equals("")) {
return BASE_URL + "/member/taskList115.html?member_id=" + ExApplication.MEMBER_ID + "&page=" + page;
}
return BASE_URL + "/member/taskList115.html?page=" + page;
}
/**
* 接受任务
* <p>
*
* @return {
* "result": true,
* "data": [],
* "msg": "接受任务成功"
* }
*/
public static final String acceptTask(String task_id) {
return BASE_URL + "/member/acceptTask.html?member_id=" + ExApplication.MEMBER_ID + "&task_id=" + task_id;
}
/**
* 完成任务
* V1.1.4
*
* @param id
* @return
*/
public static String completeMission(String id) {
return BASE_URL + "/member/doTask.html?member_id=" + ExApplication.MEMBER_ID + "&task_id=" + id;
}
/**
* 做任务方法接口
* <p>
* v1.1.5
*
* @return {
* "result": true,
* "data": [],
* "msg": "任务操作成功"
* }
*/
public static final String doTask115(String task_id) {
return BASE_URL + "/member/doTask115.html?member_id=" + ExApplication.MEMBER_ID + "&task_id=" + task_id;
}
/**
* 做任务方法接口
* <p>
* v1.1.7
*
* @return {
* "result": true,
* "data": [],
* "msg": "任务操作成功"
* }
*/
public static final String doTask117(String task_id) {
return BASE_URL + "/member/doTask117.html?member_id=" + ExApplication.MEMBER_ID + "&task_id=" + task_id;
}
/**
* 判断是否完成任务接口
* <p>
*
* @return {
* "result": true,
* "data": [],
* "msg": "任务完成成功"
* }
*/
public static final String finishTaskNew(String task_id) {
return BASE_URL + "/member/finishTaskNew.html?member_id=" + ExApplication.MEMBER_ID + "&task_id=" + task_id;
}
/**
* 领取任务奖励
* <p>
*
* @param task_id
* @return {
* "result": true,
* "data": [],
* "msg": "领取经验成功"
* }
*/
public static final String getTaskReward(String task_id) {
return BASE_URL + "/member/getExp.html?member_id=" + ExApplication.MEMBER_ID + "&task_id=" + task_id;
}
/**
* 未完成任务个数接口
*
* @return {
* "result": true,
* "data": {
* "itemsCount": 9
* },
* "msg": "获取数据成功"
* }
*/
public static final String getTaskUnDoNum() {
return BASE_URL + "/member/taskUnDoNum?member_id=" + ExApplication.MEMBER_ID;
}
/**
* 返回活动页面三个数据列表(活动、赛事、任务)
*
* @param page
* @return
*/
public static final String getActivityFrameList(String page) {
if (!ExApplication.MEMBER_ID.equals("")) {
return BASE_URL + "/member/taskList.html?page=" + page + "&member_id=" + ExApplication.MEMBER_ID + "&flag=activity";
}
return BASE_URL + "/member/taskList.html?page=" + page + "&flag=activity";
}
/**
* 返回活动中心路径
*
* @param page
* @return
*/
public static final String getMoreActivityUrl(String page) {
return BASE_URL + "/focuse/getFocuseList.html?page=" + page;
}
/**
* 活动详情
*
* @param id
* @return
*/
public static final String getActivityDetailUrl(String id) {
return BASE_URL + "/recommend/activityDetail.html?id=" + id;
}
/**
* 活动信息
* <p>
* V1.1.5
*
* @param match_id
* @return
*/
public static final String getMatchInfoUrl(String match_id) {
if (!ExApplication.MEMBER_ID.equals("")) {
return BASE_URL + "/Match/matchInfo.html?match_id=" + match_id + "&member_id=" + ExApplication.MEMBER_ID;
}
return BASE_URL + "/Match/matchInfo.html?match_id=" + match_id;
}
/**
* 活动信息 中 对应赛事的参赛视频列表信息
* <p>
* V1.1.5
*
* @param match_id
* @return
*/
public static final String getMatchVideoListUrl(String match_id, String page) {
return BASE_URL + "/Match/matchVideoList.html?match_id=" + match_id + "&page=" + page;
}
/**
* 返回赛事中心路径(旧接口)
*
* @param page
* @return
*/
public static final String getMoreMatchUrl(String page) {
return BASE_URL + "/member/getMatchList.html?page=" + page;
}
/**
* 返回 主页活动 热门活动 路径
* V1.1.5
*
* @param page
* @return
*/
public static final String getHotMatchUrl(String page) {
return BASE_URL + "/Match/getMatchList.html?page=" + page;
}
/**
* 返回 主页活动 我的活动 路径
* V1.1.5
*
* @param
* @return
*/
public static final String getMyMatchUrl() {
return BASE_URL + "/Match/myMatchList.html?member_id=" + ExApplication.MEMBER_ID;
}
/**
* 返回 参加赛事活动 路径
* V1.1.5
*
* @param match_id
* @return
*/
public static final String getJoinMatchUrl(String match_id) {
return BASE_URL + "/match/joinMatch.html?member_id=" + ExApplication.MEMBER_ID + "&match_id=" + match_id;
}
/**
* 搜索礼包的路径
*
* @param name
* @param page
* @return
*/
public static final String getSearchGiftUrl(String name, String page) {
return BASE_URL + "/search/searchPackage.html?name=" + name + "&page=" + page;
}
/**
* 返回搜索到的任务
*
* @param name
* @param page
* @return
*/
public static final String getSearchMisssionUrl(String name, String page) {
return BASE_URL + "/search/searchTask.html?name=" + name + "&page=" + page;
}
/**
* 搜索用户昵称
*
* @param nickname
* @return
*/
public static final String getFindUser(String nickname, String page) {
return BASE_URL + "/search/searchMember.html?name=" + nickname + "&page=" + page;
}
/**
* 达人榜接口
*
* @param member_id
* @param flag
* @param page
* @return
*/
public static final String getExpertUrl(String member_id, String flag, String page) {
return BASE_URL + "/member/daRenListNew.html?member_id=" + member_id + "&flag=" + flag + "&page=" + page;
}
/**
* 关注列表
*
* @param member_id
* @param page
* @return
*/
public static final String getMyAttentionUrl(String member_id, String page) {
return BASE_URL + "/member/personalAttention.html?member_id=" + member_id + "&page=" + page;
}
/**
* 粉丝列表
*
* @param member_id
* @param page
* @return
*/
public static final String getMyFansUrl(String member_id, String page) {
return BASE_URL + "/member/personalFans.html?member_id=" + member_id + "&page=" + page;
}
/**
* 个人排名
*
* @return
*/
public static final String getExpertRankUrl() {
return BASE_URL + "/member/myDaRenList.html?member_id=" + ExApplication.MEMBER_ID;
}
/**
* 游戏圈子玩家列表接口
*
* @param group_id
* @param member_id
* @param page
* @return
*/
public static final String getGameCircleUserUrl(String group_id, String member_id, String page) {
return BASE_URL + "/game/groupMemberList.html?group_id=" + group_id + "&member_id=" + member_id + "&page=" + page;
}
/**
* 关于我们
*
* @return
*/
public static final String getAboutUsUrl() {
return BASE_URL + "/index/aboutUs.html";
}
/**
* 反馈的地址
*
* @return
*/
public static final String getFeekbackUrl() {
return BASE_URL + "/index/feedback.html";
}
/**
* 获取验证码接口
*
* @return
*/
public static final String getPhoneCodeUrl() {
return BASE_URL + "/member/msgRequestNew.html";
}
/**
* 手机注册接口
*
* @return
*/
public static final String getPhoneRegisterUrl() {
return BASE_URL + "/member/verifyCodeNew.html";
}
/**
* 返回精彩推荐的地址
* <p>
* 1、有选择喜欢类型,获取数据成功
* 2、没有选择喜欢类型,获取数据成功
* <p>
* V1.1.5
*
* @param
* @return
*/
public static final String getFavorRecommendUrl() {
if (!ExApplication.MEMBER_ID.equals("")) {
return BASE_URL + "/video/likeVideoList115.html?member_id=" + ExApplication.MEMBER_ID;
}
return BASE_URL + "/video/likeVideoList115.html";
}
/**
* 大神详情头部信息接口
*
* @param id
* @param member_id
* @return
*/
public static String getMasterHeadInfoUrl(String id, String member_id) {
return BASE_URL + "/topic/specialTopic.html?id=" + id + "&member_id=" + member_id;
}
/**
* 获取更多热门推荐视频的地址
*
* @return
*/
public static String getMoreRecommendUrl(String page) {
return BASE_URL + "/video/homeDaily.html?page=" + page;
}
/**
* 返回主页 首页专栏 的地址
* <p>
* 热门视频
* 视界专栏 (舞大大学堂/小小舞玩新游/阿沫爱品评)
* 热门游戏、热门分类
* <p>
* page从1开始计算
* <p>
* V1.1.6
*
* @return
*/
public static String getHomeColumnUrl(String page) {
return BASE_URL + "/index/appIndexList.html?page=" + page;
}
/**
* 主页首页 首页专栏 更多 地址
* <p>
* 热门视频
* 视界专栏 (舞大大学堂/小小舞玩新游/阿沫爱品评)
* 热门游戏、热门分类
* <p>
* page从1开始计算
* <p>
* V1.1.6
* sort空为time,page空为1
*
* @param more_mark
* @param sort
* @param page
* @return
*/
public static String getMoreHomeColumnUrl(String more_mark, String sort, String page) {
return BASE_URL + "/index/appIndexMore.html?more_mark=" + more_mark + "&sort=" + sort + "&page=" + page;
}
/**
* 轻松一刻接口
*
* @param page
* @return
*/
public static String getRelaxeVideoUrl(String page) {
return BASE_URL + "/video/relaxedMoment.html?page=" + page;
}
/**
* 推荐ing
*
* @param page
* @return
*/
public static String getRecommendingUrl(String page) {
return BASE_URL + "/recommend/recommendList.html?page=" + page;
}
/**
* 启动页 图片(广告位) 路径
*
* @return
*/
public static String getLaunchImageUrl(String time) {
return BASE_URL + "/index/launchImage.html?target=a_sysj&time=" + time;
}
/**
* 主页 首页广告
*
* @return
*/
public static String getHomeAdUrl() {
return BASE_URL + "/recommend/homeHd.html";
}
/**
* 获取广告位的路径
*
* @return
*/
public static String getAdVedioUrl() {
return BASE_URL + "/focuse/list.html";
}
/**
* 玩家秀 滚动广告位 路径
*
* @return
*/
public static String getAdPlayerShowUrl() {
return BASE_URL + "/recommend/playerShow.html";
}
/**
* Banner广告位 路径
*
* @return
*/
public static String getBannerAdUrl(String situation) {
return BASE_URL + "/video/uplaodImage.html?situation=" + situation;
}
/**
* 获取礼包的路径
*
* @return
*/
public static String getGiftUrl() {
return BASE_URL + "/member/packageList.html";
}
/**
* 视频详情的路径
*
* @param id
* @return
*/
public static String getVedioUrl(String id, String member_id) {
return BASE_URL + "/video/detail.html?id=" + id + "&member_id=" + member_id;
}
/**
* 玩家秀视频列表
*
* @return
*/
public static String getPlayerShowUrl(String page) {
return BASE_URL + "/recommend/playerShowList.html?page=" + page;
}
/**
* 大神详情页大神更新接口
*
* @param id
* @param page
* @return
*/
public static String getMasterUpdateUrl(String id, String page) {
return BASE_URL + "/topic/topicVideoList.html?id=" + id + "&page=" + page;
}
/**
* 发现视频列表接口
*
* @return
*/
public static String getDiscoverVideoUrl() {
return BASE_URL + "/video/everyoneLook.html";
}
/**
* 下一个视频接口
*
* @param id
* @return
*/
public static String getNextVideoUrl(String id) {
return BASE_URL + "/video/playNext.html?id=" + id;
}
/**
* 获取 评论列表 的路径
*
* @param id
* @param page
* @return
*/
public static String getCommentUrl(String id, String page) {
return BASE_URL + "/video/commentList.html?id=" + id + "&page=" + page + "&member_id=" + ExApplication.MEMBER_ID;
}
/**
* 个人空间评论
*
* @param id
* @param page
* @return
*/
public static String getPersonCommentUrl(String member_id, String page, String id) {
return BASE_URL + "/member/memberReviewList.html?member_id=" + member_id + "&page=" + page + "&id=" + id;
}
/**
* 游戏圈子评论列表
*
* @param group_id
* @param member_id
* @param page
* @return
*/
public static String getGameCircleCommentUrl(String group_id, String member_id, String page) {
return BASE_URL + "/game/reviewList.html?group_id=" + group_id + "&member_id=" + member_id + "&page=" + page;
}
/**
* 获取用户上传的视频ID
*
* @param id
* @return
*/
public static final String getUserVideoId(String id) {
return BASE_URL + "/Video/getVidById.html?member_id=" + id;
}
/**
* get请求
*
* @param url
* @return
*/
public static String httpGet(String url) {
String str = "";
try {
HttpGet request = new HttpGet(url);
HttpClient httpClient = new DefaultHttpClient();////生成一个http客户端对象
HttpResponse response = httpClient.execute(request);//http客户端执行请求,得到http响应
if (response.getStatusLine().getStatusCode() == 200) {
str = EntityUtils.toString(response.getEntity());//response.getEntity() 从http响应中得到元素
}
} catch (Exception e) {
Log.e("httpGet", e.toString());
str = "";
}
Log.e("HttpGet_Response", str);
return str;
}
/**
* 获取搜索联想关键词的get请求
*
* @param url
* @param keyWord
* @return
*/
public static String[] httpGet(String url, String keyWord) {
String str = "";
String[] word = {};
HttpGet request = new HttpGet(url + "?keyWord=" + keyWord);
HttpClient httpClient = new DefaultHttpClient();
try {
HttpResponse response = httpClient.execute(request);
if (response.getStatusLine().getStatusCode() == 200) {
str = EntityUtils.toString(response.getEntity());
JSONObject object = new JSONObject(str);
JSONArray array = object.getJSONArray("data");
word = new String[array.length()];
for (int i = 0; i < array.length(); i++) {
object = array.getJSONObject(i);
word[i] = object.getString("name");
}
}
} catch (Exception e) {
Log.e("httpGet", e.toString());
str = "";
}
Log.e("HttpGet_Response", str);
return word;
}
/**
* post请求
*
* @param param 提交字段
* @param params 路径
* @return
*/
public static String httpPost(List<NameValuePair> param, String... params) {
String rs = "";
try {
HttpClient httpClient = new DefaultHttpClient();////生成一个http客户端对象
HttpParams httpparams = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(httpparams, 5000);//设置连接超时时间
HttpConnectionParams.setSoTimeout(httpparams, 5000);//设置请求超时
HttpPost httpPost = new HttpPost(params[0]);//客户端向服务器发送请求,返回一个响应对象
httpPost.setEntity(new UrlEncodedFormEntity(param, HTTP.UTF_8));
HttpResponse response = new DefaultHttpClient().execute(httpPost);
// HttpResponse response2 = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
rs = EntityUtils.toString(response.getEntity());
}
} catch (Exception e) {
Log.e("httpPost", e.toString());
rs = "";
}
Log.e("HttpPost_Response", rs);
return rs;
}
/**
* 提交用户上传视频信息的Post请求
*
* @param member_id 用户id
* @param video_id 视频id
* @param video_name 视频标题
* @param game_name 游戏名
* @param time_length 视频时长
* @param postVideoInfoUrl post请求地址
* @return
*/
public static String httpPost(String member_id, String video_id,
String video_name, String game_name, String time_length, String match_id, String phone, String qq, String postVideoInfoUrl) {
String rs = "";
HttpPost httpPost = new HttpPost(postVideoInfoUrl);
HttpClient httpClient = new DefaultHttpClient();
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("member_id", member_id));
pairs.add(new BasicNameValuePair("video_id", video_id));
pairs.add(new BasicNameValuePair("name", video_name));
pairs.add(new BasicNameValuePair("game_name", game_name));
pairs.add(new BasicNameValuePair("time_length", time_length));
if (match_id != null) {
pairs.add(new BasicNameValuePair("match_id", match_id));
pairs.add(new BasicNameValuePair("phone", phone));
pairs.add(new BasicNameValuePair("qq", qq));
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));
HttpResponse response = httpClient.execute(httpPost);
System.out.println(response.getStatusLine().getStatusCode());
if (response.getStatusLine().getStatusCode() == 200) {
rs = EntityUtils.toString(response.getEntity());
}
} catch (Exception e) {
e.printStackTrace();
rs = "";
}
return rs;
}
/**
* post请求
*
* @param params 路径
* @return
*/
public static String httpPost(String name, String descripe, String time, String id, String fileUrl, String... params) {
String rs = "";
try {
HttpClient httpClient = new DefaultHttpClient();////生成一个http客户端对象
HttpParams httpparams = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(httpparams, 20000);//设置连接超时时间
HttpConnectionParams.setSoTimeout(httpparams, 600000);//设置请求超时
HttpPost post = new HttpPost(params[0]);//客户端向服务器发送请求,返回一个响应对象
MultipartEntity entity = new MultipartEntity();
// entity.addPart("data",new StringBody(content));
if (!fileUrl.equals("")) {
File file = new File(fileUrl);
Log.e("Img", fileUrl);
entity.addPart("files", new FileBody(file));
}
entity.addPart("member_id", new StringBody(ExApplication.MEMBER_ID));
entity.addPart("name", new StringBody(name));
entity.addPart("url", new StringBody(id));
entity.addPart("descriptoin", new StringBody(descripe));
entity.addPart("time_length", new StringBody(time));
post.setEntity(entity);
// post.setEntity(new UrlEncodedFormEntity(param, HTTP.UTF_8));
HttpResponse response = new DefaultHttpClient().execute(post);
if (response.getStatusLine().getStatusCode() == 200) {
rs = EntityUtils.toString(response.getEntity());
}
} catch (Exception e) {
Log.e("httpPost", e.toString());
rs = "";
}
Log.e("HttpPost_Response", rs);
return rs;
}
/**
* 上传文件
*
* @param context
* @return
*/
public static String postImage(Context context, String httpUrl, String fileUrl) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(httpUrl);
MultipartEntity entity = new MultipartEntity();
// entity.addPart("data",new StringBody(content));
if (!fileUrl.equals("")) {
File file = new File(fileUrl);
Log.e("headImg", fileUrl);
entity.addPart("upFile", new FileBody(file));
}
postRequest.setEntity(entity);
HttpResponse response = httpClient.execute(postRequest);
if (response.getStatusLine().getStatusCode() == 200) {
String res = EntityUtils.toString(response.getEntity());
Log.e("response", res);
// return EncryptUtil.decrypt(EntityUtils.toString(response.getEntity()));
return res;
}
} catch (Exception e) {
Log.e("response_exception", e.toString());
return "";
}
return "";
}
// 请求上传凭证接口
public static final String PostVideoEntityBackToke() {
return "http://apps.ifeimo.com/home/video/doVideoMark202.html";
}
// 请求上传凭证
public static String httpPostVideoEntityBackToke(List<NameValuePair> pairs, String postUrl) {
String rs = "";
HttpPost httpPost = new HttpPost(postUrl);
HttpClient httpClient = new DefaultHttpClient();
try {
httpPost.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));
HttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
rs = EntityUtils.toString(response.getEntity());
}
} catch (Exception e) {
e.printStackTrace();
rs = "";
}
return rs;
}
//提交上传结果接口
public static final String PostVideoUploadResult() {
return "http://apps.ifeimo.com/home/video/qiniuTokenPass202.html";
}
/**
* @param context
* @param httpUrl 接口
* @param memberID 用户
* @param videokey 七牛上的视频id
* @param timeLength 时长
* @param isSuccess 是否上传成功(1为上成功,0为上传失败)
* @param fileUrl 封面在本地的位置
* @return
*/
public static String httpPostVideoUpoloadResult(Context context, String httpUrl,
String memberID, String videokey, String timeLength,
String isSuccess, String fileUrl) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(httpUrl);
MultipartEntity entity = new MultipartEntity();
entity.addPart("member_id",
new StringBody(memberID, Charset.forName("utf-8")));
entity.addPart("videokey",
new StringBody(videokey, Charset.forName("utf-8")));
entity.addPart("time_length",
new StringBody(timeLength, Charset.forName("utf-8")));
entity.addPart("is_success",
new StringBody(isSuccess, Charset.forName("utf-8")));
if (!fileUrl.equals("")) {
File file = new File(fileUrl);
Log.e("headImg", fileUrl);
entity.addPart("flag", new FileBody(file));
}
postRequest.setEntity(entity);
HttpResponse response = httpClient.execute(postRequest);
if (response.getStatusLine().getStatusCode() == 200) {
String res = EntityUtils.toString(response.getEntity());
Log.e("response", res);
return res;
}
} catch (Exception e) {
Log.e("response_exception", e.toString());
return "";
}
return "";
}
// 请求上传结果
public static String httpPostVideoUpoloadResult(List<NameValuePair> pairs,
String postUrl) {
String rs = "";
HttpPost httpPost = new HttpPost(postUrl);
HttpClient httpClient = new DefaultHttpClient();
try {
httpPost.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));
HttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
rs = EntityUtils.toString(response.getEntity());
}
} catch (Exception e) {
e.printStackTrace();
rs = "";
}
return rs;
}
/**
* 上传视频封面
*
* @return
*/
public static final String getuploadVideoCover(String videoKey) {
return "http://apps.ifeimo.com/home/video/uploadPicQiniu.html?videokey=" + videoKey;
}
/**
* 上传文件
*
* @param context
* @return
*/
public static String postImage(Context context, String videokey, String httpUrl, String fileUrl) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(httpUrl);
MultipartEntity entity = new MultipartEntity();
// entity.addPart("data",new StringBody(content));
if (!fileUrl.equals("")) {
File file = new File(fileUrl);
Log.e("headImg", fileUrl);
entity.addPart("upFile", new FileBody(file));
}
postRequest.setEntity(entity);
HttpResponse response = httpClient.execute(postRequest);
if (response.getStatusLine().getStatusCode() == 200) {
String res = EntityUtils.toString(response.getEntity());
Log.e("response", res);
// return EncryptUtil.decrypt(EntityUtils.toString(response.getEntity()));
return res;
}
} catch (Exception e) {
Log.e("response_exception", e.toString());
return "";
}
return "";
}
}
| true
|
479b49cdd713ff7d18705d429488d19612086e45
|
Java
|
jtong-kata/pos-net-shell-only
|
/java/maven/src/main/java/GotoBar2ZipCommand.java
|
UTF-8
| 353
| 2.21875
| 2
|
[] |
no_license
|
import java.util.Map;
public class GotoBar2ZipCommand implements Command {
private Map<String, Command> newMapping;
public GotoBar2ZipCommand(Map<String, Command> newMapping) {
this.newMapping = newMapping;
}
public Result invoke(String input) {
return new Result("Please input bar code:", newMapping, false);
}
}
| true
|
81ea3922daa0f80ca0c707737b2e3175dd51235a
|
Java
|
thanhlam1211/JAVALAB_J1.L.P0021
|
/LAB21/src/Validation.java
|
UTF-8
| 4,257
| 3.046875
| 3
|
[] |
no_license
|
import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput;
import java.util.ArrayList;
import java.util.Scanner;
public class Validation {
public static final Scanner sc = new Scanner(System.in);
public static int checkInputLimit(int min, int max) {
while (true) {
try{
int result = Integer.parseInt(sc.nextLine().trim());
if(result < min || result > max) {
throw new NumberFormatException();
}
return result;
}catch (NumberFormatException ex){
System.err.println("Please enter the number between [ " + min + ", "+ max+" ]");
System.out.println("Enter again");
}
}
}
public static String checkInputString() {
while (true) {
String result = sc.nextLine().trim();
if(result.isEmpty()) {
System.err.println("Can not be empty");
System.out.println("Please enter again!");
}else
return result;
}
}
public static boolean checkInputYN() {
while (true) {
String result = checkInputString();
if (result.equalsIgnoreCase("Y")) {
return true;
}
if (result.equalsIgnoreCase("N")) {
return false;
}
System.err.println("Syntax error, try again");
System.out.println("Enter again");
}
}
public static String checkInputCourse() {
while (true) {
String result = checkInputString();
if(result.equalsIgnoreCase("java")
|| result.equalsIgnoreCase(".net")
|| result.equalsIgnoreCase("c/c++")) {
return result;
}
System.err.println("There are only 3 course: Java, .Net and C/C++");
System.out.println("Enter again!");
}
}
public static boolean checkInputUD (){
while (true) {
String result = checkInputString();
if (result.equalsIgnoreCase("U")) {
return true;
}
if (result.equalsIgnoreCase("D")) {
return false;
}
System.err.println("Please enter U/u or D/d");
System.out.println("Enter again");
}
}
//check id exist
public static String checkIdExist(ArrayList<Student> listStudent, String id) {
for(Student st:listStudent) {
if(id.equalsIgnoreCase(st.getId())) {
return st.getName();
}
}
return null;
}
public static boolean checkStudentExist(ArrayList<Student> listStudent, String id, String name, String semester, String courseName){
for(Student st: listStudent) {
if(id.equals(st.getId())
&& name.equalsIgnoreCase(st.getName())
&& semester.equalsIgnoreCase(st.getSemester())
&& courseName.equalsIgnoreCase(st.getCourseName())) {
return false;
}
}
return true;
}
//check report exist
public static boolean checkReportExist(ArrayList<Report> listReport, String name, String course, int total) {
for(Report report : listReport) {
if(name.equalsIgnoreCase(report.getCourseName())
&& course.equalsIgnoreCase(report.getCourseName())
&& total == report.getTotalCourse()) {
return false;
}
}
return true;
}
//check user change or not
public static boolean checkChangeInformation(Student student, String id, String name,
String semester, String course) {
if(id.equalsIgnoreCase(student.getId())
&& name.equalsIgnoreCase(student.getName())
&& semester.equalsIgnoreCase(student.getSemester())
&& course.equalsIgnoreCase(student.getCourseName())) {
return false;
}
return true;
}
}
| true
|
39aabf9757bf1e92dd961a61447e2b055c6c9658
|
Java
|
ppetko98/proyecto
|
/JSE-SWING-JDBC-PROYECTO-CASA/src/modelo/entidades/Nomenclatura.java
|
UTF-8
| 1,809
| 2.75
| 3
|
[] |
no_license
|
package modelo.entidades;
public class Nomenclatura {
private int especie, dominio, filo, clase, orden, familia, genero;
public Nomenclatura(int especie, int genero, int clase, int filo, int orden, int familia, int dominio) {
this.especie = especie;
this.genero = genero;
this.clase = clase;
this.filo = filo;
this.orden = orden;
this.familia = familia;
this.dominio = dominio;
}
public Nomenclatura() {
}
public int getEspecie() {
return especie;
}
public void setEspecie(int especie) {
this.especie = especie;
}
public int getGenero() {
return genero;
}
public void setGenero(int genero) {
this.genero = genero;
}
public int getClase() {
return clase;
}
public void setClase(int clase) {
this.clase = clase;
}
public int getFilo() {
return filo;
}
public void setFilo(int filo) {
this.filo = filo;
}
public int getOrden() {
return orden;
}
public void setOrden(int orden) {
this.orden = orden;
}
public int getFamilia() {
return familia;
}
public void setFamilia(int familia) {
this.familia = familia;
}
public int getDominio() {
return dominio;
}
public void setDominio(int dominio) {
this.dominio = dominio;
}
@Override
public String toString() {
return "Nomenclatura{"
+ "especie=" + especie
+ ", genero=" + genero
+ ", clase=" + clase
+ ", filo=" + filo
+ ", orden=" + orden
+ ", familia=" + familia
+ ", dominio=" + dominio
+ '}';
}
}
| true
|
24df879d5a4d6dd0b9ecf830267b4c5fe2fbc0c2
|
Java
|
Witold101/camecoGoods
|
/src/by/vistar/comeco/services/ServiceMain.java
|
UTF-8
| 711
| 2.40625
| 2
|
[] |
no_license
|
package by.vistar.comeco.services;
import java.sql.Connection;
import java.sql.SQLException;
public class ServiceMain {
Connection connection;
public ServiceMain(Connection connection) {
this.connection = connection;
}
public void startTransaction() {
try {
this.connection.setAutoCommit(false);
} catch (SQLException e) {
System.out.println("Error init setAutocommit = false");
e.printStackTrace();
}
}
public void commit() {
try {
this.connection.commit();
} catch (SQLException e) {
System.out.println("Error commit");
e.printStackTrace();
}
}
}
| true
|
32d55a60274b781bac1b8c416b6577ffbbd3d9fc
|
Java
|
jango2015/RetailerAndroid
|
/app/src/main/java/com/neighbor/retailer_android/ui/activity/shopcart/OrderDetailActivity.java
|
UTF-8
| 3,966
| 2.328125
| 2
|
[] |
no_license
|
package com.neighbor.retailer_android.ui.activity.shopcart;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import com.neighbor.retailer_android.R;
import com.neighbor.retailer_android.bean.ShopInfo;
import com.neighbor.retailer_android.ui.adapter.OrderShopListAdapter;
import java.util.ArrayList;
import java.util.List;
public class OrderDetailActivity extends Activity implements View.OnClickListener{
/* 返回键 */
private ImageButton back;
/* 标题 */
private TextView title;
/* 订单中商品listview */
private ListView listView;
/* 删除订单 */
private Button delete;
/* header footer 布局画布 */
private LayoutInflater mInflater;
/* listview 头 */
private View header;
/* listview 尾 */
private View footer;
/* 切换地址按钮 */
private ImageButton addressImg;
/* 收货人 */
private TextView recName;
/* 收货人联系方式 */
private TextView recPhone;
/* 收货地址 */
private TextView recAddress;
/* 批发商名称 */
private TextView wsName;
/* 总价 */
private TextView totalPrice;
/* 订单编码 */
private TextView orderCode;
/* 下单时间 */
private TextView orderTime;
/* 分为两种(一是已完成订单的付款时间,二是订单状态) */
private TextView orderStateTag;
/* 上面Tag值(一为时间,二为状态) */
private TextView orderStateValue;
/* 适配器 */
private OrderShopListAdapter adpater;
/* 数据源 */
private List<ShopInfo> mList = new ArrayList<ShopInfo>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_detail);
back = (ImageButton)findViewById(R.id.wholesaler_back);
title = (TextView)findViewById(R.id.wholesaler_title);
title.setText("订单详情");
listView = (ListView)findViewById(R.id.order_submit_lv);
delete = (Button)findViewById(R.id.delete_order);
mInflater = LayoutInflater.from(OrderDetailActivity.this);
header = mInflater.inflate(R.layout.submit_order_lv_header, null);
footer = mInflater.inflate(R.layout.order_detail_lv_footer, null);
listView.addHeaderView(header);
listView.addFooterView(footer);
addressImg = (ImageButton)header.findViewById(R.id.chance_address);
recName = (TextView)header.findViewById(R.id.recive_name);
recPhone = (TextView)header.findViewById(R.id.recive_phone);
recAddress = (TextView)header.findViewById(R.id.recive_address);
wsName = (TextView)header.findViewById(R.id.ws_name);
totalPrice = (TextView)footer.findViewById(R.id.order_total_price);
orderCode = (TextView)footer.findViewById(R.id.order_code);
orderTime = (TextView)footer.findViewById(R.id.order_create_time);
orderStateTag = (TextView)footer.findViewById(R.id.order_state_tag);
orderStateValue = (TextView)footer.findViewById(R.id.order_state_tag_value);
back.setOnClickListener(this);
delete.setOnClickListener(this);
addressImg.setClickable(false);
adpater = new OrderShopListAdapter(this,mList);
listView.setAdapter(adpater);
for(int i = 0;i < 10;i++){
ShopInfo info = new ShopInfo();
mList.add(info);
}
adpater.notifyDataSetChanged();
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.wholesaler_back:
finish();
break;
case R.id.delete_order:
//删除订单
break;
}
}
}
| true
|
68ee02204632cc242a193da9d51e22b1ecede9c9
|
Java
|
Khushi-185/nstermwork
|
/19_KhushaliPanchal/Practicals/PasswordEncryption/Client.java
|
UTF-8
| 1,060
| 3.265625
| 3
|
[] |
no_license
|
package Assign2.que1;
import java.net.*;
import java.io.*;
import java.util.Scanner;
class Client{
public static void main(String args[]) throws Exception{
Socket s=new Socket("127.0.0.1",1234);
Scanner sc=new Scanner(System.in);
System.out.println("Enter Password : ");
String msg=sc.nextLine();
String encrypted = encryption(msg);
DataOutputStream out=new DataOutputStream(s.getOutputStream());
out.writeUTF(encrypted);
s.close();
}
public static String encryption(String msg)
{
String encrypted="";
char ch;
for(int i=0;i<msg.length();i++)
{
ch = msg.charAt(i);
if(ch > 'a' && ch < 'z')
{
ch = (char)(ch + 3);
if(ch > 'z')
{
ch = (char)(ch - 'z' + 'a'-1);
}
encrypted= encrypted + ch;
}
else if(ch >= 'A' && ch <= 'Z')
{
ch = (char)(ch + 3);
if(ch > 'Z')
{
ch = (char)(ch - 'Z' + 'A' - 1);
}
encrypted = encrypted + ch;
}
else
{
encrypted = encrypted + ch;
}
}
return encrypted;
}
}
| true
|
a6dd92d24e65adceb924b2c06ae5df10c75c0dba
|
Java
|
dzboy2k/fpl_java1
|
/Bài 04 - Lớp và Đối tượng/Slide_04/src/slide_04/SinhVien.java
|
UTF-8
| 834
| 3.09375
| 3
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package slide_04;
/**
*
* @author dzboy
*/
public class SinhVien {
private String hoTen;
private double diem;
public String getHoTen() {
return hoTen;
}
public void setHoTen(String hoTen) {
this.hoTen = hoTen;
}
public double getDiem() {
return diem;
}
// Chỉ cần thêm mã vào phương thức setDiem() để có những xử lý khi dữ liệu
// không hợp lệ
public void setDiem(double diem) {
if (diem < 0 || diem > 10) {
System.out.println("Điểm không họp lệ");
} else {
this.diem = diem;
}
}
}
| true
|
11216087f49069d09f5ccdcfaa14ba1c665caa89
|
Java
|
seongmin-kwon/Java_Basic_Pratice
|
/Method_02.java
|
UTF-8
| 1,081
| 4
| 4
|
[] |
no_license
|
package days08;
public class Method_02 {
// 매배변수 메서드 호풀시 메서드가 필요로하는 데이터를 전달해주는 매개역할의 변수
public static void myPrint() {
System.out.println("나의 출력 메서드");
}
public static void main(String[] args) {
myPrint();
myPrintWith2Int(10,20); // 10 20 은 전달인자이다.
}
//public: 공용의 의미 누구나 사용 가능 메서드 앞에 표기
//static : 정적 의미 처음부터 만들어지는 이라는 의미로 추후 객체지향에서 배움
//void : 빈 리턴값이 없다는 의미. 메서드 관련 이후 예제에서 공부
public static void myPrintWith2Int(int n1 ,int n2 ) {
System.out.println("전달 값1: " +n1 +"전달 값2:" +n2); //n1 n2는매개변수 라한다.
}
//c와 다른점이 이런 부분이다. c는 반드시 위에 선언이라도 해줘야 하지만 자바는 어디든 상관 없다.
//전달인수는매개변수의 수 와 타입에 맞게 사용해야 에러안남.
//전달 순서 역시 지켜줘야한다.
}
| true
|
1da895f497ed4fa403b7a5afe99bf084a9617f0c
|
Java
|
PhilMacGregor/xoxobot
|
/src/ai/MapResolver.java
|
UTF-8
| 152
| 1.96875
| 2
|
[] |
no_license
|
package ai;
import java.awt.Dimension;
public interface MapResolver {
public Player getFieldAt(int x, int y);
public Dimension getMapSize();
}
| true
|
1dfad14f31c8d771bb104a686aac0109b932ccc1
|
Java
|
haoduor/GuChatRoom
|
/src/main/java/com/gu/chatroom/model/Message.java
|
UTF-8
| 1,838
| 2.1875
| 2
|
[] |
no_license
|
package com.gu.chatroom.model;
import java.io.Serializable;
import java.util.Date;
public class Message implements Serializable {
private Integer id;
private Integer sender;
private Integer receiver;
private Integer chatroom;
private Integer channel;
private String message;
private Date sendTime;
private Boolean isRecall;
private Boolean isDelete;
private static final long serialVersionUID = -7933291995425364664L;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getSender() {
return sender;
}
public void setSender(Integer sender) {
this.sender = sender;
}
public Integer getReceiver() {
return receiver;
}
public void setReceiver(Integer receiver) {
this.receiver = receiver;
}
public Integer getChatroom() {
return chatroom;
}
public void setChatroom(Integer chatroom) {
this.chatroom = chatroom;
}
public Integer getChannel() {
return channel;
}
public void setChannel(Integer channel) {
this.channel = channel;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message == null ? null : message.trim();
}
public Date getSendTime() {
return sendTime;
}
public void setSendTime(Date sendTime) {
this.sendTime = sendTime;
}
public Boolean getIsRecall() {
return isRecall;
}
public void setIsRecall(Boolean isRecall) {
this.isRecall = isRecall;
}
public Boolean getIsDelete() {
return isDelete;
}
public void setIsDelete(Boolean isDelete) {
this.isDelete = isDelete;
}
}
| true
|
c15bef761fa7b964f62a84f8215e2a1917ac8970
|
Java
|
tonsr/project
|
/comm-stage/comm-db/src/main/java/com/demo/dbconnector/DataSourceProperty.java
|
UTF-8
| 1,423
| 2.421875
| 2
|
[] |
no_license
|
package com.demo.dbconnector;
import org.springframework.util.StringUtils;
public class DataSourceProperty {
public DataSourceProperty(String name) {
this.name = name;
}
public String getName() {
return name;
}
private String name;
private String url;
private String password;
private String username;
private String driver;
public String getUrl() {
return url;
}
public void setUrl(String url) {
if(StringUtils.isEmpty(url)){
throw new DataSourceException("数据源配置错误!无法设置数据库url "+this);
}
this.url = url;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
if(StringUtils.isEmpty(password)){
throw new DataSourceException("数据源配置错误!无法设置数据库password "+this);
}
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
if(StringUtils.isEmpty(username)){
throw new DataSourceException("数据源配置错误!无法设置数据库username "+this);
}
this.username = username;
}
@Override
public String toString() {
return "DataSourceProperty [name=" + name + ", url=" + url
+ ", password=" + password + ", username=" + username
+ ", driver=" + driver + "]";
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
}
| true
|