blob_id stringlengths 40 40 | __id__ int64 225 39,780B | directory_id stringlengths 40 40 | path stringlengths 6 313 | content_id stringlengths 40 40 | detected_licenses list | license_type stringclasses 2
values | repo_name stringlengths 6 132 | repo_url stringlengths 25 151 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 70 | visit_date timestamp[ns] | revision_date timestamp[ns] | committer_date timestamp[ns] | github_id int64 7.28k 689M ⌀ | star_events_count int64 0 131k | fork_events_count int64 0 48k | gha_license_id stringclasses 23
values | gha_fork bool 2
classes | gha_event_created_at timestamp[ns] | gha_created_at timestamp[ns] | gha_updated_at timestamp[ns] | gha_pushed_at timestamp[ns] | gha_size int64 0 40.4M ⌀ | gha_stargazers_count int32 0 112k ⌀ | gha_forks_count int32 0 39.4k ⌀ | gha_open_issues_count int32 0 11k ⌀ | gha_language stringlengths 1 21 ⌀ | gha_archived bool 2
classes | gha_disabled bool 1
class | content stringlengths 7 4.37M | src_encoding stringlengths 3 16 | language stringclasses 1
value | length_bytes int64 7 4.37M | extension stringclasses 24
values | filename stringlengths 4 174 | language_id stringclasses 1
value | entities list | contaminating_dataset stringclasses 0
values | malware_signatures list | redacted_content stringlengths 7 4.37M | redacted_length_bytes int64 7 4.37M | alphanum_fraction float32 0.25 0.94 | alpha_fraction float32 0.25 0.94 | num_lines int32 1 84k | avg_line_length float32 0.76 99.9 | std_line_length float32 0 220 | max_line_length int32 5 998 | is_vendor bool 2
classes | is_generated bool 1
class | max_hex_length int32 0 319 | hex_fraction float32 0 0.38 | max_unicode_length int32 0 408 | unicode_fraction float32 0 0.36 | max_base64_length int32 0 506 | base64_fraction float32 0 0.5 | avg_csv_sep_count float32 0 4 | is_autogen_header bool 1
class | is_empty_html bool 1
class | shard stringclasses 16
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
35541540b7554cd7301659c73d31d376f26fa69c | 24,275,155,167,057 | 7b516831f2b99029e8e2881e750f678dbeb38cdb | /src/main/java/org/example/LoginPage.java | 749a397ff9824eeba0fa258e3c9135e25a941fa0 | [] | no_license | bhavesh1780/Practice | https://github.com/bhavesh1780/Practice | 988f040bc17118f04253a26133caebffea0a8c21 | eebfe4b2d9420230eac4afc959b58125f9aed0c4 | refs/heads/master | 2021-07-25T09:14:04.004000 | 2020-10-14T08:14:05 | 2020-10-14T08:14:05 | 226,315,765 | 0 | 1 | null | false | 2020-10-14T08:14:53 | 2019-12-06T11:32:53 | 2020-10-14T08:14:08 | 2020-10-14T08:14:05 | 9 | 0 | 1 | 0 | Java | false | false | package org.example;
import org.openqa.selenium.By;
public class LoginPage extends Utils {
public void userIsOnLoginPage(){
driver.get("https://demo.invapay.com/content/n/login.jsp");
}
public void userEnterValidCredentiala(){
typeText(By.id("userName"), "cinvapay1111");
typeText(By.id("password"), "J4cy+YnD");
// clickOnElement(By.id("buttonSubmitLogin"));
}
public void userClickOnSigninButton(){
clickOnElement(By.id("buttonSubmitLogin"));
}
}
| UTF-8 | Java | 519 | java | LoginPage.java | Java | [
{
"context": "edentiala(){\n typeText(By.id(\"userName\"), \"cinvapay1111\");\n typeText(By.id(\"password\"), \"J4cy+YnD\"",
"end": 301,
"score": 0.9996069669723511,
"start": 289,
"tag": "USERNAME",
"value": "cinvapay1111"
},
{
"context": "vapay1111\");\n typeTex... | null | [] | package org.example;
import org.openqa.selenium.By;
public class LoginPage extends Utils {
public void userIsOnLoginPage(){
driver.get("https://demo.invapay.com/content/n/login.jsp");
}
public void userEnterValidCredentiala(){
typeText(By.id("userName"), "cinvapay1111");
typeText(By.id("password"), "<PASSWORD>");
// clickOnElement(By.id("buttonSubmitLogin"));
}
public void userClickOnSigninButton(){
clickOnElement(By.id("buttonSubmitLogin"));
}
}
| 521 | 0.65896 | 0.649326 | 22 | 22.59091 | 22.858576 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.409091 | false | false | 3 |
46f0fe877340fd605f0ca2d2f991176f49ecda15 | 2,430,951,501,151 | 2d4f7b4e268ea055d82c9dac9f051d1b5d5da6ff | /src/main/java/com/example/demo/service/IEmployeeService.java | 07d1b9c8791b4837de422a31a07e2c3688431e34 | [] | no_license | James-blue/demo | https://github.com/James-blue/demo | 4ea987f7caa2ff31c10e1f0f117103fa9fba3a04 | 4cb775412dc23f55c4e8e553e7ecf5d477cd99e0 | refs/heads/master | 2020-03-22T16:58:28.700000 | 2018-07-13T08:02:06 | 2018-07-13T08:02:06 | 140,364,132 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.demo.service;
import com.example.demo.bo.EmployeeBO;
import java.util.List;
public interface IEmployeeService {
List<EmployeeBO> listEmployee();
EmployeeBO getEmployee(Long employeeId);
}
| UTF-8 | Java | 220 | java | IEmployeeService.java | Java | [] | null | [] | package com.example.demo.service;
import com.example.demo.bo.EmployeeBO;
import java.util.List;
public interface IEmployeeService {
List<EmployeeBO> listEmployee();
EmployeeBO getEmployee(Long employeeId);
}
| 220 | 0.772727 | 0.772727 | 11 | 19 | 17.847841 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 3 |
035f7bc8beebe76b0bb958643efb1c341e42b926 | 2,697,239,509,607 | 4394bb89685ef54e62e91bcdcb5cd2a61a6d25e3 | /src/Functionality/tFile.java | c0f7ae05cb462a65d436eb3a9ce82539f9baf82b | [] | no_license | fdelu-ca/FrequencyAnalyzerV2 | https://github.com/fdelu-ca/FrequencyAnalyzerV2 | c777c050f86079567996f798d1af21e36c8b7a6d | 3268a23c59efb1872bde8aca50b6129a64ad176f | refs/heads/master | 2020-03-10T08:48:45.906000 | 2018-04-14T14:02:31 | 2018-04-14T14:02:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Functionality;
/*Выполнено*/
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class tFile{
public Stage stage;
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter(
"Текстовый файл (*.txt)",
"*.txt");
public tFile(){
stage=new Stage();
}
/**
* Выбор файла и считвание
* @return строка
*/
public String ReadFile() {
FileChooser fileChooser = new FileChooser();//Экземпляр
fileChooser.setTitle("Выбор текстового документа");
fileChooser.getExtensionFilters().add(extFilter);
File file = fileChooser.showOpenDialog(stage);
if (file != null) {
try {
String s= Files.readAllLines(Paths.get(file.getPath()), StandardCharsets.UTF_8).toString();
s=s.replaceAll("[\\[.\\]+]", "");
s=s.replace(", ", "\r\n");
return s;
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* Сохранение объекта в файл
* @param obj объект для сохранения
* @return результат сохранения
*/
public boolean SaveToFile(Object obj){
boolean comf=false; //Результат выполнения
FileChooser fileChooser = new FileChooser();//Экземпляр
fileChooser.setTitle("Выбор места для сохранения");
fileChooser.getExtensionFilters().add(extFilter);
File file = fileChooser.showSaveDialog(stage);
if (file != null)
if(saveTextToFile(obj.toString(), file))
comf=true;
return comf;
}
/**
* Сохранение текста в файл
* @param content Текст
* @param file Путь к файлу
* @return Результат сохранения
*/
private boolean saveTextToFile(String content, File file) {
try {
PrintWriter writer;
writer = new PrintWriter(file);
writer.println(content);
writer.close();
} catch (IOException ex) {
ex.printStackTrace();
return false;
}
return true;
}
}
| UTF-8 | Java | 2,636 | java | tFile.java | Java | [] | null | [] | package Functionality;
/*Выполнено*/
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class tFile{
public Stage stage;
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter(
"Текстовый файл (*.txt)",
"*.txt");
public tFile(){
stage=new Stage();
}
/**
* Выбор файла и считвание
* @return строка
*/
public String ReadFile() {
FileChooser fileChooser = new FileChooser();//Экземпляр
fileChooser.setTitle("Выбор текстового документа");
fileChooser.getExtensionFilters().add(extFilter);
File file = fileChooser.showOpenDialog(stage);
if (file != null) {
try {
String s= Files.readAllLines(Paths.get(file.getPath()), StandardCharsets.UTF_8).toString();
s=s.replaceAll("[\\[.\\]+]", "");
s=s.replace(", ", "\r\n");
return s;
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* Сохранение объекта в файл
* @param obj объект для сохранения
* @return результат сохранения
*/
public boolean SaveToFile(Object obj){
boolean comf=false; //Результат выполнения
FileChooser fileChooser = new FileChooser();//Экземпляр
fileChooser.setTitle("Выбор места для сохранения");
fileChooser.getExtensionFilters().add(extFilter);
File file = fileChooser.showSaveDialog(stage);
if (file != null)
if(saveTextToFile(obj.toString(), file))
comf=true;
return comf;
}
/**
* Сохранение текста в файл
* @param content Текст
* @param file Путь к файлу
* @return Результат сохранения
*/
private boolean saveTextToFile(String content, File file) {
try {
PrintWriter writer;
writer = new PrintWriter(file);
writer.println(content);
writer.close();
} catch (IOException ex) {
ex.printStackTrace();
return false;
}
return true;
}
}
| 2,636 | 0.579322 | 0.578903 | 92 | 24.967392 | 21.0385 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.478261 | false | false | 3 |
83aa22863ba14b7035119973c7244b72590faa40 | 12,876,311,955,805 | 0cc54ad9aa3dad091b27d05729c22bdfe6347dfd | /app/src/main/java/videoplayer/android/com/cnvideoplayer/utils/RegexUtils.java | cf6cdf4ace15b73616a453317783e67e1d4e8edf | [] | no_license | Bingoliallen/CnVideoPlayer | https://github.com/Bingoliallen/CnVideoPlayer | be2a03aad45d7db8fc14272a19b440fd6453762c | d4e604624114262235f3a54f60c87172a3f4af44 | refs/heads/master | 2022-05-21T03:51:10.087000 | 2020-04-07T05:15:15 | 2020-04-07T05:15:15 | 253,660,013 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package videoplayer.android.com.cnvideoplayer.utils;
import android.text.TextUtils;
import java.util.regex.Pattern;
/**
* Date: 2018/8/24
* Author:
* Email:
* Des:正则表达式工具类,提供一些常用的正则表达式
*/
public class RegexUtils {
/**
* 正则表达式:验证邮箱
*/
public static final String REGEX_EMAIL = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
/**
* 判断字符串是否符合手机号码格式
* 移动号段: 134,135,136,137,138,139,147,150,151,152,157,158,159,170,178,182,183,184,187,188
* 联通号段: 130,131,132,145,155,156,170,171,175,176,185,186
* 电信号段: 133,149,153,170,173,177,180,181,189
* @param mobileNums
* @return 待检测的字符串
*/
public static boolean isMobileNO(String mobileNums) {
String telRegex = "^((13[0-9])|(14[5,7,9])|(15[^4])|(18[0-9])|(17[0,1,3,5,6,7,8]))\\d{8}$";// "[1]"代表第1位为数字1,"[358]"代表第二位可以为3、5、8中的一个,"\\d{9}"代表后面是可以是0~9的数字,有9位。
if (TextUtils.isEmpty(mobileNums))
return false;
else
return mobileNums.matches(telRegex);
}
/**
* 匹配手机号的规则:[3578]是手机号第二位可能出现的数字
*/
public static final String REGEX_MOBILE = "^[1][3578][0-9]{9}$";
/**
* 校验手机号
* @param mobile
* @return 校验通过返回true,否则返回false
*/
public static boolean isMobile(String mobile) {
return Pattern.matches(REGEX_MOBILE, mobile);
}
/**
* 校验邮箱
* @param email
* @return 校验通过返回true,否则返回false
*/
public static boolean isEmail(String email) {
return Pattern.matches(REGEX_EMAIL, email);
}
}
| UTF-8 | Java | 1,887 | java | RegexUtils.java | Java | [] | null | [] | package videoplayer.android.com.cnvideoplayer.utils;
import android.text.TextUtils;
import java.util.regex.Pattern;
/**
* Date: 2018/8/24
* Author:
* Email:
* Des:正则表达式工具类,提供一些常用的正则表达式
*/
public class RegexUtils {
/**
* 正则表达式:验证邮箱
*/
public static final String REGEX_EMAIL = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
/**
* 判断字符串是否符合手机号码格式
* 移动号段: 134,135,136,137,138,139,147,150,151,152,157,158,159,170,178,182,183,184,187,188
* 联通号段: 130,131,132,145,155,156,170,171,175,176,185,186
* 电信号段: 133,149,153,170,173,177,180,181,189
* @param mobileNums
* @return 待检测的字符串
*/
public static boolean isMobileNO(String mobileNums) {
String telRegex = "^((13[0-9])|(14[5,7,9])|(15[^4])|(18[0-9])|(17[0,1,3,5,6,7,8]))\\d{8}$";// "[1]"代表第1位为数字1,"[358]"代表第二位可以为3、5、8中的一个,"\\d{9}"代表后面是可以是0~9的数字,有9位。
if (TextUtils.isEmpty(mobileNums))
return false;
else
return mobileNums.matches(telRegex);
}
/**
* 匹配手机号的规则:[3578]是手机号第二位可能出现的数字
*/
public static final String REGEX_MOBILE = "^[1][3578][0-9]{9}$";
/**
* 校验手机号
* @param mobile
* @return 校验通过返回true,否则返回false
*/
public static boolean isMobile(String mobile) {
return Pattern.matches(REGEX_MOBILE, mobile);
}
/**
* 校验邮箱
* @param email
* @return 校验通过返回true,否则返回false
*/
public static boolean isEmail(String email) {
return Pattern.matches(REGEX_EMAIL, email);
}
}
| 1,887 | 0.583918 | 0.462668 | 63 | 23.873016 | 31.110399 | 169 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.015873 | false | false | 3 |
3603ea77584788f4f1a7f40466dc6bc346b358a3 | 17,789,754,606,254 | e0821f887ba38ee8bb50312da434a7a04b40b281 | /src/com/boxysystems/libraryfinder/model/LibraryVisitor.java | 5a35e3152543ab6afde56662c08d075bf66b799f | [] | no_license | vijayvani/libraryfinder-1 | https://github.com/vijayvani/libraryfinder-1 | cc48f155a73c4a1663c5c7c39b83b85c5720a5c3 | 733d6a4d409b7b2da5d30058bb087e98273aff6e | refs/heads/master | 2020-05-16T08:56:41.620000 | 2014-11-07T18:52:16 | 2014-11-07T18:52:16 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright 2007 BoxySystems Inc. <siddique@boxysystems.com>
* http://www.BoxySystems.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.boxysystems.libraryfinder.model;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* Visitor class for visiting library files (.jar & .zip) in a specified folder
* for a matching input pattern.
*
* @author Siddique Hameed
* @version 1.0
*/
public class LibraryVisitor extends Observable {
private Pattern pattern;
private Set<LibraryFinderResult> results = new TreeSet<LibraryFinderResult>();
private boolean cancelled = false;
private LibraryFinderQuery query;
private LibraryFileFilter filter = new LibraryFileFilter();
public LibraryVisitor(LibraryFinderQuery query) throws LibraryFinderException {
this.query = query;
compilePattern(query.getFileNamePattern(), query.isCaseSensitive(), query.isRegex());
if (query.getExcludedFolders() != null) {
filter = new LibraryFileFilterWithExcludedFolders(query.getExcludedFolders());
}
}
public LibraryVisitor(LibraryFinderQuery query, Observer observer) throws LibraryFinderException {
this(query);
addObserver(observer);
}
private void compilePattern(String patternStr, boolean caseSensitive, boolean regex) throws LibraryFinderException {
try {
if (!regex) {
patternStr = PatternUtil.generateFileNamePattern(patternStr);
}
if (!caseSensitive) {
pattern = Pattern.compile(patternStr, Pattern.CASE_INSENSITIVE);
} else {
pattern = Pattern.compile(patternStr);
}
} catch (PatternSyntaxException e) {
throw new LibraryFinderException(Constants.INVALID_PATTERN_MSG_PREFIX + e.getMessage());
}
}
public void visit(ZipFile zip, ZipEntry entry) {
Matcher matcher = pattern.matcher(entry.getName());
if (matcher.matches()) {
LibraryFinderResult result = new LibraryFinderResult(new File(zip.getName()).getAbsolutePath(), new File(zip.getName()).length());
results.add(result);
}
}
public Set<LibraryFinderResult> getResults() {
return results;
}
private void visitLibrary(File libraryFile) {
ZipFile zip = null;
try {
zip = new ZipFile(libraryFile, ZipFile.OPEN_READ);
for (Enumeration entries = zip.entries(); entries.hasMoreElements();) {
ZipEntry entry = (ZipEntry) entries.nextElement();
visit(zip, entry);
}
} catch (Throwable e) {
System.err.println(Constants.ERR_MSG_PREFIX + libraryFile.getAbsolutePath());
}
finally {
if (zip != null) {
try {
zip.close();
} catch (IOException e) {
//ignore this
}
}
}
}
public void visitLibraries() throws LibraryFinderException {
File directory = new File(query.getSearchPath());
validate(directory);
visitLibraries(directory);
sendMessageToObservers(Constants.ACTION_COMPLETED_MESSAGE);
}
private void visitLibraries(File directory) throws LibraryFinderException {
File[] files = directory.listFiles(filter);
if (files != null) {
for (File file : files) {
sendMessageToObservers(Constants.SEARCH_MSG_PREFIX + file.getAbsolutePath());
if (cancelled) {
return;
}
if (file.isDirectory()) {
visitLibraries(file);
} else {
visitLibrary(file);
}
}
}
}
private void validate(File directory) throws LibraryFinderException {
if (directory.exists() && !directory.isDirectory()) {
throw new LibraryFinderException(Constants.PATH_NOT_VALID_MESSAGE);
} else if (!directory.exists()) {
throw new LibraryFinderException(Constants.PATH_NOT_FOUND_MESSAGE);
}
}
private boolean hasObservers() {
return countObservers() > 0;
}
private void sendMessageToObservers(Object message) {
if (hasObservers() && message != null) {
setChanged();
notifyObservers(message);
}
}
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
public Pattern getPattern() {
return pattern;
}
}
| UTF-8 | Java | 5,500 | java | LibraryVisitor.java | Java | [
{
"context": "/*\r\n * Copyright 2007 BoxySystems Inc. <siddique@boxysystems.com>\r\n * http://www.BoxySystems.com\r",
"end": 64,
"score": 0.9999294281005859,
"start": 40,
"tag": "EMAIL",
"value": "siddique@boxysystems.com"
},
{
"context": "\r\n * for a matching inpu... | null | [] | /*
* Copyright 2007 BoxySystems Inc. <<EMAIL>>
* http://www.BoxySystems.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.boxysystems.libraryfinder.model;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* Visitor class for visiting library files (.jar & .zip) in a specified folder
* for a matching input pattern.
*
* @author <NAME>
* @version 1.0
*/
public class LibraryVisitor extends Observable {
private Pattern pattern;
private Set<LibraryFinderResult> results = new TreeSet<LibraryFinderResult>();
private boolean cancelled = false;
private LibraryFinderQuery query;
private LibraryFileFilter filter = new LibraryFileFilter();
public LibraryVisitor(LibraryFinderQuery query) throws LibraryFinderException {
this.query = query;
compilePattern(query.getFileNamePattern(), query.isCaseSensitive(), query.isRegex());
if (query.getExcludedFolders() != null) {
filter = new LibraryFileFilterWithExcludedFolders(query.getExcludedFolders());
}
}
public LibraryVisitor(LibraryFinderQuery query, Observer observer) throws LibraryFinderException {
this(query);
addObserver(observer);
}
private void compilePattern(String patternStr, boolean caseSensitive, boolean regex) throws LibraryFinderException {
try {
if (!regex) {
patternStr = PatternUtil.generateFileNamePattern(patternStr);
}
if (!caseSensitive) {
pattern = Pattern.compile(patternStr, Pattern.CASE_INSENSITIVE);
} else {
pattern = Pattern.compile(patternStr);
}
} catch (PatternSyntaxException e) {
throw new LibraryFinderException(Constants.INVALID_PATTERN_MSG_PREFIX + e.getMessage());
}
}
public void visit(ZipFile zip, ZipEntry entry) {
Matcher matcher = pattern.matcher(entry.getName());
if (matcher.matches()) {
LibraryFinderResult result = new LibraryFinderResult(new File(zip.getName()).getAbsolutePath(), new File(zip.getName()).length());
results.add(result);
}
}
public Set<LibraryFinderResult> getResults() {
return results;
}
private void visitLibrary(File libraryFile) {
ZipFile zip = null;
try {
zip = new ZipFile(libraryFile, ZipFile.OPEN_READ);
for (Enumeration entries = zip.entries(); entries.hasMoreElements();) {
ZipEntry entry = (ZipEntry) entries.nextElement();
visit(zip, entry);
}
} catch (Throwable e) {
System.err.println(Constants.ERR_MSG_PREFIX + libraryFile.getAbsolutePath());
}
finally {
if (zip != null) {
try {
zip.close();
} catch (IOException e) {
//ignore this
}
}
}
}
public void visitLibraries() throws LibraryFinderException {
File directory = new File(query.getSearchPath());
validate(directory);
visitLibraries(directory);
sendMessageToObservers(Constants.ACTION_COMPLETED_MESSAGE);
}
private void visitLibraries(File directory) throws LibraryFinderException {
File[] files = directory.listFiles(filter);
if (files != null) {
for (File file : files) {
sendMessageToObservers(Constants.SEARCH_MSG_PREFIX + file.getAbsolutePath());
if (cancelled) {
return;
}
if (file.isDirectory()) {
visitLibraries(file);
} else {
visitLibrary(file);
}
}
}
}
private void validate(File directory) throws LibraryFinderException {
if (directory.exists() && !directory.isDirectory()) {
throw new LibraryFinderException(Constants.PATH_NOT_VALID_MESSAGE);
} else if (!directory.exists()) {
throw new LibraryFinderException(Constants.PATH_NOT_FOUND_MESSAGE);
}
}
private boolean hasObservers() {
return countObservers() > 0;
}
private void sendMessageToObservers(Object message) {
if (hasObservers() && message != null) {
setChanged();
notifyObservers(message);
}
}
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
public Pattern getPattern() {
return pattern;
}
}
| 5,474 | 0.604182 | 0.602182 | 162 | 31.950617 | 29.191534 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.407407 | false | false | 3 |
e3672b835efa486457abde3f69240fdfcb2ff65f | 22,290,880,270,409 | 5261dddd38655dfee9cdb0de063445c36ca6f386 | /src/main/java/com/github/beercafeguy/bootjdbch2/BootJdbcH2Application.java | 3e968657c62f69ef010e6a510b0b7b1f69482433 | [
"Apache-2.0"
] | permissive | beercafeguy/boot-jdbc-h2 | https://github.com/beercafeguy/boot-jdbc-h2 | 1e6174b2b3b263bb473b5dc1556d09fc5c37a572 | 76ce60d593c9317a03ca172d39a787f5d3e2dffb | refs/heads/master | 2021-05-09T09:04:57.142000 | 2018-01-29T18:04:22 | 2018-01-29T18:04:22 | 119,419,449 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.github.beercafeguy.bootjdbch2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BootJdbcH2Application implements CommandLineRunner{
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
StudentJdbcRepository repository;
@Override
public void run(String... strings) throws Exception {
logger.info("User id 10001 -> {}", repository.findById(10001L));
logger.info("All users -> {}", repository.findAll());
}
public static void main(String[] args) {
SpringApplication.run(BootJdbcH2Application.class, args);
}
}
| UTF-8 | Java | 842 | java | BootJdbcH2Application.java | Java | [
{
"context": "package com.github.beercafeguy.bootjdbch2;\n\nimport org.slf4j.Logger;\nimport org.",
"end": 30,
"score": 0.9992853403091431,
"start": 19,
"tag": "USERNAME",
"value": "beercafeguy"
}
] | null | [] | package com.github.beercafeguy.bootjdbch2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BootJdbcH2Application implements CommandLineRunner{
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
StudentJdbcRepository repository;
@Override
public void run(String... strings) throws Exception {
logger.info("User id 10001 -> {}", repository.findById(10001L));
logger.info("All users -> {}", repository.findAll());
}
public static void main(String[] args) {
SpringApplication.run(BootJdbcH2Application.class, args);
}
}
| 842 | 0.799287 | 0.781473 | 28 | 29.071428 | 25.971039 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.035714 | false | false | 3 |
0c7b88e18f24daf2c615eea5a2b8139283cc51d6 | 9,405,978,383,722 | 319189e088c3726835663a9a6480e5e7ab95cb7b | /src/org/naive/utils/DateFormatter.java | d90cbe56b79d3e8fc03c86f74017d290c0137713 | [] | no_license | lexcao/SSM-naive | https://github.com/lexcao/SSM-naive | 29276cd783868b7cf1f704745f0b977ad8c6107a | 61072acf333f002aae0ec820585d07e0316b7b2e | refs/heads/master | 2020-03-09T12:41:46.225000 | 2018-04-16T14:09:46 | 2018-04-16T14:09:46 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.naive.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @Author: clixin
* @Description:
* @Date: Created in 下午1:38 2018/4/13
* @Modified By:
**/
public class DateFormatter {
public static String getDatabaseTime(Date date) {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
}
}
| UTF-8 | Java | 355 | java | DateFormatter.java | Java | [
{
"context": "ateFormat;\nimport java.util.Date;\n\n/**\n * @Author: clixin\n * @Description:\n * @Date: Created in 下午1:38 2018",
"end": 107,
"score": 0.99961256980896,
"start": 101,
"tag": "USERNAME",
"value": "clixin"
}
] | null | [] | package org.naive.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @Author: clixin
* @Description:
* @Date: Created in 下午1:38 2018/4/13
* @Modified By:
**/
public class DateFormatter {
public static String getDatabaseTime(Date date) {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
}
}
| 355 | 0.683761 | 0.655271 | 18 | 18.5 | 19.844534 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.222222 | false | false | 3 |
0048c26df82b2fa98f4790a7ddf6df3a6d1f7e60 | 17,093,969,843,876 | d60a267ad6b09507b66027dd65ed16fcb9bdf0bf | /src/main/java/com/platzi/market/web/controller/Controller.java | db24778a88ced4d166a3a411249e9d3052bfa523 | [] | no_license | Nelsondmondragon/Platzi-Market | https://github.com/Nelsondmondragon/Platzi-Market | 83ac22ead206e86409f94cb0a143933187ee0096 | 9646a1ad10b2d0e0cf49e776a1f75d60dde26723 | refs/heads/main | 2023-08-12T02:32:28.445000 | 2021-08-02T22:32:38 | 2021-08-02T22:32:38 | 388,119,894 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.platzi.market.web.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/greet")
public class Controller {
@GetMapping("/hello")
public String greet() {
return "Hello word";
}
}
| UTF-8 | Java | 389 | java | Controller.java | Java | [] | null | [] | package com.platzi.market.web.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/greet")
public class Controller {
@GetMapping("/hello")
public String greet() {
return "Hello word";
}
}
| 389 | 0.763496 | 0.763496 | 15 | 24.933332 | 21.674768 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 3 |
7be0574e36f0c10de962815e74e6b8a72e4f9622 | 33,148,557,644,042 | 0e1c48255e445e4b96c2006903c29418a285dfdf | /src/test/java/cde/pg/OptionalShould.java | 880267d4fac9437553cec4e8cdb15dc6b51ab912 | [] | no_license | cdespona/Java11LTS | https://github.com/cdespona/Java11LTS | be6ba3662930d34bee4ad3d63d56654b51a8a755 | 91758774a7391d4ef9e12f8705fdcd02e680728b | refs/heads/master | 2020-05-14T17:40:17.224000 | 2019-04-23T10:36:06 | 2019-04-23T10:36:06 | 181,896,212 | 0 | 0 | null | false | 2019-04-22T17:03:42 | 2019-04-17T13:21:40 | 2019-04-18T10:25:51 | 2019-04-22T17:03:42 | 118 | 0 | 0 | 0 | Java | false | false | package cde.pg;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
class OptionalShould {
@Test
void J10_raise_an_exception_when_no_value_present() {
Integer actualInteger = List.of(1, 2, 3).stream()
.filter(i -> i % 2 == 0)
.findFirst()
.orElseThrow();
assertEquals(2, actualInteger);
assertThrows(NoSuchElementException.class, this::thisIsGoingToFail);
}
@Test
void J11_should_let_us_know_when_it_is_empty() {
Optional<Object> optional = Optional.empty();
assertTrue(optional.isEmpty());
}
private void thisIsGoingToFail() {
List.of(1, 2, 3).stream()
.filter(i -> i % 4 == 0)
.findFirst()
.orElseThrow();
}
}
| UTF-8 | Java | 922 | java | OptionalShould.java | Java | [] | null | [] | package cde.pg;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
class OptionalShould {
@Test
void J10_raise_an_exception_when_no_value_present() {
Integer actualInteger = List.of(1, 2, 3).stream()
.filter(i -> i % 2 == 0)
.findFirst()
.orElseThrow();
assertEquals(2, actualInteger);
assertThrows(NoSuchElementException.class, this::thisIsGoingToFail);
}
@Test
void J11_should_let_us_know_when_it_is_empty() {
Optional<Object> optional = Optional.empty();
assertTrue(optional.isEmpty());
}
private void thisIsGoingToFail() {
List.of(1, 2, 3).stream()
.filter(i -> i % 4 == 0)
.findFirst()
.orElseThrow();
}
}
| 922 | 0.588937 | 0.572668 | 38 | 23.263159 | 20.995844 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.473684 | false | false | 3 |
6bf56eba0f0802598ad311601627f011faa4e825 | 3,676,492,007,104 | 28b55bd34f185c66161079a385afa39d1d25b015 | /app/src/main/java/ga/himanshu/home/test2/services/MyNoticeService.java | c9d0d23b59337d6bfb1557a2a479d810b2b6e849 | [] | no_license | himanshu096/widget | https://github.com/himanshu096/widget | 3089838f6e7d3155398c24127697c83abd014394 | 39b945b62540cdd3558fcfac3d5e7c22a60ae3cd | refs/heads/master | 2020-03-29T00:54:46.874000 | 2017-06-17T11:33:01 | 2017-06-17T11:33:01 | 94,637,635 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ga.himanshu.home.test2.services;
import android.util.Log;
import java.io.IOException;
import java.lang.annotation.Annotation;
import ga.himanshu.home.test2.model.Message;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Converter;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by Himanshu on 7/16/2016.
*/
public class MyNoticeService {
private final String BASE_URL = "http://10.1.1.1:8090/";
private final String accessToken="8b0f1191-0167-4f58-ad07-dcaf9c35904a";
private NoticeServiceInterface service;
private Retrofit retrofit;
public MyNoticeService(){
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
service = retrofit.create(NoticeServiceInterface.class);
}
public void listNotices(String timestamp,Callback<Message> callback){
service.getNotices(timestamp,191,"gaurav",0,"2014bcs1131").enqueue(new CallbackHandler<Message>(retrofit,callback));;
}
private class CallbackHandler<T> implements retrofit2.Callback<T> {
private Retrofit retrofit;
private Callback callback;
public CallbackHandler(Retrofit retrofit, Callback callback) {
this.retrofit = retrofit;
this.callback = callback;
}
@Override
public void onResponse(Call<T> call, Response<T> response) {
if(response.isSuccessful()) {
callback.onSuccess(response.body());
} else {
Log.d("codekamp", "response isSuccessful");
Converter<ResponseBody, Error> errorConverter =
retrofit.responseBodyConverter(Error.class, new Annotation[0]);
try {
Error error = errorConverter.convert(response.errorBody());
callback.onFailure(error);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onFailure(Call<T> call, Throwable t) {
Log.d("codekamp", "response onFailure");
Error error = new Error("error occured");
callback.onFailure(error);
}
}
}
| UTF-8 | Java | 2,274 | java | MyNoticeService.java | Java | [
{
"context": "rter.gson.GsonConverterFactory;\n\n/**\n * Created by Himanshu on 7/16/2016.\n */\npublic class MyNoticeService {\n",
"end": 397,
"score": 0.9955230951309204,
"start": 389,
"tag": "USERNAME",
"value": "Himanshu"
},
{
"context": "e {\n\n private final String BASE_URL ... | null | [] | package ga.himanshu.home.test2.services;
import android.util.Log;
import java.io.IOException;
import java.lang.annotation.Annotation;
import ga.himanshu.home.test2.model.Message;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Converter;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by Himanshu on 7/16/2016.
*/
public class MyNoticeService {
private final String BASE_URL = "http://10.1.1.1:8090/";
private final String accessToken="8b0f1191-0167-4f58-ad07-dcaf9c35904a";
private NoticeServiceInterface service;
private Retrofit retrofit;
public MyNoticeService(){
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
service = retrofit.create(NoticeServiceInterface.class);
}
public void listNotices(String timestamp,Callback<Message> callback){
service.getNotices(timestamp,191,"gaurav",0,"2014bcs1131").enqueue(new CallbackHandler<Message>(retrofit,callback));;
}
private class CallbackHandler<T> implements retrofit2.Callback<T> {
private Retrofit retrofit;
private Callback callback;
public CallbackHandler(Retrofit retrofit, Callback callback) {
this.retrofit = retrofit;
this.callback = callback;
}
@Override
public void onResponse(Call<T> call, Response<T> response) {
if(response.isSuccessful()) {
callback.onSuccess(response.body());
} else {
Log.d("codekamp", "response isSuccessful");
Converter<ResponseBody, Error> errorConverter =
retrofit.responseBodyConverter(Error.class, new Annotation[0]);
try {
Error error = errorConverter.convert(response.errorBody());
callback.onFailure(error);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onFailure(Call<T> call, Throwable t) {
Log.d("codekamp", "response onFailure");
Error error = new Error("error occured");
callback.onFailure(error);
}
}
}
| 2,274 | 0.657432 | 0.631486 | 98 | 22.204082 | 25.939474 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.459184 | false | false | 3 |
802adee4d6a0d513f1fd2399b22ac77f3db3e906 | 26,018,911,883,008 | b4315bd62961ffeb8752143c2b55d97a5363385b | /classes/java/chat-client-server-tcp/src/org/academiadecodigo/gnunas/server/ClientHandler.java | 85f0c87ecc7be764361f0935e3271198bfe2b1a7 | [] | no_license | Goonfy/toolsdeveloped | https://github.com/Goonfy/toolsdeveloped | 73093635f39424a764842cb915ee10ed0b6daf84 | eb98536fe96cf358017fdd49a8ab0c66878fabf7 | refs/heads/master | 2023-02-17T16:41:08.943000 | 2021-01-18T18:34:46 | 2021-01-18T18:34:46 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.academiadecodigo.gnunas.server;
import java.io.IOException;
import java.net.Socket;
public class ClientHandler implements Runnable {
private final Socket clientSocket;
private final Server server;
private final CommandListener commandListener;
public ClientHandler(Socket clientSocket, Server server, CommandListener commandListener) {
this.clientSocket = clientSocket;
this.server = server;
this.commandListener = commandListener;
}
@Override
public void run() {
try {
handle(registerNewClient());
server.disconnect(clientSocket);
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
private void handle(String username) throws IOException {
if (username == null) {
return;
}
while (true) {
String message = server.decodePacketFrom(clientSocket);
if (message == null) {
break;
}
if (message.isEmpty() || commandListener.check(username, message)) {
continue;
}
message = username + ": " + message;
System.out.println(message);
server.sendMessagePacketToAll(message);
}
}
private String registerNewClient() throws IOException {
server.sendMessagePacketTo(clientSocket, "Please write an username and then click enter...");
String username = server.decodePacketFrom(clientSocket);
if (username == null || username.isEmpty() || server.getUser(username) != null) {
server.sendMessagePacketTo(clientSocket, ("User with same name already connected " +
"or you entered an empty username, try with different name..."));
return null;
}
server.connect(clientSocket, username);
return username;
}
}
| UTF-8 | Java | 1,925 | java | ClientHandler.java | Java | [] | null | [] | package org.academiadecodigo.gnunas.server;
import java.io.IOException;
import java.net.Socket;
public class ClientHandler implements Runnable {
private final Socket clientSocket;
private final Server server;
private final CommandListener commandListener;
public ClientHandler(Socket clientSocket, Server server, CommandListener commandListener) {
this.clientSocket = clientSocket;
this.server = server;
this.commandListener = commandListener;
}
@Override
public void run() {
try {
handle(registerNewClient());
server.disconnect(clientSocket);
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
private void handle(String username) throws IOException {
if (username == null) {
return;
}
while (true) {
String message = server.decodePacketFrom(clientSocket);
if (message == null) {
break;
}
if (message.isEmpty() || commandListener.check(username, message)) {
continue;
}
message = username + ": " + message;
System.out.println(message);
server.sendMessagePacketToAll(message);
}
}
private String registerNewClient() throws IOException {
server.sendMessagePacketTo(clientSocket, "Please write an username and then click enter...");
String username = server.decodePacketFrom(clientSocket);
if (username == null || username.isEmpty() || server.getUser(username) != null) {
server.sendMessagePacketTo(clientSocket, ("User with same name already connected " +
"or you entered an empty username, try with different name..."));
return null;
}
server.connect(clientSocket, username);
return username;
}
}
| 1,925 | 0.608831 | 0.608831 | 67 | 27.731344 | 27.794868 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.567164 | false | false | 3 |
564fa83ce9e9670f80f86fed0689c602e3128e27 | 26,018,911,882,235 | a07e700204ad84dabb80333ac2a82455eee3605f | /maven/account-email/src/main/java/com/lia/beginning/maven/account/email.java | 934c3d4814010721855015822771c5e1a68ac475 | [] | no_license | min-ye/beginning | https://github.com/min-ye/beginning | ee9c683404df7a5bb659d351a2e2efc2642383a4 | 96468bbd458564871801c7a0e9cd69dcb44a1d76 | refs/heads/master | 2021-01-12T04:59:01.593000 | 2017-01-02T06:51:04 | 2017-01-02T06:51:04 | 77,816,241 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lia.beginning.maven.account;
public class email {
} | UTF-8 | Java | 68 | java | email.java | Java | [] | null | [] | package com.lia.beginning.maven.account;
public class email {
} | 68 | 0.735294 | 0.735294 | 5 | 12.8 | 15.432433 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 3 |
588448894979793b62f9a3e4c7b9d440aa07e5e5 | 31,190,052,506,000 | 9fde3e3e91b28291606e1b277c5512b6329eb220 | /src/main/java/mate/academy/hw02/sort/MergeSort.java | 3d5baf583627b4efc4b523993dfe25dbe7803322 | [] | no_license | MateAcademy/lessons | https://github.com/MateAcademy/lessons | d85ac5f34b162eac8a8e069150c750d8fd09ba44 | ae2bb88c4537d534e115af01c2460ca748014f8b | refs/heads/master | 2020-04-18T07:27:11.205000 | 2019-04-17T08:29:12 | 2019-04-17T08:29:12 | 167,360,292 | 1 | 0 | null | false | 2019-04-17T08:36:23 | 2019-01-24T11:57:32 | 2019-04-17T08:29:16 | 2019-04-17T08:36:20 | 2,309 | 0 | 0 | 1 | Java | false | false | package mate.academy.hw02.sort;
import java.util.Arrays;
public class MergeSort {
public static void main(String[] args) {
int[] arr = {2, 1, 0, 6, 1, 9, 8, 7};//тестовый массив
System.out.println(Arrays.toString(arr));//вывод на экран исходного массива
int[] sortArr = sort(arr);//сортировка
System.out.println(Arrays.toString(sortArr));//вывод на экран отсортированного массива
}
public static int[] sort(int[] arr) {
if (arr.length < 2) return arr;
int m = arr.length / 2;
int[] arr1 = Arrays.copyOfRange(arr, 0, m);
int[] arr2 = Arrays.copyOfRange(arr, m, arr.length);
return merge(sort(arr1), sort(arr2));
}
//слияние двух массивов в один отсортированный
public static int[] merge(int[] arr1, int arr2[]) {
int n = arr1.length + arr2.length;
int[] arr = new int[n];
int i1 = 0;
int i2 = 0;
for (int i = 0; i < n; i++) {
if (i1 == arr1.length) {
arr[i] = arr2[i2++];
} else if (i2 == arr2.length) {
arr[i] = arr1[i1++];
} else {
if (arr1[i1] < arr2[i2]) {
arr[i] = arr1[i1++];
} else {
arr[i] = arr2[i2++];
}
}
}
return arr;
}
} | UTF-8 | Java | 1,487 | java | MergeSort.java | Java | [] | null | [] | package mate.academy.hw02.sort;
import java.util.Arrays;
public class MergeSort {
public static void main(String[] args) {
int[] arr = {2, 1, 0, 6, 1, 9, 8, 7};//тестовый массив
System.out.println(Arrays.toString(arr));//вывод на экран исходного массива
int[] sortArr = sort(arr);//сортировка
System.out.println(Arrays.toString(sortArr));//вывод на экран отсортированного массива
}
public static int[] sort(int[] arr) {
if (arr.length < 2) return arr;
int m = arr.length / 2;
int[] arr1 = Arrays.copyOfRange(arr, 0, m);
int[] arr2 = Arrays.copyOfRange(arr, m, arr.length);
return merge(sort(arr1), sort(arr2));
}
//слияние двух массивов в один отсортированный
public static int[] merge(int[] arr1, int arr2[]) {
int n = arr1.length + arr2.length;
int[] arr = new int[n];
int i1 = 0;
int i2 = 0;
for (int i = 0; i < n; i++) {
if (i1 == arr1.length) {
arr[i] = arr2[i2++];
} else if (i2 == arr2.length) {
arr[i] = arr1[i1++];
} else {
if (arr1[i1] < arr2[i2]) {
arr[i] = arr1[i1++];
} else {
arr[i] = arr2[i2++];
}
}
}
return arr;
}
} | 1,487 | 0.494489 | 0.46363 | 43 | 30.674419 | 21.918158 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.813953 | false | false | 3 |
ab3cc7b5f120fd28b2f799c13ed4eb735d76b4b9 | 18,949,395,736,486 | c269e9b4198829b45ad69cdbca1b68efc17ae401 | /src/ConstructorChecker.java | 4c9c40a8d704e2b4d61ae039b5b3f1d8c5e8f639 | [] | no_license | rimpybharot/202-kanban | https://github.com/rimpybharot/202-kanban | 406aa8937e99d1e0ff861bdefe641f0ba06515ec | b7413e04a061343442f747df4a66f07af78f3b61 | refs/heads/master | 2021-01-22T10:33:45.122000 | 2017-05-08T19:40:31 | 2017-05-08T19:40:31 | 82,013,998 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.ArrayList;
import java.util.List;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.body.ConstructorDeclaration;
import com.github.javaparser.ast.body.Parameter;
import com.github.javaparser.ast.visitor.VoidVisitorAdapter;
public class ConstructorChecker {
private List<ConstructorDeclaration> constructors;
private NodeList<Parameter> parameters;
public ConstructorChecker(){
}
public ConstructorChecker(ClassOrInterfaceDeclaration n){
this.constructors = new ArrayList<>();
this.parameters = new NodeList<>();
new VoidVisitorAdapter<Object>() {
@Override
public void visit(ConstructorDeclaration n, Object arg) {
super.visit(n, arg);
setClassesConstructor(n);
}
}.visit(n, null);
}
public void setClassesConstructor(ConstructorDeclaration n) {
this.constructors.add(n);
}
public List<ConstructorDeclaration> getClassesConstructor() {
return this.constructors;
}
public String constructorStringCreator(ConstructorDeclaration n){
String name = null;
String modifier = null;
String p1 ="";
parameters = n.getParameters();
boolean first = true;
for (Parameter p : parameters) {
if (first==false) {
p1 += " , "+p.getNameAsString() + ": " + p.getType();
}
else{
p1 += p.getNameAsString() + ": " + p.getType();
}
first = false;
}
name = n.getNameAsString() + "("+p1+")";
modifier = "+";
return modifier +" " + name;
}
}
| UTF-8 | Java | 1,539 | java | ConstructorChecker.java | Java | [] | null | [] | import java.util.ArrayList;
import java.util.List;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.body.ConstructorDeclaration;
import com.github.javaparser.ast.body.Parameter;
import com.github.javaparser.ast.visitor.VoidVisitorAdapter;
public class ConstructorChecker {
private List<ConstructorDeclaration> constructors;
private NodeList<Parameter> parameters;
public ConstructorChecker(){
}
public ConstructorChecker(ClassOrInterfaceDeclaration n){
this.constructors = new ArrayList<>();
this.parameters = new NodeList<>();
new VoidVisitorAdapter<Object>() {
@Override
public void visit(ConstructorDeclaration n, Object arg) {
super.visit(n, arg);
setClassesConstructor(n);
}
}.visit(n, null);
}
public void setClassesConstructor(ConstructorDeclaration n) {
this.constructors.add(n);
}
public List<ConstructorDeclaration> getClassesConstructor() {
return this.constructors;
}
public String constructorStringCreator(ConstructorDeclaration n){
String name = null;
String modifier = null;
String p1 ="";
parameters = n.getParameters();
boolean first = true;
for (Parameter p : parameters) {
if (first==false) {
p1 += " , "+p.getNameAsString() + ": " + p.getType();
}
else{
p1 += p.getNameAsString() + ": " + p.getType();
}
first = false;
}
name = n.getNameAsString() + "("+p1+")";
modifier = "+";
return modifier +" " + name;
}
}
| 1,539 | 0.705653 | 0.703054 | 67 | 21.97015 | 21.606363 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.895522 | false | false | 3 |
aeb7cf74cfcee8351618427c94b21a4a2ab174d8 | 13,752,485,282,743 | 3b55f578ef0891cbfa4931276450528d77a0610d | /C83-S3-Phjx-blog/src/main/java/com/yc/C83S3Phjxblog/biz/CommentBiz.java | 23a6fcb63ea8dc97739ee44b66adf3ce33a0c71b | [] | no_license | hujuanxiu/maven | https://github.com/hujuanxiu/maven | 4ca24f6b5302b7b1184c8fd491fe21718213ad5c | ef0bc285d527b4c47b5a29f88b1955cf4bf7decd | refs/heads/master | 2022-12-09T20:47:51.982000 | 2020-08-26T11:44:59 | 2020-08-26T11:44:59 | 285,169,631 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yc.C83S3Phjxblog.biz;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.yc.C83S3Phjxblog.bean.Comment;
import com.yc.C83S3Phjxblog.dao.CommentMapper;
@Service
public class CommentBiz {
@Resource
private CommentMapper cMapper;
public Comment create(Comment comm) {
cMapper.insert(comm);
return comm;
}
}
| UTF-8 | Java | 374 | java | CommentBiz.java | Java | [] | null | [] | package com.yc.C83S3Phjxblog.biz;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.yc.C83S3Phjxblog.bean.Comment;
import com.yc.C83S3Phjxblog.dao.CommentMapper;
@Service
public class CommentBiz {
@Resource
private CommentMapper cMapper;
public Comment create(Comment comm) {
cMapper.insert(comm);
return comm;
}
}
| 374 | 0.783422 | 0.759358 | 21 | 16.809525 | 17.01993 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.857143 | false | false | 3 |
2492b31c7ab68514593b5fe6a88745a2afcc627d | 26,113,401,227,270 | 5049fccddfdf566ae471792182262a2dcd68a905 | /app/src/main/java/curry/com/newwidget/fragment/gongban/FirstFragment.java | 82a9849b271287fd611f606215c4d12ebaef8e01 | [] | no_license | currydou/NewWidget | https://github.com/currydou/NewWidget | 088b83ed0c598507915afab8232a84802bf8c4ae | a61948bb360a06b8606d5be2d2df61b3c81cc535 | refs/heads/master | 2020-04-07T02:43:43.094000 | 2019-08-01T06:30:30 | 2019-08-01T06:30:30 | 157,987,410 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package curry.com.newwidget.fragment.gongban;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import curry.com.newwidget.R;
public class FirstFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**
* 下面一行的写法注意,false,直接复制,要不然会忘了参数
* 如果没有最后一个参数false会报错 The specified child already has a parent. You must call removeView() on the child's parent first.
*/
View v = inflater.inflate(R.layout.first_fragment, container, false);
TextView tv = (TextView)v.findViewById(R.id.msg);
tv.setText("This is first fragment.");
tv.setBackgroundColor(Color.GREEN);
return v;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
System.out.println("11111111111111111111111");
}
}
| UTF-8 | Java | 1,233 | java | FirstFragment.java | Java | [] | null | [] | package curry.com.newwidget.fragment.gongban;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import curry.com.newwidget.R;
public class FirstFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**
* 下面一行的写法注意,false,直接复制,要不然会忘了参数
* 如果没有最后一个参数false会报错 The specified child already has a parent. You must call removeView() on the child's parent first.
*/
View v = inflater.inflate(R.layout.first_fragment, container, false);
TextView tv = (TextView)v.findViewById(R.id.msg);
tv.setText("This is first fragment.");
tv.setBackgroundColor(Color.GREEN);
return v;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
System.out.println("11111111111111111111111");
}
}
| 1,233 | 0.726488 | 0.705781 | 34 | 33.058823 | 29.477749 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.617647 | false | false | 3 |
c0cc9d4c33b4c3df4213077f9b5e3ba593c77db2 | 4,501,125,733,929 | d48c1591292e285adb799aa7073618d6b34fa673 | /src/main/java/edu/sfsu/worldofbalance/atnsimulator/SimulationOscillatingSteadyStateDetector.java | e10e2c55d8fbac69ba86a494fa0786f5257bca6b | [
"MIT"
] | permissive | brsaylor/atn-simulator | https://github.com/brsaylor/atn-simulator | d4a1faddeea7072d1b1683a245b34b9f48073f3b | 4ea0c3475f9572873a876ebd58d66ba31fb4c383 | refs/heads/master | 2021-01-18T21:47:06.649000 | 2017-05-16T19:14:26 | 2017-05-16T19:14:26 | 87,022,629 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.sfsu.worldofbalance.atnsimulator;
import java.util.Arrays;
/**
* Detects an oscillating steady state and stops the integration when it occurs.
* This steady state is identified based on the observation that
* if the biomass state vector returns a value it held previously,
* then it will return to that state again and again in a periodic pattern.
*
* At the start of integration, we take a snapshot of the state vector.
* If the current biomass repeatedly reaches that state again (some minimum number of times),
* and the biomasses are exhibiting an oscillating pattern,
* then an oscillating steady state has been reached and we stop the integration.
*/
public class SimulationOscillatingSteadyStateDetector extends SimulationEventHandler {
public final double RELATIVE_ERROR_TOLERANCE = 0.01; // Maximum relative error to accept matching biomass state
public final double REQUIRED_MATCHING_STATE_COUNT = 3; // Number of state matches required before stopping integration
private double[] biomassSnapshot; // Snapshot of biomass state at start of current integration
private double biomassSnapshotSum; // Sum of the biomass snapshot
private double biomassSum; // Sum of the current biomass state
private double[] absoluteError; // Error between current state and snapshot state
private double[] relativeError; // Relative error between current state and snapshot state
private double[] minDerivative; // Minimum derivatives computed since start of current integration
private double[] maxDerivative; // Maximum derivatives computed since start of current integration
private int numOscillating; // Number of nodes with oscillating biomass
private int matchingStateCount = 0; // Number of times the current biomass state has matched the snapshot
public SimulationOscillatingSteadyStateDetector(ModelEquations equations) {
super(equations);
}
/**
* Called at the start of an integration.
* Note that this is not necessarily the start of a simulation.
*
* @param t0 Integration start time (not 0 unless this is the start of the simulation)
* @param B0 Biomass of each node at time t0
* @param t Target time for the integration
*/
@Override
public void init(double t0, double[] B0, double t) {
// Take a snapshot of the biomass at the start of integration
biomassSnapshot = Arrays.copyOf(B0, B0.length);
biomassSnapshotSum = 0;
for (double b : B0) {
biomassSnapshotSum += b;
}
absoluteError = new double[B0.length];
relativeError = new double[B0.length];
minDerivative = new double[B0.length];
maxDerivative = new double[B0.length];
for (int i = 0; i < B0.length; i++) {
minDerivative[i] = Double.POSITIVE_INFINITY;
maxDerivative[i] = Double.NEGATIVE_INFINITY;
}
numOscillating = 0;
matchingStateCount = 0;
}
/**
* Compute the switching function.
* When the sign of this continuous function changes,
* an event is triggered and handled by eventOccurred().
*
* This switching function crosses zero when the current total biomass
* equals the total biomass at the start of integration (the biomass "snapshot").
* g() always crosses zero where the current biomass state equals the snapshot;
* however, it can cross zero at other times, too,
* so we check for a true match in eventOccurred().
*
* @param t Time
* @param Bt Biomass of each node at time t
* @return the value of the switching function
*/
@Override
public double g(double t, double[] Bt) {
// Compute the current total biomass
// and the min and max derivatives since the start of the integration, which we'll use later.
double[] currentDerivatives = equations.getCurrentDerivatives();
biomassSum = 0;
for (int i = 0; i < Bt.length; i++) {
minDerivative[i] = Math.min(minDerivative[i], currentDerivatives[i]);
maxDerivative[i] = Math.max(maxDerivative[i], currentDerivatives[i]);
biomassSum += Bt[i];
}
return biomassSnapshotSum - biomassSum;
}
/**
* Called when the switching function crosses zero.
* Stops the integration if:
* - the current biomass state equals the snapshot within a tolerance, and
* - at least one node is oscillating, and
* - those two conditions have been met a minimum number of times since the start of the integration.
*
* @param t Time
* @param Bt Biomass of each node at time t
* @param increasing If true, g() is increasing at time t
* @return Action.STOP if the integration should be stopped; Action.CONTINUE otherwise
*/
@Override
public Action eventOccurred(double t, double[] Bt, boolean increasing) {
numOscillating = 0;
for (int i = 0; i < Bt.length; i++) {
// If the biomass of node i is not within the error tolerance,
// don't stop the integration.
absoluteError[i] = Math.abs(Bt[i] - biomassSnapshot[i]);
relativeError[i] = absoluteError[i] / biomassSnapshot[i];
if (relativeError[i] > RELATIVE_ERROR_TOLERANCE) {
return Action.CONTINUE;
}
// Count the number of oscillating node,
// "oscillating" defined very generally as having had both a negative and a positive derivative
// since the start of the current integration.
if (minDerivative[i] < 0 && maxDerivative[i] > 0) {
numOscillating++;
}
}
// At this point, all biomasses match the snapshot within RELATIVE_ERROR_TOLERANCE.
if (numOscillating > 0) {
// At least one node is oscillating; count this as a matching state
matchingStateCount++;
if (matchingStateCount == REQUIRED_MATCHING_STATE_COUNT) {
// We've seen enough repeated matching states to be sure a steady state has been reached,
// so stop the integration
timeStopped = t;
stopEvent = EventType.OSCILLATING_STEADY_STATE;
return Action.STOP;
} else {
// We need to keep watching for more matching states
return Action.CONTINUE;
}
} else {
// No nodes are oscillating; do not count this as a matching state
return Action.CONTINUE;
}
}
/**
* Get the number of nodes that have had both positive and negative derivatives
* since the start of the integration. The value is only meaningful
* if this event handler has just stopped the integration.
*
* @return the number of nodes with oscillating biomass
*/
public int getNumOscillating() {
return numOscillating;
}
} | UTF-8 | Java | 7,013 | java | SimulationOscillatingSteadyStateDetector.java | Java | [] | null | [] | package edu.sfsu.worldofbalance.atnsimulator;
import java.util.Arrays;
/**
* Detects an oscillating steady state and stops the integration when it occurs.
* This steady state is identified based on the observation that
* if the biomass state vector returns a value it held previously,
* then it will return to that state again and again in a periodic pattern.
*
* At the start of integration, we take a snapshot of the state vector.
* If the current biomass repeatedly reaches that state again (some minimum number of times),
* and the biomasses are exhibiting an oscillating pattern,
* then an oscillating steady state has been reached and we stop the integration.
*/
public class SimulationOscillatingSteadyStateDetector extends SimulationEventHandler {
public final double RELATIVE_ERROR_TOLERANCE = 0.01; // Maximum relative error to accept matching biomass state
public final double REQUIRED_MATCHING_STATE_COUNT = 3; // Number of state matches required before stopping integration
private double[] biomassSnapshot; // Snapshot of biomass state at start of current integration
private double biomassSnapshotSum; // Sum of the biomass snapshot
private double biomassSum; // Sum of the current biomass state
private double[] absoluteError; // Error between current state and snapshot state
private double[] relativeError; // Relative error between current state and snapshot state
private double[] minDerivative; // Minimum derivatives computed since start of current integration
private double[] maxDerivative; // Maximum derivatives computed since start of current integration
private int numOscillating; // Number of nodes with oscillating biomass
private int matchingStateCount = 0; // Number of times the current biomass state has matched the snapshot
public SimulationOscillatingSteadyStateDetector(ModelEquations equations) {
super(equations);
}
/**
* Called at the start of an integration.
* Note that this is not necessarily the start of a simulation.
*
* @param t0 Integration start time (not 0 unless this is the start of the simulation)
* @param B0 Biomass of each node at time t0
* @param t Target time for the integration
*/
@Override
public void init(double t0, double[] B0, double t) {
// Take a snapshot of the biomass at the start of integration
biomassSnapshot = Arrays.copyOf(B0, B0.length);
biomassSnapshotSum = 0;
for (double b : B0) {
biomassSnapshotSum += b;
}
absoluteError = new double[B0.length];
relativeError = new double[B0.length];
minDerivative = new double[B0.length];
maxDerivative = new double[B0.length];
for (int i = 0; i < B0.length; i++) {
minDerivative[i] = Double.POSITIVE_INFINITY;
maxDerivative[i] = Double.NEGATIVE_INFINITY;
}
numOscillating = 0;
matchingStateCount = 0;
}
/**
* Compute the switching function.
* When the sign of this continuous function changes,
* an event is triggered and handled by eventOccurred().
*
* This switching function crosses zero when the current total biomass
* equals the total biomass at the start of integration (the biomass "snapshot").
* g() always crosses zero where the current biomass state equals the snapshot;
* however, it can cross zero at other times, too,
* so we check for a true match in eventOccurred().
*
* @param t Time
* @param Bt Biomass of each node at time t
* @return the value of the switching function
*/
@Override
public double g(double t, double[] Bt) {
// Compute the current total biomass
// and the min and max derivatives since the start of the integration, which we'll use later.
double[] currentDerivatives = equations.getCurrentDerivatives();
biomassSum = 0;
for (int i = 0; i < Bt.length; i++) {
minDerivative[i] = Math.min(minDerivative[i], currentDerivatives[i]);
maxDerivative[i] = Math.max(maxDerivative[i], currentDerivatives[i]);
biomassSum += Bt[i];
}
return biomassSnapshotSum - biomassSum;
}
/**
* Called when the switching function crosses zero.
* Stops the integration if:
* - the current biomass state equals the snapshot within a tolerance, and
* - at least one node is oscillating, and
* - those two conditions have been met a minimum number of times since the start of the integration.
*
* @param t Time
* @param Bt Biomass of each node at time t
* @param increasing If true, g() is increasing at time t
* @return Action.STOP if the integration should be stopped; Action.CONTINUE otherwise
*/
@Override
public Action eventOccurred(double t, double[] Bt, boolean increasing) {
numOscillating = 0;
for (int i = 0; i < Bt.length; i++) {
// If the biomass of node i is not within the error tolerance,
// don't stop the integration.
absoluteError[i] = Math.abs(Bt[i] - biomassSnapshot[i]);
relativeError[i] = absoluteError[i] / biomassSnapshot[i];
if (relativeError[i] > RELATIVE_ERROR_TOLERANCE) {
return Action.CONTINUE;
}
// Count the number of oscillating node,
// "oscillating" defined very generally as having had both a negative and a positive derivative
// since the start of the current integration.
if (minDerivative[i] < 0 && maxDerivative[i] > 0) {
numOscillating++;
}
}
// At this point, all biomasses match the snapshot within RELATIVE_ERROR_TOLERANCE.
if (numOscillating > 0) {
// At least one node is oscillating; count this as a matching state
matchingStateCount++;
if (matchingStateCount == REQUIRED_MATCHING_STATE_COUNT) {
// We've seen enough repeated matching states to be sure a steady state has been reached,
// so stop the integration
timeStopped = t;
stopEvent = EventType.OSCILLATING_STEADY_STATE;
return Action.STOP;
} else {
// We need to keep watching for more matching states
return Action.CONTINUE;
}
} else {
// No nodes are oscillating; do not count this as a matching state
return Action.CONTINUE;
}
}
/**
* Get the number of nodes that have had both positive and negative derivatives
* since the start of the integration. The value is only meaningful
* if this event handler has just stopped the integration.
*
* @return the number of nodes with oscillating biomass
*/
public int getNumOscillating() {
return numOscillating;
}
} | 7,013 | 0.654784 | 0.650506 | 169 | 40.50296 | 33.243431 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.455621 | false | false | 3 |
728d6c308f116ecb8d6366db27ff9c92df6d0da5 | 5,712,306,519,951 | 0f3b8a0cab7673671c5905bcf1cac41c3168ad2c | /src/test/java/com/zsy/springframework/test/bean/IUserService.java | 24a4727c00410e320f487366a47651e4e7d8bda2 | [] | no_license | ZHUSHENGYU/spring.01 | https://github.com/ZHUSHENGYU/spring.01 | 0f36a8c7d67d0139b5184cdc3edc8f7296e22034 | da81ff9ea7a795de9c6b8bd46da48de577818f12 | refs/heads/main | 2023-07-28T18:26:02.195000 | 2021-09-14T06:09:17 | 2021-09-14T06:09:17 | 403,795,039 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zsy.springframework.test.bean;
public interface IUserService {
String queryUserInfo();
}
| UTF-8 | Java | 107 | java | IUserService.java | Java | [] | null | [] | package com.zsy.springframework.test.bean;
public interface IUserService {
String queryUserInfo();
}
| 107 | 0.766355 | 0.766355 | 6 | 16.833334 | 17.10182 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 3 |
eac7211247f3166916d5e7bc6354994ace0afa73 | 36,438,502,544,049 | 41803a2e63d5413aedadd28129afb75bf9115ccf | /portlets/winners-portlet/docroot/WEB-INF/src/com/playtech/portal/platform/portlet/winners/model/SortBy.java | 0b890edce0ce41f894f94b8fd09f81fb665888b5 | [] | no_license | ramiavi/my-proj | https://github.com/ramiavi/my-proj | 06a50e0eb085ef3c678421ffb26ef210a38a26c0 | 8ce464cadb210169ca7cff29f209f7c2d4f3f475 | refs/heads/master | 2020-02-05T06:35:03.554000 | 2016-05-16T19:40:26 | 2016-05-16T19:40:26 | 58,965,356 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.playtech.portal.platform.portlet.winners.model;
/**
*
*
* @author: Roman Bizhko
* Date: 1/17/14
* Time: 4:30 PM
*/
public enum SortBy {
WIN_AMOUNT, DATE
}
| UTF-8 | Java | 176 | java | SortBy.java | Java | [
{
"context": "form.portlet.winners.model;\n\n/**\n *\n *\n * @author: Roman Bizhko\n * Date: 1/17/14\n * Time: 4:30 PM\n */\npublic enum",
"end": 95,
"score": 0.9998584985733032,
"start": 83,
"tag": "NAME",
"value": "Roman Bizhko"
}
] | null | [] | package com.playtech.portal.platform.portlet.winners.model;
/**
*
*
* @author: <NAME>
* Date: 1/17/14
* Time: 4:30 PM
*/
public enum SortBy {
WIN_AMOUNT, DATE
}
| 170 | 0.653409 | 0.607955 | 12 | 13.666667 | 16.017351 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.166667 | false | false | 3 |
1ebee92028eb2fb0b8e2edcc515a2a9fbfa91f9b | 27,273,042,358,629 | d40e814dad4fc2187e463dd7362f0f0ff8ee64a4 | /Parentheses.java | e122f94c924ea1b2efb81529be90cfa06d02596a | [] | no_license | anayw2001/apcs | https://github.com/anayw2001/apcs | eb9b316bd77ad2bbabd6accd1fb83c5e6251a229 | cd79ef559b38ed71cdcb26914fab003f67cb1441 | refs/heads/master | 2018-11-24T10:45:17.304000 | 2018-11-16T00:29:24 | 2018-11-16T00:29:24 | 146,774,091 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.*;
public class Parentheses {
private static final char L_PAREN = '(';
private static final char R_PAREN = ')';
private static Stack<Character> stack = new Stack<Character>();
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Enter your string below:");
String s = console.nextLine();
int length = s.length();
boolean b = isBalanced(s,length);
System.out.println(b);
int counter = 0;
int max = 0;
if (b==true) {
for (int i = 0; i < length; i++) {
if (s.charAt(i) == L_PAREN) {
counter++;
} else if (s.charAt(i) == R_PAREN) {
counter--;
}
if (counter > max) {
max = counter;
}
}
System.out.println(max);
}
}
public static boolean isBalanced(String s, int length) {
for (int i = 0; i < length; i++) {
if (s.charAt(i) == L_PAREN)
stack.push(L_PAREN);
else if (s.charAt(i) == R_PAREN) {
if (stack.isEmpty())
return false;
if (stack.pop() != L_PAREN)
return false;
}
}
return stack.isEmpty();
}
}
| UTF-8 | Java | 1,202 | java | Parentheses.java | Java | [] | null | [] | import java.util.*;
public class Parentheses {
private static final char L_PAREN = '(';
private static final char R_PAREN = ')';
private static Stack<Character> stack = new Stack<Character>();
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Enter your string below:");
String s = console.nextLine();
int length = s.length();
boolean b = isBalanced(s,length);
System.out.println(b);
int counter = 0;
int max = 0;
if (b==true) {
for (int i = 0; i < length; i++) {
if (s.charAt(i) == L_PAREN) {
counter++;
} else if (s.charAt(i) == R_PAREN) {
counter--;
}
if (counter > max) {
max = counter;
}
}
System.out.println(max);
}
}
public static boolean isBalanced(String s, int length) {
for (int i = 0; i < length; i++) {
if (s.charAt(i) == L_PAREN)
stack.push(L_PAREN);
else if (s.charAt(i) == R_PAREN) {
if (stack.isEmpty())
return false;
if (stack.pop() != L_PAREN)
return false;
}
}
return stack.isEmpty();
}
}
| 1,202 | 0.526622 | 0.523295 | 44 | 26.318182 | 15.802435 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.590909 | false | false | 3 |
758f2c8801dd17538fe601d74b0e8901eadb835c | 30,511,447,719,901 | 12611a84ff19984b05a7c6b28b8d8cc28a1e9955 | /PictureFragment.java | 899a4717000a860dd27f5de405cf15685f26c2c1 | [] | no_license | nickspoerk/cs407h1 | https://github.com/nickspoerk/cs407h1 | f51cd7ba49d490c7a5a9da15b2bcaa3e2aabeb4a | 92d3e5bcf4a537f352394fd10a9d8ad1eaf4f7d1 | refs/heads/master | 2021-01-10T06:28:01.328000 | 2016-02-23T03:27:02 | 2016-02-23T03:27:02 | 52,135,328 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.commonsware.android.homework1;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
/**
* A simple {@link Fragment} subclass.
*/
public class PictureFragment extends Fragment {
private int score;
public PictureFragment() {
// Required empty public constructor
}
public static PictureFragment newInstance(int score) {
PictureFragment frag = new PictureFragment();
Bundle args = new Bundle();
frag.setArguments(args);
return frag;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.picture_fragement_layout, container, false);
TextView text = (TextView) view.findViewById(R.id.picQuestion);
final EditText mascot = (EditText) view.findViewById(R.id.editText);
Button next = (Button) view.findViewById(R.id.submitPic);
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String answer = mascot.getText().toString();
boolean correct;
correct = (answer.equalsIgnoreCase("Bucky"));
int score = 0;
if (correct) {
score++;
}
((MainActivity)getActivity()).doQuiz(2, score);
}
});
return view;
}
}
| UTF-8 | Java | 1,777 | java | PictureFragment.java | Java | [] | null | [] | package com.commonsware.android.homework1;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
/**
* A simple {@link Fragment} subclass.
*/
public class PictureFragment extends Fragment {
private int score;
public PictureFragment() {
// Required empty public constructor
}
public static PictureFragment newInstance(int score) {
PictureFragment frag = new PictureFragment();
Bundle args = new Bundle();
frag.setArguments(args);
return frag;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.picture_fragement_layout, container, false);
TextView text = (TextView) view.findViewById(R.id.picQuestion);
final EditText mascot = (EditText) view.findViewById(R.id.editText);
Button next = (Button) view.findViewById(R.id.submitPic);
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String answer = mascot.getText().toString();
boolean correct;
correct = (answer.equalsIgnoreCase("Bucky"));
int score = 0;
if (correct) {
score++;
}
((MainActivity)getActivity()).doQuiz(2, score);
}
});
return view;
}
}
| 1,777 | 0.60045 | 0.598762 | 60 | 27.616667 | 24.034067 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.516667 | false | false | 3 |
db9ef25d1fdc7e3913bac5a7511d05e4d533a56e | 3,023,657,038,036 | ccc3e5b53efef3b524496c5378465972fe1742c5 | /src/main/java/com/ef/accesslog/AccessLogManager.java | 61cb2f58302adec7995d76dd82b034e04e0fd06c | [] | no_license | leowada/javaMySqlTest | https://github.com/leowada/javaMySqlTest | c297c20256cf295018098dbd6656d1fa35e656ad | 54a50e0abde546864e3112fa65fcdbf150da6548 | refs/heads/master | 2020-03-23T18:54:22.848000 | 2018-07-25T05:38:52 | 2018-07-25T05:38:52 | 141,939,890 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ef.accesslog;
import com.ef.arguments.ArgumentsDTO;
import org.springframework.stereotype.Component;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Component
@Transactional
public class AccessLogManager {
private static String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";
private static String START_DATE_FORMAT = "yyyy-MM-dd.HH:mm:ss";
private static String HOURLY = "hourly";
private static String DAILY = "daily";
@PersistenceContext
private EntityManager entityManager;
public void loadAccessLog(ArgumentsDTO argumentsDTO) {
String accessLogPath = argumentsDTO.getAccessLogPath();
List<String> accessLogList = new ArrayList<>();
LocalDateTime startDate = this.convertStringToLocalDate(argumentsDTO.getStartDate(), START_DATE_FORMAT);
LocalDateTime endDate = this.getEndDate(startDate, argumentsDTO.getDuration());
try (BufferedReader bufferedReaderFiles = Files.newBufferedReader(Paths.get(accessLogPath))) {
accessLogList = bufferedReaderFiles.lines().collect(Collectors.toList());
} catch (IOException e) {
System.out.println("Error while reading the access log files!");
e.printStackTrace();
}
AccessLogBetweenDuration accessLogBetweenDuration = new AccessLogBetweenDuration();
this.parseToAccessLog(accessLogList, argumentsDTO, startDate, accessLogBetweenDuration, endDate);
this.findAccessExceedThreshold(accessLogBetweenDuration, argumentsDTO.getThreshold(), startDate, endDate);
}
private void parseToAccessLog(List<String> accessLogList, ArgumentsDTO argumentsDTO, LocalDateTime startDate,
AccessLogBetweenDuration accessLogBetweenDuration, LocalDateTime endDate) {
for (String accessLogAsString : accessLogList) {
String[] accessLogValues = accessLogAsString.split("\\|");
String date = accessLogValues[0];
String ip = accessLogValues[1];
String request = accessLogValues[2];
Integer status = Integer.parseInt(accessLogValues[3]);
String userAgent = accessLogValues[4];
LocalDateTime localDate = this.convertStringToLocalDate(date, DATE_FORMAT);
AccessLogLine accessLogLine = new AccessLogLine(localDate, ip, request, status, userAgent);
this.entityManager.persist(accessLogLine);
boolean isAccessInDuration = validateAccessInDuration(startDate, accessLogLine, endDate);
if (isAccessInDuration) {
accessLogBetweenDuration.add(accessLogLine);
}
}
}
private void findAccessExceedThreshold(AccessLogBetweenDuration accessLogBetweenDuration, Integer threshold, LocalDateTime startDate,
LocalDateTime endDate) {
for (String ip : accessLogBetweenDuration.getMapIpAccessLogs().keySet()) {
int accessSize = accessLogBetweenDuration.getMapIpAccessLogs().get(ip).size();
if (accessSize > threshold) {
System.out.println(ip + " has " + accessSize + " access.");
BlockedIp blockedIp =
new BlockedIp(ip, "Blocked because has " + accessSize + " access between " + startDate + " and " + endDate);
this.entityManager.persist(blockedIp);
}
}
}
private LocalDateTime convertStringToLocalDate(String localDateAsString, String dateFormat) {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(dateFormat);
return LocalDateTime.parse(localDateAsString, dateTimeFormatter);
}
public boolean validateAccessInDuration(LocalDateTime startDate, AccessLogLine accessLogLine, LocalDateTime endDate) {
LocalDateTime logDate = accessLogLine.getDate();
if ((logDate.isAfter(startDate) || logDate.isEqual(startDate)) && logDate.isBefore(endDate)) {
return true;
}
return false;
}
private LocalDateTime getEndDate(LocalDateTime startDate, String duration) {
LocalDateTime endDate = startDate;
if (HOURLY.equals(duration)) {
return endDate.plusHours(1);
} else if (DAILY.equals(duration)) {
return endDate.plusDays(1);
}
throw new RuntimeException("Value of duration is wrong!");
}
private class AccessLogBetweenDuration {
final Map<String, List<AccessLogLine>> mapIpAccessLogs = new HashMap<>();
public Map<String, List<AccessLogLine>> getMapIpAccessLogs() {
return mapIpAccessLogs;
}
public void add(AccessLogLine accessLogLine) {
if (mapIpAccessLogs.containsKey(accessLogLine.getIp())) {
mapIpAccessLogs.get(accessLogLine.getIp()).add(accessLogLine);
} else {
List<AccessLogLine> accessLogLineList = new ArrayList<>();
accessLogLineList.add(accessLogLine);
mapIpAccessLogs.put(accessLogLine.getIp(), accessLogLineList);
}
}
}
}
| UTF-8 | Java | 5,506 | java | AccessLogManager.java | Java | [] | null | [] | package com.ef.accesslog;
import com.ef.arguments.ArgumentsDTO;
import org.springframework.stereotype.Component;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Component
@Transactional
public class AccessLogManager {
private static String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";
private static String START_DATE_FORMAT = "yyyy-MM-dd.HH:mm:ss";
private static String HOURLY = "hourly";
private static String DAILY = "daily";
@PersistenceContext
private EntityManager entityManager;
public void loadAccessLog(ArgumentsDTO argumentsDTO) {
String accessLogPath = argumentsDTO.getAccessLogPath();
List<String> accessLogList = new ArrayList<>();
LocalDateTime startDate = this.convertStringToLocalDate(argumentsDTO.getStartDate(), START_DATE_FORMAT);
LocalDateTime endDate = this.getEndDate(startDate, argumentsDTO.getDuration());
try (BufferedReader bufferedReaderFiles = Files.newBufferedReader(Paths.get(accessLogPath))) {
accessLogList = bufferedReaderFiles.lines().collect(Collectors.toList());
} catch (IOException e) {
System.out.println("Error while reading the access log files!");
e.printStackTrace();
}
AccessLogBetweenDuration accessLogBetweenDuration = new AccessLogBetweenDuration();
this.parseToAccessLog(accessLogList, argumentsDTO, startDate, accessLogBetweenDuration, endDate);
this.findAccessExceedThreshold(accessLogBetweenDuration, argumentsDTO.getThreshold(), startDate, endDate);
}
private void parseToAccessLog(List<String> accessLogList, ArgumentsDTO argumentsDTO, LocalDateTime startDate,
AccessLogBetweenDuration accessLogBetweenDuration, LocalDateTime endDate) {
for (String accessLogAsString : accessLogList) {
String[] accessLogValues = accessLogAsString.split("\\|");
String date = accessLogValues[0];
String ip = accessLogValues[1];
String request = accessLogValues[2];
Integer status = Integer.parseInt(accessLogValues[3]);
String userAgent = accessLogValues[4];
LocalDateTime localDate = this.convertStringToLocalDate(date, DATE_FORMAT);
AccessLogLine accessLogLine = new AccessLogLine(localDate, ip, request, status, userAgent);
this.entityManager.persist(accessLogLine);
boolean isAccessInDuration = validateAccessInDuration(startDate, accessLogLine, endDate);
if (isAccessInDuration) {
accessLogBetweenDuration.add(accessLogLine);
}
}
}
private void findAccessExceedThreshold(AccessLogBetweenDuration accessLogBetweenDuration, Integer threshold, LocalDateTime startDate,
LocalDateTime endDate) {
for (String ip : accessLogBetweenDuration.getMapIpAccessLogs().keySet()) {
int accessSize = accessLogBetweenDuration.getMapIpAccessLogs().get(ip).size();
if (accessSize > threshold) {
System.out.println(ip + " has " + accessSize + " access.");
BlockedIp blockedIp =
new BlockedIp(ip, "Blocked because has " + accessSize + " access between " + startDate + " and " + endDate);
this.entityManager.persist(blockedIp);
}
}
}
private LocalDateTime convertStringToLocalDate(String localDateAsString, String dateFormat) {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(dateFormat);
return LocalDateTime.parse(localDateAsString, dateTimeFormatter);
}
public boolean validateAccessInDuration(LocalDateTime startDate, AccessLogLine accessLogLine, LocalDateTime endDate) {
LocalDateTime logDate = accessLogLine.getDate();
if ((logDate.isAfter(startDate) || logDate.isEqual(startDate)) && logDate.isBefore(endDate)) {
return true;
}
return false;
}
private LocalDateTime getEndDate(LocalDateTime startDate, String duration) {
LocalDateTime endDate = startDate;
if (HOURLY.equals(duration)) {
return endDate.plusHours(1);
} else if (DAILY.equals(duration)) {
return endDate.plusDays(1);
}
throw new RuntimeException("Value of duration is wrong!");
}
private class AccessLogBetweenDuration {
final Map<String, List<AccessLogLine>> mapIpAccessLogs = new HashMap<>();
public Map<String, List<AccessLogLine>> getMapIpAccessLogs() {
return mapIpAccessLogs;
}
public void add(AccessLogLine accessLogLine) {
if (mapIpAccessLogs.containsKey(accessLogLine.getIp())) {
mapIpAccessLogs.get(accessLogLine.getIp()).add(accessLogLine);
} else {
List<AccessLogLine> accessLogLineList = new ArrayList<>();
accessLogLineList.add(accessLogLine);
mapIpAccessLogs.put(accessLogLine.getIp(), accessLogLineList);
}
}
}
}
| 5,506 | 0.683255 | 0.681983 | 128 | 42.015625 | 35.473137 | 137 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.757813 | false | false | 3 |
1aae2c24ed5c26ff4510806426d40cf28d42faa9 | 901,943,195,572 | b383d4178c38392d901dfcd2875b36ce4dc872f9 | /biz.aQute.bndlib/src/aQute/bnd/service/diff/Type.java | 91b186c1593e7a1d98844c61ed77945aa82cd87f | [
"Apache-2.0"
] | permissive | atlassian/bnd | https://github.com/atlassian/bnd | 6cc323f9f1a66d1693772b97746c692159c5b453 | 1544d4ba2c9fc2f60945d4712502d641235d5512 | refs/heads/master | 2023-08-21T14:22:00.971000 | 2016-04-28T00:23:50 | 2016-04-28T00:28:53 | 57,100,267 | 0 | 1 | Apache-2.0 | true | 2023-08-15T17:43:08 | 2016-04-26T05:24:14 | 2016-04-26T05:24:20 | 2023-08-15T17:43:07 | 274,184 | 0 | 1 | 2 | Java | false | false | package aQute.bnd.service.diff;
public enum Type {
ACCESS, BUNDLE, API, MANIFEST, PACKAGE, CLASS, INTERFACE, ANNOTATION, ENUM, EXTENDS, IMPLEMENTS, FIELD, METHOD, ANNOTATED, PROPERTY, RESOURCE, SHA, CUSTOM, CLAUSE, HEADER, PARAMETER, CLASS_VERSION, RESOURCES, CONSTANT, RETURN, VERSION, DEPRECATED, REPO, PROGRAM, REVISION;
public boolean isInherited() {
// TODO Auto-generated method stub
return false;
}
}
| UTF-8 | Java | 417 | java | Type.java | Java | [] | null | [] | package aQute.bnd.service.diff;
public enum Type {
ACCESS, BUNDLE, API, MANIFEST, PACKAGE, CLASS, INTERFACE, ANNOTATION, ENUM, EXTENDS, IMPLEMENTS, FIELD, METHOD, ANNOTATED, PROPERTY, RESOURCE, SHA, CUSTOM, CLAUSE, HEADER, PARAMETER, CLASS_VERSION, RESOURCES, CONSTANT, RETURN, VERSION, DEPRECATED, REPO, PROGRAM, REVISION;
public boolean isInherited() {
// TODO Auto-generated method stub
return false;
}
}
| 417 | 0.752998 | 0.752998 | 10 | 40.700001 | 78.572327 | 273 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.9 | false | false | 3 |
38cf1022c1c2c5f9321412539aa3e5d2c3888e21 | 34,711,925,687,788 | 3fc8cb4d8005aa9ee9628b9fd57d41544561fcfb | /app/actions/paipai/PaiPaiAction.java | 6efcfa1773a13735dfeee6598057f5d8cb263f92 | [] | no_license | caoyd/tm | https://github.com/caoyd/tm | a9d799ca58b2624e5c2fca30c9b9453e46b094a0 | 62a6fc77fe152b2a73110b67d55a13d01c995cb1 | refs/heads/master | 2020-04-05T02:26:15.779000 | 2018-03-21T13:09:17 | 2018-03-21T13:09:17 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
package actions.paipai;
import java.util.List;
import java.util.concurrent.Callable;
import models.paipai.PaiPaiUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import play.mvc.results.Redirect;
import ppapi.PaiPaiSubscribeApi;
import ppapi.PaiPaiUserInfoApi;
import ppapi.models.PaiPaiSubscribe;
import ppapi.models.PaiPaiUserInfo;
import titleDiag.DiagResult;
import transaction.TransactionSecurity;
import actions.UserLoginAction;
import com.ciaosir.client.CommonUtils;
import configs.Subscribe;
import configs.Subscribe.Version;
import configs.TMConfigs;
import controllers.PaiPaiAPIConfig;
/**
* @author navins
* @date 2013-7-8 下午3:23:45
*/
public class PaiPaiAction {
private static final Logger log = LoggerFactory.getLogger(PaiPaiAction.class);
public static final String PAIPAI_REDIRECT_URL = "http://fuwu.paipai.com/my/app/authorizeGetAccessToken.xhtml?responseType=access_token&appOAuthID=";
public static PaiPaiAction _instance = new PaiPaiAction();
public static PaiPaiAction get() {
return _instance;
}
public PaiPaiUser checkLogin(long uin, String accessToken) {
if (uin < 10000) {
throw new Redirect(buildRedir());
}
PaiPaiUser user = PaiPaiUser.findByUserId(uin);
if (user == null) {
user = new PaiPaiUser(uin, accessToken);
PaiPaiUserInfo info = new PaiPaiUserInfoApi(user).call();
if (info == null) {
throw new Redirect(buildRedir());
}
user.setFirstLoginTime(System.currentTimeMillis());
user.setNick(info.getNick());
} else {
user.setAccessToken(accessToken);
}
int version = getVersion(user);
user.setVersion(version);
user.jdbcSave();
log.info("[save paipai user:]" + user);
return user;
}
public int getVersion(PaiPaiUser user) {
boolean isValid = false;
int version = Version.FREE;
List<PaiPaiSubscribe> subList = new PaiPaiSubscribeApi.PaiPaiSubscribeListApi(user).call();
if(user.getId()==301074800){
return 1;
}
if (CommonUtils.isEmpty(subList)) {
user.setVersion(version);
user.setValid(isValid);
user.jdbcSave();
return Version.FREE;
}
// long recent = Long.MAX_VALUE;
long ts = System.currentTimeMillis();
for (PaiPaiSubscribe sub : subList) {
// if(recent > sub.getDeadLine()) {
int tmp = Subscribe.getVersionByCode(String.valueOf(sub.getChargeItemId()));
if (tmp > version && ts < sub.getDeadLine()) {
version = tmp;
}
if (ts < sub.getDeadLine()) {
isValid = true;
}
// recent = sub.getDeadLine();
// }
}
user.setVersion(version);
user.setValid(isValid);
user.jdbcSave();
return version;
}
public String buildRedir() {
// String origin = PAIPAI_REDIRECT_URL + "&appOAuthID=%s&appOAuthkey=%s";
// String url = String.format(origin, apiConfig.getAppOAuthID(), apiConfig.getAppOAuthkey());
String url = PAIPAI_REDIRECT_URL + PaiPaiAPIConfig.get().getAppOAuthID();
return url;
}
public void ensureBaseInfo(final PaiPaiUser pUser) {
UserLoginAction.lockUserTag(pUser.getId());
TMConfigs.getDiagResultPool().submit(new Callable<DiagResult>() {
@Override
public DiagResult call() throws Exception {
return new TransactionSecurity<DiagResult>() {
@Override
public DiagResult operateOnDB() {
doForPaiPaiUser(pUser);
return null;
}
}.execute();
}
});
}
private void doForPaiPaiUser(PaiPaiUser pUser) {
// TODO item update job we need
UserLoginAction.unLockUserTag(pUser.getId());
}
}
| UTF-8 | Java | 4,117 | java | PaiPaiAction.java | Java | [
{
"context": "mport controllers.PaiPaiAPIConfig;\n\n/**\n * @author navins\n * @date 2013-7-8 下午3:23:45\n */\npublic class PaiP",
"end": 650,
"score": 0.999494194984436,
"start": 644,
"tag": "USERNAME",
"value": "navins"
}
] | null | [] | /**
*
*/
package actions.paipai;
import java.util.List;
import java.util.concurrent.Callable;
import models.paipai.PaiPaiUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import play.mvc.results.Redirect;
import ppapi.PaiPaiSubscribeApi;
import ppapi.PaiPaiUserInfoApi;
import ppapi.models.PaiPaiSubscribe;
import ppapi.models.PaiPaiUserInfo;
import titleDiag.DiagResult;
import transaction.TransactionSecurity;
import actions.UserLoginAction;
import com.ciaosir.client.CommonUtils;
import configs.Subscribe;
import configs.Subscribe.Version;
import configs.TMConfigs;
import controllers.PaiPaiAPIConfig;
/**
* @author navins
* @date 2013-7-8 下午3:23:45
*/
public class PaiPaiAction {
private static final Logger log = LoggerFactory.getLogger(PaiPaiAction.class);
public static final String PAIPAI_REDIRECT_URL = "http://fuwu.paipai.com/my/app/authorizeGetAccessToken.xhtml?responseType=access_token&appOAuthID=";
public static PaiPaiAction _instance = new PaiPaiAction();
public static PaiPaiAction get() {
return _instance;
}
public PaiPaiUser checkLogin(long uin, String accessToken) {
if (uin < 10000) {
throw new Redirect(buildRedir());
}
PaiPaiUser user = PaiPaiUser.findByUserId(uin);
if (user == null) {
user = new PaiPaiUser(uin, accessToken);
PaiPaiUserInfo info = new PaiPaiUserInfoApi(user).call();
if (info == null) {
throw new Redirect(buildRedir());
}
user.setFirstLoginTime(System.currentTimeMillis());
user.setNick(info.getNick());
} else {
user.setAccessToken(accessToken);
}
int version = getVersion(user);
user.setVersion(version);
user.jdbcSave();
log.info("[save paipai user:]" + user);
return user;
}
public int getVersion(PaiPaiUser user) {
boolean isValid = false;
int version = Version.FREE;
List<PaiPaiSubscribe> subList = new PaiPaiSubscribeApi.PaiPaiSubscribeListApi(user).call();
if(user.getId()==301074800){
return 1;
}
if (CommonUtils.isEmpty(subList)) {
user.setVersion(version);
user.setValid(isValid);
user.jdbcSave();
return Version.FREE;
}
// long recent = Long.MAX_VALUE;
long ts = System.currentTimeMillis();
for (PaiPaiSubscribe sub : subList) {
// if(recent > sub.getDeadLine()) {
int tmp = Subscribe.getVersionByCode(String.valueOf(sub.getChargeItemId()));
if (tmp > version && ts < sub.getDeadLine()) {
version = tmp;
}
if (ts < sub.getDeadLine()) {
isValid = true;
}
// recent = sub.getDeadLine();
// }
}
user.setVersion(version);
user.setValid(isValid);
user.jdbcSave();
return version;
}
public String buildRedir() {
// String origin = PAIPAI_REDIRECT_URL + "&appOAuthID=%s&appOAuthkey=%s";
// String url = String.format(origin, apiConfig.getAppOAuthID(), apiConfig.getAppOAuthkey());
String url = PAIPAI_REDIRECT_URL + PaiPaiAPIConfig.get().getAppOAuthID();
return url;
}
public void ensureBaseInfo(final PaiPaiUser pUser) {
UserLoginAction.lockUserTag(pUser.getId());
TMConfigs.getDiagResultPool().submit(new Callable<DiagResult>() {
@Override
public DiagResult call() throws Exception {
return new TransactionSecurity<DiagResult>() {
@Override
public DiagResult operateOnDB() {
doForPaiPaiUser(pUser);
return null;
}
}.execute();
}
});
}
private void doForPaiPaiUser(PaiPaiUser pUser) {
// TODO item update job we need
UserLoginAction.unLockUserTag(pUser.getId());
}
}
| 4,117 | 0.601994 | 0.595186 | 142 | 27.964788 | 25.232277 | 153 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.478873 | false | false | 3 |
35beb4642b6215edc5687cb6edef7f7b60a3422c | 19,963,008,026,327 | 779374d3536940ab5e815266ee801d9c1ddc4e22 | /flare-java/src/main/java/org/nting/flare/java/BlockTypes.java | 111c4a6d09a96281c4a26646b7fe349ba749d56d | [] | no_license | zsoltborcsok/flare | https://github.com/zsoltborcsok/flare | 5a34e8626836db60be20eaa7ae50a5573fa581ea | 2a77134e2ec42bc218a358c3090eb16ea0e640f9 | refs/heads/master | 2022-12-25T17:14:19.078000 | 2020-10-04T11:59:26 | 2020-10-04T13:51:56 | 263,033,422 | 0 | 0 | null | false | 2020-10-13T21:54:31 | 2020-05-11T12:17:25 | 2020-10-04T13:52:47 | 2020-10-13T21:54:30 | 957 | 0 | 0 | 1 | Java | false | false | package org.nting.flare.java;
import java.util.Map;
import com.google.common.collect.ImmutableMap;
public class BlockTypes {
public static final int unknown = 0;
public static final int components = 1;
public static final int actorNode = 2;
public static final int actorBone = 3;
public static final int actorRootBone = 4;
public static final int actorImage = 5;
public static final int view = 6;
public static final int animation = 7;
public static final int animations = 8;
public static final int atlases = 9;
public static final int atlas = 10;
public static final int actorIKTarget = 11;
public static final int actorEvent = 12;
public static final int customIntProperty = 13;
public static final int customFloatProperty = 14;
public static final int customStringProperty = 15;
public static final int customBooleanProperty = 16;
public static final int actorColliderRectangle = 17;
public static final int actorColliderTriangle = 18;
public static final int actorColliderCircle = 19;
public static final int actorColliderPolygon = 20;
public static final int actorColliderLine = 21;
public static final int actorImageSequence = 22;
public static final int actorNodeSolo = 23;
public static final int jellyComponent = 28;
public static final int actorJellyBone = 29;
public static final int actorIKConstraint = 30;
public static final int actorDistanceConstraint = 31;
public static final int actorTranslationConstraint = 32;
public static final int actorRotationConstraint = 33;
public static final int actorScaleConstraint = 34;
public static final int actorTransformConstraint = 35;
public static final int actorShape = 100;
public static final int actorPath = 101;
public static final int colorFill = 102;
public static final int colorStroke = 103;
public static final int gradientFill = 104;
public static final int gradientStroke = 105;
public static final int radialGradientFill = 106;
public static final int radialGradientStroke = 107;
public static final int actorEllipse = 108;
public static final int actorRectangle = 109;
public static final int actorTriangle = 110;
public static final int actorStar = 111;
public static final int actorPolygon = 112;
public static final int actorSkin = 113;
public static final int actorArtboard = 114;
public static final int artboards = 115;
public static final int actorLayerEffectRenderer = 116;
public static final int actorMask = 117;
public static final int actorBlur = 118;
public static final int actorDropShadow = 119;
public static final int actorInnerShadow = 120;
public static final Map<String, Integer> blockTypesMap = ImmutableMap.<String, Integer> builder()
.put("unknown", BlockTypes.unknown) //
.put("nodes", BlockTypes.components) //
.put("node", BlockTypes.actorNode) //
.put("bone", BlockTypes.actorBone) //
.put("rootBone", BlockTypes.actorRootBone) //
.put("image", BlockTypes.actorImage) //
.put("view", BlockTypes.view) //
.put("animation", BlockTypes.animation) //
.put("animations", BlockTypes.animations) //
.put("atlases", BlockTypes.atlases) //
.put("atlas", BlockTypes.atlas) //
.put("event", BlockTypes.actorEvent) //
.put("customInt", BlockTypes.customIntProperty) //
.put("customFloat", BlockTypes.customFloatProperty) //
.put("customString", BlockTypes.customStringProperty) //
.put("customBoolean", BlockTypes.customBooleanProperty) //
.put("rectangleCollider", BlockTypes.actorColliderRectangle) //
.put("triangleCollider", BlockTypes.actorColliderTriangle) //
.put("circleCollider", BlockTypes.actorColliderCircle) //
.put("polygonCollider", BlockTypes.actorColliderPolygon) //
.put("lineCollider", BlockTypes.actorColliderLine) //
.put("imageSequence", BlockTypes.actorImageSequence) //
.put("solo", BlockTypes.actorNodeSolo) //
.put("jelly", BlockTypes.jellyComponent) //
.put("jellyBone", BlockTypes.actorJellyBone) //
.put("ikConstraint", BlockTypes.actorIKConstraint) //
.put("distanceConstraint", BlockTypes.actorDistanceConstraint) //
.put("translationConstraint", BlockTypes.actorTranslationConstraint) //
.put("rotationConstraint", BlockTypes.actorRotationConstraint) //
.put("scaleConstraint", BlockTypes.actorScaleConstraint) //
.put("transformConstraint", BlockTypes.actorTransformConstraint) //
.put("shape", BlockTypes.actorShape) //
.put("path", BlockTypes.actorPath) //
.put("colorFill", BlockTypes.colorFill) //
.put("colorStroke", BlockTypes.colorStroke) //
.put("gradientFill", BlockTypes.gradientFill) //
.put("gradientStroke", BlockTypes.gradientStroke) //
.put("radialGradientFill", BlockTypes.radialGradientFill) //
.put("radialGradientStroke", BlockTypes.radialGradientStroke) //
.put("ellipse", BlockTypes.actorEllipse) //
.put("rectangle", BlockTypes.actorRectangle) //
.put("triangle", BlockTypes.actorTriangle) //
.put("star", BlockTypes.actorStar) //
.put("polygon", BlockTypes.actorPolygon) //
.put("artboards", BlockTypes.artboards) //
.put("artboard", BlockTypes.actorArtboard) //
.put("effectRenderer", BlockTypes.actorLayerEffectRenderer) //
.put("mask", BlockTypes.actorMask) //
.put("blur", BlockTypes.actorBlur) //
.put("dropShadow", BlockTypes.actorDropShadow) //
.put("innerShadow", BlockTypes.actorInnerShadow).build();
}
| UTF-8 | Java | 5,987 | java | BlockTypes.java | Java | [] | null | [] | package org.nting.flare.java;
import java.util.Map;
import com.google.common.collect.ImmutableMap;
public class BlockTypes {
public static final int unknown = 0;
public static final int components = 1;
public static final int actorNode = 2;
public static final int actorBone = 3;
public static final int actorRootBone = 4;
public static final int actorImage = 5;
public static final int view = 6;
public static final int animation = 7;
public static final int animations = 8;
public static final int atlases = 9;
public static final int atlas = 10;
public static final int actorIKTarget = 11;
public static final int actorEvent = 12;
public static final int customIntProperty = 13;
public static final int customFloatProperty = 14;
public static final int customStringProperty = 15;
public static final int customBooleanProperty = 16;
public static final int actorColliderRectangle = 17;
public static final int actorColliderTriangle = 18;
public static final int actorColliderCircle = 19;
public static final int actorColliderPolygon = 20;
public static final int actorColliderLine = 21;
public static final int actorImageSequence = 22;
public static final int actorNodeSolo = 23;
public static final int jellyComponent = 28;
public static final int actorJellyBone = 29;
public static final int actorIKConstraint = 30;
public static final int actorDistanceConstraint = 31;
public static final int actorTranslationConstraint = 32;
public static final int actorRotationConstraint = 33;
public static final int actorScaleConstraint = 34;
public static final int actorTransformConstraint = 35;
public static final int actorShape = 100;
public static final int actorPath = 101;
public static final int colorFill = 102;
public static final int colorStroke = 103;
public static final int gradientFill = 104;
public static final int gradientStroke = 105;
public static final int radialGradientFill = 106;
public static final int radialGradientStroke = 107;
public static final int actorEllipse = 108;
public static final int actorRectangle = 109;
public static final int actorTriangle = 110;
public static final int actorStar = 111;
public static final int actorPolygon = 112;
public static final int actorSkin = 113;
public static final int actorArtboard = 114;
public static final int artboards = 115;
public static final int actorLayerEffectRenderer = 116;
public static final int actorMask = 117;
public static final int actorBlur = 118;
public static final int actorDropShadow = 119;
public static final int actorInnerShadow = 120;
public static final Map<String, Integer> blockTypesMap = ImmutableMap.<String, Integer> builder()
.put("unknown", BlockTypes.unknown) //
.put("nodes", BlockTypes.components) //
.put("node", BlockTypes.actorNode) //
.put("bone", BlockTypes.actorBone) //
.put("rootBone", BlockTypes.actorRootBone) //
.put("image", BlockTypes.actorImage) //
.put("view", BlockTypes.view) //
.put("animation", BlockTypes.animation) //
.put("animations", BlockTypes.animations) //
.put("atlases", BlockTypes.atlases) //
.put("atlas", BlockTypes.atlas) //
.put("event", BlockTypes.actorEvent) //
.put("customInt", BlockTypes.customIntProperty) //
.put("customFloat", BlockTypes.customFloatProperty) //
.put("customString", BlockTypes.customStringProperty) //
.put("customBoolean", BlockTypes.customBooleanProperty) //
.put("rectangleCollider", BlockTypes.actorColliderRectangle) //
.put("triangleCollider", BlockTypes.actorColliderTriangle) //
.put("circleCollider", BlockTypes.actorColliderCircle) //
.put("polygonCollider", BlockTypes.actorColliderPolygon) //
.put("lineCollider", BlockTypes.actorColliderLine) //
.put("imageSequence", BlockTypes.actorImageSequence) //
.put("solo", BlockTypes.actorNodeSolo) //
.put("jelly", BlockTypes.jellyComponent) //
.put("jellyBone", BlockTypes.actorJellyBone) //
.put("ikConstraint", BlockTypes.actorIKConstraint) //
.put("distanceConstraint", BlockTypes.actorDistanceConstraint) //
.put("translationConstraint", BlockTypes.actorTranslationConstraint) //
.put("rotationConstraint", BlockTypes.actorRotationConstraint) //
.put("scaleConstraint", BlockTypes.actorScaleConstraint) //
.put("transformConstraint", BlockTypes.actorTransformConstraint) //
.put("shape", BlockTypes.actorShape) //
.put("path", BlockTypes.actorPath) //
.put("colorFill", BlockTypes.colorFill) //
.put("colorStroke", BlockTypes.colorStroke) //
.put("gradientFill", BlockTypes.gradientFill) //
.put("gradientStroke", BlockTypes.gradientStroke) //
.put("radialGradientFill", BlockTypes.radialGradientFill) //
.put("radialGradientStroke", BlockTypes.radialGradientStroke) //
.put("ellipse", BlockTypes.actorEllipse) //
.put("rectangle", BlockTypes.actorRectangle) //
.put("triangle", BlockTypes.actorTriangle) //
.put("star", BlockTypes.actorStar) //
.put("polygon", BlockTypes.actorPolygon) //
.put("artboards", BlockTypes.artboards) //
.put("artboard", BlockTypes.actorArtboard) //
.put("effectRenderer", BlockTypes.actorLayerEffectRenderer) //
.put("mask", BlockTypes.actorMask) //
.put("blur", BlockTypes.actorBlur) //
.put("dropShadow", BlockTypes.actorDropShadow) //
.put("innerShadow", BlockTypes.actorInnerShadow).build();
}
| 5,987 | 0.671288 | 0.651745 | 115 | 51.060871 | 16.63798 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.956522 | false | false | 3 |
a835f8fe8d7920fdfe64fd98a0a90195c504f983 | 13,151,189,890,372 | 80e1e6aec24b025d24ef735c51a84a7b7a3413e6 | /src/com/exam/wangyi/Question1.java | 696b277508af4979ec64b3c0fff2d52a9a0c5275 | [] | no_license | Keeplingshi/JavaAlgorithms | https://github.com/Keeplingshi/JavaAlgorithms | 1d363b21bc8f9f86a2ac21b5539cff315d19ee55 | ee316d7460071597aa0520bcf34f6b59f2dab64c | refs/heads/master | 2018-10-28T05:02:16.678000 | 2018-08-22T14:19:56 | 2018-08-22T14:19:56 | 111,682,221 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.exam.wangyi;
import java.util.Scanner;
/**
*
6 3
1 3 5 2 5 4
1 1 0 1 0 0
* @author Administrator
*
*/
public class Question1 {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
int n=sc.nextInt();
int k=sc.nextInt();
int value[]=new int[n];
int wake[]=new int[n];
for(int i=0;i<n;i++){
value[i]=sc.nextInt();
}
for(int i=0;i<n;i++){
wake[i]=sc.nextInt();
}
int value_front[]=new int[n];
int sum1=0;
if(wake[0]==1){
sum1=value[0];
value_front[0]=value[0];
}
for(int i=1;i<n;i++)
{
if(wake[i]==0){
value_front[i]=sum1;
continue;
}
value_front[i]=sum1+value[i];
sum1+=value[i];
}
int value_back[]=new int[n];
int sum2=0;
if(wake[n-1]==1){
sum2=value[n-1];
value_back[n-1]=value[n-1];
}
for(int i=n-2;i>=0;i--)
{
if(wake[i]==0){
value_back[i]=sum2;
continue;
}
value_back[i]=sum2+value[i];
sum2+=value[i];
}
int max=0;
if(wake[0]==1){
max=value[0];
}
//滑动窗口
for(int i=1;i<n;i++)
{
//滑动窗口起始位置
if(wake[i]==1){
continue;
}
int sum=value_front[i];
for(int j=i;(j<i+k)&&(j<n);j++)
{
sum+=value[j];
}
if(i+k>=n){
sum+=value_back[n-1];
}else{
sum+=value_back[i+k];
}
max=max>sum?max:sum;
}
System.out.println(max);
}
}
| UTF-8 | Java | 1,467 | java | Question1.java | Java | [
{
"context": "**\r\n * \r\n6 3\r\n1 3 5 2 5 4\r\n1 1 0 1 0 0\r\n * @author Administrator\r\n *\r\n */\r\npublic class Question1 {\r\n\r\n\tpublic sta",
"end": 122,
"score": 0.8553717732429504,
"start": 109,
"tag": "USERNAME",
"value": "Administrator"
}
] | null | [] | package com.exam.wangyi;
import java.util.Scanner;
/**
*
6 3
1 3 5 2 5 4
1 1 0 1 0 0
* @author Administrator
*
*/
public class Question1 {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
int n=sc.nextInt();
int k=sc.nextInt();
int value[]=new int[n];
int wake[]=new int[n];
for(int i=0;i<n;i++){
value[i]=sc.nextInt();
}
for(int i=0;i<n;i++){
wake[i]=sc.nextInt();
}
int value_front[]=new int[n];
int sum1=0;
if(wake[0]==1){
sum1=value[0];
value_front[0]=value[0];
}
for(int i=1;i<n;i++)
{
if(wake[i]==0){
value_front[i]=sum1;
continue;
}
value_front[i]=sum1+value[i];
sum1+=value[i];
}
int value_back[]=new int[n];
int sum2=0;
if(wake[n-1]==1){
sum2=value[n-1];
value_back[n-1]=value[n-1];
}
for(int i=n-2;i>=0;i--)
{
if(wake[i]==0){
value_back[i]=sum2;
continue;
}
value_back[i]=sum2+value[i];
sum2+=value[i];
}
int max=0;
if(wake[0]==1){
max=value[0];
}
//滑动窗口
for(int i=1;i<n;i++)
{
//滑动窗口起始位置
if(wake[i]==1){
continue;
}
int sum=value_front[i];
for(int j=i;(j<i+k)&&(j<n);j++)
{
sum+=value[j];
}
if(i+k>=n){
sum+=value_back[n-1];
}else{
sum+=value_back[i+k];
}
max=max>sum?max:sum;
}
System.out.println(max);
}
}
| 1,467 | 0.487872 | 0.452529 | 91 | 13.857142 | 10.756619 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.571429 | false | false | 3 |
dd9b0e2583c1384527811857b249a53e0fdd2cfe | 14,912,126,485,831 | 692b7aeb91f8e4e03e912fc0d7157dbd76941ba4 | /src/main/java/pl/wastesegregation/segregation/TextAreaPanel.java | f80a75b179efa6565e238f91ca679d791dce1a8f | [] | no_license | kamisc/Waste_Segregation | https://github.com/kamisc/Waste_Segregation | 2316bb9c91d6d27357cddfe965c1da992d0dcb72 | b20a303699185b6440879eebed74db413002bbd4 | refs/heads/master | 2020-04-18T18:36:14.511000 | 2019-02-02T12:07:36 | 2019-02-02T12:07:36 | 167,684,070 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pl.wastesegregation.segregation;
import java.awt.BorderLayout;
import javax.swing.JEditorPane;
public class TextAreaPanel extends JEditorPane {
// pole z wygenerowanym tekstem
public JEditorPane editorPane = new JEditorPane();
public JEditorPane getEditorPane() {
return editorPane;
}
public void setEditorPane(JEditorPane editorPane) {
this.editorPane = editorPane;
}
public TextAreaPanel() {
super();
setLayout(new BorderLayout());
this.add(editorPane);
editorPane.setEditable(false);
}
}
| UTF-8 | Java | 589 | java | TextAreaPanel.java | Java | [] | null | [] | package pl.wastesegregation.segregation;
import java.awt.BorderLayout;
import javax.swing.JEditorPane;
public class TextAreaPanel extends JEditorPane {
// pole z wygenerowanym tekstem
public JEditorPane editorPane = new JEditorPane();
public JEditorPane getEditorPane() {
return editorPane;
}
public void setEditorPane(JEditorPane editorPane) {
this.editorPane = editorPane;
}
public TextAreaPanel() {
super();
setLayout(new BorderLayout());
this.add(editorPane);
editorPane.setEditable(false);
}
}
| 589 | 0.680815 | 0.680815 | 28 | 20 | 19.050684 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.357143 | false | false | 3 |
f7f951835669d2e04f50c481b9584a0a7b44a3bd | 1,322,849,931,843 | 556340e01c9ddc74a075b4fb5f290d35e7a40a46 | /src/view/console/Unit.java | 4c027adee0f31fc13d155a46380ad5596b4513e5 | [] | no_license | Thirdwater/sudoku | https://github.com/Thirdwater/sudoku | 6a7c39773d3dc928468f93c01fbe382e7eb2f230 | 116b8ae6e91edf907b64e6794dce8bce28184b79 | refs/heads/master | 2023-02-21T12:43:08.672000 | 2021-01-29T15:06:52 | 2021-01-29T15:06:52 | 295,703,737 | 0 | 0 | null | false | 2020-09-19T11:57:40 | 2020-09-15T11:20:29 | 2020-09-15T11:46:03 | 2020-09-19T11:57:40 | 3,028 | 0 | 0 | 0 | null | false | false | package view.console;
public class Unit {
private UnitType unitType;
private LineType lineType;
private LineWeight lineWeight;
private boolean isSubgrid;
private char lightNormal;
private char heavyNormal;
private char lightDotted;
private char heavyDotted;
private char doubleLined;
private char currentChar;
private int currentNum;
public Unit (UnitInstanceType instanceType) {
unitType = instanceType.unitType;
lineType = LineType.NORMAL;
lineWeight = LineWeight.LIGHT;
isSubgrid = instanceType.isSubgrid;
lightNormal = instanceType.lightNormal;
heavyNormal = instanceType.heavyNormal;
lightDotted = instanceType.lightDotted;
heavyDotted = instanceType.heavyDotted;
doubleLined = instanceType.doubleLined;
currentChar = lightNormal;
currentNum = 0;
}
public UnitType getType () {
return unitType;
}
public boolean isSubgrid () {
return isSubgrid;
}
public void setNum (int num) {
if (unitType != UnitType.NUMBER) {
return;
}
assert 0 <= num && num <= 9;
currentNum = num;
}
public void setLineType (LineType lineType) {
if (unitType != UnitType.LINE || this.lineType == lineType) {
return;
}
this.lineType = lineType;
updateCurrentCharacter();
}
public void setLineWeight (LineWeight lineWeight) {
if (unitType != UnitType.LINE || this.lineWeight == lineWeight) {
return;
}
this.lineWeight = lineWeight;
updateCurrentCharacter();
}
private void updateCurrentCharacter () {
if (unitType != UnitType.LINE) {
return;
}
switch (lineType) {
case NORMAL:
switch (lineWeight) {
case LIGHT:
currentChar = lightNormal;
break;
case HEAVY:
currentChar = heavyNormal;
break;
}
break;
case DOTTED:
switch (lineWeight) {
case LIGHT:
currentChar = lightDotted;
break;
case HEAVY:
currentChar = heavyDotted;
break;
}
break;
case DOUBLE:
currentChar = doubleLined;
break;
case BLANK:
currentChar = ' ';
break;
}
}
@Override
public String toString () {
switch (unitType) {
case SPACE:
return " ";
case NUMBER:
if (currentNum == 0) {
return " ";
}
return String.valueOf(currentNum);
case LINE:
default:
return Character.toString(currentChar);
}
}
}
| UTF-8 | Java | 3,080 | java | Unit.java | Java | [] | null | [] | package view.console;
public class Unit {
private UnitType unitType;
private LineType lineType;
private LineWeight lineWeight;
private boolean isSubgrid;
private char lightNormal;
private char heavyNormal;
private char lightDotted;
private char heavyDotted;
private char doubleLined;
private char currentChar;
private int currentNum;
public Unit (UnitInstanceType instanceType) {
unitType = instanceType.unitType;
lineType = LineType.NORMAL;
lineWeight = LineWeight.LIGHT;
isSubgrid = instanceType.isSubgrid;
lightNormal = instanceType.lightNormal;
heavyNormal = instanceType.heavyNormal;
lightDotted = instanceType.lightDotted;
heavyDotted = instanceType.heavyDotted;
doubleLined = instanceType.doubleLined;
currentChar = lightNormal;
currentNum = 0;
}
public UnitType getType () {
return unitType;
}
public boolean isSubgrid () {
return isSubgrid;
}
public void setNum (int num) {
if (unitType != UnitType.NUMBER) {
return;
}
assert 0 <= num && num <= 9;
currentNum = num;
}
public void setLineType (LineType lineType) {
if (unitType != UnitType.LINE || this.lineType == lineType) {
return;
}
this.lineType = lineType;
updateCurrentCharacter();
}
public void setLineWeight (LineWeight lineWeight) {
if (unitType != UnitType.LINE || this.lineWeight == lineWeight) {
return;
}
this.lineWeight = lineWeight;
updateCurrentCharacter();
}
private void updateCurrentCharacter () {
if (unitType != UnitType.LINE) {
return;
}
switch (lineType) {
case NORMAL:
switch (lineWeight) {
case LIGHT:
currentChar = lightNormal;
break;
case HEAVY:
currentChar = heavyNormal;
break;
}
break;
case DOTTED:
switch (lineWeight) {
case LIGHT:
currentChar = lightDotted;
break;
case HEAVY:
currentChar = heavyDotted;
break;
}
break;
case DOUBLE:
currentChar = doubleLined;
break;
case BLANK:
currentChar = ' ';
break;
}
}
@Override
public String toString () {
switch (unitType) {
case SPACE:
return " ";
case NUMBER:
if (currentNum == 0) {
return " ";
}
return String.valueOf(currentNum);
case LINE:
default:
return Character.toString(currentChar);
}
}
}
| 3,080 | 0.504221 | 0.502922 | 113 | 26.256638 | 16.083729 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.504425 | false | false | 3 |
8df51e7daf366966e504aaf292db27664cce07ef | 28,269,474,795,810 | 9eb88736f632b25d2908106d56c415a69e8b72cf | /bibsonomy/bibsonomy-scraper/src/main/java/org/bibsonomy/scraper/url/kde/jstor/JStorScraper.java | 4844ba683ca913aec380c7dddcf9a3e0364264b3 | [] | no_license | jppazmin/bibsonomy-social | https://github.com/jppazmin/bibsonomy-social | 8aabcc77d4f5f75f31b0dfb1112968ab62598941 | 09766fe30744dfbe226b4d8a2f6dc5849920b41a | refs/heads/master | 2016-08-02T21:09:20.835000 | 2013-06-18T05:03:34 | 2013-06-18T05:03:34 | 10,136,522 | 3 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
* BibSonomy-Scraper - Web page scrapers returning BibTeX for BibSonomy.
*
* Copyright (C) 2006 - 2011 Knowledge & Data Engineering Group,
* University of Kassel, Germany
* http://www.kde.cs.uni-kassel.de/
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.bibsonomy.scraper.url.kde.jstor;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Pattern;
import org.bibsonomy.scraper.ScrapingContext;
import org.bibsonomy.scraper.Tuple;
import org.bibsonomy.scraper.AbstractUrlScraper;
import org.bibsonomy.scraper.exceptions.InternalFailureException;
import org.bibsonomy.scraper.exceptions.ScrapingException;
import org.bibsonomy.scraper.exceptions.ScrapingFailureException;
/**
* @author wbi
* @version $Id: JStorScraper.java,v 1.13 2011-04-29 07:24:36 bibsonomy Exp $
*/
public class JStorScraper extends AbstractUrlScraper {
private static final String info = "This Scraper parses a publication from " + href("http://www.jstor.org/", "JSTOR");
private static final String JSTOR_HOST = "jstor.org";
private static final String JSTOR_HOST_NAME = "http://www.jstor.org";
private static final String JSTOR_ABSTRACT_PATH = "/pss/";
private static final String JSTOR_EXPORT_PATH = "/action/exportSingleCitation";
private static final String JSTOR_EXPORT_PATH_AND_QUERY = "/action/exportSingleCitation?singleCitation=true&suffix=";
private static final String JSTOR_DOWNLOAD_PATH = "/action/downloadSingleCitation?format=bibtex&include=abs&singleCitation=true&noDoi=yesDoi&suffix={id}&downloadFileName={id}";
private static final List<Tuple<Pattern,Pattern>> patterns = new LinkedList<Tuple<Pattern,Pattern>>();
static {
final Pattern hostPattern = Pattern.compile(".*" + JSTOR_HOST);
patterns.add(new Tuple<Pattern, Pattern>(hostPattern, Pattern.compile(JSTOR_ABSTRACT_PATH + ".*")));
patterns.add(new Tuple<Pattern, Pattern>(hostPattern, Pattern.compile(JSTOR_EXPORT_PATH + ".*")));
}
public String getInfo() {
return info;
}
protected boolean scrapeInternal(ScrapingContext sc) throws ScrapingException {
sc.setScraper(this);
String url = sc.getUrl().toString();
String id = null;
if(url.startsWith(JSTOR_HOST_NAME + JSTOR_ABSTRACT_PATH)) {
if(url.contains("?cookieSet=")) {
id = url.substring(url.indexOf(JSTOR_ABSTRACT_PATH) + JSTOR_ABSTRACT_PATH.length(), url.indexOf("?cookieSet="));
} else {
id = url.substring(url.indexOf(JSTOR_ABSTRACT_PATH) + JSTOR_ABSTRACT_PATH.length());
}
}
if(url.startsWith(JSTOR_HOST_NAME + JSTOR_EXPORT_PATH_AND_QUERY)) {
id = url.substring(url.indexOf("&suffix=") + "&suffix=".length());
}
if(id != null) {
String downloadLink = new String(JSTOR_HOST_NAME + JSTOR_DOWNLOAD_PATH.replace("{id}", id));
// get cookies from the server
String cookies = null;
try {
cookies = getCookies(sc.getUrl());
} catch (IOException ex) {
throw new InternalFailureException("Failed to download Cookies for " + downloadLink);
}
//download the bibtex file from the server
String bibtex = null;
try {
bibtex = getContent(new URL(downloadLink), cookies);
} catch (IOException ex) {
throw new InternalFailureException("Failed to download the bibtex file.");
}
if(bibtex != null) {
//delete the information in the bibtex file
bibtex = bibtex.replace("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nJSTOR CITATION LIST\r\n\r\n\r\n", "");
//replace CR+LF with LF
bibtex = bibtex.replace("\r\n", "\n");
//Convert to UTF-8. Because Server sends a ISO8859-1 encoded string
try {
bibtex = new String(bibtex.getBytes("ISO8859-1"), "UTF-8");
} catch (UnsupportedEncodingException ex) {
throw new InternalFailureException("Could not convert to UTF-8!");
}
sc.setBibtexResult(bibtex);
return true;
} else
throw new ScrapingFailureException("getting bibtex failed");
} else {
//missing id
throw new ScrapingFailureException("ID is missing!");
}
}
/** FIXME: refactor
* @param queryURL
* @param cookie
* @return
* @throws IOException
*/
private String getContent(URL queryURL, String cookie) throws IOException {
HttpURLConnection urlConn = (HttpURLConnection) queryURL.openConnection();
urlConn.setAllowUserInteraction(false);
urlConn.setDoInput(true);
urlConn.setDoOutput(false);
urlConn.setUseCaches(false);
/*
* set user agent (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html) since some
* pages require it to download content.
*/
urlConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)");
//insert cookie
urlConn.setRequestProperty("Cookie", cookie);
urlConn.connect();
StringWriter out = new StringWriter();
InputStream in = new BufferedInputStream(urlConn.getInputStream());
int b;
while ((b = in.read()) >= 0) {
out.write(b);
}
urlConn.disconnect();
return out.toString();
}
/** FIXME: refactor
* @param queryURL
* @return
* @throws IOException
*/
private String getCookies(URL queryURL) throws IOException {
HttpURLConnection urlConn = null;
urlConn = (HttpURLConnection) queryURL.openConnection();
urlConn.setAllowUserInteraction(false);
urlConn.setDoInput(true);
urlConn.setDoOutput(false);
urlConn.setUseCaches(false);
/*
* set user agent (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html) since some
* pages require it to download content.
*/
urlConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)");
//seems that the application needs this cookie even before getting the other cookies, strange :-\
urlConn.setRequestProperty("Cookie", "I2KBRCK=1");
urlConn.connect();
/*
* extract cookie from connection
*/
List<String> cookies = urlConn.getHeaderFields().get("Set-Cookie");
StringBuffer cookieString = new StringBuffer();
for(String cookie : cookies) {
cookieString.append(cookie.substring(0, cookie.indexOf(";") + 1) + " ");
}
//This is neccessary, otherwise we don't get the Bibtex file.
cookieString.append("I2KBRCK=1");
urlConn.disconnect();
return cookieString.toString();
}
public List<Tuple<Pattern, Pattern>> getUrlPatterns() {
return patterns;
}
public String getSupportedSiteName() {
return "JSTOR";
}
public String getSupportedSiteURL() {
return JSTOR_HOST_NAME;
}
}
| UTF-8 | Java | 7,385 | java | JStorScraper.java | Java | [
{
"context": "ceptions.ScrapingFailureException;\n\n/**\n * @author wbi\n * @version $Id: JStorScraper.java,v 1.13 2011-04",
"end": 1705,
"score": 0.9996482133865356,
"start": 1702,
"tag": "USERNAME",
"value": "wbi"
},
{
"context": " $Id: JStorScraper.java,v 1.13 2011-04-29 07:24:36 ... | null | [] | /**
*
* BibSonomy-Scraper - Web page scrapers returning BibTeX for BibSonomy.
*
* Copyright (C) 2006 - 2011 Knowledge & Data Engineering Group,
* University of Kassel, Germany
* http://www.kde.cs.uni-kassel.de/
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.bibsonomy.scraper.url.kde.jstor;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Pattern;
import org.bibsonomy.scraper.ScrapingContext;
import org.bibsonomy.scraper.Tuple;
import org.bibsonomy.scraper.AbstractUrlScraper;
import org.bibsonomy.scraper.exceptions.InternalFailureException;
import org.bibsonomy.scraper.exceptions.ScrapingException;
import org.bibsonomy.scraper.exceptions.ScrapingFailureException;
/**
* @author wbi
* @version $Id: JStorScraper.java,v 1.13 2011-04-29 07:24:36 bibsonomy Exp $
*/
public class JStorScraper extends AbstractUrlScraper {
private static final String info = "This Scraper parses a publication from " + href("http://www.jstor.org/", "JSTOR");
private static final String JSTOR_HOST = "jstor.org";
private static final String JSTOR_HOST_NAME = "http://www.jstor.org";
private static final String JSTOR_ABSTRACT_PATH = "/pss/";
private static final String JSTOR_EXPORT_PATH = "/action/exportSingleCitation";
private static final String JSTOR_EXPORT_PATH_AND_QUERY = "/action/exportSingleCitation?singleCitation=true&suffix=";
private static final String JSTOR_DOWNLOAD_PATH = "/action/downloadSingleCitation?format=bibtex&include=abs&singleCitation=true&noDoi=yesDoi&suffix={id}&downloadFileName={id}";
private static final List<Tuple<Pattern,Pattern>> patterns = new LinkedList<Tuple<Pattern,Pattern>>();
static {
final Pattern hostPattern = Pattern.compile(".*" + JSTOR_HOST);
patterns.add(new Tuple<Pattern, Pattern>(hostPattern, Pattern.compile(JSTOR_ABSTRACT_PATH + ".*")));
patterns.add(new Tuple<Pattern, Pattern>(hostPattern, Pattern.compile(JSTOR_EXPORT_PATH + ".*")));
}
public String getInfo() {
return info;
}
protected boolean scrapeInternal(ScrapingContext sc) throws ScrapingException {
sc.setScraper(this);
String url = sc.getUrl().toString();
String id = null;
if(url.startsWith(JSTOR_HOST_NAME + JSTOR_ABSTRACT_PATH)) {
if(url.contains("?cookieSet=")) {
id = url.substring(url.indexOf(JSTOR_ABSTRACT_PATH) + JSTOR_ABSTRACT_PATH.length(), url.indexOf("?cookieSet="));
} else {
id = url.substring(url.indexOf(JSTOR_ABSTRACT_PATH) + JSTOR_ABSTRACT_PATH.length());
}
}
if(url.startsWith(JSTOR_HOST_NAME + JSTOR_EXPORT_PATH_AND_QUERY)) {
id = url.substring(url.indexOf("&suffix=") + "&suffix=".length());
}
if(id != null) {
String downloadLink = new String(JSTOR_HOST_NAME + JSTOR_DOWNLOAD_PATH.replace("{id}", id));
// get cookies from the server
String cookies = null;
try {
cookies = getCookies(sc.getUrl());
} catch (IOException ex) {
throw new InternalFailureException("Failed to download Cookies for " + downloadLink);
}
//download the bibtex file from the server
String bibtex = null;
try {
bibtex = getContent(new URL(downloadLink), cookies);
} catch (IOException ex) {
throw new InternalFailureException("Failed to download the bibtex file.");
}
if(bibtex != null) {
//delete the information in the bibtex file
bibtex = bibtex.replace("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nJSTOR CITATION LIST\r\n\r\n\r\n", "");
//replace CR+LF with LF
bibtex = bibtex.replace("\r\n", "\n");
//Convert to UTF-8. Because Server sends a ISO8859-1 encoded string
try {
bibtex = new String(bibtex.getBytes("ISO8859-1"), "UTF-8");
} catch (UnsupportedEncodingException ex) {
throw new InternalFailureException("Could not convert to UTF-8!");
}
sc.setBibtexResult(bibtex);
return true;
} else
throw new ScrapingFailureException("getting bibtex failed");
} else {
//missing id
throw new ScrapingFailureException("ID is missing!");
}
}
/** FIXME: refactor
* @param queryURL
* @param cookie
* @return
* @throws IOException
*/
private String getContent(URL queryURL, String cookie) throws IOException {
HttpURLConnection urlConn = (HttpURLConnection) queryURL.openConnection();
urlConn.setAllowUserInteraction(false);
urlConn.setDoInput(true);
urlConn.setDoOutput(false);
urlConn.setUseCaches(false);
/*
* set user agent (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html) since some
* pages require it to download content.
*/
urlConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)");
//insert cookie
urlConn.setRequestProperty("Cookie", cookie);
urlConn.connect();
StringWriter out = new StringWriter();
InputStream in = new BufferedInputStream(urlConn.getInputStream());
int b;
while ((b = in.read()) >= 0) {
out.write(b);
}
urlConn.disconnect();
return out.toString();
}
/** FIXME: refactor
* @param queryURL
* @return
* @throws IOException
*/
private String getCookies(URL queryURL) throws IOException {
HttpURLConnection urlConn = null;
urlConn = (HttpURLConnection) queryURL.openConnection();
urlConn.setAllowUserInteraction(false);
urlConn.setDoInput(true);
urlConn.setDoOutput(false);
urlConn.setUseCaches(false);
/*
* set user agent (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html) since some
* pages require it to download content.
*/
urlConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)");
//seems that the application needs this cookie even before getting the other cookies, strange :-\
urlConn.setRequestProperty("Cookie", "I2KBRCK=1");
urlConn.connect();
/*
* extract cookie from connection
*/
List<String> cookies = urlConn.getHeaderFields().get("Set-Cookie");
StringBuffer cookieString = new StringBuffer();
for(String cookie : cookies) {
cookieString.append(cookie.substring(0, cookie.indexOf(";") + 1) + " ");
}
//This is neccessary, otherwise we don't get the Bibtex file.
cookieString.append("I2KBRCK=1");
urlConn.disconnect();
return cookieString.toString();
}
public List<Tuple<Pattern, Pattern>> getUrlPatterns() {
return patterns;
}
public String getSupportedSiteName() {
return "JSTOR";
}
public String getSupportedSiteURL() {
return JSTOR_HOST_NAME;
}
}
| 7,385 | 0.711578 | 0.69763 | 225 | 31.822222 | 32.577625 | 177 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.902222 | false | false | 3 |
70d86c9bbc1da25d6d187add13c946038614a7a4 | 9,938,554,390,304 | 1bebf9af941cf5236d878d48f302a7c667fe4407 | /src/main/java/com/hello/world/demo/service/CricketCoach.java | 2110957dc8b6734057e35f9b860c5ae0c229e5bf | [] | no_license | deepthi432/SpringBoot | https://github.com/deepthi432/SpringBoot | 54b36b6e463741c8e8537d707aa093db962cb713 | 1f1cbdf214bb575aeb387497b4ef129431ad636a | refs/heads/main | 2023-06-07T05:53:39.239000 | 2021-06-25T05:11:33 | 2021-06-25T05:11:33 | 380,129,965 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hello.world.demo.service;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.springframework.stereotype.Service;
@Service
public class CricketCoach implements Coach {
@PostConstruct
public void printPostConstructData() {
System.out.println("This is a post construct method");
}
@PreDestroy
public void printPreDestroyData() {
System.out.println("This is a pre destroy method");
}
@Override
public String giveWorkout() {
return "Practice Cricket daily";
}
@Override
public String getFortune() {
return "This is the day for Cricket";
}
}
| UTF-8 | Java | 626 | java | CricketCoach.java | Java | [] | null | [] | package com.hello.world.demo.service;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.springframework.stereotype.Service;
@Service
public class CricketCoach implements Coach {
@PostConstruct
public void printPostConstructData() {
System.out.println("This is a post construct method");
}
@PreDestroy
public void printPreDestroyData() {
System.out.println("This is a pre destroy method");
}
@Override
public String giveWorkout() {
return "Practice Cricket daily";
}
@Override
public String getFortune() {
return "This is the day for Cricket";
}
}
| 626 | 0.738019 | 0.738019 | 35 | 16.885714 | 18.53764 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.085714 | false | false | 3 |
bef89fdd86ef93d287c3e0beb56ba99f1b616c95 | 21,543,555,998,302 | 11c9a1c4818fda13c7ef12f0351cf11b9bf79743 | /backend/src/main/java/com/bakdata/conquery/models/error/ConqueryErrorInfo.java | 5875d5324950fd37c82367e7e6760a62335b8d9e | [
"MIT"
] | permissive | ingef/conquery | https://github.com/ingef/conquery | b304115774412a784017afd455f67a7b8019d397 | 9422cd5fd27bc12ce8ee94b6e04f24cf7f463bcf | refs/heads/develop | 2023-08-26T16:27:53.107000 | 2023-08-23T14:54:31 | 2023-08-23T14:54:31 | 96,970,120 | 3 | 0 | MIT | false | 2023-09-14T11:38:21 | 2017-07-12T05:52:05 | 2023-07-31T19:25:47 | 2023-09-14T11:38:20 | 47,375 | 33 | 11 | 42 | Java | false | false | package com.bakdata.conquery.models.error;
import java.util.Comparator;
import java.util.UUID;
/**
* Base interface for errors that should be displayed as an info in the Frontend
*/
public interface ConqueryErrorInfo {
/**
* A unique id for this error to retrieve it in the logs.
*/
UUID getId();
String getCode();
String getMessage();
SimpleErrorInfo asPlain();
/**
* Method to check if two errors are basically the same, by not checking the id and the context (which possibly checks on hashcode basis).
*/
default boolean equalsRegardingCodeAndMessage(ConqueryErrorInfo other) {
return Comparator
.comparing(ConqueryErrorInfo::getCode)
.thenComparing(ConqueryErrorInfo::getMessage)
.compare(this, other) == 0;
}
}
| UTF-8 | Java | 756 | java | ConqueryErrorInfo.java | Java | [] | null | [] | package com.bakdata.conquery.models.error;
import java.util.Comparator;
import java.util.UUID;
/**
* Base interface for errors that should be displayed as an info in the Frontend
*/
public interface ConqueryErrorInfo {
/**
* A unique id for this error to retrieve it in the logs.
*/
UUID getId();
String getCode();
String getMessage();
SimpleErrorInfo asPlain();
/**
* Method to check if two errors are basically the same, by not checking the id and the context (which possibly checks on hashcode basis).
*/
default boolean equalsRegardingCodeAndMessage(ConqueryErrorInfo other) {
return Comparator
.comparing(ConqueryErrorInfo::getCode)
.thenComparing(ConqueryErrorInfo::getMessage)
.compare(this, other) == 0;
}
}
| 756 | 0.734127 | 0.732804 | 32 | 22.625 | 30.304445 | 139 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.125 | false | false | 3 |
b995bc449b7c317d8e105944c74866ee7552a3d9 | 30,408,368,523,726 | dada01a755f310896b313252d1ce22652cec6fb5 | /app/src/main/java/com/example/mac/bugfree/activity/ChooseLocationOnMapActivity.java | efad269e859c572b6dba6b60e3c23c0550106208 | [
"MIT"
] | permissive | lijunzhuo/BugFree | https://github.com/lijunzhuo/BugFree | 5cc44d42df276d64c57428c68b2488d916a31d82 | ef9f84fbbc9bfebbe79e8683d9ff88f9be75715e | refs/heads/master | 2021-01-18T20:09:29.535000 | 2017-04-01T20:07:50 | 2017-04-01T20:07:50 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.mac.bugfree.activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.mac.bugfree.R;
import com.example.mac.bugfree.util.CurrentLocation;
import com.example.mac.bugfree.util.SaveFile;
//import org.osmdroid.DefaultResourceProxyImpl;
//import org.osmdroid.ResourceProxy;
import org.osmdroid.api.IGeoPoint;
import org.osmdroid.api.IMapController;
import org.osmdroid.events.MapEventsReceiver;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.Projection;
import org.osmdroid.views.overlay.ItemizedIconOverlay;
import org.osmdroid.views.overlay.MapEventsOverlay;
import org.osmdroid.views.overlay.Overlay;
import org.osmdroid.views.overlay.OverlayItem;
import org.osmdroid.views.overlay.Polygon;
import org.osmdroid.views.overlay.ScaleBarOverlay;
import org.osmdroid.views.overlay.infowindow.BasicInfoWindow;
import org.osmdroid.views.overlay.infowindow.InfoWindow;
import org.osmdroid.views.overlay.mylocation.GpsMyLocationProvider;
import org.osmdroid.views.overlay.mylocation.MyLocationNewOverlay;
import java.io.Serializable;
import java.util.List;
import static com.example.mac.bugfree.R.id.current_location;
import static com.example.mac.bugfree.R.id.map;
/**
* Created by heyuehuang on 2017-03-29.
*/
public class ChooseLocationOnMapActivity extends AppCompatActivity implements MapEventsReceiver,Serializable {
private MapView mapView;
private GeoPoint currentPoint;
private GeoPoint chosenLocation;
private GeoPoint startPoint;
private double lon;
private double lat;
private MapEventsOverlay mapEventsOverlay;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Context context = getApplicationContext();
// important! set your agent to prevent getting banned from the osm servers
org.osmdroid.config.Configuration.getInstance().load(context, PreferenceManager.getDefaultSharedPreferences(context));
setContentView(R.layout.activity_choose_location_on_map);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mapView = (MapView) findViewById(map);
mapView.setTileSource(TileSourceFactory.MAPNIK);
mapView.setBuiltInZoomControls(true);
mapView.setMultiTouchControls(true);
IMapController mapController = mapView.getController();
mapController.setZoom(18);
startPoint = getCurrentPosition();
mapController.setCenter(startPoint);
//Add Scale Bar
ScaleBarOverlay myScaleBarOverlay = new ScaleBarOverlay(mapView);
mapView.getOverlays().add(myScaleBarOverlay);
mapEventsOverlay = new MapEventsOverlay(this, this);
mapView.getOverlays().add(0, mapEventsOverlay);
}
public void onResume() {
super.onResume();
org.osmdroid.config.Configuration.getInstance().load(this, PreferenceManager.getDefaultSharedPreferences(this));
}
// Taken from http://stackoverflow.com/questions/35648913/how-to-set-menu-to-toolbar-in-android
// combine the menu and the layout
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_choose_location, menu);
return true;
}
// Taken from http://stackoverflow.com/questions/7479992/handling-a-menu-item-click-event-android
// Determines if Action bar item was selected. If true then do corresponding action.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//handle presses on the action bar items
switch (item.getItemId()) {
// if the item in tool bar is selected
case R.id.action_clear_choose:
clearAllLocation();
return true;
case R.id.activity_choose_location_on_map:
if (chosenLocation != null){
Intent parent = new Intent();
parent.putExtra("chosenLocationLat", lat);
parent.putExtra("chosenLocationLon", lon);
setResult(RESULT_OK,parent);
finish();
} else {
Intent parent = new Intent();
String mes = "isnull";
parent.putExtra("flag", mes);
setResult(RESULT_OK,parent);
finish();
}
return true;
}
return super.onOptionsItemSelected(item);
}
@Override public boolean singleTapConfirmedHelper(GeoPoint p) {
Toast.makeText(this, "Tap on ("+p.getLatitude()+","+p.getLongitude()+")", Toast.LENGTH_SHORT).show();
// InfoWindow.closeAllInfoWindowsOn(mapView);
return true;
}
@Override public boolean longPressHelper(GeoPoint p) {
//DO NOTHING FOR NOW:
clearAllLocation();
Polygon circle = new Polygon(this);
circle.setPoints(Polygon.pointsAsCircle(p, 50.0));
circle.setFillColor(0x12121212);
circle.setStrokeColor(Color.RED);
circle.setStrokeWidth(2);
mapView.getOverlays().add(circle);
mapView.invalidate();
lat = p.getLatitudeE6()/1E6;
lon = p.getLongitudeE6()/1E6;
chosenLocation = new GeoPoint(lat, lon);
// circle.setInfoWindow(new BasicInfoWindow(org.osmdroid.bonuspack.R.layout.bonuspack_bubble, mapView));
// circle.setTitle("Centered on "+p.getLatitude()+","+p.getLongitude());
Toast.makeText(this, "Long Press on ("+p.getLatitude()+","+p.getLongitude()+")", Toast.LENGTH_SHORT).show();
return false;
}
private GeoPoint getCurrentPosition() {
try {
CurrentLocation locationListener = new CurrentLocation();
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
int latitude = (int) (location.getLatitude() * 1E6);
int longitude = (int) (location.getLongitude() * 1E6);
currentPoint = new GeoPoint(latitude, longitude);
}
} catch (SecurityException e) {
e.printStackTrace();
}
return currentPoint;
}
private void clearAllLocation(){
mapView.getOverlays().clear();
ScaleBarOverlay myScaleBarOverlay = new ScaleBarOverlay(mapView);
mapView.getOverlays().add(myScaleBarOverlay);
mapEventsOverlay = new MapEventsOverlay(this, this);
mapView.getOverlays().add(0, mapEventsOverlay);
chosenLocation = null;
mapView.invalidate();
}
}
| UTF-8 | Java | 7,458 | java | ChooseLocationOnMapActivity.java | Java | [
{
"context": "m.example.mac.bugfree.R.id.map;\n\n/**\n * Created by heyuehuang on 2017-03-29.\n */\n\npublic class ChooseLocationOn",
"end": 1844,
"score": 0.9994015693664551,
"start": 1834,
"tag": "USERNAME",
"value": "heyuehuang"
}
] | null | [] | package com.example.mac.bugfree.activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.mac.bugfree.R;
import com.example.mac.bugfree.util.CurrentLocation;
import com.example.mac.bugfree.util.SaveFile;
//import org.osmdroid.DefaultResourceProxyImpl;
//import org.osmdroid.ResourceProxy;
import org.osmdroid.api.IGeoPoint;
import org.osmdroid.api.IMapController;
import org.osmdroid.events.MapEventsReceiver;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.Projection;
import org.osmdroid.views.overlay.ItemizedIconOverlay;
import org.osmdroid.views.overlay.MapEventsOverlay;
import org.osmdroid.views.overlay.Overlay;
import org.osmdroid.views.overlay.OverlayItem;
import org.osmdroid.views.overlay.Polygon;
import org.osmdroid.views.overlay.ScaleBarOverlay;
import org.osmdroid.views.overlay.infowindow.BasicInfoWindow;
import org.osmdroid.views.overlay.infowindow.InfoWindow;
import org.osmdroid.views.overlay.mylocation.GpsMyLocationProvider;
import org.osmdroid.views.overlay.mylocation.MyLocationNewOverlay;
import java.io.Serializable;
import java.util.List;
import static com.example.mac.bugfree.R.id.current_location;
import static com.example.mac.bugfree.R.id.map;
/**
* Created by heyuehuang on 2017-03-29.
*/
public class ChooseLocationOnMapActivity extends AppCompatActivity implements MapEventsReceiver,Serializable {
private MapView mapView;
private GeoPoint currentPoint;
private GeoPoint chosenLocation;
private GeoPoint startPoint;
private double lon;
private double lat;
private MapEventsOverlay mapEventsOverlay;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Context context = getApplicationContext();
// important! set your agent to prevent getting banned from the osm servers
org.osmdroid.config.Configuration.getInstance().load(context, PreferenceManager.getDefaultSharedPreferences(context));
setContentView(R.layout.activity_choose_location_on_map);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mapView = (MapView) findViewById(map);
mapView.setTileSource(TileSourceFactory.MAPNIK);
mapView.setBuiltInZoomControls(true);
mapView.setMultiTouchControls(true);
IMapController mapController = mapView.getController();
mapController.setZoom(18);
startPoint = getCurrentPosition();
mapController.setCenter(startPoint);
//Add Scale Bar
ScaleBarOverlay myScaleBarOverlay = new ScaleBarOverlay(mapView);
mapView.getOverlays().add(myScaleBarOverlay);
mapEventsOverlay = new MapEventsOverlay(this, this);
mapView.getOverlays().add(0, mapEventsOverlay);
}
public void onResume() {
super.onResume();
org.osmdroid.config.Configuration.getInstance().load(this, PreferenceManager.getDefaultSharedPreferences(this));
}
// Taken from http://stackoverflow.com/questions/35648913/how-to-set-menu-to-toolbar-in-android
// combine the menu and the layout
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_choose_location, menu);
return true;
}
// Taken from http://stackoverflow.com/questions/7479992/handling-a-menu-item-click-event-android
// Determines if Action bar item was selected. If true then do corresponding action.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//handle presses on the action bar items
switch (item.getItemId()) {
// if the item in tool bar is selected
case R.id.action_clear_choose:
clearAllLocation();
return true;
case R.id.activity_choose_location_on_map:
if (chosenLocation != null){
Intent parent = new Intent();
parent.putExtra("chosenLocationLat", lat);
parent.putExtra("chosenLocationLon", lon);
setResult(RESULT_OK,parent);
finish();
} else {
Intent parent = new Intent();
String mes = "isnull";
parent.putExtra("flag", mes);
setResult(RESULT_OK,parent);
finish();
}
return true;
}
return super.onOptionsItemSelected(item);
}
@Override public boolean singleTapConfirmedHelper(GeoPoint p) {
Toast.makeText(this, "Tap on ("+p.getLatitude()+","+p.getLongitude()+")", Toast.LENGTH_SHORT).show();
// InfoWindow.closeAllInfoWindowsOn(mapView);
return true;
}
@Override public boolean longPressHelper(GeoPoint p) {
//DO NOTHING FOR NOW:
clearAllLocation();
Polygon circle = new Polygon(this);
circle.setPoints(Polygon.pointsAsCircle(p, 50.0));
circle.setFillColor(0x12121212);
circle.setStrokeColor(Color.RED);
circle.setStrokeWidth(2);
mapView.getOverlays().add(circle);
mapView.invalidate();
lat = p.getLatitudeE6()/1E6;
lon = p.getLongitudeE6()/1E6;
chosenLocation = new GeoPoint(lat, lon);
// circle.setInfoWindow(new BasicInfoWindow(org.osmdroid.bonuspack.R.layout.bonuspack_bubble, mapView));
// circle.setTitle("Centered on "+p.getLatitude()+","+p.getLongitude());
Toast.makeText(this, "Long Press on ("+p.getLatitude()+","+p.getLongitude()+")", Toast.LENGTH_SHORT).show();
return false;
}
private GeoPoint getCurrentPosition() {
try {
CurrentLocation locationListener = new CurrentLocation();
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
int latitude = (int) (location.getLatitude() * 1E6);
int longitude = (int) (location.getLongitude() * 1E6);
currentPoint = new GeoPoint(latitude, longitude);
}
} catch (SecurityException e) {
e.printStackTrace();
}
return currentPoint;
}
private void clearAllLocation(){
mapView.getOverlays().clear();
ScaleBarOverlay myScaleBarOverlay = new ScaleBarOverlay(mapView);
mapView.getOverlays().add(myScaleBarOverlay);
mapEventsOverlay = new MapEventsOverlay(this, this);
mapView.getOverlays().add(0, mapEventsOverlay);
chosenLocation = null;
mapView.invalidate();
}
}
| 7,458 | 0.6904 | 0.683159 | 195 | 37.246155 | 27.855137 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.753846 | false | false | 3 |
5c7a90e3a3b72358bee84ae248e1b89c5f03dffe | 30,408,368,521,995 | e9eee91588d30cdd5dbf3cfa6bbe6e2952a0a428 | /BfcPushSdk/src/main/java/com/eebbk/bfc/im/push/bean/AliasAndTagsInfo.java | 78dffe9b27124604400f45ebb035a44ee0bfedab | [] | no_license | wenzhu2018/android-push | https://github.com/wenzhu2018/android-push | cc542a12af8ab549a50bf94abb0a316294808821 | 234c203aed740737c667acd6d37fe42a38193326 | refs/heads/master | 2020-11-27T10:10:32.273000 | 2019-02-01T02:05:18 | 2019-02-01T02:05:18 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.eebbk.bfc.im.push.bean;
import android.text.TextUtils;
import java.util.Arrays;
import java.util.List;
public class AliasAndTagsInfo {
public static AliasAndTagsInfo EMPTY_ALIAS_TAGS_INFO =new AliasAndTagsInfo();
private String alias;
private String tags;
private boolean isSet;
public AliasAndTagsInfo() {
}
public AliasAndTagsInfo(String alias, List<String> tags, boolean isSet) {
this.alias = alias;
this.isSet=isSet;
this.tags=getTagString(tags);
}
public AliasAndTagsInfo(String alias, String tags, boolean isSet) {
this.alias = alias;
this.tags = tags;
this.isSet = isSet;
}
private String getTagString(List<String> tags){
if(tags==null||tags.isEmpty()){
return null;
}else{
StringBuilder tagsTemp=new StringBuilder();
int size=tags.size();
for(int i=0;i<size;i++){
if(i!=0){
tagsTemp.append(",");
}
tagsTemp.append(tags.get(i));
}
return tagsTemp.toString();
}
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public String getTags() {
return tags;
}
public List<String> getTagsList(){
if(TextUtils.isEmpty(tags)){
return null;
}else{
return Arrays.asList(tags.split(","));
}
}
public void setTags(String tags) {
this.tags = tags;
}
public void setTags(List<String> tags) {
this.tags = getTagString(tags);
}
public boolean isSet() {
return isSet;
}
public void setSet(boolean set) {
isSet = set;
}
@Override
public String toString() {
return "AliasAndTagsInfo{" +
"alias='" + alias + '\'' +
", tags='" + tags + '\'' +
", isSet=" + isSet +
'}';
}
}
| UTF-8 | Java | 2,053 | java | AliasAndTagsInfo.java | Java | [] | null | [] | package com.eebbk.bfc.im.push.bean;
import android.text.TextUtils;
import java.util.Arrays;
import java.util.List;
public class AliasAndTagsInfo {
public static AliasAndTagsInfo EMPTY_ALIAS_TAGS_INFO =new AliasAndTagsInfo();
private String alias;
private String tags;
private boolean isSet;
public AliasAndTagsInfo() {
}
public AliasAndTagsInfo(String alias, List<String> tags, boolean isSet) {
this.alias = alias;
this.isSet=isSet;
this.tags=getTagString(tags);
}
public AliasAndTagsInfo(String alias, String tags, boolean isSet) {
this.alias = alias;
this.tags = tags;
this.isSet = isSet;
}
private String getTagString(List<String> tags){
if(tags==null||tags.isEmpty()){
return null;
}else{
StringBuilder tagsTemp=new StringBuilder();
int size=tags.size();
for(int i=0;i<size;i++){
if(i!=0){
tagsTemp.append(",");
}
tagsTemp.append(tags.get(i));
}
return tagsTemp.toString();
}
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public String getTags() {
return tags;
}
public List<String> getTagsList(){
if(TextUtils.isEmpty(tags)){
return null;
}else{
return Arrays.asList(tags.split(","));
}
}
public void setTags(String tags) {
this.tags = tags;
}
public void setTags(List<String> tags) {
this.tags = getTagString(tags);
}
public boolean isSet() {
return isSet;
}
public void setSet(boolean set) {
isSet = set;
}
@Override
public String toString() {
return "AliasAndTagsInfo{" +
"alias='" + alias + '\'' +
", tags='" + tags + '\'' +
", isSet=" + isSet +
'}';
}
}
| 2,053 | 0.533853 | 0.532879 | 92 | 21.315218 | 18.54954 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.456522 | false | false | 3 |
db68a02c979d65383cc6b7ce57eb1934c6fdd3a4 | 30,408,368,524,335 | 298cdbf66c4aebe8003519ec95f20a742e77acbb | /adicionais/src/br/edu/ufcg/srh/adicionais/client/mapper/AdicionaisAcitivityMapper.java | 7c3c0843b28ad6024a9262f1ee27b3970c941890 | [] | no_license | clebersousa/projadicionais-cv | https://github.com/clebersousa/projadicionais-cv | 7cf306759ca95952ab4a10ceb5a131c0e197081e | af6a15d51195430bb4dc35cd8bb5b31ae7303153 | refs/heads/master | 2021-01-23T03:04:35.387000 | 2011-09-02T22:07:11 | 2011-09-02T22:07:11 | 2,316,749 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.edu.ufcg.srh.adicionais.client.mapper;
import br.edu.ufcg.srh.adicionais.client.ClientFactory;
import br.edu.ufcg.srh.adicionais.client.activity.CentroActivity;
import br.edu.ufcg.srh.adicionais.client.activity.LoginActivity;
import br.edu.ufcg.srh.adicionais.client.activity.SrhActivity;
import br.edu.ufcg.srh.adicionais.client.place.CentroPlace;
import br.edu.ufcg.srh.adicionais.client.place.LoginPlace;
import br.edu.ufcg.srh.adicionais.client.place.SrhPlace;
import com.google.gwt.activity.shared.Activity;
import com.google.gwt.activity.shared.ActivityMapper;
import com.google.gwt.place.shared.Place;
public class AdicionaisAcitivityMapper implements ActivityMapper {
private ClientFactory clientFactory;
public AdicionaisAcitivityMapper(ClientFactory clientFactory) {
this.clientFactory = clientFactory;
}
@Override
public Activity getActivity(Place place) {
if (place instanceof LoginPlace) {
return new LoginActivity(this.clientFactory);
}
if (place instanceof CentroPlace) {
return new CentroActivity(this.clientFactory);
}
if (place instanceof SrhPlace) {
return new SrhActivity(this.clientFactory);
}
return null;
}
}
| UTF-8 | Java | 1,180 | java | AdicionaisAcitivityMapper.java | Java | [] | null | [] | package br.edu.ufcg.srh.adicionais.client.mapper;
import br.edu.ufcg.srh.adicionais.client.ClientFactory;
import br.edu.ufcg.srh.adicionais.client.activity.CentroActivity;
import br.edu.ufcg.srh.adicionais.client.activity.LoginActivity;
import br.edu.ufcg.srh.adicionais.client.activity.SrhActivity;
import br.edu.ufcg.srh.adicionais.client.place.CentroPlace;
import br.edu.ufcg.srh.adicionais.client.place.LoginPlace;
import br.edu.ufcg.srh.adicionais.client.place.SrhPlace;
import com.google.gwt.activity.shared.Activity;
import com.google.gwt.activity.shared.ActivityMapper;
import com.google.gwt.place.shared.Place;
public class AdicionaisAcitivityMapper implements ActivityMapper {
private ClientFactory clientFactory;
public AdicionaisAcitivityMapper(ClientFactory clientFactory) {
this.clientFactory = clientFactory;
}
@Override
public Activity getActivity(Place place) {
if (place instanceof LoginPlace) {
return new LoginActivity(this.clientFactory);
}
if (place instanceof CentroPlace) {
return new CentroActivity(this.clientFactory);
}
if (place instanceof SrhPlace) {
return new SrhActivity(this.clientFactory);
}
return null;
}
}
| 1,180 | 0.802542 | 0.802542 | 36 | 31.777779 | 24.681427 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.333333 | false | false | 3 |
f57cbee644223b2b644f129cc030871ebb8d7fa6 | 19,576,460,968,299 | ab01b5f5bef3560778e86ffafa4bd94f932c6bc0 | /hanmote/src/com/hanmote/entity/OrgProduct.java | 8abc1ec05274a6489197c9f576a3c70fdc033fa1 | [
"MIT"
] | permissive | bellmit/HMT | https://github.com/bellmit/HMT | e02d0816558415256ee9b46d6959c07664717712 | d411e537eab3054e30624ff2af273aedadbac2fc | refs/heads/master | 2022-02-02T12:36:19.790000 | 2016-12-29T07:57:03 | 2016-12-29T07:57:03 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hanmote.entity;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
* 产品/产能实体类
* @author Administrator
*
*/
@Entity
@Table(name = "Org_Product", schema = "dbo")
public class OrgProduct implements java.io.Serializable {
// Fields
private static final long serialVersionUID = 1L;
private Integer id;
private OrgCapacity orgCapacity;
private String productName;
private Float annualSupply;
private String equipmentType;
private Float loadRatio;
// Constructors
/** default constructor */
public OrgProduct() {
}
/** full constructor */
public OrgProduct(OrgCapacity orgCapacity, String productName,
Float annualSupply, String equipmentType, Float loadRatio) {
this.orgCapacity = orgCapacity;
this.productName = productName;
this.annualSupply = annualSupply;
this.equipmentType = equipmentType;
this.loadRatio = loadRatio;
}
// Property accessors
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "ID", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.LAZY)
@JoinColumn(name = "capacityId")
public OrgCapacity getOrgCapacity() {
return this.orgCapacity;
}
public void setOrgCapacity(OrgCapacity orgCapacity) {
this.orgCapacity = orgCapacity;
}
@Column(name = "productName")
public String getProductName() {
return this.productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
@Column(name = "annualSupply", precision = 24, scale = 0)
public Float getAnnualSupply() {
return this.annualSupply;
}
public void setAnnualSupply(Float annualSupply) {
this.annualSupply = annualSupply;
}
@Column(name = "equipmentType")
public String getEquipmentType() {
return this.equipmentType;
}
public void setEquipmentType(String equipmentType) {
this.equipmentType = equipmentType;
}
@Column(name = "loadRatio", precision = 24, scale = 0)
public Float getLoadRatio() {
return this.loadRatio;
}
public void setLoadRatio(Float loadRatio) {
this.loadRatio = loadRatio;
}
} | UTF-8 | Java | 2,487 | java | OrgProduct.java | Java | [
{
"context": "ax.persistence.Table;\n\n\n/**\n * 产品/产能实体类\n * @author Administrator\n *\n */\n@Entity\n@Table(name = \"Org_Product\", schem",
"end": 443,
"score": 0.7858210802078247,
"start": 430,
"tag": "USERNAME",
"value": "Administrator"
}
] | null | [] | package com.hanmote.entity;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
* 产品/产能实体类
* @author Administrator
*
*/
@Entity
@Table(name = "Org_Product", schema = "dbo")
public class OrgProduct implements java.io.Serializable {
// Fields
private static final long serialVersionUID = 1L;
private Integer id;
private OrgCapacity orgCapacity;
private String productName;
private Float annualSupply;
private String equipmentType;
private Float loadRatio;
// Constructors
/** default constructor */
public OrgProduct() {
}
/** full constructor */
public OrgProduct(OrgCapacity orgCapacity, String productName,
Float annualSupply, String equipmentType, Float loadRatio) {
this.orgCapacity = orgCapacity;
this.productName = productName;
this.annualSupply = annualSupply;
this.equipmentType = equipmentType;
this.loadRatio = loadRatio;
}
// Property accessors
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "ID", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.LAZY)
@JoinColumn(name = "capacityId")
public OrgCapacity getOrgCapacity() {
return this.orgCapacity;
}
public void setOrgCapacity(OrgCapacity orgCapacity) {
this.orgCapacity = orgCapacity;
}
@Column(name = "productName")
public String getProductName() {
return this.productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
@Column(name = "annualSupply", precision = 24, scale = 0)
public Float getAnnualSupply() {
return this.annualSupply;
}
public void setAnnualSupply(Float annualSupply) {
this.annualSupply = annualSupply;
}
@Column(name = "equipmentType")
public String getEquipmentType() {
return this.equipmentType;
}
public void setEquipmentType(String equipmentType) {
this.equipmentType = equipmentType;
}
@Column(name = "loadRatio", precision = 24, scale = 0)
public Float getLoadRatio() {
return this.loadRatio;
}
public void setLoadRatio(Float loadRatio) {
this.loadRatio = loadRatio;
}
} | 2,487 | 0.750101 | 0.747271 | 108 | 21.907408 | 18.920662 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.231481 | false | false | 3 |
e74bbc48bfd1b7247ec7b8a160e74ace3dfd53be | 32,109,175,506,279 | 71a0495d6f2b28bb99c78102f81fb05436749f17 | /demo-list/demo-all/src/main/java/win/yulongsun/demo/all/readerwriter/ReaderWriterTest.java | 1cdcde0a56eb860fcfdffbe2d5684a129eb1c293 | [] | no_license | yulongsun007/learn-list | https://github.com/yulongsun007/learn-list | f41b9579c9d6f3ecb833ab69fcf83b6cacc9aa2e | 07fbbdad6d72a22b1551d17412898ac5188dbac0 | refs/heads/master | 2022-12-25T04:09:46.357000 | 2018-09-04T14:34:33 | 2018-09-04T14:34:33 | 97,855,579 | 0 | 1 | null | false | 2022-12-16T10:47:53 | 2017-07-20T16:15:59 | 2019-08-15T02:14:01 | 2022-12-16T10:47:49 | 6,588 | 0 | 0 | 64 | Java | false | false | package win.yulongsun.demo.all.readerwriter;
import java.io.*;
import java.nio.channels.FileLock;
import java.nio.charset.Charset;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* 读者写着模型
*
* @author Sun.YuLong on 2018/5/29.
*/
public class ReaderWriterTest implements Reader, Writer {
@Override
public void read(String fileNamePath) {
// System.out.println("读者begin");
// System.out.println("读者-" + Thread.currentThread().getId() + "-content=" + readFile(fileNamePath));
// System.out.println("读者end");
// System.out.println("-------------------------------");
//以上读取方法不能保证数据一致性,因为当文件锁的时候,还读取文件内容
try {
System.out.println("读者begin-" + Thread.currentThread().getId());
RandomAccessFile file = new RandomAccessFile(new File(fileNamePath), "r");
String line = file.readLine();
System.out.println("读者-" + Thread.currentThread().getId() + "-content=" + line);
System.out.println("读者end-" + Thread.currentThread().getId());
System.out.println("-------------------------------");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// e.printStackTrace();
System.out.println("重试-" + Thread.currentThread().getId());
read(fileNamePath);
}
}
@Override
public void write(String fileNamePath) {
try {
RandomAccessFile file = new RandomAccessFile(new File(fileNamePath), "rw");
FileLock fileLock = file.getChannel().tryLock();
System.out.println("写者begin-" + Thread.currentThread().getId());
file.seek(file.length());
file.write("write\t".getBytes());
System.out.println("写者-" + Thread.currentThread().getId() + "-write");
System.out.println("写者end-" + Thread.currentThread().getId());
System.out.println("-------------------------------");
fileLock.release();
file.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ReaderWriterTest readerWriterTest = new ReaderWriterTest();
String fileNamePath = "D:\\readme.txt";
//写者:单线程池
Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
readerWriterTest.write(fileNamePath);
}
}, 0L, 1L, TimeUnit.SECONDS);
//读者
Executors.newScheduledThreadPool(10).scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
readerWriterTest.read(fileNamePath);
}
}, 0L, 10L, TimeUnit.MILLISECONDS);
}
public static String readFile(String fileName) {
FileInputStream fis = null;
StringBuffer sb = new StringBuffer();
try {
fis = new FileInputStream(new File(fileName));
byte[] b = new byte[100];
int readbyte = 0;
while ((readbyte = fis.read(b)) != -1) {
sb.append(new String(b, 0, readbyte, Charset.defaultCharset()));
}
} catch (FileNotFoundException e) {
throw new RuntimeException("文件[" + fileName + "]未发现", e);
} catch (IOException e) {
throw new RuntimeException("文件读取[" + fileName + "]失败", e);
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (IOException e) {
}
}
return sb.toString().trim();
}
}
interface Reader {
void read(String fileNamePath);
}
interface Writer {
void write(String fileNamePath);
}
| UTF-8 | Java | 4,213 | java | ReaderWriterTest.java | Java | [
{
"context": ".concurrent.TimeUnit;\n\n/**\n * 读者写着模型\n *\n * @author Sun.YuLong on 2018/5/29.\n */\npublic class ReaderWriterTest i",
"end": 248,
"score": 0.9998340606689453,
"start": 238,
"tag": "NAME",
"value": "Sun.YuLong"
}
] | null | [] | package win.yulongsun.demo.all.readerwriter;
import java.io.*;
import java.nio.channels.FileLock;
import java.nio.charset.Charset;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* 读者写着模型
*
* @author Sun.YuLong on 2018/5/29.
*/
public class ReaderWriterTest implements Reader, Writer {
@Override
public void read(String fileNamePath) {
// System.out.println("读者begin");
// System.out.println("读者-" + Thread.currentThread().getId() + "-content=" + readFile(fileNamePath));
// System.out.println("读者end");
// System.out.println("-------------------------------");
//以上读取方法不能保证数据一致性,因为当文件锁的时候,还读取文件内容
try {
System.out.println("读者begin-" + Thread.currentThread().getId());
RandomAccessFile file = new RandomAccessFile(new File(fileNamePath), "r");
String line = file.readLine();
System.out.println("读者-" + Thread.currentThread().getId() + "-content=" + line);
System.out.println("读者end-" + Thread.currentThread().getId());
System.out.println("-------------------------------");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// e.printStackTrace();
System.out.println("重试-" + Thread.currentThread().getId());
read(fileNamePath);
}
}
@Override
public void write(String fileNamePath) {
try {
RandomAccessFile file = new RandomAccessFile(new File(fileNamePath), "rw");
FileLock fileLock = file.getChannel().tryLock();
System.out.println("写者begin-" + Thread.currentThread().getId());
file.seek(file.length());
file.write("write\t".getBytes());
System.out.println("写者-" + Thread.currentThread().getId() + "-write");
System.out.println("写者end-" + Thread.currentThread().getId());
System.out.println("-------------------------------");
fileLock.release();
file.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ReaderWriterTest readerWriterTest = new ReaderWriterTest();
String fileNamePath = "D:\\readme.txt";
//写者:单线程池
Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
readerWriterTest.write(fileNamePath);
}
}, 0L, 1L, TimeUnit.SECONDS);
//读者
Executors.newScheduledThreadPool(10).scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
readerWriterTest.read(fileNamePath);
}
}, 0L, 10L, TimeUnit.MILLISECONDS);
}
public static String readFile(String fileName) {
FileInputStream fis = null;
StringBuffer sb = new StringBuffer();
try {
fis = new FileInputStream(new File(fileName));
byte[] b = new byte[100];
int readbyte = 0;
while ((readbyte = fis.read(b)) != -1) {
sb.append(new String(b, 0, readbyte, Charset.defaultCharset()));
}
} catch (FileNotFoundException e) {
throw new RuntimeException("文件[" + fileName + "]未发现", e);
} catch (IOException e) {
throw new RuntimeException("文件读取[" + fileName + "]失败", e);
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (IOException e) {
}
}
return sb.toString().trim();
}
}
interface Reader {
void read(String fileNamePath);
}
interface Writer {
void write(String fileNamePath);
}
| 4,213 | 0.545477 | 0.540547 | 116 | 33.974136 | 25.953028 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.560345 | false | false | 3 |
a6104fba86f4f25fd05a1cdf455d5af564027017 | 1,340,029,818,444 | 5588a98ae499998b2ede956542121cee3dafa826 | /app/src/main/java/com/example/suelliton/sir/NodeAdapter.java | 93b2dc5454d01af9d6a0752a87f4f0a6878d2cb5 | [] | no_license | suelliton/SIR | https://github.com/suelliton/SIR | 4ed4a74c2aee04cadca77773b7cd93985df04ec5 | a07668e425cd760e1cadd633f310fda342b877a9 | refs/heads/master | 2021-08-23T05:17:26.445000 | 2017-12-03T15:40:27 | 2017-12-03T15:40:27 | 103,942,044 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.suelliton.sir;
import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Chronometer;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import com.example.suelliton.sir.model.Node;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.List;
import static android.os.SystemClock.elapsedRealtime;
import static com.example.suelliton.sir.FragmentGrafico.keyClicado;
/**
* Created by suelliton on 18/11/17.
*/
public class NodeAdapter extends RecyclerView.Adapter {
Context context;
private List<Node> listaNodes;
private FirebaseDatabase database ;
private DatabaseReference nodeReference ;
public static String nameClicado = "" ;
static int duracao;
public NodeAdapter(Context context, List<Node> lista){
this.context = context;
this.listaNodes = lista;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//infla layout node_inflate
View view = LayoutInflater.from(context).inflate(R.layout.node_inflate,parent,false);
NodeViewHolder holder = new NodeViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
database = FirebaseDatabase.getInstance();//pega uma instancia do banco
nodeReference = database.getReference("Node");//pega referencia node
final NodeViewHolder nodeHolder = (NodeViewHolder) holder;//faz cast do holder para nodeViewHolder
//seta os valores nas views pegando dos elementos nodes da lista que recebeu no construtor
nodeHolder.node_temperatura.setText(listaNodes.get(position).getTemperatura()+"°");
nodeHolder.node_umidade_ar.setText(listaNodes.get(position).getUmidade_ar()+"%");
nodeHolder.node_umidade_solo.setText(listaNodes.get(position).getUmidade_solo()+"%");
nodeHolder.node_nome.setText(listaNodes.get(position).getNome());
//aplica o formato hora:minuto:segundo
//cron.setText(DateFormat.format("00:mm:ss", 0));
nodeHolder.node_cronometro.setBase(elapsedRealtime() );
nodeHolder.node_cronometro.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
@Override
public void onChronometerTick(Chronometer chronometer) {
//Seta o tempo de início - o tempo de execução do cronômetro
nodeHolder.node_cronometro.setText(DateFormat.format("00:mm", listaNodes.get(position).getTempoAtivo()));
}
});
//listener de status para mudar a cor do dispositivo
nodeReference.child(listaNodes.get(position).getKey()).child("status").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String status = (String) dataSnapshot.getValue();
if(status != null) {
if (status.equals("ligado")) {
nodeHolder.node_status.setChecked(true);
//nodeHolder.row.setBackgroundColor(Color.parseColor("#0df009"));
nodeHolder.row.setBackgroundColor(Color.argb(100,178,223,219));
nodeHolder.node_cronometro.setVisibility(View.VISIBLE);
} else {
nodeHolder.node_status.setChecked(false);
nodeHolder.row.setBackgroundColor(Color.parseColor("#FFFFFF"));
nodeHolder.node_cronometro.setVisibility(View.INVISIBLE);
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
//verifica o click no botao de status e trata e seta no firebase se esta ativado ou não
nodeHolder.node_status.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(nodeHolder.node_status.isChecked()){
nodeReference.child(listaNodes.get(position).getKey()).child("status").setValue("ligado");
iniciarCronometro(nodeHolder.node_cronometro);
}else{
nodeReference.child(listaNodes.get(position).getKey()).child("status").setValue("desligado");
int tempoAtivo = pararCronometro(nodeHolder.node_cronometro);
int tempoGravado = listaNodes.get(position).getTempoAtivo();//pego o tempo que ja está gravado no firebase
//incremento o tempo ativo mais o que ja estava no firebase
//nodeReference.child(listaNodes.get(position).getKey()).child("tempoAtivo").setValue(tempoGravado+tempoAtivo);
}
}
});
//verifica o click na row_clicavel e seta a keyClicado e chama o fragment de graficos
final String clicado = listaNodes.get(position).getKey();
nodeHolder.row_clicavel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
keyClicado = clicado;
nameClicado = listaNodes.get(position).getNome();
Log.i("clicado",keyClicado);
MainActivity.tabLayout.getTabAt(1).select();
}
});
//replica a função acima para chamar o grafico só que clicando no nome do dispositivo
nodeHolder.node_nome.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
keyClicado = clicado;
nameClicado = listaNodes.get(position).getNome();
Log.i("clicado",keyClicado);
MainActivity.tabLayout.getTabAt(1).select();
}
});
}
private void iniciarCronometro(Chronometer cron){
cron.setBase(elapsedRealtime());
cron.start();
}
private int pararCronometro(Chronometer cron){
cron.stop();
duracao = (int) (elapsedRealtime() - cron.getBase());
Log.i("duracao",duracao+"");
return duracao;
}
@Override
public int getItemCount() {
return listaNodes.size();
}
@Override
public long getItemId(int position) {
return position;
}
public class NodeViewHolder extends RecyclerView.ViewHolder{
final TextView node_temperatura ;
final TextView node_umidade_ar ;
final TextView node_umidade_solo ;
final TextView node_nome;
final Switch node_status;
final LinearLayout row;
final LinearLayout row_clicavel;
final Chronometer node_cronometro;
public NodeViewHolder(View view){
super(view);
node_temperatura = view.findViewById(R.id.text_temperatura);
node_umidade_ar = view.findViewById(R.id.text_umidade_ar);
node_umidade_solo = view.findViewById(R.id.text_umidade_solo);
node_nome = view.findViewById(R.id.text_nome);
node_status = view.findViewById(R.id.switch_status);
row = view.findViewById(R.id.row);
row_clicavel = view.findViewById(R.id.row_clicavel);
node_cronometro = view.findViewById(R.id.cronometro);
}
}
}
| UTF-8 | Java | 7,938 | java | NodeAdapter.java | Java | [
{
"context": "ir.FragmentGrafico.keyClicado;\n\n\n/**\n * Created by suelliton on 18/11/17.\n */\n\npublic class NodeAdapter extend",
"end": 922,
"score": 0.9987725019454956,
"start": 913,
"tag": "USERNAME",
"value": "suelliton"
}
] | null | [] | package com.example.suelliton.sir;
import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Chronometer;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import com.example.suelliton.sir.model.Node;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.List;
import static android.os.SystemClock.elapsedRealtime;
import static com.example.suelliton.sir.FragmentGrafico.keyClicado;
/**
* Created by suelliton on 18/11/17.
*/
public class NodeAdapter extends RecyclerView.Adapter {
Context context;
private List<Node> listaNodes;
private FirebaseDatabase database ;
private DatabaseReference nodeReference ;
public static String nameClicado = "" ;
static int duracao;
public NodeAdapter(Context context, List<Node> lista){
this.context = context;
this.listaNodes = lista;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//infla layout node_inflate
View view = LayoutInflater.from(context).inflate(R.layout.node_inflate,parent,false);
NodeViewHolder holder = new NodeViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
database = FirebaseDatabase.getInstance();//pega uma instancia do banco
nodeReference = database.getReference("Node");//pega referencia node
final NodeViewHolder nodeHolder = (NodeViewHolder) holder;//faz cast do holder para nodeViewHolder
//seta os valores nas views pegando dos elementos nodes da lista que recebeu no construtor
nodeHolder.node_temperatura.setText(listaNodes.get(position).getTemperatura()+"°");
nodeHolder.node_umidade_ar.setText(listaNodes.get(position).getUmidade_ar()+"%");
nodeHolder.node_umidade_solo.setText(listaNodes.get(position).getUmidade_solo()+"%");
nodeHolder.node_nome.setText(listaNodes.get(position).getNome());
//aplica o formato hora:minuto:segundo
//cron.setText(DateFormat.format("00:mm:ss", 0));
nodeHolder.node_cronometro.setBase(elapsedRealtime() );
nodeHolder.node_cronometro.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
@Override
public void onChronometerTick(Chronometer chronometer) {
//Seta o tempo de início - o tempo de execução do cronômetro
nodeHolder.node_cronometro.setText(DateFormat.format("00:mm", listaNodes.get(position).getTempoAtivo()));
}
});
//listener de status para mudar a cor do dispositivo
nodeReference.child(listaNodes.get(position).getKey()).child("status").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String status = (String) dataSnapshot.getValue();
if(status != null) {
if (status.equals("ligado")) {
nodeHolder.node_status.setChecked(true);
//nodeHolder.row.setBackgroundColor(Color.parseColor("#0df009"));
nodeHolder.row.setBackgroundColor(Color.argb(100,178,223,219));
nodeHolder.node_cronometro.setVisibility(View.VISIBLE);
} else {
nodeHolder.node_status.setChecked(false);
nodeHolder.row.setBackgroundColor(Color.parseColor("#FFFFFF"));
nodeHolder.node_cronometro.setVisibility(View.INVISIBLE);
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
//verifica o click no botao de status e trata e seta no firebase se esta ativado ou não
nodeHolder.node_status.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(nodeHolder.node_status.isChecked()){
nodeReference.child(listaNodes.get(position).getKey()).child("status").setValue("ligado");
iniciarCronometro(nodeHolder.node_cronometro);
}else{
nodeReference.child(listaNodes.get(position).getKey()).child("status").setValue("desligado");
int tempoAtivo = pararCronometro(nodeHolder.node_cronometro);
int tempoGravado = listaNodes.get(position).getTempoAtivo();//pego o tempo que ja está gravado no firebase
//incremento o tempo ativo mais o que ja estava no firebase
//nodeReference.child(listaNodes.get(position).getKey()).child("tempoAtivo").setValue(tempoGravado+tempoAtivo);
}
}
});
//verifica o click na row_clicavel e seta a keyClicado e chama o fragment de graficos
final String clicado = listaNodes.get(position).getKey();
nodeHolder.row_clicavel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
keyClicado = clicado;
nameClicado = listaNodes.get(position).getNome();
Log.i("clicado",keyClicado);
MainActivity.tabLayout.getTabAt(1).select();
}
});
//replica a função acima para chamar o grafico só que clicando no nome do dispositivo
nodeHolder.node_nome.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
keyClicado = clicado;
nameClicado = listaNodes.get(position).getNome();
Log.i("clicado",keyClicado);
MainActivity.tabLayout.getTabAt(1).select();
}
});
}
private void iniciarCronometro(Chronometer cron){
cron.setBase(elapsedRealtime());
cron.start();
}
private int pararCronometro(Chronometer cron){
cron.stop();
duracao = (int) (elapsedRealtime() - cron.getBase());
Log.i("duracao",duracao+"");
return duracao;
}
@Override
public int getItemCount() {
return listaNodes.size();
}
@Override
public long getItemId(int position) {
return position;
}
public class NodeViewHolder extends RecyclerView.ViewHolder{
final TextView node_temperatura ;
final TextView node_umidade_ar ;
final TextView node_umidade_solo ;
final TextView node_nome;
final Switch node_status;
final LinearLayout row;
final LinearLayout row_clicavel;
final Chronometer node_cronometro;
public NodeViewHolder(View view){
super(view);
node_temperatura = view.findViewById(R.id.text_temperatura);
node_umidade_ar = view.findViewById(R.id.text_umidade_ar);
node_umidade_solo = view.findViewById(R.id.text_umidade_solo);
node_nome = view.findViewById(R.id.text_nome);
node_status = view.findViewById(R.id.switch_status);
row = view.findViewById(R.id.row);
row_clicavel = view.findViewById(R.id.row_clicavel);
node_cronometro = view.findViewById(R.id.cronometro);
}
}
}
| 7,938 | 0.641271 | 0.637487 | 189 | 40.94709 | 32.177376 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.57672 | false | false | 3 |
b75a1f793f0f69cbc427233eb3f3f82df8ccb7f6 | 30,880,814,909,565 | a5c755b3354d99314d76dd30454431042c47a605 | /lists/src/com/comphel/lists/business/RoundNG.java | d68ef0b520ab5c61b5b809b1f1007edda2bb32e7 | [] | no_license | gundermann/comphel | https://github.com/gundermann/comphel | ac80a711c4137e099ac8da3607f2901d0bbe58c7 | 792544f4fdbfbe3554945f0bb7a49d02c38bf6af | HEAD | 2016-03-31T18:14:08.695000 | 2016-02-12T10:23:18 | 2016-02-12T10:23:18 | 15,620,161 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.comphel.lists.business;
import java.util.ArrayList;
import java.util.List;
import com.comphel.android_common.business.CompetitorNG;
import com.comphel.android_common.business.MatchNG;
import com.ng.apersist.annotation.Column;
import com.ng.apersist.annotation.Id;
import com.ng.apersist.annotation.PersistenceClass;
import com.ng.apersist.annotation.Table;
import com.ng.apersist.annotation.ToMany;
@PersistenceClass
@Table(name = "rounds")
public class RoundNG {
@Id(autoincrement = true)
private Long id;
@Column
private Integer number;
@ToMany(target = CompetitorNG.class)
private List<CompetitorNG> competitorToEvaluate;
@ToMany(target = MatchNG.class)
private List<MatchNG> matches;
@Column
private Integer competitorCountOfNextRound;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
public List<CompetitorNG> getCompetitorToEvaluate() {
if (competitorToEvaluate == null)
competitorToEvaluate = new ArrayList<CompetitorNG>();
return competitorToEvaluate;
}
public void setCompetitorToEvaluate(List<CompetitorNG> competitorToEvaluate) {
this.competitorToEvaluate = competitorToEvaluate;
}
public List<MatchNG> getMatches() {
return matches;
}
public void setMatches(List<MatchNG> matches) {
this.matches = matches;
}
public Integer getCompetitorCountOfNextRound() {
return competitorCountOfNextRound;
}
public void setCompetitorCountOfNextRound(Integer competitorCountOfNextRound) {
this.competitorCountOfNextRound = competitorCountOfNextRound;
}
@Override
public String toString() {
if (number < 10)
return String.valueOf(number);
else
return String.valueOf(number / 10) + " - "
+ String.valueOf(number % 10);
}
@Override
public boolean equals(Object o) {
return o instanceof RoundNG && ((RoundNG) o).getId().equals(getId());
}
}
| UTF-8 | Java | 2,076 | java | RoundNG.java | Java | [] | null | [] | package com.comphel.lists.business;
import java.util.ArrayList;
import java.util.List;
import com.comphel.android_common.business.CompetitorNG;
import com.comphel.android_common.business.MatchNG;
import com.ng.apersist.annotation.Column;
import com.ng.apersist.annotation.Id;
import com.ng.apersist.annotation.PersistenceClass;
import com.ng.apersist.annotation.Table;
import com.ng.apersist.annotation.ToMany;
@PersistenceClass
@Table(name = "rounds")
public class RoundNG {
@Id(autoincrement = true)
private Long id;
@Column
private Integer number;
@ToMany(target = CompetitorNG.class)
private List<CompetitorNG> competitorToEvaluate;
@ToMany(target = MatchNG.class)
private List<MatchNG> matches;
@Column
private Integer competitorCountOfNextRound;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
public List<CompetitorNG> getCompetitorToEvaluate() {
if (competitorToEvaluate == null)
competitorToEvaluate = new ArrayList<CompetitorNG>();
return competitorToEvaluate;
}
public void setCompetitorToEvaluate(List<CompetitorNG> competitorToEvaluate) {
this.competitorToEvaluate = competitorToEvaluate;
}
public List<MatchNG> getMatches() {
return matches;
}
public void setMatches(List<MatchNG> matches) {
this.matches = matches;
}
public Integer getCompetitorCountOfNextRound() {
return competitorCountOfNextRound;
}
public void setCompetitorCountOfNextRound(Integer competitorCountOfNextRound) {
this.competitorCountOfNextRound = competitorCountOfNextRound;
}
@Override
public String toString() {
if (number < 10)
return String.valueOf(number);
else
return String.valueOf(number / 10) + " - "
+ String.valueOf(number % 10);
}
@Override
public boolean equals(Object o) {
return o instanceof RoundNG && ((RoundNG) o).getId().equals(getId());
}
}
| 2,076 | 0.723025 | 0.720135 | 89 | 21.325842 | 21.116465 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.202247 | false | false | 3 |
92e160a69ecee48a59b56e261e2e068dcdc49ec6 | 19,945,828,182,348 | 2bf31cda0751a831bd167adafb1d440b25a81cc8 | /src/main/java/clashsoft/cslib/minecraft/stack/RandomStack.java | ce9d1637e76fc21953add99971d725e10dd2892d | [] | no_license | MinestrapTeam/Clashsoft-Lib | https://github.com/MinestrapTeam/Clashsoft-Lib | 5eaed9964f09cd928ea2dfc1d5ff72a6bdf20ec5 | 771f2d62deb87d63e29aaf138a043bec36aa06b2 | refs/heads/master | 2021-01-18T22:43:21.492000 | 2015-01-17T14:55:22 | 2015-01-17T14:55:22 | 9,415,157 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package clashsoft.cslib.minecraft.stack;
import java.util.Random;
import cpw.mods.fml.common.registry.RegistryDelegate;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
public abstract class RandomStack
{
protected Item item;
protected int metadata;
public RegistryDelegate<Item> delegate;
public RandomStack(Item item, int metadata)
{
this.item = item;
this.delegate = item.delegate;
this.metadata = metadata;
}
public RandomStack(Block block, int metadata)
{
this(Item.getItemFromBlock(block), metadata);
}
public Item getItem()
{
return this.delegate != null ? this.delegate.get() : this.item;
}
public int getMetadata()
{
return this.metadata;
}
public abstract int getStackSize(Random random);
public ItemStack toItemStack(Random random)
{
return new ItemStack(this.getItem(), this.getStackSize(random), this.metadata);
}
}
| UTF-8 | Java | 942 | java | RandomStack.java | Java | [] | null | [] | package clashsoft.cslib.minecraft.stack;
import java.util.Random;
import cpw.mods.fml.common.registry.RegistryDelegate;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
public abstract class RandomStack
{
protected Item item;
protected int metadata;
public RegistryDelegate<Item> delegate;
public RandomStack(Item item, int metadata)
{
this.item = item;
this.delegate = item.delegate;
this.metadata = metadata;
}
public RandomStack(Block block, int metadata)
{
this(Item.getItemFromBlock(block), metadata);
}
public Item getItem()
{
return this.delegate != null ? this.delegate.get() : this.item;
}
public int getMetadata()
{
return this.metadata;
}
public abstract int getStackSize(Random random);
public ItemStack toItemStack(Random random)
{
return new ItemStack(this.getItem(), this.getStackSize(random), this.metadata);
}
}
| 942 | 0.738854 | 0.738854 | 46 | 19.47826 | 20.935448 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.586957 | false | false | 3 |
45c1d969c5dcd7241dce18d2f82fc1963f06d00e | 22,041,772,225,718 | b9719d600365dd95c026c307603d11a4dbd99332 | /src/com/cdac/clinic/dao/IDaoPatient.java | 12484f2e66b568ceb4dcf8c3ee7d2a360626ed24 | [] | no_license | arki7n/java-basic-jdbc | https://github.com/arki7n/java-basic-jdbc | ebbf393c2dd90fa45b746af21feb2c75dce8bff7 | 9e347d7e960dc3de92ef9175a049ee7a3c1c8196 | refs/heads/master | 2020-05-24T17:12:38.767000 | 2019-06-21T09:50:56 | 2019-06-21T09:50:56 | 187,378,857 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cdac.clinic.dao;
import java.sql.SQLException;
import java.util.ArrayList;
import com.cdac.clinic.models.Patient;
public interface IDaoPatient {
ArrayList<Patient> getpatientdetails() throws ClassNotFoundException, SQLException;
}
| UTF-8 | Java | 250 | java | IDaoPatient.java | Java | [] | null | [] | package com.cdac.clinic.dao;
import java.sql.SQLException;
import java.util.ArrayList;
import com.cdac.clinic.models.Patient;
public interface IDaoPatient {
ArrayList<Patient> getpatientdetails() throws ClassNotFoundException, SQLException;
}
| 250 | 0.808 | 0.808 | 12 | 19.833334 | 24.213747 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 3 |
d594b377bd12045d1130dbb40a85fab9c230cd14 | 2,413,771,681,667 | 497fcb88c10c94fed1caa160ee110561c07b594c | /web/web-lobby/src/main/java/com/yazino/web/payment/flurry/EarnFreeChipsController.java | e677d0d7b9d712308727e0b0285504428338749c | [] | no_license | ShahakBH/jazzino-master | https://github.com/ShahakBH/jazzino-master | 3f116a609c5648c00dfbe6ab89c6c3ce1903fc1a | 2401394022106d2321873d15996953f2bbc2a326 | refs/heads/master | 2016-09-02T01:26:44.514000 | 2015-08-10T13:06:54 | 2015-08-10T13:06:54 | 40,482,590 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yazino.web.payment.flurry;
import com.yazino.platform.Platform;
import com.yazino.platform.account.*;
import com.yazino.platform.community.PlayerService;
import com.yazino.spring.security.AllowPublicAccess;
import com.yazino.web.domain.email.EarnedChipsEmailBuilder;
import com.yazino.web.service.QuietPlayerEmailer;
import com.yazino.web.session.LobbySession;
import com.yazino.web.session.LobbySessionCache;
import com.yazino.web.util.WebApiResponses;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Currency;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
@Controller
@AllowPublicAccess
@RequestMapping("/payment/flurry/*")
public class EarnFreeChipsController {
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormat.forPattern("yyyyMMdd'T'HHmmss");
private static final AtomicLong ATOMIC_LONG = new AtomicLong();
public static final String FLURRY_CLIPS_EARN_FREE_CHIPS_VIDEO_HOOK = "FLURRY_CLIPS_EARN_FREE_CHIPS_VIDEO_HOOK";
public static final String NO_CONFIG = "NO_CONFIG";
public static final String INVALID_TICKET = "INVALID_TICKET";
public static final String NO_SESSION = "NO_SESSION";
public static final String NO_PROFILE_FOUND = "NO_PROFILE_FOUND";
public static final String FLURRY_MOBILE = "FLURRY_MOBILE";
public static final int TWO_HUNDRED = 200;
public static final BigDecimal CHIP_MULTIPLIER = new BigDecimal("0.0001");
public static final Currency CURRENCY = Currency.getInstance("USD");
private final Map<String, EarnFreeChipsConfiguration> configurations = new HashMap<String, EarnFreeChipsConfiguration>();
private final WebApiResponses responseWriter;
private FreeChipsTickets ticketMachine = defaultTicketMachine();
private final WalletService walletService;
private final PlayerService playerService;
private final LobbySessionCache lobbySessionCache;
private final QuietPlayerEmailer emailer;
@Autowired(required = true)
public EarnFreeChipsController(
WebApiResponses responseWriter, final WalletService walletService,
final PlayerService playerService,
final LobbySessionCache lobbySessionCache,
final QuietPlayerEmailer emailer) {
this.responseWriter = responseWriter;
final EarnFreeChipsConfiguration flurryConfig = new EarnFreeChipsConfiguration(FLURRY_CLIPS_EARN_FREE_CHIPS_VIDEO_HOOK, TWO_HUNDRED);
this.configurations.put(FLURRY_CLIPS_EARN_FREE_CHIPS_VIDEO_HOOK, flurryConfig);
this.playerService = playerService;
this.walletService = walletService;
this.lobbySessionCache = lobbySessionCache;
this.emailer = emailer;
}
public void setTicketMachine(final FreeChipsTickets ticketMachine) {
this.ticketMachine = ticketMachine;
}
@RequestMapping("/configuration")
public void earnFreeChipsConfigurationForType(@RequestParam(value = "code", required = false) final String code,
final HttpServletResponse response) throws IOException {
final EarnFreeChipsConfiguration config = findFreeChipsConfigurationForCode(code);
this.responseWriter.writeOk(response, config);
}
private EarnFreeChipsConfiguration findFreeChipsConfigurationForCode(final String code) {
EarnFreeChipsConfiguration config = this.configurations.get(code);
if (config == null) {
config = new EarnFreeChipsConfiguration(code, 0);
}
return config;
}
@RequestMapping("/issueTicket")
public void issueTicket(final HttpServletResponse response)
throws IOException, IllegalBlockSizeException, InvalidKeyException,
NoSuchAlgorithmException, NoSuchPaddingException, BadPaddingException,
InvalidAlgorithmParameterException, NoSuchProviderException {
final FreeChipTicket ticket = new FreeChipTicket(this.ticketMachine.newTicket());
this.responseWriter.writeOk(response, ticket);
}
@RequestMapping("/awardFreeChips")
public void awardFreeChips(@RequestParam(value = "code", required = true) final String code,
@RequestParam(value = "signedTicket", required = true) final String signedTicket,
@RequestParam(value = "application", required = false, defaultValue = "UNKNOWN") final String application,
final HttpServletRequest request,
final HttpServletResponse response)
throws IllegalBlockSizeException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException,
BadPaddingException, IOException, WalletServiceException {
final EarnFreeChipsConfiguration config = findFreeChipsConfigurationForCode(code);
if (config.getChips() <= 0) {
this.responseWriter.writeOk(response, new FreeChipTicketRedemption(false, 0, NO_CONFIG, null));
return;
}
final boolean isValidTicket = ticketMachine.checkTicketAndRemove(signedTicket, true);
if (!isValidTicket) {
final FreeChipTicketRedemption redemption = new FreeChipTicketRedemption(
isValidTicket,
config.getChips(),
INVALID_TICKET,
null);
this.responseWriter.writeOk(response, redemption);
return;
}
final LobbySession session = lobbySessionCache.getActiveSession(request);
if (session == null) {
final FreeChipTicketRedemption redemption = new FreeChipTicketRedemption(
false,
config.getChips(),
NO_SESSION,
null);
this.responseWriter.writeOk(response, redemption);
return;
}
final BigDecimal accountId = playerService.getAccountId(session.getPlayerId());
if (accountId == null) {
final FreeChipTicketRedemption redemption = new FreeChipTicketRedemption(
false,
config.getChips(),
NO_PROFILE_FOUND,
null);
this.responseWriter.writeOk(
response,
redemption);
return;
}
final DateTime now = new DateTime();
final String internalId = buildInternalId(now, accountId, FLURRY_MOBILE);
final BigDecimal chips = BigDecimal.valueOf(config.chips);
final BigDecimal cashAmount = CHIP_MULTIPLIER.multiply(chips);
final ExternalTransaction externalTransaction = ExternalTransaction.newExternalTransaction(accountId)
.withInternalTransactionId(internalId)
.withExternalTransactionId(internalId)
.withMessage(signedTicket, now)
.withAmount(CURRENCY, cashAmount)
.withPaymentOption(chips, null)
.withCreditCardNumber("x-x-x")
.withCashierName(FLURRY_MOBILE)
.withStatus(ExternalTransactionStatus.SUCCESS)
.withType(ExternalTransactionType.DEPOSIT)
.withGameType(application)
.withPlayerId(session.getPlayerId())
.withSessionId(session.getSessionId())
.withPromotionId(null)
.withPlatform(Platform.ANDROID)
.build();
final BigDecimal newBalance = walletService.record(externalTransaction);
this.responseWriter.writeOk(response, new FreeChipTicketRedemption(true, config.getChips(), null, newBalance));
final EarnedChipsEmailBuilder builder = new EarnedChipsEmailBuilder(session.getPlayerId(),
internalId, BigDecimal.valueOf(config.getChips()));
emailer.quietlySendEmail(builder);
}
String buildInternalId(final DateTime messageTimeStamp,
final BigDecimal accountId,
final String productIdentifier) {
final DateTime dtLondon = messageTimeStamp.withZone(DateTimeZone.forID("Europe/London"));
final String date = DATE_TIME_FORMATTER.print(dtLondon);
final long nextIncrement = ATOMIC_LONG.getAndIncrement();
return String.format("%s_%s_%s_%s", productIdentifier, accountId.toPlainString(), date, nextIncrement);
}
public WebApiResponses getResponseWriter() {
return responseWriter;
}
private static FreeChipsTickets defaultTicketMachine() {
try {
return new FreeChipsTickets();
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e);
}
}
public static class FreeChipTicketRedemption {
private final boolean successful;
private final int chipsAwarded;
private final String message;
private final BigDecimal newBalance;
public FreeChipTicketRedemption(final boolean successful, final int chipsAwarded,
final String message, final BigDecimal newBalance) {
this.successful = successful;
this.chipsAwarded = chipsAwarded;
this.message = message;
this.newBalance = newBalance;
}
public boolean isSuccessful() {
return successful;
}
public int getChipsAwarded() {
return chipsAwarded;
}
public String getMessage() {
return message;
}
public BigDecimal getNewBalance() {
return newBalance;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final FreeChipTicketRedemption that = (FreeChipTicketRedemption) o;
return new EqualsBuilder()
.append(successful, that.successful)
.append(chipsAwarded, that.chipsAwarded)
.append(message, that.message)
.append(newBalance, that.newBalance)
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder()
.append(successful)
.append(chipsAwarded)
.append(message)
.append(newBalance)
.hashCode();
}
public String toString() {
return ReflectionToStringBuilder.reflectionToString(this);
}
}
public static class EarnFreeChipsConfiguration {
private final String code;
private final int chips;
public EarnFreeChipsConfiguration(final String code, final int chips) {
this.code = code;
this.chips = chips;
}
public String getCode() {
return code;
}
public int getChips() {
return chips;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final EarnFreeChipsConfiguration that = (EarnFreeChipsConfiguration) o;
return new EqualsBuilder()
.append(chips, that.chips)
.append(code, that.code)
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder()
.append(chips)
.append(code)
.hashCode();
}
}
public static class FreeChipTicket {
private final String ticket;
public FreeChipTicket(final String ticket) {
this.ticket = ticket;
}
public String getTicket() {
return ticket;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final FreeChipTicket that = (FreeChipTicket) o;
return new EqualsBuilder()
.append(ticket, that.ticket)
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder()
.append(ticket)
.hashCode();
}
}
}
| UTF-8 | Java | 13,756 | java | EarnFreeChipsController.java | Java | [] | null | [] | package com.yazino.web.payment.flurry;
import com.yazino.platform.Platform;
import com.yazino.platform.account.*;
import com.yazino.platform.community.PlayerService;
import com.yazino.spring.security.AllowPublicAccess;
import com.yazino.web.domain.email.EarnedChipsEmailBuilder;
import com.yazino.web.service.QuietPlayerEmailer;
import com.yazino.web.session.LobbySession;
import com.yazino.web.session.LobbySessionCache;
import com.yazino.web.util.WebApiResponses;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Currency;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
@Controller
@AllowPublicAccess
@RequestMapping("/payment/flurry/*")
public class EarnFreeChipsController {
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormat.forPattern("yyyyMMdd'T'HHmmss");
private static final AtomicLong ATOMIC_LONG = new AtomicLong();
public static final String FLURRY_CLIPS_EARN_FREE_CHIPS_VIDEO_HOOK = "FLURRY_CLIPS_EARN_FREE_CHIPS_VIDEO_HOOK";
public static final String NO_CONFIG = "NO_CONFIG";
public static final String INVALID_TICKET = "INVALID_TICKET";
public static final String NO_SESSION = "NO_SESSION";
public static final String NO_PROFILE_FOUND = "NO_PROFILE_FOUND";
public static final String FLURRY_MOBILE = "FLURRY_MOBILE";
public static final int TWO_HUNDRED = 200;
public static final BigDecimal CHIP_MULTIPLIER = new BigDecimal("0.0001");
public static final Currency CURRENCY = Currency.getInstance("USD");
private final Map<String, EarnFreeChipsConfiguration> configurations = new HashMap<String, EarnFreeChipsConfiguration>();
private final WebApiResponses responseWriter;
private FreeChipsTickets ticketMachine = defaultTicketMachine();
private final WalletService walletService;
private final PlayerService playerService;
private final LobbySessionCache lobbySessionCache;
private final QuietPlayerEmailer emailer;
@Autowired(required = true)
public EarnFreeChipsController(
WebApiResponses responseWriter, final WalletService walletService,
final PlayerService playerService,
final LobbySessionCache lobbySessionCache,
final QuietPlayerEmailer emailer) {
this.responseWriter = responseWriter;
final EarnFreeChipsConfiguration flurryConfig = new EarnFreeChipsConfiguration(FLURRY_CLIPS_EARN_FREE_CHIPS_VIDEO_HOOK, TWO_HUNDRED);
this.configurations.put(FLURRY_CLIPS_EARN_FREE_CHIPS_VIDEO_HOOK, flurryConfig);
this.playerService = playerService;
this.walletService = walletService;
this.lobbySessionCache = lobbySessionCache;
this.emailer = emailer;
}
public void setTicketMachine(final FreeChipsTickets ticketMachine) {
this.ticketMachine = ticketMachine;
}
@RequestMapping("/configuration")
public void earnFreeChipsConfigurationForType(@RequestParam(value = "code", required = false) final String code,
final HttpServletResponse response) throws IOException {
final EarnFreeChipsConfiguration config = findFreeChipsConfigurationForCode(code);
this.responseWriter.writeOk(response, config);
}
private EarnFreeChipsConfiguration findFreeChipsConfigurationForCode(final String code) {
EarnFreeChipsConfiguration config = this.configurations.get(code);
if (config == null) {
config = new EarnFreeChipsConfiguration(code, 0);
}
return config;
}
@RequestMapping("/issueTicket")
public void issueTicket(final HttpServletResponse response)
throws IOException, IllegalBlockSizeException, InvalidKeyException,
NoSuchAlgorithmException, NoSuchPaddingException, BadPaddingException,
InvalidAlgorithmParameterException, NoSuchProviderException {
final FreeChipTicket ticket = new FreeChipTicket(this.ticketMachine.newTicket());
this.responseWriter.writeOk(response, ticket);
}
@RequestMapping("/awardFreeChips")
public void awardFreeChips(@RequestParam(value = "code", required = true) final String code,
@RequestParam(value = "signedTicket", required = true) final String signedTicket,
@RequestParam(value = "application", required = false, defaultValue = "UNKNOWN") final String application,
final HttpServletRequest request,
final HttpServletResponse response)
throws IllegalBlockSizeException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException,
BadPaddingException, IOException, WalletServiceException {
final EarnFreeChipsConfiguration config = findFreeChipsConfigurationForCode(code);
if (config.getChips() <= 0) {
this.responseWriter.writeOk(response, new FreeChipTicketRedemption(false, 0, NO_CONFIG, null));
return;
}
final boolean isValidTicket = ticketMachine.checkTicketAndRemove(signedTicket, true);
if (!isValidTicket) {
final FreeChipTicketRedemption redemption = new FreeChipTicketRedemption(
isValidTicket,
config.getChips(),
INVALID_TICKET,
null);
this.responseWriter.writeOk(response, redemption);
return;
}
final LobbySession session = lobbySessionCache.getActiveSession(request);
if (session == null) {
final FreeChipTicketRedemption redemption = new FreeChipTicketRedemption(
false,
config.getChips(),
NO_SESSION,
null);
this.responseWriter.writeOk(response, redemption);
return;
}
final BigDecimal accountId = playerService.getAccountId(session.getPlayerId());
if (accountId == null) {
final FreeChipTicketRedemption redemption = new FreeChipTicketRedemption(
false,
config.getChips(),
NO_PROFILE_FOUND,
null);
this.responseWriter.writeOk(
response,
redemption);
return;
}
final DateTime now = new DateTime();
final String internalId = buildInternalId(now, accountId, FLURRY_MOBILE);
final BigDecimal chips = BigDecimal.valueOf(config.chips);
final BigDecimal cashAmount = CHIP_MULTIPLIER.multiply(chips);
final ExternalTransaction externalTransaction = ExternalTransaction.newExternalTransaction(accountId)
.withInternalTransactionId(internalId)
.withExternalTransactionId(internalId)
.withMessage(signedTicket, now)
.withAmount(CURRENCY, cashAmount)
.withPaymentOption(chips, null)
.withCreditCardNumber("x-x-x")
.withCashierName(FLURRY_MOBILE)
.withStatus(ExternalTransactionStatus.SUCCESS)
.withType(ExternalTransactionType.DEPOSIT)
.withGameType(application)
.withPlayerId(session.getPlayerId())
.withSessionId(session.getSessionId())
.withPromotionId(null)
.withPlatform(Platform.ANDROID)
.build();
final BigDecimal newBalance = walletService.record(externalTransaction);
this.responseWriter.writeOk(response, new FreeChipTicketRedemption(true, config.getChips(), null, newBalance));
final EarnedChipsEmailBuilder builder = new EarnedChipsEmailBuilder(session.getPlayerId(),
internalId, BigDecimal.valueOf(config.getChips()));
emailer.quietlySendEmail(builder);
}
String buildInternalId(final DateTime messageTimeStamp,
final BigDecimal accountId,
final String productIdentifier) {
final DateTime dtLondon = messageTimeStamp.withZone(DateTimeZone.forID("Europe/London"));
final String date = DATE_TIME_FORMATTER.print(dtLondon);
final long nextIncrement = ATOMIC_LONG.getAndIncrement();
return String.format("%s_%s_%s_%s", productIdentifier, accountId.toPlainString(), date, nextIncrement);
}
public WebApiResponses getResponseWriter() {
return responseWriter;
}
private static FreeChipsTickets defaultTicketMachine() {
try {
return new FreeChipsTickets();
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e);
}
}
public static class FreeChipTicketRedemption {
private final boolean successful;
private final int chipsAwarded;
private final String message;
private final BigDecimal newBalance;
public FreeChipTicketRedemption(final boolean successful, final int chipsAwarded,
final String message, final BigDecimal newBalance) {
this.successful = successful;
this.chipsAwarded = chipsAwarded;
this.message = message;
this.newBalance = newBalance;
}
public boolean isSuccessful() {
return successful;
}
public int getChipsAwarded() {
return chipsAwarded;
}
public String getMessage() {
return message;
}
public BigDecimal getNewBalance() {
return newBalance;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final FreeChipTicketRedemption that = (FreeChipTicketRedemption) o;
return new EqualsBuilder()
.append(successful, that.successful)
.append(chipsAwarded, that.chipsAwarded)
.append(message, that.message)
.append(newBalance, that.newBalance)
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder()
.append(successful)
.append(chipsAwarded)
.append(message)
.append(newBalance)
.hashCode();
}
public String toString() {
return ReflectionToStringBuilder.reflectionToString(this);
}
}
public static class EarnFreeChipsConfiguration {
private final String code;
private final int chips;
public EarnFreeChipsConfiguration(final String code, final int chips) {
this.code = code;
this.chips = chips;
}
public String getCode() {
return code;
}
public int getChips() {
return chips;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final EarnFreeChipsConfiguration that = (EarnFreeChipsConfiguration) o;
return new EqualsBuilder()
.append(chips, that.chips)
.append(code, that.code)
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder()
.append(chips)
.append(code)
.hashCode();
}
}
public static class FreeChipTicket {
private final String ticket;
public FreeChipTicket(final String ticket) {
this.ticket = ticket;
}
public String getTicket() {
return ticket;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final FreeChipTicket that = (FreeChipTicket) o;
return new EqualsBuilder()
.append(ticket, that.ticket)
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder()
.append(ticket)
.hashCode();
}
}
}
| 13,756 | 0.639067 | 0.638267 | 357 | 37.532211 | 29.159124 | 141 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.62465 | false | false | 3 |
abf969d89eb15ca5d4f7f0e93c9f42465ce0609d | 3,272,765,145,967 | b2a044e8db43463243b333b53898c3baba340a10 | /src/com/denis/command/CommandLogout.java | 1fec20e3892070a230e5df97dc11cb4cb0455c4d | [] | no_license | dvasin/OnlineChat | https://github.com/dvasin/OnlineChat | 0c613d8f8397c7923996dae9bf6178b5f46e4058 | 557398504ec0c2a49ce8bcc352d935e4e13179c9 | refs/heads/master | 2021-01-01T03:54:11.398000 | 2016-05-03T19:52:34 | 2016-05-03T19:52:34 | 57,333,009 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.denis.command;
import com.denis.bean.User;
import com.denis.dao.DAOFactory;
import com.denis.dao.UserDAO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* Created by denis on 29.04.16.
*/
public class CommandLogout implements Command {
@Override
public String execute(HttpServletRequest request) {
HttpSession session = request.getSession();
User user = (User)session.getAttribute("user");
UserDAO userDao = DAOFactory.getInstance().getUserDAO();
userDao.logout(user);
request.getSession().invalidate();
String page = "/index.jsp";
return page;
}
}
| UTF-8 | Java | 679 | java | CommandLogout.java | Java | [
{
"context": "javax.servlet.http.HttpSession;\n\n/**\n * Created by denis on 29.04.16.\n */\npublic class CommandLogout imple",
"end": 229,
"score": 0.9989417195320129,
"start": 224,
"tag": "USERNAME",
"value": "denis"
}
] | null | [] | package com.denis.command;
import com.denis.bean.User;
import com.denis.dao.DAOFactory;
import com.denis.dao.UserDAO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* Created by denis on 29.04.16.
*/
public class CommandLogout implements Command {
@Override
public String execute(HttpServletRequest request) {
HttpSession session = request.getSession();
User user = (User)session.getAttribute("user");
UserDAO userDao = DAOFactory.getInstance().getUserDAO();
userDao.logout(user);
request.getSession().invalidate();
String page = "/index.jsp";
return page;
}
}
| 679 | 0.692194 | 0.683358 | 27 | 24.148148 | 20.563728 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.481481 | false | false | 3 |
cd79852be373dcfd61d1c6b7993a4aa6d110f6f2 | 24,867,860,686,723 | 9185c58e40bcc7d69a11b90af9d43c8826a33b11 | /src/main/java/org/gibello/zql/ZAliasedName.java | 6f24bb723598fb3c04e6ea6182271c11a6082fad | [] | no_license | josemgomez/zql | https://github.com/josemgomez/zql | f2a802a02bd3629f7b8a33e2857d6dcce5c013dc | 3305359c72c5ca7a80add421a98e5b8aebe311ed | refs/heads/master | 2021-01-02T08:32:37.490000 | 2014-02-24T18:10:00 | 2014-02-24T18:10:00 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* This file is part of Zql.
*
* Zql is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Zql is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Zql. If not, see <http://www.gnu.org/licenses/>.
*/
package org.gibello.zql;
import java.util.StringTokenizer;
/**
* A name/alias association<br>
* Names can have two forms:
* <ul>
* <li>FORM_TABLE for table names ([schema.]table)</li>
* <li>FORM_COLUMN for column names ([[schema.]table.]column)</li>
* </ul>
*/
public class ZAliasedName implements java.io.Serializable {
private static final long serialVersionUID = -7797251652151607601L;
private String strform = "";
private String schema = null;
private String table = null;
private String column = null;
private String alias = null;
public static enum Form {
TABLE, COLUMN
}
Form form = Form.COLUMN;
public ZAliasedName() {
}
/**
* Create a new ZAliasedName given it's full name.
*
* @param fullname
* The full name: [[schema.]table.]column
* @param form
* The name form (FORM_TABLE or FORM_COLUMN)
*/
public ZAliasedName(String fullname, Form form) {
this.form = form;
this.strform = fullname;
StringTokenizer st = new StringTokenizer(fullname, ".");
switch (st.countTokens()) {
case 1:
if (form == Form.TABLE) {
table = st.nextToken();
} else {
column = st.nextToken();
}
break;
case 2:
if (form == Form.TABLE) {
schema = st.nextToken();
table = st.nextToken();
} else {
table = st.nextToken();
column = st.nextToken();
}
break;
case 3:
default:
schema = st.nextToken();
table = st.nextToken();
column = st.nextToken();
break;
}
schema = postProcess(schema);
table = postProcess(table);
column = postProcess(column);
}
private String postProcess(final String val) {
if (val == null) {
return null;
}
String ret = val;
if (ret.indexOf('(') >= 0) {
ret = ret.substring(ret.lastIndexOf('(') + 1);
}
if (ret.indexOf(')') >= 0) {
ret = val.substring(0, ret.indexOf(')'));
}
return ret.trim();
}
public String toString() {
if (alias == null) {
return strform;
} else {
return strform + " " + alias;
}
}
/**
* @return If the name is of the form schema.table.column, returns the schema part
*/
public String getSchema() {
return schema;
}
/**
* @return If the name is of the form [schema.]table.column, returns the schema part
*/
public String getTable() {
return table;
}
/**
* @return The name is of the form [[schema.]table.]column: return the column part
*/
public String getColumn() {
return column;
}
protected void setStrform (final String strform) {
this.strform = strform;
}
/**
* @return true if column is "*", false otherwise. Example: *, table.* are wildcards.
*/
public boolean isWildcard() {
if (form == Form.TABLE) {
return table != null && "*".equals(table);
} else {
return column != null && column.indexOf('*') >= 0;
}
}
/**
* @return the alias associated to the current name.
*/
public String getAlias() {
return alias;
}
/**
* Associate an alias with the current name.
*
* @param a
* the alias associated to the current name.
*/
public void setAlias(String a) {
this.alias = a;
}
}
| UTF-8 | Java | 3,748 | java | ZAliasedName.java | Java | [] | null | [] | /*
* This file is part of Zql.
*
* Zql is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Zql is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Zql. If not, see <http://www.gnu.org/licenses/>.
*/
package org.gibello.zql;
import java.util.StringTokenizer;
/**
* A name/alias association<br>
* Names can have two forms:
* <ul>
* <li>FORM_TABLE for table names ([schema.]table)</li>
* <li>FORM_COLUMN for column names ([[schema.]table.]column)</li>
* </ul>
*/
public class ZAliasedName implements java.io.Serializable {
private static final long serialVersionUID = -7797251652151607601L;
private String strform = "";
private String schema = null;
private String table = null;
private String column = null;
private String alias = null;
public static enum Form {
TABLE, COLUMN
}
Form form = Form.COLUMN;
public ZAliasedName() {
}
/**
* Create a new ZAliasedName given it's full name.
*
* @param fullname
* The full name: [[schema.]table.]column
* @param form
* The name form (FORM_TABLE or FORM_COLUMN)
*/
public ZAliasedName(String fullname, Form form) {
this.form = form;
this.strform = fullname;
StringTokenizer st = new StringTokenizer(fullname, ".");
switch (st.countTokens()) {
case 1:
if (form == Form.TABLE) {
table = st.nextToken();
} else {
column = st.nextToken();
}
break;
case 2:
if (form == Form.TABLE) {
schema = st.nextToken();
table = st.nextToken();
} else {
table = st.nextToken();
column = st.nextToken();
}
break;
case 3:
default:
schema = st.nextToken();
table = st.nextToken();
column = st.nextToken();
break;
}
schema = postProcess(schema);
table = postProcess(table);
column = postProcess(column);
}
private String postProcess(final String val) {
if (val == null) {
return null;
}
String ret = val;
if (ret.indexOf('(') >= 0) {
ret = ret.substring(ret.lastIndexOf('(') + 1);
}
if (ret.indexOf(')') >= 0) {
ret = val.substring(0, ret.indexOf(')'));
}
return ret.trim();
}
public String toString() {
if (alias == null) {
return strform;
} else {
return strform + " " + alias;
}
}
/**
* @return If the name is of the form schema.table.column, returns the schema part
*/
public String getSchema() {
return schema;
}
/**
* @return If the name is of the form [schema.]table.column, returns the schema part
*/
public String getTable() {
return table;
}
/**
* @return The name is of the form [[schema.]table.]column: return the column part
*/
public String getColumn() {
return column;
}
protected void setStrform (final String strform) {
this.strform = strform;
}
/**
* @return true if column is "*", false otherwise. Example: *, table.* are wildcards.
*/
public boolean isWildcard() {
if (form == Form.TABLE) {
return table != null && "*".equals(table);
} else {
return column != null && column.indexOf('*') >= 0;
}
}
/**
* @return the alias associated to the current name.
*/
public String getAlias() {
return alias;
}
/**
* Associate an alias with the current name.
*
* @param a
* the alias associated to the current name.
*/
public void setAlias(String a) {
this.alias = a;
}
}
| 3,748 | 0.639541 | 0.63207 | 166 | 21.578314 | 21.877325 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.578313 | false | false | 3 |
b70be355dd0c034c662cb1384d2015349f105aae | 6,725,918,786,447 | 7128ff7ea35d9251324d617472a6767e5bbfe2f6 | /oda-hardware/jdkdio/src/test/java/es/amplia/oda/hardware/jdkdio/ActivatorTest.java | 754ff301f72debfb1e7be9aaf0d2abfa30416099 | [
"Apache-2.0"
] | permissive | amplia-iiot/oda | https://github.com/amplia-iiot/oda | a0cdcf50a6360e9db05f1a04210e7727355eacf6 | 22be33ccbcd672814a873135e3b0d8ba8aeed1b1 | refs/heads/master | 2023-08-24T16:37:41.161000 | 2023-08-22T14:09:25 | 2023-08-22T14:09:25 | 153,408,098 | 2 | 6 | Apache-2.0 | false | 2023-06-20T16:33:56 | 2018-10-17T06:42:57 | 2023-04-03T16:51:26 | 2023-06-20T16:33:52 | 46,771 | 1 | 4 | 15 | Java | false | false | package es.amplia.oda.hardware.jdkdio;
import es.amplia.oda.core.commons.gpio.GpioService;
import es.amplia.oda.core.commons.utils.ConfigurableBundleImpl;
import es.amplia.oda.hardware.jdkdio.configuration.JdkDioConfigurationHandler;
import es.amplia.oda.hardware.jdkdio.gpio.JdkDioGpioService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.internal.util.reflection.Whitebox;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.util.Collections;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(PowerMockRunner.class)
@PrepareForTest(Activator.class)
public class ActivatorTest {
@Mock
private BundleContext mockedContext;
@InjectMocks
private Activator testActivator;
@Mock
private JdkDioGpioService mockedGpioService;
@Mock
private JdkDioConfigurationHandler mockedConfigHandler;
@Mock
private ConfigurableBundleImpl mockedConfigBundle;
@Mock
private ServiceRegistration<GpioService> mockedRegistration;
@Test
public void start() throws Exception {
PowerMockito.whenNew(JdkDioGpioService.class).withAnyArguments().thenReturn(mockedGpioService);
PowerMockito.whenNew(JdkDioConfigurationHandler.class).withAnyArguments().thenReturn(mockedConfigHandler);
PowerMockito.whenNew(ConfigurableBundleImpl.class).withAnyArguments().thenReturn(mockedConfigBundle);
when(mockedContext.registerService(eq(GpioService.class), any(), any())).thenReturn(mockedRegistration);
testActivator.start(mockedContext);
PowerMockito.verifyNew(JdkDioGpioService.class).withNoArguments();
PowerMockito.verifyNew(JdkDioConfigurationHandler.class).withArguments(eq(mockedGpioService));
verify(mockedContext).registerService(eq(GpioService.class), eq(mockedGpioService), any());
PowerMockito.verifyNew(ConfigurableBundleImpl.class).withArguments(eq(mockedContext), eq(mockedConfigHandler),
eq(Collections.singletonList(mockedRegistration)));
}
@Test
public void stop() {
Whitebox.setInternalState(testActivator, "gpioService", mockedGpioService);
Whitebox.setInternalState(testActivator, "configurableBundle", mockedConfigBundle);
Whitebox.setInternalState(testActivator, "gpioServiceRegistration", mockedRegistration);
testActivator.stop(mockedContext);
verify(mockedRegistration).unregister();
verify(mockedConfigBundle).close();
verify(mockedGpioService).release();
}
} | UTF-8 | Java | 2,902 | java | ActivatorTest.java | Java | [] | null | [] | package es.amplia.oda.hardware.jdkdio;
import es.amplia.oda.core.commons.gpio.GpioService;
import es.amplia.oda.core.commons.utils.ConfigurableBundleImpl;
import es.amplia.oda.hardware.jdkdio.configuration.JdkDioConfigurationHandler;
import es.amplia.oda.hardware.jdkdio.gpio.JdkDioGpioService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.internal.util.reflection.Whitebox;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.util.Collections;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(PowerMockRunner.class)
@PrepareForTest(Activator.class)
public class ActivatorTest {
@Mock
private BundleContext mockedContext;
@InjectMocks
private Activator testActivator;
@Mock
private JdkDioGpioService mockedGpioService;
@Mock
private JdkDioConfigurationHandler mockedConfigHandler;
@Mock
private ConfigurableBundleImpl mockedConfigBundle;
@Mock
private ServiceRegistration<GpioService> mockedRegistration;
@Test
public void start() throws Exception {
PowerMockito.whenNew(JdkDioGpioService.class).withAnyArguments().thenReturn(mockedGpioService);
PowerMockito.whenNew(JdkDioConfigurationHandler.class).withAnyArguments().thenReturn(mockedConfigHandler);
PowerMockito.whenNew(ConfigurableBundleImpl.class).withAnyArguments().thenReturn(mockedConfigBundle);
when(mockedContext.registerService(eq(GpioService.class), any(), any())).thenReturn(mockedRegistration);
testActivator.start(mockedContext);
PowerMockito.verifyNew(JdkDioGpioService.class).withNoArguments();
PowerMockito.verifyNew(JdkDioConfigurationHandler.class).withArguments(eq(mockedGpioService));
verify(mockedContext).registerService(eq(GpioService.class), eq(mockedGpioService), any());
PowerMockito.verifyNew(ConfigurableBundleImpl.class).withArguments(eq(mockedContext), eq(mockedConfigHandler),
eq(Collections.singletonList(mockedRegistration)));
}
@Test
public void stop() {
Whitebox.setInternalState(testActivator, "gpioService", mockedGpioService);
Whitebox.setInternalState(testActivator, "configurableBundle", mockedConfigBundle);
Whitebox.setInternalState(testActivator, "gpioServiceRegistration", mockedRegistration);
testActivator.stop(mockedContext);
verify(mockedRegistration).unregister();
verify(mockedConfigBundle).close();
verify(mockedGpioService).release();
}
} | 2,902 | 0.781185 | 0.780841 | 72 | 39.319443 | 33.547573 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 3 |
824e7e24bd058bbaada401e4d8c305dc83da6050 | 36,928,128,819,549 | 2bea4db3fe05242834602d8837a42cde356caed9 | /IamHere/app/src/main/java/com/bobo/iamhere/WebContentActivity.java | 805a7b54fcdab1152ea1f5b6d4c937fe2c431a1f | [] | no_license | Otakar81/android | https://github.com/Otakar81/android | 0da59e4adf543eb0715b3ace053e6a939e75a641 | 400a45295f210fb9b98d0f3e28aba40548babacd | refs/heads/master | 2020-03-21T01:35:20.757000 | 2020-01-30T20:44:17 | 2020-01-30T20:44:17 | 137,362,026 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bobo.iamhere;
import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
public class WebContentActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_content);
Intent intent = getIntent();
String urlEsterno = intent.getStringExtra("url");
String htmlEmbed = intent.getStringExtra("html");
//Inizializzo il webContent e mostro il contenuto della notizia a video
WebView contentNotiziaView = findViewById(R.id.webContentView);
contentNotiziaView.getSettings().setJavaScriptEnabled(true);
contentNotiziaView.setWebChromeClient(new WebChromeClient());
if(urlEsterno != null && urlEsterno.trim().length() > 0) //Url esterno
{
contentNotiziaView.loadUrl(urlEsterno); //Set url
}else{
contentNotiziaView.loadData(htmlEmbed, "text/html", "UTF-8"); //HTML offline da DB
}
}
}
| UTF-8 | Java | 1,162 | java | WebContentActivity.java | Java | [] | null | [] | package com.bobo.iamhere;
import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
public class WebContentActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_content);
Intent intent = getIntent();
String urlEsterno = intent.getStringExtra("url");
String htmlEmbed = intent.getStringExtra("html");
//Inizializzo il webContent e mostro il contenuto della notizia a video
WebView contentNotiziaView = findViewById(R.id.webContentView);
contentNotiziaView.getSettings().setJavaScriptEnabled(true);
contentNotiziaView.setWebChromeClient(new WebChromeClient());
if(urlEsterno != null && urlEsterno.trim().length() > 0) //Url esterno
{
contentNotiziaView.loadUrl(urlEsterno); //Set url
}else{
contentNotiziaView.loadData(htmlEmbed, "text/html", "UTF-8"); //HTML offline da DB
}
}
}
| 1,162 | 0.70568 | 0.703959 | 33 | 34.21212 | 28.714643 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.545455 | false | false | 3 |
dbf71a24aac3eb1ced7b4c93c5886d49ed27c865 | 1,090,921,711,542 | a98fe8c616436080558d9de1fc38b3411736c66c | /manager/src/main/java/cabare/exceptions/EmployeeNotSpecifiedException.java | 4da32631c605ea77b00e18eb8d7c676909992fdf | [] | no_license | andrey-kravchuk/HoReCa | https://github.com/andrey-kravchuk/HoReCa | 37457403febd2f72d9d0887d0530d0c088fbe2ed | 6985c1564fff0e06fdeb7b551771720163c2a6f2 | refs/heads/master | 2020-04-16T10:47:13.547000 | 2018-06-17T16:40:15 | 2018-06-17T16:40:15 | 165,516,843 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cabare.exceptions;
public class EmployeeNotSpecifiedException extends ApplicationException {
private static String msg = "employee is not specified";
public EmployeeNotSpecifiedException() {
super(msg);
}
public EmployeeNotSpecifiedException(String message) {
super(msg + "; " + message);
}
}
| UTF-8 | Java | 323 | java | EmployeeNotSpecifiedException.java | Java | [] | null | [] | package cabare.exceptions;
public class EmployeeNotSpecifiedException extends ApplicationException {
private static String msg = "employee is not specified";
public EmployeeNotSpecifiedException() {
super(msg);
}
public EmployeeNotSpecifiedException(String message) {
super(msg + "; " + message);
}
}
| 323 | 0.743034 | 0.743034 | 14 | 22.071428 | 24.952711 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.357143 | false | false | 3 |
654171a4edf06afe690479902ef872d78ba38f06 | 13,829,794,709,343 | 8ffebb12912b03579975edc6dcf937e94cc6da36 | /src/java/com/sun/mail/dsn/message_deliverystatus.java | 789d8eec4a064795fae25adaae0d8bf7e46bf878 | [] | no_license | ThakurPrajjwal/Minor_Project | https://github.com/ThakurPrajjwal/Minor_Project | 9365ae1b9d7c8314458c582dd733219d421438e3 | b478945be2b5bf7d7715ce97d027bef7316aabad | refs/heads/main | 2023-01-03T00:45:01.040000 | 2020-11-05T07:58:30 | 2020-11-05T07:58:30 | 310,216,217 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Decompiled with CFR 0.0.
*
* Could not load the following classes:
* java.io.IOException
* java.io.InputStream
* java.io.OutputStream
* java.lang.Class
* java.lang.Object
* java.lang.String
* javax.activation.ActivationDataFlavor
* javax.activation.DataContentHandler
* javax.activation.DataSource
* javax.mail.MessagingException
*/
package com.sun.mail.dsn;
import com.sun.mail.dsn.DeliveryStatus;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.activation.ActivationDataFlavor;
import javax.activation.DataContentHandler;
import javax.activation.DataSource;
import javax.mail.MessagingException;
import myjava.awt.datatransfer.DataFlavor;
public class message_deliverystatus
implements DataContentHandler {
ActivationDataFlavor ourDataFlavor = new ActivationDataFlavor(DeliveryStatus.class, "message/delivery-status", "Delivery Status");
public Object getContent(DataSource dataSource) throws IOException {
try {
DeliveryStatus deliveryStatus = new DeliveryStatus(dataSource.getInputStream());
return deliveryStatus;
}
catch (MessagingException messagingException) {
throw new IOException("Exception creating DeliveryStatus in message/devliery-status DataContentHandler: " + messagingException.toString());
}
}
public Object getTransferData(DataFlavor dataFlavor, DataSource dataSource) throws IOException {
if (this.ourDataFlavor.equals(dataFlavor)) {
return this.getContent(dataSource);
}
return null;
}
public DataFlavor[] getTransferDataFlavors() {
DataFlavor[] arrdataFlavor = new DataFlavor[]{this.ourDataFlavor};
return arrdataFlavor;
}
public void writeTo(Object object, String string2, OutputStream outputStream) throws IOException {
if (object instanceof DeliveryStatus) {
DeliveryStatus deliveryStatus = (DeliveryStatus)object;
try {
deliveryStatus.writeTo(outputStream);
return;
}
catch (MessagingException messagingException) {
throw new IOException(messagingException.toString());
}
}
throw new IOException("unsupported object");
}
}
| UTF-8 | Java | 2,325 | java | message_deliverystatus.java | Java | [] | null | [] | /*
* Decompiled with CFR 0.0.
*
* Could not load the following classes:
* java.io.IOException
* java.io.InputStream
* java.io.OutputStream
* java.lang.Class
* java.lang.Object
* java.lang.String
* javax.activation.ActivationDataFlavor
* javax.activation.DataContentHandler
* javax.activation.DataSource
* javax.mail.MessagingException
*/
package com.sun.mail.dsn;
import com.sun.mail.dsn.DeliveryStatus;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.activation.ActivationDataFlavor;
import javax.activation.DataContentHandler;
import javax.activation.DataSource;
import javax.mail.MessagingException;
import myjava.awt.datatransfer.DataFlavor;
public class message_deliverystatus
implements DataContentHandler {
ActivationDataFlavor ourDataFlavor = new ActivationDataFlavor(DeliveryStatus.class, "message/delivery-status", "Delivery Status");
public Object getContent(DataSource dataSource) throws IOException {
try {
DeliveryStatus deliveryStatus = new DeliveryStatus(dataSource.getInputStream());
return deliveryStatus;
}
catch (MessagingException messagingException) {
throw new IOException("Exception creating DeliveryStatus in message/devliery-status DataContentHandler: " + messagingException.toString());
}
}
public Object getTransferData(DataFlavor dataFlavor, DataSource dataSource) throws IOException {
if (this.ourDataFlavor.equals(dataFlavor)) {
return this.getContent(dataSource);
}
return null;
}
public DataFlavor[] getTransferDataFlavors() {
DataFlavor[] arrdataFlavor = new DataFlavor[]{this.ourDataFlavor};
return arrdataFlavor;
}
public void writeTo(Object object, String string2, OutputStream outputStream) throws IOException {
if (object instanceof DeliveryStatus) {
DeliveryStatus deliveryStatus = (DeliveryStatus)object;
try {
deliveryStatus.writeTo(outputStream);
return;
}
catch (MessagingException messagingException) {
throw new IOException(messagingException.toString());
}
}
throw new IOException("unsupported object");
}
}
| 2,325 | 0.706237 | 0.704946 | 67 | 33.686565 | 31.026329 | 151 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.41791 | false | false | 3 |
2760d143bf07da55cafc9a6689c33f9a293553d5 | 17,042,430,245,371 | 2abd1262a4df672143053b9f5dbc422de61b69c5 | /src/GraphSearch.java | cffbee5fadd93c44c82e14d38b8cf40cd4deda3c | [] | no_license | alsenydiallo/Graph_MazeGeneration | https://github.com/alsenydiallo/Graph_MazeGeneration | d7d514bb166e10c154e841b95e61a53d40624538 | 13399fa03bb75840413cce2298aea4bcd70391cd | refs/heads/master | 2021-01-10T13:45:26.405000 | 2016-02-04T23:08:44 | 2016-02-04T23:08:44 | 51,112,198 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.ArrayList;
import java.util.Random;
import java.util.Stack;
public class GraphSearch {
public static int[] mazeDFS(Graph G, int s){
boolean[] visited = new boolean[G.numVerts()];
int[] parent = new int[G.numVerts()];
ArrayList<ArrayList<Integer>> neighbors = new ArrayList<>();
Stack<Integer> stack = new Stack<>();
Random rnd = new Random(1234);
int visitCount = 0;
visited[s] = true;
stack.push(s);
parent[s] = -1;
visitCount = 1;
// create a list of each node with all it neighbors
for(int i=0; i<G.numVerts(); i++)
neighbors.add(G.adjacents(i));
while(visitCount != G.numVerts()){
if(!neighbors.get(s).isEmpty()){
// randomly visit a neighbor
int index = Math.abs(rnd.nextInt() % neighbors.get(s).size());
int w = neighbors.get(s).remove(index); // remove visited neighbors from the list
if(!visited[w]){
visited[w] = true;
visitCount++;
parent[w] = s;
stack.push(w);
s = w;
}
}
else{
s = stack.pop();
}
}
return parent;
}
}
| UTF-8 | Java | 1,112 | java | GraphSearch.java | Java | [] | null | [] | import java.util.ArrayList;
import java.util.Random;
import java.util.Stack;
public class GraphSearch {
public static int[] mazeDFS(Graph G, int s){
boolean[] visited = new boolean[G.numVerts()];
int[] parent = new int[G.numVerts()];
ArrayList<ArrayList<Integer>> neighbors = new ArrayList<>();
Stack<Integer> stack = new Stack<>();
Random rnd = new Random(1234);
int visitCount = 0;
visited[s] = true;
stack.push(s);
parent[s] = -1;
visitCount = 1;
// create a list of each node with all it neighbors
for(int i=0; i<G.numVerts(); i++)
neighbors.add(G.adjacents(i));
while(visitCount != G.numVerts()){
if(!neighbors.get(s).isEmpty()){
// randomly visit a neighbor
int index = Math.abs(rnd.nextInt() % neighbors.get(s).size());
int w = neighbors.get(s).remove(index); // remove visited neighbors from the list
if(!visited[w]){
visited[w] = true;
visitCount++;
parent[w] = s;
stack.push(w);
s = w;
}
}
else{
s = stack.pop();
}
}
return parent;
}
}
| 1,112 | 0.584532 | 0.577338 | 47 | 21.659575 | 19.412956 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.87234 | false | false | 3 |
6e8edbebf9ebaa2e227f35983370ef81402e52f0 | 27,152,783,256,730 | 8de6ad6ee9d79f5227725f687a6a2f769483e294 | /readwrite/WriteAccount.java | d92367b6af9b7f6c9fe563740a1ec6806f800115 | [] | no_license | 14sxlin/lin | https://github.com/14sxlin/lin | 561f30848d5fdb1071c0060199851a3e964ea9f3 | 7e4a21aa74c3f4ed1cef58451b67792a49b61b41 | refs/heads/master | 2015-09-26T01:26:49.341000 | 2015-09-02T08:17:00 | 2015-09-02T08:17:00 | 41,785,808 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package lin.readwrite;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import javax.swing.JOptionPane;
public class WriteAccount {
public PrintWriter out;
/*
* 用完后要记得关闭流
*/
public WriteAccount() {
// TODO Auto-generated constructor stub
out=this.openStream(ResourcePath.ACCOUNTPATH);
}
public PrintWriter openStream(String path)
{
PrintWriter out=null;
try {
File f=new File(path);//这句话并不会新建文件
OutputStream in=new FileOutputStream(f,true);//让文件可以追加内容,而且这句话这里自动新建了一个
out=new PrintWriter(in);
} catch (Exception e) {
// TODO Auto-generated catch block
JOptionPane.showMessageDialog(null, "打开文件或流失败失败\n"+this.getClass().getName());
}
return out;
}
public void writeAccount(PrintWriter out,String name,String password)
{
String str="";
str+="AuthenticateUser="+name+"&"+"AuthenticatePassword="+password+"&shit";
out.append(str+"\r\n");
out.close();
}
public void writeAccount(PrintWriter out,String params)
{
out.append(params+"\r\n");
}
}
| GB18030 | Java | 1,216 | java | WriteAccount.java | Java | [
{
"context": "thenticateUser=\"+name+\"&\"+\"AuthenticatePassword=\"+password+\"&shit\";\r\n\t\tout.append(str+\"\\r\\n\");\r\n\t\tout.close(",
"end": 955,
"score": 0.8334702253341675,
"start": 947,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "User=\"+name+\"&\"+\"Authenti... | null | [] | package lin.readwrite;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import javax.swing.JOptionPane;
public class WriteAccount {
public PrintWriter out;
/*
* 用完后要记得关闭流
*/
public WriteAccount() {
// TODO Auto-generated constructor stub
out=this.openStream(ResourcePath.ACCOUNTPATH);
}
public PrintWriter openStream(String path)
{
PrintWriter out=null;
try {
File f=new File(path);//这句话并不会新建文件
OutputStream in=new FileOutputStream(f,true);//让文件可以追加内容,而且这句话这里自动新建了一个
out=new PrintWriter(in);
} catch (Exception e) {
// TODO Auto-generated catch block
JOptionPane.showMessageDialog(null, "打开文件或流失败失败\n"+this.getClass().getName());
}
return out;
}
public void writeAccount(PrintWriter out,String name,String password)
{
String str="";
str+="AuthenticateUser="+name+"&"+"AuthenticatePassword="+<PASSWORD>+"<PASSWORD>";
out.append(str+"\r\n");
out.close();
}
public void writeAccount(PrintWriter out,String params)
{
out.append(params+"\r\n");
}
}
| 1,223 | 0.689748 | 0.689748 | 46 | 22.173914 | 22.149986 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.782609 | false | false | 3 |
8235f5f8fae834dba7bc8632e42b827156598861 | 16,149,077,054,259 | cfe03deaa418862be7807e9312c571837bc9b758 | /src/main/java/domonx/game/core/entity/containers/NeBoxContainer.java | 360103758981cbd6eef26e06c8e3fd3e4077a2a6 | [] | no_license | DomonX/JavaGameEngine | https://github.com/DomonX/JavaGameEngine | b017bc1b1e7ae5d93c38c58d917ca615ce20e5cb | c2f61e481e8a94e51f176c6bec888ee386ba19ed | refs/heads/master | 2022-04-08T13:20:57.916000 | 2020-04-04T20:45:51 | 2020-04-04T20:45:51 | 247,321,174 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package domonx.game.core.entity.containers;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.image.ImageObserver;
import domonx.game.core.controller.NeController;
import domonx.game.core.entity.NeVisual;
import domonx.game.core.entity.NeVisualEntity;
public class NeBoxContainer<TContent extends NeVisualEntity>
extends NeBaseContainer<TContent> implements NeVisual{
public NeBoxContainer() {
super();
}
public NeBoxContainer(NeController controller) {
super(controller);
}
protected Point getItemPosition(TContent item) {
return new Point(item.getX(), item.getY());
}
@Override
public void tick(int hertzPassed) {
// TODO Auto-generated method stub
}
@Override
protected TContent reloadItem(TContent item) {
// TODO Auto-generated method stub
return item;
}
@Override
public void draw(Graphics g, ImageObserver observer) {
content.forEach(i -> {
i.draw(g, observer);
});
}
@Override
public void load(String srcPath) {
// TODO Auto-generated method stub
}
@Override
public int getCachedWidth() {
// TODO Auto-generated method stub
return getWidth();
}
@Override
public int getCachedHeight() {
// TODO Auto-generated method stub
return getHeight();
}
@Override
public void setScale(double scale) {
// TODO Auto-generated method stub
}
@Override
public double getScale() {
// TODO Auto-generated method stub
return 1;
}
public void setWidth(int width) {
super.setWidth(width);
}
public void setHeight(int height) {
super.setHeight(height);
}
}
| UTF-8 | Java | 1,552 | java | NeBoxContainer.java | Java | [] | null | [] | package domonx.game.core.entity.containers;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.image.ImageObserver;
import domonx.game.core.controller.NeController;
import domonx.game.core.entity.NeVisual;
import domonx.game.core.entity.NeVisualEntity;
public class NeBoxContainer<TContent extends NeVisualEntity>
extends NeBaseContainer<TContent> implements NeVisual{
public NeBoxContainer() {
super();
}
public NeBoxContainer(NeController controller) {
super(controller);
}
protected Point getItemPosition(TContent item) {
return new Point(item.getX(), item.getY());
}
@Override
public void tick(int hertzPassed) {
// TODO Auto-generated method stub
}
@Override
protected TContent reloadItem(TContent item) {
// TODO Auto-generated method stub
return item;
}
@Override
public void draw(Graphics g, ImageObserver observer) {
content.forEach(i -> {
i.draw(g, observer);
});
}
@Override
public void load(String srcPath) {
// TODO Auto-generated method stub
}
@Override
public int getCachedWidth() {
// TODO Auto-generated method stub
return getWidth();
}
@Override
public int getCachedHeight() {
// TODO Auto-generated method stub
return getHeight();
}
@Override
public void setScale(double scale) {
// TODO Auto-generated method stub
}
@Override
public double getScale() {
// TODO Auto-generated method stub
return 1;
}
public void setWidth(int width) {
super.setWidth(width);
}
public void setHeight(int height) {
super.setHeight(height);
}
}
| 1,552 | 0.729381 | 0.728737 | 72 | 20.555555 | 17.700352 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.458333 | false | false | 3 |
ea013fc96ebb5d17e278322fe2cd5ea13703d2ba | 6,940,667,168,910 | 8fd6b90a34ec2be72a3621ad726e1e83c7defe71 | /While_loop2.java | 49a5194549ed76ce22f709e4c7c755266647940f | [] | no_license | Arnav146/PracticePrograms | https://github.com/Arnav146/PracticePrograms | 321c3575293d1796c40f60bf5895048c084d8698 | d75c93eb25afba323e1b46107ff928f385b5243c | refs/heads/main | 2023-02-04T05:45:52.961000 | 2020-12-26T19:08:07 | 2020-12-26T19:08:07 | 324,616,909 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.*;
class While_loop2
{
int a;
void init()
{
Scanner sc=new Scanner(System.in);
a=sc.nextInt();
}
void calc()
{
int n=a,pro=1;
while(n!=0)
{
pro*=n%10;
n=n/10;
}
System.out.println(pro);
}
public static void main()
{
While_loop2 obj=new While_loop2();
obj.init();
obj.calc();
}
} | UTF-8 | Java | 439 | java | While_loop2.java | Java | [] | null | [] | import java.util.*;
class While_loop2
{
int a;
void init()
{
Scanner sc=new Scanner(System.in);
a=sc.nextInt();
}
void calc()
{
int n=a,pro=1;
while(n!=0)
{
pro*=n%10;
n=n/10;
}
System.out.println(pro);
}
public static void main()
{
While_loop2 obj=new While_loop2();
obj.init();
obj.calc();
}
} | 439 | 0.43508 | 0.414579 | 26 | 15.923077 | 11.190391 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.461538 | false | false | 3 |
acf45b39f2817cc06a706a89dbadef1370cbdb35 | 17,514,876,655,040 | 4235d50af4c4aba910fe95f9778d1725c8a77ae7 | /backend/src/main/java/stand/lemonade/models/HistoryModel.java | 40ebf6ad14ca6129f944dc6dcb9b6ba1f0646279 | [] | no_license | MariaCatalina/LemonadeStand | https://github.com/MariaCatalina/LemonadeStand | 19c17a86c91505f635b152ef05d6d150627a822e | 88e1203f03b85bae3ac057e7dc7c7187170819f7 | refs/heads/master | 2016-08-12T17:37:12.095000 | 2016-02-14T14:57:06 | 2016-02-14T14:57:06 | 51,698,741 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package stand.lemonade.models;
import java.util.ArrayList;
import java.util.List;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;
public class HistoryModel {
@NotNull
@NotEmpty
private String walletName;
@NotNull
private List<HistoryWalletModel> data;
public HistoryModel(String walletName) {
this.walletName = walletName;
data = new ArrayList<>();
}
public HistoryModel() {
data = new ArrayList<>();
}
public String getWalletName() {
return walletName;
}
public void setWalletName(String walletName) {
this.walletName = walletName;
}
public List<HistoryWalletModel> getData() {
return data;
}
public void setData(List<HistoryWalletModel> data) {
this.data = data;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
HistoryModel other = (HistoryModel) obj;
if (walletName == null) {
if (other.walletName != null)
return false;
} else if (!walletName.equals(other.walletName))
return false;
return true;
}
@Override
public String toString() {
return "HistoryModel [walletName=" + walletName + ", data=" + data + "]";
}
}
| UTF-8 | Java | 1,263 | java | HistoryModel.java | Java | [] | null | [] | package stand.lemonade.models;
import java.util.ArrayList;
import java.util.List;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;
public class HistoryModel {
@NotNull
@NotEmpty
private String walletName;
@NotNull
private List<HistoryWalletModel> data;
public HistoryModel(String walletName) {
this.walletName = walletName;
data = new ArrayList<>();
}
public HistoryModel() {
data = new ArrayList<>();
}
public String getWalletName() {
return walletName;
}
public void setWalletName(String walletName) {
this.walletName = walletName;
}
public List<HistoryWalletModel> getData() {
return data;
}
public void setData(List<HistoryWalletModel> data) {
this.data = data;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
HistoryModel other = (HistoryModel) obj;
if (walletName == null) {
if (other.walletName != null)
return false;
} else if (!walletName.equals(other.walletName))
return false;
return true;
}
@Override
public String toString() {
return "HistoryModel [walletName=" + walletName + ", data=" + data + "]";
}
}
| 1,263 | 0.699921 | 0.699921 | 66 | 18.136364 | 17.454605 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.439394 | false | false | 3 |
2041e058063d2cd4e4bd7d2f279bafe6fae3c35b | 1,400,159,357,914 | 28da7255b82ea7e73aa5abe0c7e8bfbb169f983d | /src/test/java/moshi/factory/factory/StaticFactory.java | 601f6d691e94702172f60182bf2a8ac832a3a930 | [] | no_license | HouChenggong/thread_test | https://github.com/HouChenggong/thread_test | 85f1446da28528784a0f9c2a464a634d7865c02a | b4a8519af847b2fea9c6e186bfd7614bdfd6c825 | refs/heads/master | 2020-04-18T07:07:45.313000 | 2019-06-21T06:35:20 | 2019-06-21T06:35:20 | 167,349,479 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package moshi.factory.factory;
import moshi.factory.SendMessageInterface;
import moshi.factory.bean.Mail;
import moshi.factory.bean.Phone;
public class StaticFactory {
public static Mail produceMail() {
return new Mail();
}
public static Phone producePhone() {
return new Phone();
}
}
| UTF-8 | Java | 322 | java | StaticFactory.java | Java | [] | null | [] | package moshi.factory.factory;
import moshi.factory.SendMessageInterface;
import moshi.factory.bean.Mail;
import moshi.factory.bean.Phone;
public class StaticFactory {
public static Mail produceMail() {
return new Mail();
}
public static Phone producePhone() {
return new Phone();
}
}
| 322 | 0.695652 | 0.695652 | 17 | 17.941177 | 16.199022 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.352941 | false | false | 3 |
ee3dfa343b07d9f7873e565345eb46bbfefffd7c | 5,703,716,606,759 | 02c690a36c75c9eebe3bed9c280720c6fb7b9f21 | /src/main/java/com/ms/assessment/Service/impl/MCQService.java | 7c5897554dbb76cd2c7e42ee0860f5e32dd169e0 | [] | no_license | NandhiniMB/Assessment-Backend | https://github.com/NandhiniMB/Assessment-Backend | 6ad3f9b49f113ecd79194ca6bd16d6980e93902b | 208497d81d60e97bb326763a37e4d3bbc4313e9b | refs/heads/main | 2023-05-31T14:30:34.240000 | 2021-06-14T06:16:42 | 2021-06-14T06:16:42 | 376,721,533 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ms.assessment.Service.impl;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ms.assessment.Entity.MCQ;
import com.ms.assessment.Entity.Question;
import com.ms.assessment.Repository.IMCQRepository;
import com.ms.assessment.Repository.IQuestionRepository;
import com.ms.assessment.Service.IMCQService;
@Service
public class MCQService implements IMCQService{
@Autowired
IMCQRepository mcqRepository;
@Autowired
IQuestionRepository questionRepository;
@Override
public MCQ saveMCQ(MCQ mcq) {
// TODO Auto-generated method stub
MCQ obj = new MCQ();
obj.setName(mcq.getName());
obj.setCreator(mcq.getCreator());
obj.setCourse(mcq.getCourse());
obj.setCreatedOn(new Date(System.currentTimeMillis()));
return mcqRepository.save(obj);
}
@Override
public List<MCQ> getMCQ() {
// TODO Auto-generated method stub
return mcqRepository.findAll();
}
@Override
public List<Question> findQuestions(int id) {
// TODO Auto-generated method stub
return questionRepository.findAllById(id);
}
@Override
public void deleteMCQ(int id) {
// TODO Auto-generated method stub
mcqRepository.deleteById(id);
}
}
| UTF-8 | Java | 1,274 | java | MCQService.java | Java | [] | null | [] | package com.ms.assessment.Service.impl;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ms.assessment.Entity.MCQ;
import com.ms.assessment.Entity.Question;
import com.ms.assessment.Repository.IMCQRepository;
import com.ms.assessment.Repository.IQuestionRepository;
import com.ms.assessment.Service.IMCQService;
@Service
public class MCQService implements IMCQService{
@Autowired
IMCQRepository mcqRepository;
@Autowired
IQuestionRepository questionRepository;
@Override
public MCQ saveMCQ(MCQ mcq) {
// TODO Auto-generated method stub
MCQ obj = new MCQ();
obj.setName(mcq.getName());
obj.setCreator(mcq.getCreator());
obj.setCourse(mcq.getCourse());
obj.setCreatedOn(new Date(System.currentTimeMillis()));
return mcqRepository.save(obj);
}
@Override
public List<MCQ> getMCQ() {
// TODO Auto-generated method stub
return mcqRepository.findAll();
}
@Override
public List<Question> findQuestions(int id) {
// TODO Auto-generated method stub
return questionRepository.findAllById(id);
}
@Override
public void deleteMCQ(int id) {
// TODO Auto-generated method stub
mcqRepository.deleteById(id);
}
}
| 1,274 | 0.766876 | 0.766876 | 54 | 22.592592 | 18.81146 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.277778 | false | false | 3 |
d472728eb38984f87c1f6619957584d3bfa4493f | 10,548,439,724,883 | 666e6e173c60c92059a0ab7063d17b430c654207 | /Junior/Module3/src/main/java/com/epam/javase03/t03/HtmlParser.java | 2fcb9ef46bd2546844527d284cb7cd766581b36e | [] | no_license | NickolayVasilishin/EPAM | https://github.com/NickolayVasilishin/EPAM | be8009413567feb437645cca46f86355a6bb9221 | 1079be97128f93ef8b6aabee1c0b6686ebf56255 | refs/heads/master | 2021-01-18T22:04:11.133000 | 2017-07-13T18:34:26 | 2017-07-13T18:34:26 | 52,553,805 | 0 | 0 | null | false | 2021-08-11T18:51:27 | 2016-02-25T20:15:17 | 2021-08-11T18:50:00 | 2021-08-11T18:49:57 | 841 | 0 | 0 | 0 | HTML | false | false | package com.epam.javase03.t03;
import java.io.*;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
/**
* Created by Nick on 27.03.2016.
*/
public class HtmlParser {
private long currentLineNumber;
private int currentPicture;
private int currentReference;
private String currentLine;
//// String p1 = "<img.*src=\".*/(pic\\d+)\\.jpg\".*>";
// static String textReferencePattern = "[Рр]ис[\\.а-яА-Я]+\\s(\\d{1,2})";
// static String tagAndPicRefPattern = "<(p|div)>.*[Рр]ис[\\.а-яА-Я]+\\s(\\d{1,2}).*<\\/(?1)>";
//// static String picturePattern =
// static String hasLinePicRef = ".*([Рр]ис[\\.а-яА-Я]+\\s\\d{1,2})+.*";
Pattern linkPattern = Pattern.compile(".*<img.*/pic(\\d+)\\.jpg\".*>.*");
Pattern referencePattern = Pattern.compile(".*[Рр]ис[\\.а-яА-Я]+\\s(\\d{1,2}).*");
Pattern sentencePattern = Pattern.compile("[^.]*[Рр]ис[\\.а-яА-Я]+\\s\\d{1,2}+[^.]*\\.");
Matcher matcher;
public static void main(String[] args) throws IOException {
new HtmlParser().parse("Module3\\src\\main\\resources\\file.html");
}
public void parse(String file) {
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
while((currentLine = reader.readLine()) != null) {
currentLineNumber++;
if(containsLink())
currentPicture = getCurrentPicture();
if(containsReference()) {
currentReference = getReference();
if(currentReference > currentPicture)
System.err.println("Wrong reference at line: " + currentLineNumber +
". Referenced picture " + currentReference +
" while last introduced picture was " + currentPicture);
Stream.of(extractSentences()).forEach(System.out::println);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private boolean containsLink() {
matcher = linkPattern.matcher(currentLine);
return matcher.matches();
}
private boolean containsReference() {
matcher = referencePattern.matcher(currentLine);
return matcher.matches(); }
private int getCurrentPicture() {
return Integer.parseInt(matcher.group(1));
}
private int getReference() {
return Integer.parseInt(matcher.group(1));
}
private List<String> extractSentences() {
List<String> sentences = new LinkedList<>();
matcher = sentencePattern.matcher(currentLine);
while(matcher.find())
sentences.add(matcher.group().replaceAll("</?.{1,5}>", "").replaceAll(" ", ""));
return sentences;
}
}
| UTF-8 | Java | 3,032 | java | HtmlParser.java | Java | [
{
"context": "import java.util.stream.Stream;\n\n/**\n * Created by Nick on 27.03.2016.\n */\npublic class HtmlParser {\n ",
"end": 257,
"score": 0.9905330538749695,
"start": 253,
"tag": "NAME",
"value": "Nick"
}
] | null | [] | package com.epam.javase03.t03;
import java.io.*;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
/**
* Created by Nick on 27.03.2016.
*/
public class HtmlParser {
private long currentLineNumber;
private int currentPicture;
private int currentReference;
private String currentLine;
//// String p1 = "<img.*src=\".*/(pic\\d+)\\.jpg\".*>";
// static String textReferencePattern = "[Рр]ис[\\.а-яА-Я]+\\s(\\d{1,2})";
// static String tagAndPicRefPattern = "<(p|div)>.*[Рр]ис[\\.а-яА-Я]+\\s(\\d{1,2}).*<\\/(?1)>";
//// static String picturePattern =
// static String hasLinePicRef = ".*([Рр]ис[\\.а-яА-Я]+\\s\\d{1,2})+.*";
Pattern linkPattern = Pattern.compile(".*<img.*/pic(\\d+)\\.jpg\".*>.*");
Pattern referencePattern = Pattern.compile(".*[Рр]ис[\\.а-яА-Я]+\\s(\\d{1,2}).*");
Pattern sentencePattern = Pattern.compile("[^.]*[Рр]ис[\\.а-яА-Я]+\\s\\d{1,2}+[^.]*\\.");
Matcher matcher;
public static void main(String[] args) throws IOException {
new HtmlParser().parse("Module3\\src\\main\\resources\\file.html");
}
public void parse(String file) {
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
while((currentLine = reader.readLine()) != null) {
currentLineNumber++;
if(containsLink())
currentPicture = getCurrentPicture();
if(containsReference()) {
currentReference = getReference();
if(currentReference > currentPicture)
System.err.println("Wrong reference at line: " + currentLineNumber +
". Referenced picture " + currentReference +
" while last introduced picture was " + currentPicture);
Stream.of(extractSentences()).forEach(System.out::println);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private boolean containsLink() {
matcher = linkPattern.matcher(currentLine);
return matcher.matches();
}
private boolean containsReference() {
matcher = referencePattern.matcher(currentLine);
return matcher.matches(); }
private int getCurrentPicture() {
return Integer.parseInt(matcher.group(1));
}
private int getReference() {
return Integer.parseInt(matcher.group(1));
}
private List<String> extractSentences() {
List<String> sentences = new LinkedList<>();
matcher = sentencePattern.matcher(currentLine);
while(matcher.find())
sentences.add(matcher.group().replaceAll("</?.{1,5}>", "").replaceAll(" ", ""));
return sentences;
}
}
| 3,032 | 0.582888 | 0.573195 | 84 | 34.619049 | 28.041595 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 3 |
8a6cfec3579147351066e66dcc25324f4f2f41a5 | 16,758,962,425,649 | d46647c33836e2a2f685c51ab65e08f1b05e0351 | /src/main/java/co/com/personas/dtos/PersonaDTO.java | b1bd50c2165e6ac67887283dc8b0ced3f5bf4c3e | [] | no_license | JuanCamilloAce/Personas | https://github.com/JuanCamilloAce/Personas | aeda7b74a0af2ffcde033983dd1ab0d835481906 | 66f82141bba584d68e097b74d789ff1f57792ae2 | refs/heads/master | 2023-06-07T05:15:45.415000 | 2020-04-24T12:31:54 | 2020-04-24T12:31:54 | 258,506,596 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package co.com.personas.dtos;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
*
* @author Jacevedo
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class PersonaDTO implements Serializable {
private String tipoDocumento;
private String documento;
private String primerNombre;
private String segundoNombre;
private String primerApellido;
private String segundoApellido;
}
| UTF-8 | Java | 506 | java | PersonaDTO.java | Java | [
{
"context": "mport java.io.Serializable;\r\n\r\n/**\r\n *\r\n * @author Jacevedo\r\n */\r\n@Data\r\n@AllArgsConstructor\r\n@NoArgsConstruc",
"end": 185,
"score": 0.9134006500244141,
"start": 177,
"tag": "USERNAME",
"value": "Jacevedo"
}
] | null | [] | package co.com.personas.dtos;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
*
* @author Jacevedo
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class PersonaDTO implements Serializable {
private String tipoDocumento;
private String documento;
private String primerNombre;
private String segundoNombre;
private String primerApellido;
private String segundoApellido;
}
| 506 | 0.737154 | 0.737154 | 25 | 18.24 | 15.10041 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.44 | false | false | 3 |
9a5ce6a1cf2490148257952befbbf9d6c77e8ba7 | 21,139,829,061,265 | 82686dfc4dca897b6f54d5d31ec62262e2b7bfb6 | /WEBPJ/src/main/java/webpj/demo/ENTITY/ResourceEntity.java | 2a868951b99be5a539a1b4c303f2986993ee7562 | [] | no_license | cmm1114070674/OnlinePj | https://github.com/cmm1114070674/OnlinePj | eb1492fd4cecce7e9782ee23b329edddf56780c1 | bfd395309f5a057f9582afbb10c0344d098dd8b4 | refs/heads/master | 2022-07-05T11:48:53.941000 | 2019-06-21T04:19:07 | 2019-06-21T04:19:07 | 193,029,381 | 0 | 0 | null | false | 2020-07-01T23:33:01 | 2019-06-21T04:16:13 | 2019-06-21T04:22:55 | 2020-07-01T23:33:00 | 109,905 | 0 | 0 | 1 | Java | false | false | package webpj.demo.ENTITY;
import javax.persistence.*;
import java.sql.Date;
import java.util.Objects;
@Entity
@Table(name = "resource", schema = "onlinepj")
public class ResourceEntity {
private int rid;
private int courseId;
private Date createTime;
private String path;
@Id
@Column(name = "RID")
public int getRid() {
return rid;
}
public void setRid(int rid) {
this.rid = rid;
}
@Basic
@Column(name = "CourseID")
public int getCourseId() {
return courseId;
}
public void setCourseId(int courseId) {
this.courseId = courseId;
}
@Basic
@Column(name = "createtime")
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Basic
@Column(name = "Path")
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ResourceEntity that = (ResourceEntity) o;
return Objects.equals(rid, that.rid) &&
Objects.equals(courseId, that.courseId) &&
Objects.equals(createTime, that.createTime) &&
Objects.equals(path, that.path);
}
@Override
public int hashCode() {
return Objects.hash(rid, courseId, createTime, path);
}
}
| UTF-8 | Java | 1,551 | java | ResourceEntity.java | Java | [] | null | [] | package webpj.demo.ENTITY;
import javax.persistence.*;
import java.sql.Date;
import java.util.Objects;
@Entity
@Table(name = "resource", schema = "onlinepj")
public class ResourceEntity {
private int rid;
private int courseId;
private Date createTime;
private String path;
@Id
@Column(name = "RID")
public int getRid() {
return rid;
}
public void setRid(int rid) {
this.rid = rid;
}
@Basic
@Column(name = "CourseID")
public int getCourseId() {
return courseId;
}
public void setCourseId(int courseId) {
this.courseId = courseId;
}
@Basic
@Column(name = "createtime")
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Basic
@Column(name = "Path")
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ResourceEntity that = (ResourceEntity) o;
return Objects.equals(rid, that.rid) &&
Objects.equals(courseId, that.courseId) &&
Objects.equals(createTime, that.createTime) &&
Objects.equals(path, that.path);
}
@Override
public int hashCode() {
return Objects.hash(rid, courseId, createTime, path);
}
}
| 1,551 | 0.589942 | 0.589942 | 70 | 21.157143 | 17.719751 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.442857 | false | false | 3 |
72d17c21eeae53538f6b641989a9fee54dc410c3 | 14,766,097,580,623 | c188408c9ec0425666250b45734f8b4c9644a946 | /open-sphere-base/core/src/main/java/io/opensphere/core/math/AbstractShape.java | 11fc16750d75b9d4d38e6841ac904f000c5ca5a2 | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | permissive | rkausch/opensphere-desktop | https://github.com/rkausch/opensphere-desktop | ef8067eb03197c758e3af40ebe49e182a450cc02 | c871c4364b3456685411fddd22414fd40ce65699 | refs/heads/snapshot_5.2.7 | 2023-04-13T21:00:00.575000 | 2020-07-29T17:56:10 | 2020-07-29T17:56:10 | 360,594,280 | 0 | 0 | Apache-2.0 | true | 2021-04-22T17:40:38 | 2021-04-22T16:58:41 | 2021-04-22T16:58:42 | 2021-04-22T17:40:38 | 73,289 | 0 | 0 | 1 | null | false | false | package io.opensphere.core.math;
/**
* Abstract base class for shapes.
*/
public abstract class AbstractShape implements Shape
{
/**
* The name of this shape.
*/
private String myName = "AbstractShape";
@Override
public String getName()
{
return myName;
}
/**
* Set the name.
*
* @param name the name to set
*/
public void setName(String name)
{
myName = name;
}
}
| UTF-8 | Java | 484 | java | AbstractShape.java | Java | [] | null | [] | package io.opensphere.core.math;
/**
* Abstract base class for shapes.
*/
public abstract class AbstractShape implements Shape
{
/**
* The name of this shape.
*/
private String myName = "AbstractShape";
@Override
public String getName()
{
return myName;
}
/**
* Set the name.
*
* @param name the name to set
*/
public void setName(String name)
{
myName = name;
}
}
| 484 | 0.530992 | 0.530992 | 28 | 15.285714 | 14.937626 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.142857 | false | false | 3 |
f020fbdd00b72479cd0f3750911cc7412ec9d418 | 2,757,369,045,243 | 8b6b025408deed1d067ff8bd4ef3c536f9c79543 | /validators-soap-message/src/main/java/gov/nist/toolkit/validatorsSoapMessage/message/HttpMessageValidator.java | 96e7c68c211539e5cfd3e69c4748ce5e113fa4ac | [] | no_license | usnistgov/iheos-toolkit2 | https://github.com/usnistgov/iheos-toolkit2 | 96847a78a05ff4e86fb9ed78ab67db9851170f9d | 61b612a7378e1df32f8685ac13f1a14b1bf69002 | refs/heads/master | 2023-08-17T07:16:34.206000 | 2023-06-21T17:02:37 | 2023-06-21T17:02:37 | 61,730,404 | 48 | 29 | null | false | 2023-07-13T23:54:57 | 2016-06-22T15:32:13 | 2023-07-12T03:02:57 | 2023-07-13T23:54:53 | 197,987 | 41 | 26 | 261 | Java | false | false | package gov.nist.toolkit.validatorsSoapMessage.message;
import gov.nist.toolkit.errorrecording.ErrorRecorder;
import gov.nist.toolkit.errorrecording.factories.ErrorRecorderBuilder;
import gov.nist.toolkit.http.HttpParseException;
import gov.nist.toolkit.http.HttpParserBa;
import gov.nist.toolkit.http.ParseException;
import gov.nist.toolkit.installation.shared.TestSession;
import gov.nist.toolkit.valsupport.client.ValidationContext;
import gov.nist.toolkit.valsupport.engine.MessageValidatorEngine;
import gov.nist.toolkit.valsupport.message.AbstractMessageValidator;
import gov.nist.toolkit.valsupport.registry.RegistryValidationInterface;
/**
* Validate HTTP message. Launches either MtomMessageValidator or SimpleSoapHttpHeaderValidator as appropriate.
* @author bill
*
*/
public class HttpMessageValidator extends AbstractMessageValidator {
// Either header and body OR hparser are initialized by the constructor
String header = null;
byte[] body;
HttpParserBa hparser = null;
ErrorRecorderBuilder erBuilder;
MessageValidatorEngine mvc;
RegistryValidationInterface rvi;
TestSession testSession;
public HttpParserBa getHttpParserBa() {
return hparser;
}
public HttpMessageValidator(ValidationContext vc, String header, byte[] body,
ErrorRecorderBuilder erBuilder, MessageValidatorEngine mvc,
RegistryValidationInterface rvi, TestSession testSession) {
super(vc);
this.header = header;
this.body = body;
this.erBuilder = erBuilder;
this.mvc = mvc;
this.rvi = rvi;
this.testSession = testSession;
}
public HttpMessageValidator(ValidationContext vc, HttpParserBa hparser,
ErrorRecorderBuilder erBuilder, MessageValidatorEngine mvc,
RegistryValidationInterface rvi, TestSession testSession) {
super(vc);
this.hparser = hparser;
this.erBuilder = erBuilder;
this.mvc = mvc;
this.rvi = rvi;
this.testSession = testSession;
}
public void run(ErrorRecorder er, MessageValidatorEngine mvc) {
this.er = er;
er.registerValidator(this);
try {
if (mvc == null)
mvc = new MessageValidatorEngine();
er.sectionHeading("HTTP message format validation");
if (!vc.isValid()) {
er.err(vc.getBasicErrorCode(), "Internal Error: Invalid message format: " + vc, this, "");
er.unRegisterValidator(this);
return;
}
if (header != null)
if (vc.isRad55) hparser = new HttpParserBa(header.getBytes(), new String[] {"GET"});
else hparser = new HttpParserBa(header.getBytes()); // since this is an exploratory parse, don't pass er
else
body = hparser.getBody();
hparser.setErrorRecorder(er);
if (hparser.isMultipart()) {
if (vc.requiresSimpleSoap()) {
er.error("", "Message Format", "Multipart", "SIMPLE Format", "ITI TF Volumes 2a and 2b");
} else {
er.success("", "Message format", "Multipart", "Multipart", "ITI TF Volumes 2a and 2b");
}
mvc.addMessageValidator("Validate MTOM", new MtomMessageValidator(vc, hparser, body, erBuilder, mvc, rvi, testSession), erBuilder.buildNewErrorRecorder());
} else {
boolean mt = vc.requiresMtom();
if (mt) {
er.error("", "Message Format", "SIMPLE Format", "Multipart", "ITI TF Volumes 2a and 2b");
} else {
er.success("", "Message format", "SIMPLE Format", "SIMPLE Format", "ITI TF Volumes 2a and 2b");
}
if (!vc.isRad55)
mvc.addMessageValidator("Parse SIMPLE SOAP message", new SimpleSoapHttpHeaderValidator(vc, hparser, body, erBuilder, mvc, rvi, testSession), erBuilder.buildNewErrorRecorder());
}
} catch (HttpParseException e) {
er.err(vc.getBasicErrorCode(), e);
} catch (ParseException e) {
er.err(vc.getBasicErrorCode(), e);
}
finally {
er.unRegisterValidator(this);
}
}
@Override
public boolean isSystemValidator() { return true; }
}
| UTF-8 | Java | 3,975 | java | HttpMessageValidator.java | Java | [
{
"context": "SoapHttpHeaderValidator as appropriate.\n * @author bill\n * \n */\npublic class HttpMessageValidator exten",
"end": 778,
"score": 0.9056366086006165,
"start": 774,
"tag": "NAME",
"value": "bill"
}
] | null | [] | package gov.nist.toolkit.validatorsSoapMessage.message;
import gov.nist.toolkit.errorrecording.ErrorRecorder;
import gov.nist.toolkit.errorrecording.factories.ErrorRecorderBuilder;
import gov.nist.toolkit.http.HttpParseException;
import gov.nist.toolkit.http.HttpParserBa;
import gov.nist.toolkit.http.ParseException;
import gov.nist.toolkit.installation.shared.TestSession;
import gov.nist.toolkit.valsupport.client.ValidationContext;
import gov.nist.toolkit.valsupport.engine.MessageValidatorEngine;
import gov.nist.toolkit.valsupport.message.AbstractMessageValidator;
import gov.nist.toolkit.valsupport.registry.RegistryValidationInterface;
/**
* Validate HTTP message. Launches either MtomMessageValidator or SimpleSoapHttpHeaderValidator as appropriate.
* @author bill
*
*/
public class HttpMessageValidator extends AbstractMessageValidator {
// Either header and body OR hparser are initialized by the constructor
String header = null;
byte[] body;
HttpParserBa hparser = null;
ErrorRecorderBuilder erBuilder;
MessageValidatorEngine mvc;
RegistryValidationInterface rvi;
TestSession testSession;
public HttpParserBa getHttpParserBa() {
return hparser;
}
public HttpMessageValidator(ValidationContext vc, String header, byte[] body,
ErrorRecorderBuilder erBuilder, MessageValidatorEngine mvc,
RegistryValidationInterface rvi, TestSession testSession) {
super(vc);
this.header = header;
this.body = body;
this.erBuilder = erBuilder;
this.mvc = mvc;
this.rvi = rvi;
this.testSession = testSession;
}
public HttpMessageValidator(ValidationContext vc, HttpParserBa hparser,
ErrorRecorderBuilder erBuilder, MessageValidatorEngine mvc,
RegistryValidationInterface rvi, TestSession testSession) {
super(vc);
this.hparser = hparser;
this.erBuilder = erBuilder;
this.mvc = mvc;
this.rvi = rvi;
this.testSession = testSession;
}
public void run(ErrorRecorder er, MessageValidatorEngine mvc) {
this.er = er;
er.registerValidator(this);
try {
if (mvc == null)
mvc = new MessageValidatorEngine();
er.sectionHeading("HTTP message format validation");
if (!vc.isValid()) {
er.err(vc.getBasicErrorCode(), "Internal Error: Invalid message format: " + vc, this, "");
er.unRegisterValidator(this);
return;
}
if (header != null)
if (vc.isRad55) hparser = new HttpParserBa(header.getBytes(), new String[] {"GET"});
else hparser = new HttpParserBa(header.getBytes()); // since this is an exploratory parse, don't pass er
else
body = hparser.getBody();
hparser.setErrorRecorder(er);
if (hparser.isMultipart()) {
if (vc.requiresSimpleSoap()) {
er.error("", "Message Format", "Multipart", "SIMPLE Format", "ITI TF Volumes 2a and 2b");
} else {
er.success("", "Message format", "Multipart", "Multipart", "ITI TF Volumes 2a and 2b");
}
mvc.addMessageValidator("Validate MTOM", new MtomMessageValidator(vc, hparser, body, erBuilder, mvc, rvi, testSession), erBuilder.buildNewErrorRecorder());
} else {
boolean mt = vc.requiresMtom();
if (mt) {
er.error("", "Message Format", "SIMPLE Format", "Multipart", "ITI TF Volumes 2a and 2b");
} else {
er.success("", "Message format", "SIMPLE Format", "SIMPLE Format", "ITI TF Volumes 2a and 2b");
}
if (!vc.isRad55)
mvc.addMessageValidator("Parse SIMPLE SOAP message", new SimpleSoapHttpHeaderValidator(vc, hparser, body, erBuilder, mvc, rvi, testSession), erBuilder.buildNewErrorRecorder());
}
} catch (HttpParseException e) {
er.err(vc.getBasicErrorCode(), e);
} catch (ParseException e) {
er.err(vc.getBasicErrorCode(), e);
}
finally {
er.unRegisterValidator(this);
}
}
@Override
public boolean isSystemValidator() { return true; }
}
| 3,975 | 0.697862 | 0.694843 | 110 | 35.136364 | 35.319447 | 180 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.154546 | false | false | 3 |
3fa1a780564669f952fde136cacf65205cdf6087 | 22,428,319,245,319 | 6d97c6e52a46e38285d861096a90567188a287e1 | /src/main/java/easy/LC257.java | 8fd258ec9a03ac35a054860b67d1894c54fad285 | [] | no_license | liux0054/LCSolution | https://github.com/liux0054/LCSolution | 6839fec24515bcb8cb8b304afdd2c7760ec19b90 | c0a8364e5591d635f60d96e91fe318de4b777316 | refs/heads/master | 2021-09-09T13:20:22.585000 | 2021-09-02T14:35:31 | 2021-09-02T14:35:31 | 143,372,519 | 0 | 0 | null | false | 2021-01-19T12:34:17 | 2018-08-03T03:23:09 | 2020-08-02T08:03:10 | 2021-01-19T12:34:16 | 271 | 0 | 0 | 0 | Java | false | false | package easy;
import java.util.ArrayList;
import java.util.List;
import common.TreeNode;
public class LC257 {
private List<String> answer = new ArrayList<>();
public List<String> binaryTreePaths(TreeNode root) {
if(root == null){
return new ArrayList<>();
}else{
getPath(root, "");
}
return answer;
}
private void getPath(TreeNode root, String pathTillNow){
if(root.left == null && root.right == null){
answer.add(pathTillNow + root.val);
}else{
if(root.left != null){
getPath(root.left, pathTillNow + root.val + "->");
}
if(root.right != null){
getPath(root.right, pathTillNow + root.val + "->");
}
}
}
}
| UTF-8 | Java | 803 | java | LC257.java | Java | [] | null | [] | package easy;
import java.util.ArrayList;
import java.util.List;
import common.TreeNode;
public class LC257 {
private List<String> answer = new ArrayList<>();
public List<String> binaryTreePaths(TreeNode root) {
if(root == null){
return new ArrayList<>();
}else{
getPath(root, "");
}
return answer;
}
private void getPath(TreeNode root, String pathTillNow){
if(root.left == null && root.right == null){
answer.add(pathTillNow + root.val);
}else{
if(root.left != null){
getPath(root.left, pathTillNow + root.val + "->");
}
if(root.right != null){
getPath(root.right, pathTillNow + root.val + "->");
}
}
}
}
| 803 | 0.525529 | 0.521793 | 32 | 24.09375 | 20.641825 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.46875 | false | false | 3 |
f63d3fb9e767e623e25d1f3adde21ded0ede4d38 | 214,748,372,565 | af2b0772556a0ec7e8523754dea22637857a62cc | /src/com/kileyowen/utils/NullUtils.java | 181e29e995a8a9fb193ffb0200dcc0a361b550ba | [] | no_license | yeliknewo/utilities | https://github.com/yeliknewo/utilities | dd9b3b29c2e97eb98d9606a0575d5aba84606b63 | 25aee53662d30ea9777a96fc98ca583585bd0c43 | refs/heads/master | 2021-01-23T13:32:05.056000 | 2017-08-19T00:01:35 | 2017-08-19T00:01:35 | 102,671,265 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.kileyowen.utils;
import org.eclipse.jdt.annotation.Nullable;
import com.kileyowen.exceptions.ExceptionNull;
//TODO Document
public class NullUtils {
// TODO Document
public static final <T> T assertNotNull(final @Nullable T obj) throws ExceptionNull {
// TODO Document
if (obj == null) {
// TODO Document
throw new ExceptionNull();
}
// TODO Document
return obj;
}
}
| UTF-8 | Java | 436 | java | NullUtils.java | Java | [] | null | [] |
package com.kileyowen.utils;
import org.eclipse.jdt.annotation.Nullable;
import com.kileyowen.exceptions.ExceptionNull;
//TODO Document
public class NullUtils {
// TODO Document
public static final <T> T assertNotNull(final @Nullable T obj) throws ExceptionNull {
// TODO Document
if (obj == null) {
// TODO Document
throw new ExceptionNull();
}
// TODO Document
return obj;
}
}
| 436 | 0.662844 | 0.662844 | 26 | 14.692307 | 19.665998 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.923077 | false | false | 3 |
4b00763b36b9230891f3bce4ed87999f797ee16e | 11,201,274,737,802 | 4ddf80e8614fd7305671c19715473d396b7b459b | /app/src/main/java/app/pankaj/googleplacesusingretrofit/interfaces/ConnectionInterface.java | 4444f1886a6cf065b48f717f21e0bef67cce6d7d | [] | no_license | adarshravi/GooglePlacesUsingRetrofit | https://github.com/adarshravi/GooglePlacesUsingRetrofit | 6ae46d7365b75266cc661a588f65e7a158adcbe7 | ecf3a3e55dd9fcd3559e4f87f6c3043226e18816 | refs/heads/master | 2021-04-29T20:12:33.326000 | 2018-02-15T04:58:56 | 2018-02-15T04:58:56 | 121,288,642 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package app.pankaj.googleplacesusingretrofit.interfaces;
import app.pankaj.googleplacesusingretrofit.model.ResponseData;
import retrofit.Call;
import retrofit.Response;
import retrofit.http.GET;
import retrofit.http.Query;
public interface ConnectionInterface {
@GET("api/place/nearbysearch/json?sensor=true&key=AIzaSyDHxSsf1YQlDhyxr9Ho-jKokac2xN_pBxc")
Call<ResponseData> getNearbyPlaces(@Query("type") String type, @Query("location") String location, @Query("radius") int radius);
}
| UTF-8 | Java | 498 | java | ConnectionInterface.java | Java | [
{
"context": "@GET(\"api/place/nearbysearch/json?sensor=true&key=AIzaSyDHxSsf1YQlDhyxr9Ho-jKokac2xN_pBxc\")\n Call<ResponseData> getNearbyPlaces(@Query(\"",
"end": 360,
"score": 0.999550998210907,
"start": 321,
"tag": "KEY",
"value": "AIzaSyDHxSsf1YQlDhyxr9Ho-jKokac2xN_pBxc"
}
] | null | [] | package app.pankaj.googleplacesusingretrofit.interfaces;
import app.pankaj.googleplacesusingretrofit.model.ResponseData;
import retrofit.Call;
import retrofit.Response;
import retrofit.http.GET;
import retrofit.http.Query;
public interface ConnectionInterface {
@GET("api/place/nearbysearch/json?sensor=true&key=<KEY>")
Call<ResponseData> getNearbyPlaces(@Query("type") String type, @Query("location") String location, @Query("radius") int radius);
}
| 464 | 0.803213 | 0.797189 | 15 | 32.200001 | 38.180622 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 3 |
69b4e556b10c3ee5d97fc644c038fb02b7da993f | 29,016,799,068,784 | 3296d9ef714faf53810c6ecf52ee4adc4ae48fbe | /Amdocs_Challenge/src/drive/Program.java | 37b74bd71f61d181a7dcd0bd54b834d80842a563 | [] | no_license | token-cjg/CarClassChallenge | https://github.com/token-cjg/CarClassChallenge | 4db77ebe2c33410543d9939b03bef1497db55f25 | 6bd76ac810468e2013d2338c4917790ec2d45c5b | refs/heads/master | 2021-03-12T21:41:59.370000 | 2015-05-18T10:46:24 | 2015-05-18T10:46:24 | 35,260,271 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package drive;
public class Program {
public static void main(String [] args)
{
Executor executor = new Executor();
executor.ReadInputFile("data/input.txt");
}
}
| UTF-8 | Java | 174 | java | Program.java | Java | [] | null | [] | package drive;
public class Program {
public static void main(String [] args)
{
Executor executor = new Executor();
executor.ReadInputFile("data/input.txt");
}
}
| 174 | 0.689655 | 0.689655 | 11 | 14.818182 | 16.770203 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.090909 | false | false | 3 |
453edc3ee4d8442bf70afca59a281ebd73d699ed | 747,324,354,196 | 5907f5fbef45bcd0da02aa2642c839a6a1fe7398 | /app/src/main/java/com/tnc/wishlist/adapters/WishRecycleViewAdapter.java | 69ad2e440a28b23507967b2606280d1c287ecfb5 | [] | no_license | mubeen-ikram/WishList | https://github.com/mubeen-ikram/WishList | 1cc97311d4c41f62400044faf6486f589bdb8496 | b853b74e77aefd9af174ff93563bee4c3c12ef98 | refs/heads/master | 2020-09-12T10:00:19.114000 | 2019-12-17T03:39:09 | 2019-12-17T03:39:09 | 222,388,344 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tnc.wishlist.adapters;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.tnc.wishlist.ModelClasses.Wishinformation;
import com.tnc.wishlist.R;
import com.tnc.wishlist.activities.ShowWishActivity;
import com.tnc.wishlist.staticClass.DataCentre;
import java.util.ArrayList;
public class WishRecycleViewAdapter extends RecyclerView.Adapter<WishRecycleViewAdapter.MyViewHolder> {
private Context context;
private int resources;
private ArrayList<Wishinformation> wishData;
FirebaseDatabase database;
DatabaseReference myRefrence;
public WishRecycleViewAdapter(Context context, int resources, ArrayList<Wishinformation> wishData) {
this.context = context;
this.resources = resources;
this.wishData = wishData;
database=FirebaseDatabase.getInstance();
myRefrence=database.getReference().child(context.getString(R.string.wishesFirebaseReference));
}
@NonNull
@Override
public WishRecycleViewAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View myview = LayoutInflater.from(parent.getContext()).inflate(resources, parent, false);
return new WishRecycleViewAdapter.MyViewHolder(myview);
}
@Override
public void onBindViewHolder(@NonNull WishRecycleViewAdapter.MyViewHolder holder, int position) {
final Wishinformation wish = wishData.get(position);
holder.accept.setVisibility(View.GONE);
holder.decline.setVisibility(View.GONE);
if(!wish.getCurrentCondition().equals(context.getString(R.string.approved))&&!wish.getCurrentCondition().equals(context.getString(R.string.completed))&&!wish.getCurrentCondition().equals(context.getString(R.string.aproval_complete))){
Integer myInt=Integer.parseInt(wish.getCurrentCondition());
Integer userType=DataCentre.userType;
if(myInt<userType){
holder.accept.setVisibility(View.VISIBLE);
holder.decline.setVisibility(View.VISIBLE);
}
}
if (wishData.get(position).getPhoto() != null)
Glide.with(context).load(wish.getPhoto()).diskCacheStrategy(DiskCacheStrategy.ALL).placeholder(R.drawable.ic_add_item).into(holder.profilePic);
else
holder.profilePic.setVisibility(View.GONE);
holder.tvDate.setText("Date: " + wish.getDate());
holder.tvPrice.setText("Price: " + wish.getPrice());
holder.tvWisher.setText("Wished by : " + wish.getWisherName());
holder.wishName.setText(wish.getName());
holder.accept.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(DataCentre.userType>1) {
wish.setCurrentCondition(context.getString(R.string.approved));
}
else{
wish.setCurrentCondition(String.valueOf(DataCentre.userType));
}
String wisherName=wish.getWisherName();
wish.setWisherName("");
myRefrence.child(wish.getWishId()).setValue(wish);
wish.setWisherName(wisherName);
}
});
holder.decline.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
wish.setCurrentCondition(context.getString(R.string.decline));
String wisherName=wish.getWisherName();
wish.setWisherName("");
myRefrence.child(wish.getWishId()).setValue(wish);
wish.setWisherName(wisherName);
}
});
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
DataCentre.selectedWish=wish;
Intent intent=new Intent(context, ShowWishActivity.class);
context.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return wishData.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView wishName, tvWisher, tvPrice, tvDate;
ImageView profilePic,accept,decline;
LinearLayout linearLayout;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
wishName = itemView.findViewById(R.id.wishCardName);
tvWisher = itemView.findViewById(R.id.wishCardWisher);
tvPrice = itemView.findViewById(R.id.wishCardPrice);
tvDate = itemView.findViewById(R.id.wishCardDate);
profilePic = itemView.findViewById(R.id.wishProfile);
accept=itemView.findViewById(R.id.acceptWish);
decline=itemView.findViewById(R.id.rejectWish);
linearLayout = itemView.findViewById(R.id.wishCardLinearLayout);
}
}
}
| UTF-8 | Java | 5,422 | java | WishRecycleViewAdapter.java | Java | [] | null | [] | package com.tnc.wishlist.adapters;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.tnc.wishlist.ModelClasses.Wishinformation;
import com.tnc.wishlist.R;
import com.tnc.wishlist.activities.ShowWishActivity;
import com.tnc.wishlist.staticClass.DataCentre;
import java.util.ArrayList;
public class WishRecycleViewAdapter extends RecyclerView.Adapter<WishRecycleViewAdapter.MyViewHolder> {
private Context context;
private int resources;
private ArrayList<Wishinformation> wishData;
FirebaseDatabase database;
DatabaseReference myRefrence;
public WishRecycleViewAdapter(Context context, int resources, ArrayList<Wishinformation> wishData) {
this.context = context;
this.resources = resources;
this.wishData = wishData;
database=FirebaseDatabase.getInstance();
myRefrence=database.getReference().child(context.getString(R.string.wishesFirebaseReference));
}
@NonNull
@Override
public WishRecycleViewAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View myview = LayoutInflater.from(parent.getContext()).inflate(resources, parent, false);
return new WishRecycleViewAdapter.MyViewHolder(myview);
}
@Override
public void onBindViewHolder(@NonNull WishRecycleViewAdapter.MyViewHolder holder, int position) {
final Wishinformation wish = wishData.get(position);
holder.accept.setVisibility(View.GONE);
holder.decline.setVisibility(View.GONE);
if(!wish.getCurrentCondition().equals(context.getString(R.string.approved))&&!wish.getCurrentCondition().equals(context.getString(R.string.completed))&&!wish.getCurrentCondition().equals(context.getString(R.string.aproval_complete))){
Integer myInt=Integer.parseInt(wish.getCurrentCondition());
Integer userType=DataCentre.userType;
if(myInt<userType){
holder.accept.setVisibility(View.VISIBLE);
holder.decline.setVisibility(View.VISIBLE);
}
}
if (wishData.get(position).getPhoto() != null)
Glide.with(context).load(wish.getPhoto()).diskCacheStrategy(DiskCacheStrategy.ALL).placeholder(R.drawable.ic_add_item).into(holder.profilePic);
else
holder.profilePic.setVisibility(View.GONE);
holder.tvDate.setText("Date: " + wish.getDate());
holder.tvPrice.setText("Price: " + wish.getPrice());
holder.tvWisher.setText("Wished by : " + wish.getWisherName());
holder.wishName.setText(wish.getName());
holder.accept.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(DataCentre.userType>1) {
wish.setCurrentCondition(context.getString(R.string.approved));
}
else{
wish.setCurrentCondition(String.valueOf(DataCentre.userType));
}
String wisherName=wish.getWisherName();
wish.setWisherName("");
myRefrence.child(wish.getWishId()).setValue(wish);
wish.setWisherName(wisherName);
}
});
holder.decline.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
wish.setCurrentCondition(context.getString(R.string.decline));
String wisherName=wish.getWisherName();
wish.setWisherName("");
myRefrence.child(wish.getWishId()).setValue(wish);
wish.setWisherName(wisherName);
}
});
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
DataCentre.selectedWish=wish;
Intent intent=new Intent(context, ShowWishActivity.class);
context.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return wishData.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView wishName, tvWisher, tvPrice, tvDate;
ImageView profilePic,accept,decline;
LinearLayout linearLayout;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
wishName = itemView.findViewById(R.id.wishCardName);
tvWisher = itemView.findViewById(R.id.wishCardWisher);
tvPrice = itemView.findViewById(R.id.wishCardPrice);
tvDate = itemView.findViewById(R.id.wishCardDate);
profilePic = itemView.findViewById(R.id.wishProfile);
accept=itemView.findViewById(R.id.acceptWish);
decline=itemView.findViewById(R.id.rejectWish);
linearLayout = itemView.findViewById(R.id.wishCardLinearLayout);
}
}
}
| 5,422 | 0.675028 | 0.674843 | 128 | 41.359375 | 33.624008 | 242 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.679688 | false | false | 3 |
889b60d40aeb50aae1e168d1712ac74fbfddd958 | 30,176,440,278,974 | e0336ed8fc8599ccc2a2ec9db75b71b2c69b6f78 | /Snapdeal-es-gateway/src/main/java/com/hc/es/core/utils/FieldInfo.java | 8a55c5b3dee08497c26f7ecfbaa393be5747cef3 | [] | no_license | harish840/hackarthon_mailer | https://github.com/harish840/hackarthon_mailer | 5f1cd260019576c9a46c6f60be15dea4f27c7c9f | 1572927fd07d8e51f75c7ef93c0d90ab596e69ef | refs/heads/master | 2021-01-01T18:03:12.445000 | 2015-09-04T20:19:48 | 2015-09-04T20:19:48 | 41,779,116 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.hc.es.core.utils;
/**
*
* @author root
*/
public class FieldInfo {
String name;
String type;
String analyser;
/**
* @param name field info name
* @param type type
* @param analyser analyser
*/
public FieldInfo(String name, String type, String analyser) {
this.name = name;
this.type = type;
this.analyser = analyser;
}
/**
* @return String name of field
*/
public String getName() {
return name;
}
/**
* @return String type of field
*/
public String getType() {
return type;
}
/**
* @return String analyser for field
*/
public String getAnalyser() {
return analyser;
}
}
| UTF-8 | Java | 944 | java | FieldInfo.java | Java | [
{
"context": "/\npackage com.hc.es.core.utils;\n\n/**\n *\n * @author root\n */\npublic class FieldInfo {\n String name;\n ",
"end": 238,
"score": 0.9986903667449951,
"start": 234,
"tag": "USERNAME",
"value": "root"
}
] | null | [] | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.hc.es.core.utils;
/**
*
* @author root
*/
public class FieldInfo {
String name;
String type;
String analyser;
/**
* @param name field info name
* @param type type
* @param analyser analyser
*/
public FieldInfo(String name, String type, String analyser) {
this.name = name;
this.type = type;
this.analyser = analyser;
}
/**
* @return String name of field
*/
public String getName() {
return name;
}
/**
* @return String type of field
*/
public String getType() {
return type;
}
/**
* @return String analyser for field
*/
public String getAnalyser() {
return analyser;
}
}
| 944 | 0.574153 | 0.574153 | 50 | 17.879999 | 17.63365 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3 | false | false | 3 |
5d70598ea759a97bc29ac8714d7f02d92a26138f | 15,187,004,421,719 | c58e0ffe3c491be6152b7fb923bc3a418e93a43c | /src/com/tyl/activity/UsersListActivity.java | 3f8904fb1c6847e89fb44d11cc9cc19c9a2fb314 | [
"Apache-2.0"
] | permissive | tianyl1984/androidApp | https://github.com/tianyl1984/androidApp | e1fdf97437597ea602e6ba987417488506fe3e4c | 6e702052f6fc7d48a8021ac88ccf69beb3ecfccb | refs/heads/master | 2021-01-12T00:38:27.633000 | 2015-02-15T15:13:02 | 2015-02-15T15:13:02 | 78,750,695 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tyl.activity;
import java.util.ArrayList;
import java.util.List;
import com.tyl.R;
import com.tyl.R.id;
import com.tyl.R.layout;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class UsersListActivity extends ListActivity {
TextView userNameView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_list);
userNameView = (TextView) findViewById(R.id.userNameView);
List<String> users = new ArrayList<String>();
users.add("aaa");
users.add("bbb");
users.add("ccc");
users.add("ddd");
Log.v("aaa", "asdf");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_row, users);
this.setListAdapter(adapter);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
userNameView.setText(l.getItemAtPosition(position).toString());
}
}
| UTF-8 | Java | 1,122 | java | UsersListActivity.java | Java | [] | null | [] | package com.tyl.activity;
import java.util.ArrayList;
import java.util.List;
import com.tyl.R;
import com.tyl.R.id;
import com.tyl.R.layout;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class UsersListActivity extends ListActivity {
TextView userNameView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_list);
userNameView = (TextView) findViewById(R.id.userNameView);
List<String> users = new ArrayList<String>();
users.add("aaa");
users.add("bbb");
users.add("ccc");
users.add("ddd");
Log.v("aaa", "asdf");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_row, users);
this.setListAdapter(adapter);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
userNameView.setText(l.getItemAtPosition(position).toString());
}
}
| 1,122 | 0.753119 | 0.753119 | 44 | 24.5 | 21.618069 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.568182 | false | false | 3 |
0376a5eb03c644a13f901009fc07b0845f18ccce | 5,145,370,825,957 | 3f15be400a4758e1b18cbb17fbde4cf460fdccf5 | /iSoccer/src/Person.java | afdc5d93fcde2aa235c4fcc0804d9fc96da8a1bd | [] | no_license | soficastro/REAViSoccer | https://github.com/soficastro/REAViSoccer | 7504fa396dea1cb27567f3cb314fe337b6a5467b | 083e94e0dc65f2c03aa681a5530ab6e7384c4846 | refs/heads/master | 2020-05-07T20:40:46.502000 | 2019-04-17T05:16:05 | 2019-04-17T05:16:05 | 180,872,046 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class Person {
private String name;
private String email;
private String cpf;
private String telephone;
public Person(PersonBuilder builder) {
this.name = builder.name;
this.email = builder.email;
this.cpf = builder.cpf;
this.telephone = builder.telephone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
@Override
public String toString() {
return "Name: " + name + "; Email: " + email + "; Cpf: " + cpf + "; Telephone: " + telephone + "\n";
}
public static class PersonBuilder {
private String name, email, cpf, telephone;
public PersonBuilder(){
}
public PersonBuilder setName(String name) {
this.name = name;
return this;
}
public PersonBuilder setEmail(String email) {
this.email = email;
return this;
}
public PersonBuilder setCpf(String cpf) {
this.cpf = cpf;
return this;
}
public PersonBuilder setTelephone(String telephone) {
this.telephone = telephone;
return this;
}
public Person build() {
return new Person(this);
}
}
}
| UTF-8 | Java | 1,835 | java | Person.java | Java | [] | null | [] | public class Person {
private String name;
private String email;
private String cpf;
private String telephone;
public Person(PersonBuilder builder) {
this.name = builder.name;
this.email = builder.email;
this.cpf = builder.cpf;
this.telephone = builder.telephone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
@Override
public String toString() {
return "Name: " + name + "; Email: " + email + "; Cpf: " + cpf + "; Telephone: " + telephone + "\n";
}
public static class PersonBuilder {
private String name, email, cpf, telephone;
public PersonBuilder(){
}
public PersonBuilder setName(String name) {
this.name = name;
return this;
}
public PersonBuilder setEmail(String email) {
this.email = email;
return this;
}
public PersonBuilder setCpf(String cpf) {
this.cpf = cpf;
return this;
}
public PersonBuilder setTelephone(String telephone) {
this.telephone = telephone;
return this;
}
public Person build() {
return new Person(this);
}
}
}
| 1,835 | 0.522071 | 0.522071 | 83 | 20.108435 | 19.113493 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.39759 | false | false | 3 |
5ffae3da2a288ff12e53f875d77a0442c56f78d0 | 23,459,111,414,899 | 1549df057e1a3e55e484cc711a43fba551d0a6ff | /ProyectoPOO/test/proyectopoo/RolesTest.java | e5c59d9dab9c03f5897583f21c192d66a79231c8 | [] | no_license | Walterfuentes/UPC-TrabajoFinal-2012-2-M2 | https://github.com/Walterfuentes/UPC-TrabajoFinal-2012-2-M2 | 79ddd8caad3787275bcbffa9ba94cd6a8d075ca4 | 839cb14c67ea2a896919ca4daa497849c874c74d | refs/heads/master | 2021-01-20T21:32:26.485000 | 2012-12-06T19:19:12 | 2012-12-06T19:19:12 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Historia de Usuario: Roles Test
* Desarrollado: Carlos Ricaldi
*/
package proyectopoo;
import org.junit.Test;
import static org.junit.Assert.*;
public class RolesTest {
public RolesTest() {
}
@Test
public void rolesDebeCrearseConNombreYDescripcion(){
String nombre = "Administrador";
String descripcion = "Role asignado al Administrador";
Roles rol = new Roles(nombre, descripcion);
assertNotNull(rol);
assertEquals(nombre, rol.getNombre());
assertEquals(descripcion, rol.getDescripcion());
}
@Test
public void rolesDebeCrearseConModuloYAutorizacion(){
String modulo = "Compras";
boolean acceso = true;
boolean adicionar = true;
boolean editar = true;
boolean eliminar = true;
Roles rol = new Roles(modulo,acceso,adicionar,editar,eliminar);
assertNotNull(rol);
assertEquals(modulo, rol.getModulo());
assertTrue("SI tiene permiso para acceder", rol.isAcceso());
assertTrue("SI tiene permiso para adicionar", rol.isAdicionar());
assertTrue("SI tiene permiso para editar", rol.isEditar());
assertTrue("SI tiene permiso para eliminar", rol.isEliminar());
}
@Test
public void rolesDebeEditarNombreYDescripcion(){
String nombre = "Admin";
String descripcion = "Role asignado al Administrador";
Roles rol = new Roles(nombre, descripcion);
assertNotNull(rol);
assertEquals(nombre, rol.getNombre());
assertEquals(descripcion, rol.getDescripcion());
}
@Test
public void rolesDebeEditarModuloYAutorizacion(){
String modulo = "Compras";
boolean acceso = true;
boolean adicionar = true;
boolean editar = true;
boolean eliminar = true;
Roles rol = new Roles(modulo, acceso, adicionar, editar, eliminar);
assertNotNull(rol);
assertEquals(modulo,rol.getModulo());
assertTrue("SI tiene permiso para acceder", rol.isAcceso());
assertTrue("SI tiene permiso para adicionar", rol.isAdicionar());
assertTrue("SI tiene permiso para editar", rol.isEditar());
assertTrue("SI tiene permiso para eliminar", rol.isEliminar());
}
}
| UTF-8 | Java | 2,432 | java | RolesTest.java | Java | [
{
"context": " Historia de Usuario: Roles Test\r\n * Desarrollado: Carlos Ricaldi\r\n */\r\npackage proyectopoo;\r\n\r\nimport org.junit.Te",
"end": 71,
"score": 0.9998893737792969,
"start": 57,
"tag": "NAME",
"value": "Carlos Ricaldi"
}
] | null | [] | /*
* Historia de Usuario: Roles Test
* Desarrollado: <NAME>
*/
package proyectopoo;
import org.junit.Test;
import static org.junit.Assert.*;
public class RolesTest {
public RolesTest() {
}
@Test
public void rolesDebeCrearseConNombreYDescripcion(){
String nombre = "Administrador";
String descripcion = "Role asignado al Administrador";
Roles rol = new Roles(nombre, descripcion);
assertNotNull(rol);
assertEquals(nombre, rol.getNombre());
assertEquals(descripcion, rol.getDescripcion());
}
@Test
public void rolesDebeCrearseConModuloYAutorizacion(){
String modulo = "Compras";
boolean acceso = true;
boolean adicionar = true;
boolean editar = true;
boolean eliminar = true;
Roles rol = new Roles(modulo,acceso,adicionar,editar,eliminar);
assertNotNull(rol);
assertEquals(modulo, rol.getModulo());
assertTrue("SI tiene permiso para acceder", rol.isAcceso());
assertTrue("SI tiene permiso para adicionar", rol.isAdicionar());
assertTrue("SI tiene permiso para editar", rol.isEditar());
assertTrue("SI tiene permiso para eliminar", rol.isEliminar());
}
@Test
public void rolesDebeEditarNombreYDescripcion(){
String nombre = "Admin";
String descripcion = "Role asignado al Administrador";
Roles rol = new Roles(nombre, descripcion);
assertNotNull(rol);
assertEquals(nombre, rol.getNombre());
assertEquals(descripcion, rol.getDescripcion());
}
@Test
public void rolesDebeEditarModuloYAutorizacion(){
String modulo = "Compras";
boolean acceso = true;
boolean adicionar = true;
boolean editar = true;
boolean eliminar = true;
Roles rol = new Roles(modulo, acceso, adicionar, editar, eliminar);
assertNotNull(rol);
assertEquals(modulo,rol.getModulo());
assertTrue("SI tiene permiso para acceder", rol.isAcceso());
assertTrue("SI tiene permiso para adicionar", rol.isAdicionar());
assertTrue("SI tiene permiso para editar", rol.isEditar());
assertTrue("SI tiene permiso para eliminar", rol.isEliminar());
}
}
| 2,424 | 0.606086 | 0.606086 | 76 | 30 | 23.689327 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.828947 | false | false | 3 |
58fcc7c52c9035c9013b30a510e82df97aea791e | 29,343,216,625,099 | 844d104491600578c6ce668aa325f80f76e7c53e | /Unalbum/src/main/java/com/mwh/album/model/PictureTag.java | cafcdfd51d9329ff0c230f78d4b670f9af815d5f | [] | no_license | timeliving/Unalbum | https://github.com/timeliving/Unalbum | d634e0bbaec954bd7dae1588722f2acf4c0597e0 | 19ce2df53b509b4f2f94734b4453b53d8a61587c | refs/heads/master | 2021-09-11T13:52:42.211000 | 2018-04-08T09:30:18 | 2018-04-08T09:30:18 | 125,140,698 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mwh.album.model;
import java.util.Date;
public class PictureTag implements java.io.Serializable{
/**
* 序列化值
*/
private static final long serialVersionUID = -4115672886748923337L;
private Integer id;
private Integer tagId;
private Integer pictureId;
private Date createDate;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getTagId() {
return tagId;
}
public void setTagId(Integer tagId) {
this.tagId = tagId;
}
public Integer getPictureId() {
return pictureId;
}
public void setPictureId(Integer pictureId) {
this.pictureId = pictureId;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
}
| UTF-8 | Java | 916 | java | PictureTag.java | Java | [] | null | [] | package com.mwh.album.model;
import java.util.Date;
public class PictureTag implements java.io.Serializable{
/**
* 序列化值
*/
private static final long serialVersionUID = -4115672886748923337L;
private Integer id;
private Integer tagId;
private Integer pictureId;
private Date createDate;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getTagId() {
return tagId;
}
public void setTagId(Integer tagId) {
this.tagId = tagId;
}
public Integer getPictureId() {
return pictureId;
}
public void setPictureId(Integer pictureId) {
this.pictureId = pictureId;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
}
| 916 | 0.622247 | 0.601322 | 48 | 17.916666 | 17.586493 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3125 | false | false | 3 |
193053ee2a87a613d40a4df8539821d27f241183 | 23,794,118,864,210 | 7780422ea62de5e5e91d75cd14344de1fbfe451a | /pluginloader/src/main/java/com/mchenys/pluginloader/core/hook/IAndroidHook.java | 769d8dbe802ab5f562b2d25605e9e2908cfd75e0 | [] | no_license | mChenys/MyDynamicLoaderHook | https://github.com/mChenys/MyDynamicLoaderHook | e3dee58da9ef082a3875d0925a3e797ff4be1374 | b3653d51d7f61e4a61d57cfec05cecef63f9f6d5 | refs/heads/master | 2023-04-30T19:39:07.917000 | 2021-05-16T14:15:13 | 2021-05-16T14:15:13 | 365,275,601 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mchenys.pluginloader.core.hook;
import android.app.Application;
import android.os.Handler;
/**
* @Author: mChenys
* @Date: 2021/5/12
* @Description:
*/
public interface IAndroidHook extends Handler.Callback {
void hookAms(Application application) throws Exception;
void hookActivityThread(Application application) throws Exception;
}
| UTF-8 | Java | 362 | java | IAndroidHook.java | Java | [
{
"context": "ation;\nimport android.os.Handler;\n\n/**\n * @Author: mChenys\n * @Date: 2021/5/12\n * @Description:\n */\npublic i",
"end": 128,
"score": 0.9996463656425476,
"start": 121,
"tag": "USERNAME",
"value": "mChenys"
}
] | null | [] | package com.mchenys.pluginloader.core.hook;
import android.app.Application;
import android.os.Handler;
/**
* @Author: mChenys
* @Date: 2021/5/12
* @Description:
*/
public interface IAndroidHook extends Handler.Callback {
void hookAms(Application application) throws Exception;
void hookActivityThread(Application application) throws Exception;
}
| 362 | 0.765193 | 0.745856 | 16 | 21.625 | 23.072914 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3125 | false | false | 3 |
59395f8fbdb15aeb38d528ed1243176a181d62d1 | 15,796,889,753,689 | e1e640758ecf0134551fa4ebde3440d3a11b1431 | /src/com/aaa/db/DBAccess.java | 8e16426bc4c57d1e392b024f92f0578e6b5445e8 | [] | no_license | Alexygui/MicroMessage | https://github.com/Alexygui/MicroMessage | 1e959af3d6da880c62693b88806e440b5113fbcc | 967f7073ca916433c3978db0d58056169ad41cbb | refs/heads/master | 2021-01-20T20:32:49.028000 | 2016-08-08T13:33:38 | 2016-08-08T13:33:38 | 64,918,389 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.aaa.db;
import java.io.IOException;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
/**
* 访问数据库类
*/
public class DBAccess {
public SqlSession getSqlSession() throws IOException {
//通过配置文件获取数据库连接信息
Reader reader = Resources.getResourceAsReader("com/aaa/config/Configuration.xml");
//通过配置信息构建一个SqlSessionFactory
SqlSessionFactory aSqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
//通过SqlSessionFactory打开一个数据库会话
SqlSession aSqlSession = aSqlSessionFactory.openSession();
return aSqlSession;
}
}
| UTF-8 | Java | 796 | java | DBAccess.java | Java | [] | null | [] | package com.aaa.db;
import java.io.IOException;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
/**
* 访问数据库类
*/
public class DBAccess {
public SqlSession getSqlSession() throws IOException {
//通过配置文件获取数据库连接信息
Reader reader = Resources.getResourceAsReader("com/aaa/config/Configuration.xml");
//通过配置信息构建一个SqlSessionFactory
SqlSessionFactory aSqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
//通过SqlSessionFactory打开一个数据库会话
SqlSession aSqlSession = aSqlSessionFactory.openSession();
return aSqlSession;
}
}
| 796 | 0.803371 | 0.803371 | 24 | 28.666666 | 25.571251 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.125 | false | false | 3 |
22f208822245ad307a100ff849133b23d2856d0d | 3,427,383,919,344 | 27457a770a64531d75091410bb07353e435707e6 | /java/pgm12_01.java | a4390650c6ede4c99663d54252a2809f03710c11 | [] | no_license | boyddensmore/source-data-structures-and-algorithms-with-oop | https://github.com/boyddensmore/source-data-structures-and-algorithms-with-oop | fc331f1504b3acb26a73ea23f37d0148cf845b50 | 7a06d2459761190cd3011206653ade8f01916070 | refs/heads/master | 2020-12-25T22:28:37.607000 | 2014-01-31T17:42:38 | 2014-01-31T17:42:38 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | //
// This file contains the Java code from Program 12.1 of
// "Data Structures and Algorithms
// with Object-Oriented Design Patterns in Java"
// by Bruno R. Preiss.
//
// Copyright (c) 1998 by Bruno R. Preiss, P.Eng. All rights reserved.
//
// http://www.pads.uwaterloo.ca/Bruno.Preiss/books/opus5/programs/pgm12_01.txt
//
public interface Set
extends SearchableContainer
{
Set union (Set set);
Set intersection (Set set);
Set difference (Set set);
boolean isEQ (Set set);
boolean isSubset (Set set);
}
| UTF-8 | Java | 543 | java | pgm12_01.java | Java | [
{
"context": "h Object-Oriented Design Patterns in Java\"\n// by Bruno R. Preiss.\n//\n// Copyright (c) 1998 by Bruno R. Preiss, P",
"end": 174,
"score": 0.9998937845230103,
"start": 159,
"tag": "NAME",
"value": "Bruno R. Preiss"
},
{
"context": " by Bruno R. Preiss.\n//\n// Co... | null | [] | //
// This file contains the Java code from Program 12.1 of
// "Data Structures and Algorithms
// with Object-Oriented Design Patterns in Java"
// by <NAME>.
//
// Copyright (c) 1998 by <NAME>, P.Eng. All rights reserved.
//
// http://www.pads.uwaterloo.ca/Bruno.Preiss/books/opus5/programs/pgm12_01.txt
//
public interface Set
extends SearchableContainer
{
Set union (Set set);
Set intersection (Set set);
Set difference (Set set);
boolean isEQ (Set set);
boolean isSubset (Set set);
}
| 525 | 0.677716 | 0.655617 | 19 | 27.578947 | 23.414606 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.315789 | false | false | 3 |
e98b727233da671efee0fa7f998bc87368601b16 | 11,295,764,049,706 | 929b9153efcb8e9865f0a92db0113b65fc9e63b7 | /emailSender/src/main/java/com/przemo/emailsender/emailSenders/ScheduledEmails.java | 960168ddd10d5b027a1d1969c5d4f77803108771 | [] | no_license | przemekwoj/RentCarRest | https://github.com/przemekwoj/RentCarRest | 95619cc74007d60a0ddd0e4342188995544d664c | 03fe696c43b0dd93a6c4b490e07de36102f0dfff | refs/heads/master | 2023-01-08T13:43:16.965000 | 2020-04-13T15:08:46 | 2020-04-13T15:08:46 | 196,867,037 | 0 | 0 | null | false | 2023-01-07T09:34:56 | 2019-07-14T17:51:22 | 2020-04-13T15:09:00 | 2023-01-07T09:34:56 | 5,290 | 0 | 0 | 28 | Java | false | false | package com.przemo.emailsender.emailSenders;
import com.przemo.emailsender.consumerWrapper.ConsumerWrapper;
import com.przemo.emailsender.models.Email;
import com.przemo.emailsender.repositories.queries.ClientQueries;
import com.przemo.emailsender.reveivers.QueueType;
import com.przemo.emailsender.reveivers.ReceiversService;
import com.przemo.emailsender.reveivers.ReceiversServiceImpl;
import com.przemo.emailsender.services.ClientService;
import com.przemo.emailsender.services.EmailService;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@Service
public class ScheduledEmails implements Job {
@Autowired
private EmailService emailService;
@Autowired
private ReceiversService receiversService;
@Override
public void execute(JobExecutionContext jobExecutionContext) {
sendDetainedEmailInformation();
}
private void sendDetainedEmailInformation() {
ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
sendEmailsPartially(executorService);
}
private void sendEmailsPartially(ExecutorService executorService) {
for (int index = 0; index < receiversService.amountOfBatchFetch(QueueType.DETAINED_ORDER); index++) {
CompletableFuture<List<String>> partOrEmails = getPartOfEmails(QueueType.DETAINED_ORDER, index, executorService);
partOrEmails.thenAcceptAsync(receivers -> sendEmailToReceivers(receivers));
}
}
private void sendEmailToReceivers(List<String> receivers) {
receivers.forEach(ConsumerWrapper.throwingConsumerWrapper(receiver ->
emailService.sendEmail(receiver, "Detained", "Your Order is detained", Collections.emptyList()))
);
}
private CompletableFuture<List<String>> getPartOfEmails(QueueType detainedOrder, int index, ExecutorService executorService) {
return CompletableFuture.supplyAsync(() -> receiversService.getPartOfReceivers(detainedOrder, index), executorService);
}
}
| UTF-8 | Java | 2,527 | java | ScheduledEmails.java | Java | [] | null | [] | package com.przemo.emailsender.emailSenders;
import com.przemo.emailsender.consumerWrapper.ConsumerWrapper;
import com.przemo.emailsender.models.Email;
import com.przemo.emailsender.repositories.queries.ClientQueries;
import com.przemo.emailsender.reveivers.QueueType;
import com.przemo.emailsender.reveivers.ReceiversService;
import com.przemo.emailsender.reveivers.ReceiversServiceImpl;
import com.przemo.emailsender.services.ClientService;
import com.przemo.emailsender.services.EmailService;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@Service
public class ScheduledEmails implements Job {
@Autowired
private EmailService emailService;
@Autowired
private ReceiversService receiversService;
@Override
public void execute(JobExecutionContext jobExecutionContext) {
sendDetainedEmailInformation();
}
private void sendDetainedEmailInformation() {
ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
sendEmailsPartially(executorService);
}
private void sendEmailsPartially(ExecutorService executorService) {
for (int index = 0; index < receiversService.amountOfBatchFetch(QueueType.DETAINED_ORDER); index++) {
CompletableFuture<List<String>> partOrEmails = getPartOfEmails(QueueType.DETAINED_ORDER, index, executorService);
partOrEmails.thenAcceptAsync(receivers -> sendEmailToReceivers(receivers));
}
}
private void sendEmailToReceivers(List<String> receivers) {
receivers.forEach(ConsumerWrapper.throwingConsumerWrapper(receiver ->
emailService.sendEmail(receiver, "Detained", "Your Order is detained", Collections.emptyList()))
);
}
private CompletableFuture<List<String>> getPartOfEmails(QueueType detainedOrder, int index, ExecutorService executorService) {
return CompletableFuture.supplyAsync(() -> receiversService.getPartOfReceivers(detainedOrder, index), executorService);
}
}
| 2,527 | 0.787495 | 0.787099 | 65 | 37.861538 | 35.094105 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.676923 | false | false | 3 |
8a68096ad289eefd954efe475a1cfe22c97d956c | 21,741,124,454,816 | 48817230d84dd4ae250dacf38bbe524d9c8b02d6 | /SemiProject/SameCardChkGame/src/com/SemeProJ/CardChkGame/Server/ServerMsgRXtoTX.java | 88732d0a537ca56f527ce98e67af390d08e1c878 | [] | no_license | honbob123/SameCardChkGame | https://github.com/honbob123/SameCardChkGame | 8e063e585da38fe7adb07866ecb8fd910234d4f6 | 693baf8dd7614ebdabec4a4729573906d4461d59 | refs/heads/master | 2020-06-10T18:20:54.925000 | 2016-12-21T08:27:00 | 2016-12-21T08:27:00 | 75,910,781 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.SemeProJ.CardChkGame.Server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Random;
import java.util.Vector;
import javax.swing.JOptionPane;
class ServerMsgRxtoTX extends Thread { //클라이언트로부터 전송된 메시지를 받고 다른 클라이언트한테 보내는 스레드
private Socket client_socekt; //클라이언트 소켓
private Vector<Socket> socket_vec; //들어오는 순서대로 벡터에 저장
private Vector<String> Info_vec; //들어오는 순서대로 아이디와 캐릭터값 저장
private BufferedReader bufferedReader = null;
private int [] arr = new int[16];
int turntoChk = 0;
static int end = 0;
static int score1 = 0, score2 = 0;
public ServerMsgRxtoTX(Socket socket, Vector<Socket> socket_vec,Vector<String> Info_vec) { //생성자
this.client_socekt = socket;
this.socket_vec = socket_vec;
this.Info_vec = Info_vec;
try {
//클라이언트 소켓에서 데이터를 수신받기 위한 객체생성
bufferedReader = new BufferedReader(new InputStreamReader(client_socekt.getInputStream()));
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "스트림 설정 에러!","에러창", JOptionPane.ERROR_MESSAGE);
System.out.println("스트림 설정 에러");
}
}
@Override
public void run() {
String Id = null;
String fullname = null;
try {
while(true) {
String msg = null;
msg = bufferedReader.readLine(); //메시지 받아서 읽기
if(msg != null) {
if(msg.substring(0, 9).equals("Send_Info")) {
fullname = msg.substring(10); //Info_vec에서 삭제하기 위해 값을 저장
Id = msg.substring(11); //아이디값 넣어서 나갔을 때 아이디 표시해준다
Send_Info(msg); //클라이언트한테 플레이어 정보 보내는 메소드
if(socket_vec.size() == 2) { //소켓벡터에 2명이 들어오면(즉, 1p, 2p가 들어오면 if문 실행)
randNumber(); //랜덤으로 16개 카드 값을 클라이언트측으로 보낸다
Send_Start(); //소켓벡터에 2명이 들어오면 게임 시작메소드 실행
}
}else if(msg.substring(0, 9).equals("Send_Chat")) {
Send_Msg(msg); //다른 모든 클라이언트에게 메시지 보내기
}else if(msg.substring(0, 9).equals("Game_turn")) {
Send_Turn(); //상대에게 턴을 넘기는 메소드
}
else if(msg.substring(0, 20).equals("Game_Score_and_Array")) {
Send_GameInfo(msg); //게임 카드 짝을 맞췄을 때 다른 플레이어한테 보여주는 메소드
Send_GameResult(msg); //게임 점수를 올리고 결과를 나타내는 메소드
}
}else //클라이언트가 나갔을 때 while문을 빠져 나간다
break;
}
} catch (IOException e) {
System.out.println("클라이언트와 접속이 끊겼습니다");
}finally { //플레이어가 나갔을 때 finally 실행
try {
Send_Msg("Send_Chat" + Id + "님이 방에서 나갔습니다");
Send_Out(Id); //플레이어가 나갔을 때 정보 삭제하는 메소드
socket_vec.remove(client_socekt); //벡터에서 해당 소켓 삭제
Info_vec.remove(fullname); //해당 소켓 Info_vec벡터 삭제
if(bufferedReader != null) bufferedReader.close(); //사용한 시스템 자원을 반납하고 입력 스트림을 닫는다
if(client_socekt != null) client_socekt.close(); //소켓을 닫는다
} catch (IOException e) {}
}
}
private void Send_GameResult(String msg) { //게임 점수를 올리고 결과를 나타내는 메소드
String [] split_End = msg.substring(21).split(",");
String id = split_End[0]; //맞춘 id
if(id.equals(Info_vec.get(0).substring(1))) score1++; //플1이 맞추면
else if (id.equals(Info_vec.get(1).substring(1))) score2++; //플2가 맞추면
end++;
System.out.println(end + " " + score1 + " " + score2);
if(end == 8) { //정답을 다 맞췄을 때
PrintWriter printWriter;
try {
if(score1 > score2) { //스코어점수가 높은 1p가 이겼을 때
Socket socket_player1 = socket_vec.get(0);
Socket socket_player2 = socket_vec.get(1);
printWriter = new PrintWriter(socket_player1.getOutputStream(), true);
printWriter.println("Game_Win");
printWriter = new PrintWriter(socket_player2.getOutputStream(), true);
printWriter.println("Game_Lose");
}
else if(score1 < score2) { //스코어점수가 높은 2p가 이겼을 때
Socket socket_player1 = socket_vec.get(0);
Socket socket_player2 = socket_vec.get(1);
printWriter = new PrintWriter(socket_player1.getOutputStream(), true);
printWriter.println("Game_Lose");
printWriter = new PrintWriter(socket_player2.getOutputStream(), true);
printWriter.println("Game_Win");
}
else { //비겼을 때 모든 플레이어 나가진다
for(Socket socket : socket_vec) {
printWriter = new PrintWriter(socket.getOutputStream(), true);
printWriter.println("Game_Draw");
}
}
} catch (IOException e) {}
end=0; //게임이 끝나서 총 정답수를 초기화
score1=0; //게임이 끝나서 플레이어1 스코어를 초기화
score2=0; //게임이 끝나서 플레이어2 스코어를 초기화
}
}
private void Send_Turn() { //상대한테 턴 넘기는 메소드
for(Socket socket : socket_vec) {
PrintWriter printWriter;
try {
printWriter = new PrintWriter(socket.getOutputStream(), true);
if(socket != this.client_socekt){
printWriter.println("Game_play");
}else {
printWriter.println("Game_stop");
}
} catch (IOException e) {}
}
}
private void Send_GameInfo(String msg) { //게임 카드 짝을 맞췄을 때 다른 플레이어한테 보여주는 메소드
for(Socket socket : socket_vec) {
PrintWriter printWriter;
try {
printWriter = new PrintWriter(socket.getOutputStream(), true);
printWriter.println(msg);
} catch (IOException e) {}
}
}
private void Send_Start() { //클라이언트한테 게임시작 보내는 메소드
try {
sleep(3000); //2p가 들어오고 3초후에 게임 카운터를 세고 게임이 시작된다
} catch (InterruptedException e) {}
for(Socket socket : socket_vec) {
PrintWriter printWriter;
try {
printWriter = new PrintWriter(socket.getOutputStream(), true);
printWriter.println("Send_Start" + "5초 후에 게임이 시작됩니다!" + turntoChk++);
} catch (IOException e) {}
}
}
private void Send_Info(String msg) { //클라이언트한테 플레이어 정보 보내는 메소드
Info_vec.add(msg.substring(10)); //벡터에 순서대로 이미지순서,ID 삽입
for(Socket socket : socket_vec) { //모든 클라이언트한테 정보를 낸다
PrintWriter printWriter;
for(int i=0; i<Info_vec.size(); i++) {
try {
String s = String.valueOf(i);
printWriter = new PrintWriter(socket.getOutputStream(), true);
printWriter.println(s + "Send_Info/" + Info_vec.get(i));
printWriter.flush();
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "스트림 설정 에러!","에러창", JOptionPane.ERROR_MESSAGE);
System.out.println("클라이언트한테 메시지 보내는 에러");
}
}
}
}
private void Send_Msg(String msg) { //모든 클라이언트한테 메시지 보내는 메소드
for(Socket socket : socket_vec) { //자신을 제외한 다른 클라이언트에게 메시지를 보낸다
PrintWriter printWriter;
if(socket != this.client_socekt) {
try {
printWriter = new PrintWriter(socket.getOutputStream(), true);
printWriter.println(msg); //클라이언트에게 보내기
printWriter.flush();
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "스트림 설정 에러!","에러창", JOptionPane.ERROR_MESSAGE);
System.out.println("클라이언트한테 메시지 보내는 에러");
}
}
}
}
private void Send_Out(String Id) { //클라이언트한테 플레이어가 나갔을 때 정보 삭제하는 메소드
for(Socket socket : socket_vec) {
PrintWriter printWriter;
try {
printWriter = new PrintWriter(socket.getOutputStream(), true);
end = 0;
score1 = 0;
score2 = 0;
String removePanel = "Go_to_the_hell" + Id;
printWriter.println(removePanel);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "스트림 설정 에러!","에러창", JOptionPane.ERROR_MESSAGE);
System.out.println("클라이언트한테 메시지 보내는 에러");
}
}
}
public void randNumber() { // 게임화면 배열 보내는 부분
String str_GameArr = "TEST :";
int check=0;
Random rand=new Random();
int return_GameArr[] = new int[16];
for(int i=0;i<arr.length;i++) {
arr[i]=rand.nextInt(8);
for(int x=0;x<i;x++) {
if(arr[i]==arr[x])
check++;
}
if(check==2) {
check=0;
i--;
continue;
}
System.out.println(arr[i]);
check = 0; // if2의 조건이 만족하지 않으면, 변수 check에 0을 대입한다.
str_GameArr = str_GameArr.concat(Integer.toString(arr[i]));
str_GameArr = str_GameArr.concat(",");
System.out.println(str_GameArr);
} // for1 조건이 만족하면 for1종료
String[] split_return = (str_GameArr.substring(str_GameArr.indexOf(":")+1).split(","));
for(int i = 0; i < split_return.length; i++) {
return_GameArr[i] = Integer.parseInt(split_return[i]);
System.out.println(return_GameArr[i]);
}
for(Socket socket : socket_vec) {
PrintWriter printWriter;
try {
printWriter = new PrintWriter(socket.getOutputStream(), true);
printWriter.println("Game_Array" + str_GameArr);
printWriter.flush();
} catch (IOException e) {}
}
}
} | UTF-8 | Java | 10,306 | java | ServerMsgRXtoTX.java | Java | [] | null | [] | package com.SemeProJ.CardChkGame.Server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Random;
import java.util.Vector;
import javax.swing.JOptionPane;
class ServerMsgRxtoTX extends Thread { //클라이언트로부터 전송된 메시지를 받고 다른 클라이언트한테 보내는 스레드
private Socket client_socekt; //클라이언트 소켓
private Vector<Socket> socket_vec; //들어오는 순서대로 벡터에 저장
private Vector<String> Info_vec; //들어오는 순서대로 아이디와 캐릭터값 저장
private BufferedReader bufferedReader = null;
private int [] arr = new int[16];
int turntoChk = 0;
static int end = 0;
static int score1 = 0, score2 = 0;
public ServerMsgRxtoTX(Socket socket, Vector<Socket> socket_vec,Vector<String> Info_vec) { //생성자
this.client_socekt = socket;
this.socket_vec = socket_vec;
this.Info_vec = Info_vec;
try {
//클라이언트 소켓에서 데이터를 수신받기 위한 객체생성
bufferedReader = new BufferedReader(new InputStreamReader(client_socekt.getInputStream()));
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "스트림 설정 에러!","에러창", JOptionPane.ERROR_MESSAGE);
System.out.println("스트림 설정 에러");
}
}
@Override
public void run() {
String Id = null;
String fullname = null;
try {
while(true) {
String msg = null;
msg = bufferedReader.readLine(); //메시지 받아서 읽기
if(msg != null) {
if(msg.substring(0, 9).equals("Send_Info")) {
fullname = msg.substring(10); //Info_vec에서 삭제하기 위해 값을 저장
Id = msg.substring(11); //아이디값 넣어서 나갔을 때 아이디 표시해준다
Send_Info(msg); //클라이언트한테 플레이어 정보 보내는 메소드
if(socket_vec.size() == 2) { //소켓벡터에 2명이 들어오면(즉, 1p, 2p가 들어오면 if문 실행)
randNumber(); //랜덤으로 16개 카드 값을 클라이언트측으로 보낸다
Send_Start(); //소켓벡터에 2명이 들어오면 게임 시작메소드 실행
}
}else if(msg.substring(0, 9).equals("Send_Chat")) {
Send_Msg(msg); //다른 모든 클라이언트에게 메시지 보내기
}else if(msg.substring(0, 9).equals("Game_turn")) {
Send_Turn(); //상대에게 턴을 넘기는 메소드
}
else if(msg.substring(0, 20).equals("Game_Score_and_Array")) {
Send_GameInfo(msg); //게임 카드 짝을 맞췄을 때 다른 플레이어한테 보여주는 메소드
Send_GameResult(msg); //게임 점수를 올리고 결과를 나타내는 메소드
}
}else //클라이언트가 나갔을 때 while문을 빠져 나간다
break;
}
} catch (IOException e) {
System.out.println("클라이언트와 접속이 끊겼습니다");
}finally { //플레이어가 나갔을 때 finally 실행
try {
Send_Msg("Send_Chat" + Id + "님이 방에서 나갔습니다");
Send_Out(Id); //플레이어가 나갔을 때 정보 삭제하는 메소드
socket_vec.remove(client_socekt); //벡터에서 해당 소켓 삭제
Info_vec.remove(fullname); //해당 소켓 Info_vec벡터 삭제
if(bufferedReader != null) bufferedReader.close(); //사용한 시스템 자원을 반납하고 입력 스트림을 닫는다
if(client_socekt != null) client_socekt.close(); //소켓을 닫는다
} catch (IOException e) {}
}
}
private void Send_GameResult(String msg) { //게임 점수를 올리고 결과를 나타내는 메소드
String [] split_End = msg.substring(21).split(",");
String id = split_End[0]; //맞춘 id
if(id.equals(Info_vec.get(0).substring(1))) score1++; //플1이 맞추면
else if (id.equals(Info_vec.get(1).substring(1))) score2++; //플2가 맞추면
end++;
System.out.println(end + " " + score1 + " " + score2);
if(end == 8) { //정답을 다 맞췄을 때
PrintWriter printWriter;
try {
if(score1 > score2) { //스코어점수가 높은 1p가 이겼을 때
Socket socket_player1 = socket_vec.get(0);
Socket socket_player2 = socket_vec.get(1);
printWriter = new PrintWriter(socket_player1.getOutputStream(), true);
printWriter.println("Game_Win");
printWriter = new PrintWriter(socket_player2.getOutputStream(), true);
printWriter.println("Game_Lose");
}
else if(score1 < score2) { //스코어점수가 높은 2p가 이겼을 때
Socket socket_player1 = socket_vec.get(0);
Socket socket_player2 = socket_vec.get(1);
printWriter = new PrintWriter(socket_player1.getOutputStream(), true);
printWriter.println("Game_Lose");
printWriter = new PrintWriter(socket_player2.getOutputStream(), true);
printWriter.println("Game_Win");
}
else { //비겼을 때 모든 플레이어 나가진다
for(Socket socket : socket_vec) {
printWriter = new PrintWriter(socket.getOutputStream(), true);
printWriter.println("Game_Draw");
}
}
} catch (IOException e) {}
end=0; //게임이 끝나서 총 정답수를 초기화
score1=0; //게임이 끝나서 플레이어1 스코어를 초기화
score2=0; //게임이 끝나서 플레이어2 스코어를 초기화
}
}
private void Send_Turn() { //상대한테 턴 넘기는 메소드
for(Socket socket : socket_vec) {
PrintWriter printWriter;
try {
printWriter = new PrintWriter(socket.getOutputStream(), true);
if(socket != this.client_socekt){
printWriter.println("Game_play");
}else {
printWriter.println("Game_stop");
}
} catch (IOException e) {}
}
}
private void Send_GameInfo(String msg) { //게임 카드 짝을 맞췄을 때 다른 플레이어한테 보여주는 메소드
for(Socket socket : socket_vec) {
PrintWriter printWriter;
try {
printWriter = new PrintWriter(socket.getOutputStream(), true);
printWriter.println(msg);
} catch (IOException e) {}
}
}
private void Send_Start() { //클라이언트한테 게임시작 보내는 메소드
try {
sleep(3000); //2p가 들어오고 3초후에 게임 카운터를 세고 게임이 시작된다
} catch (InterruptedException e) {}
for(Socket socket : socket_vec) {
PrintWriter printWriter;
try {
printWriter = new PrintWriter(socket.getOutputStream(), true);
printWriter.println("Send_Start" + "5초 후에 게임이 시작됩니다!" + turntoChk++);
} catch (IOException e) {}
}
}
private void Send_Info(String msg) { //클라이언트한테 플레이어 정보 보내는 메소드
Info_vec.add(msg.substring(10)); //벡터에 순서대로 이미지순서,ID 삽입
for(Socket socket : socket_vec) { //모든 클라이언트한테 정보를 낸다
PrintWriter printWriter;
for(int i=0; i<Info_vec.size(); i++) {
try {
String s = String.valueOf(i);
printWriter = new PrintWriter(socket.getOutputStream(), true);
printWriter.println(s + "Send_Info/" + Info_vec.get(i));
printWriter.flush();
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "스트림 설정 에러!","에러창", JOptionPane.ERROR_MESSAGE);
System.out.println("클라이언트한테 메시지 보내는 에러");
}
}
}
}
private void Send_Msg(String msg) { //모든 클라이언트한테 메시지 보내는 메소드
for(Socket socket : socket_vec) { //자신을 제외한 다른 클라이언트에게 메시지를 보낸다
PrintWriter printWriter;
if(socket != this.client_socekt) {
try {
printWriter = new PrintWriter(socket.getOutputStream(), true);
printWriter.println(msg); //클라이언트에게 보내기
printWriter.flush();
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "스트림 설정 에러!","에러창", JOptionPane.ERROR_MESSAGE);
System.out.println("클라이언트한테 메시지 보내는 에러");
}
}
}
}
private void Send_Out(String Id) { //클라이언트한테 플레이어가 나갔을 때 정보 삭제하는 메소드
for(Socket socket : socket_vec) {
PrintWriter printWriter;
try {
printWriter = new PrintWriter(socket.getOutputStream(), true);
end = 0;
score1 = 0;
score2 = 0;
String removePanel = "Go_to_the_hell" + Id;
printWriter.println(removePanel);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "스트림 설정 에러!","에러창", JOptionPane.ERROR_MESSAGE);
System.out.println("클라이언트한테 메시지 보내는 에러");
}
}
}
public void randNumber() { // 게임화면 배열 보내는 부분
String str_GameArr = "TEST :";
int check=0;
Random rand=new Random();
int return_GameArr[] = new int[16];
for(int i=0;i<arr.length;i++) {
arr[i]=rand.nextInt(8);
for(int x=0;x<i;x++) {
if(arr[i]==arr[x])
check++;
}
if(check==2) {
check=0;
i--;
continue;
}
System.out.println(arr[i]);
check = 0; // if2의 조건이 만족하지 않으면, 변수 check에 0을 대입한다.
str_GameArr = str_GameArr.concat(Integer.toString(arr[i]));
str_GameArr = str_GameArr.concat(",");
System.out.println(str_GameArr);
} // for1 조건이 만족하면 for1종료
String[] split_return = (str_GameArr.substring(str_GameArr.indexOf(":")+1).split(","));
for(int i = 0; i < split_return.length; i++) {
return_GameArr[i] = Integer.parseInt(split_return[i]);
System.out.println(return_GameArr[i]);
}
for(Socket socket : socket_vec) {
PrintWriter printWriter;
try {
printWriter = new PrintWriter(socket.getOutputStream(), true);
printWriter.println("Game_Array" + str_GameArr);
printWriter.flush();
} catch (IOException e) {}
}
}
} | 10,306 | 0.613886 | 0.602567 | 244 | 33.131149 | 25.043716 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.704918 | false | false | 3 |
88df573034b9dd1016615eb30df69d5c35b8f8de | 33,663,953,730,194 | 50a0d676c6d81610b9432beb9e0bc3e019aa1cf8 | /programación/tema 4/ejercicio8.java | d1229c24d280028c462c3d7514f293d81473c724 | [] | no_license | Ianbt2000/ian-trabajos | https://github.com/Ianbt2000/ian-trabajos | 320a6d89ab38491c7effce0b7c9b7044b1f49697 | 3d730c61d5a7034807a140967d5ee631da5021ff | refs/heads/master | 2020-08-01T16:15:19.085000 | 2019-12-06T14:29:31 | 2019-12-06T14:29:31 | 211,043,451 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Scanner;
public class ejercicio8 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Este programa efectua la media de tres notas");
System.out.print("introduzca las tres notas (entre 0 y 10) separadas por espacio ");
double n1;
double n2;
double n3;
double media;
String calif;
n1 = s.nextDouble();
n2 = s.nextDouble();
n3 = s.nextDouble();
media = (n1+n2+n3)/3;
if ((media >= 0) && (media < 5)) {
calif = "insuficiente";
System.out.println("nota 1 =" + n1);
System.out.println("nota 2 =" + n2);
System.out.println("nota 3 =" + n3);
System.out.printf("%-1s%.2f\n","nota media = ", media);
System.out.println("tu calificación final es: " + calif);
} else {
if ((media >= 5) && (media < 6)){
calif = "suficiente";
System.out.println("nota 1 =" + n1);
System.out.println("nota 2 =" + n2);
System.out.println("nota 3 =" + n3);
System.out.printf("%-1s%.2f\n","nota media = ", media);
System.out.println("tu calificación final es: " + calif);
}
else {
if ((media >= 6) && (media < 7)) {
calif = "bien";
System.out.println("nota 1 =" + n1);
System.out.println("nota 2 =" + n2);
System.out.println("nota 3 =" + n3);
System.out.printf("%-1s%.2f\n","nota media = ", media);
System.out.println("tu calificación final es: " + calif);
} else {
if ((media >=7) && (media < 9)) {
calif = "notable";
System.out.println("nota 1 =" + n1);
System.out.println("nota 2 =" + n2);
System.out.println("nota 3 =" + n3);
System.out.printf("%-1s%.2f\n","nota media = ", media);
System.out.println("tu calificación final es: " + calif);
} else {
if ((media >=9) && (media <= 10)) {
calif = "sobresaliente";
System.out.println("nota 1 =" + n1);
System.out.println("nota 2 =" + n2);
System.out.println("nota 3 =" + n3);
System.out.printf("%-1s%.2f\n","nota media = ", media);
System.out.println("tu calificación final es: " + calif);
} else {
System.out.println("nota incorrecta");
}
}
}
}
}
}
}
| UTF-8 | Java | 2,119 | java | ejercicio8.java | Java | [] | null | [] | import java.util.Scanner;
public class ejercicio8 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Este programa efectua la media de tres notas");
System.out.print("introduzca las tres notas (entre 0 y 10) separadas por espacio ");
double n1;
double n2;
double n3;
double media;
String calif;
n1 = s.nextDouble();
n2 = s.nextDouble();
n3 = s.nextDouble();
media = (n1+n2+n3)/3;
if ((media >= 0) && (media < 5)) {
calif = "insuficiente";
System.out.println("nota 1 =" + n1);
System.out.println("nota 2 =" + n2);
System.out.println("nota 3 =" + n3);
System.out.printf("%-1s%.2f\n","nota media = ", media);
System.out.println("tu calificación final es: " + calif);
} else {
if ((media >= 5) && (media < 6)){
calif = "suficiente";
System.out.println("nota 1 =" + n1);
System.out.println("nota 2 =" + n2);
System.out.println("nota 3 =" + n3);
System.out.printf("%-1s%.2f\n","nota media = ", media);
System.out.println("tu calificación final es: " + calif);
}
else {
if ((media >= 6) && (media < 7)) {
calif = "bien";
System.out.println("nota 1 =" + n1);
System.out.println("nota 2 =" + n2);
System.out.println("nota 3 =" + n3);
System.out.printf("%-1s%.2f\n","nota media = ", media);
System.out.println("tu calificación final es: " + calif);
} else {
if ((media >=7) && (media < 9)) {
calif = "notable";
System.out.println("nota 1 =" + n1);
System.out.println("nota 2 =" + n2);
System.out.println("nota 3 =" + n3);
System.out.printf("%-1s%.2f\n","nota media = ", media);
System.out.println("tu calificación final es: " + calif);
} else {
if ((media >=9) && (media <= 10)) {
calif = "sobresaliente";
System.out.println("nota 1 =" + n1);
System.out.println("nota 2 =" + n2);
System.out.println("nota 3 =" + n3);
System.out.printf("%-1s%.2f\n","nota media = ", media);
System.out.println("tu calificación final es: " + calif);
} else {
System.out.println("nota incorrecta");
}
}
}
}
}
}
}
| 2,119 | 0.581362 | 0.550615 | 94 | 21.489361 | 21.195517 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.574468 | false | false | 3 |
86f213a7bc739b389c2d3072851162bcbe81dc91 | 6,038,724,031,416 | 171b3877548f80dcf65d3cebc03a3d075bc17e86 | /ITP1_4/ITP1_4_A.java | 58c9ea2c42ff6bb4fff97f8f486ea68b43d37a42 | [] | no_license | s14004/Prog.Lit.2016 | https://github.com/s14004/Prog.Lit.2016 | 63e69b6a69792e30427c957dbd0e298e744b9964 | 4e9610b8e66f8ffae94af507c0fbcf1452f4a3a9 | refs/heads/master | 2021-01-10T03:54:42.631000 | 2016-04-15T06:24:28 | 2016-04-15T06:24:28 | 55,930,815 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int b = scanner.nextInt();
int div = a / b;
int rem = a % b;
double fp = (double)a / (double)b;
String after = String.format("%.16f", fp);
System.out.pritln(div + " " + rem + " " + after);
}
}
| UTF-8 | Java | 381 | java | ITP1_4_A.java | Java | [] | null | [] | import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int b = scanner.nextInt();
int div = a / b;
int rem = a % b;
double fp = (double)a / (double)b;
String after = String.format("%.16f", fp);
System.out.pritln(div + " " + rem + " " + after);
}
}
| 381 | 0.577428 | 0.572178 | 16 | 22.8125 | 17.703173 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.875 | false | false | 3 |
591662a4ce0a242883adfac9f8997a9fc0eeb319 | 29,137,058,189,810 | 2fa213e42d4cbac8d29704e8d181e9fb4589a359 | /src/main/java/com/cg/go/greatoutdoor/dao/IProductRepository.java | e3d0c9b34aa68a58f6b9d7d4047574bba48c3624 | [] | no_license | NareshKumarThonupunoori/GreatOutdoorBackend | https://github.com/NareshKumarThonupunoori/GreatOutdoorBackend | e02be9c0f20a053966cdceb5677691ee822984be | faac62b86d9de128f79bbd8d3ed19069e870a7e0 | refs/heads/master | 2023-01-21T12:49:33.851000 | 2020-11-28T18:02:11 | 2020-11-28T18:02:11 | 316,007,167 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cg.go.greatoutdoor.dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.cg.go.greatoutdoor.entity.ProductEntity;
@Repository
public interface IProductRepository extends JpaRepository<ProductEntity,Integer>{
@Query("from ProductEntity where price<=:maxPrice")
List<ProductEntity> findByRange(@Param("maxPrice") double maxPrice);
List<ProductEntity> findByCategory(String productCategory);
List<ProductEntity> findByProductName(String keyword);
}
| UTF-8 | Java | 681 | java | IProductRepository.java | Java | [] | null | [] | package com.cg.go.greatoutdoor.dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.cg.go.greatoutdoor.entity.ProductEntity;
@Repository
public interface IProductRepository extends JpaRepository<ProductEntity,Integer>{
@Query("from ProductEntity where price<=:maxPrice")
List<ProductEntity> findByRange(@Param("maxPrice") double maxPrice);
List<ProductEntity> findByCategory(String productCategory);
List<ProductEntity> findByProductName(String keyword);
}
| 681 | 0.82232 | 0.82232 | 23 | 28.608696 | 28.143637 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.782609 | false | false | 3 |
2614f9b07aa2e2c6d27b2e6ef6e946005ae17a84 | 22,780,506,561,116 | e80c3dc2de5b854338da926384651262b21b809f | /src/com/czbk/java/exception/ByZeroException.java | 09236062119326dfb0c52b49df16a23c08aece30 | [] | no_license | twentwo/java-test | https://github.com/twentwo/java-test | 09a5c8a968d9cd264460ade4768ce707cae3ca96 | cbe819f4b04cdb8d0f01fe8418513176ef3aa636 | refs/heads/master | 2016-09-08T01:03:16.147000 | 2015-08-16T14:59:48 | 2015-08-16T14:59:48 | 40,824,246 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.czbk.java.exception;
public class ByZeroException extends Exception{
ByZeroException(){
super();
}
ByZeroException(String mess){
super(mess);
}
}
| UTF-8 | Java | 166 | java | ByZeroException.java | Java | [] | null | [] | package com.czbk.java.exception;
public class ByZeroException extends Exception{
ByZeroException(){
super();
}
ByZeroException(String mess){
super(mess);
}
}
| 166 | 0.740964 | 0.740964 | 9 | 17.444445 | 15.12989 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.222222 | false | false | 3 |
7521d8c064e00d2b2ca51b042b190532c76c9f01 | 28,733,331,232,263 | 7573ad9f60a4c3c050d9127c74f16a1b8f8d128b | /app/src/main/java/com/pachouri/technovanzahackathon/widgets/DialogUtil.java | 275d47cfde7d80b906a6948a1a252396ce1c5c1b | [] | no_license | Pachouri-Sikandar/TechnovanzaHackathon | https://github.com/Pachouri-Sikandar/TechnovanzaHackathon | 275e71613aa8515366d69f55c8c7aaa21ae202cd | 38e77c780c35a60544392de9b7ecf18122e89c13 | refs/heads/master | 2021-01-01T03:58:25.794000 | 2016-12-24T11:58:00 | 2016-12-24T11:58:00 | 77,270,569 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.pachouri.technovanzahackathon.widgets;
import android.app.Dialog;
import android.content.Context;
import android.view.View;
import android.widget.Button;
import com.pachouri.technovanzahackathon.R;
/**
* Created by tt-riyaz on 26/10/16.
*/
public class DialogUtil {
public interface IDialog {
void onSubmitClick();
void onCancelClick();
}
public interface IImageSelectionDialog{
void onClickCamera();
void onClickGallery();
}
public interface IInputDialog {
void onSubmitClick(String value);
void onCancelClick();
}
public static void showDialog(Context context, CharSequence displayText, final IDialog iDialog) {
showDialog(context, displayText, "Yes", "No", false, iDialog);
}
public static void showDialog(Context context, CharSequence displayText) {
showDialog(context, displayText, "", "", true, null);
}
public static void showDialog(Context context, CharSequence displayText, String yesBtnText, String noBtnText, final IDialog iDialog) {
showDialog(context, displayText, yesBtnText, noBtnText, false, iDialog);
}
public static void showDialog(Context context, CharSequence displayText, String yesBtnText, String noBtnText,
final boolean shouldShowSingleButtons, final IDialog iDialog) {
final Dialog dialog = new Dialog(context, R.style.dialog_theme);
dialog.setContentView(R.layout.layout_confirmation_dialog);
Button btnNo = (Button) dialog.findViewById(R.id.btn_no);
Button btnYes = (Button) dialog.findViewById(R.id.btn_yes);
btnYes.setText(yesBtnText);
btnNo.setText(noBtnText);
AppTextView txtDialogMsg = (AppTextView) dialog.findViewById(R.id.txt_dialog_msg);
txtDialogMsg.setText(displayText);
if (!shouldShowSingleButtons) {
//Two buttons 'Yes' and 'No'
btnYes.setVisibility(View.VISIBLE);
btnNo.setVisibility(View.VISIBLE);
btnNo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
iDialog.onCancelClick();
}
});
btnYes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
iDialog.onSubmitClick();
dialog.dismiss();
}
});
} else {
//One button 'Ok'
btnYes.setVisibility(View.VISIBLE);
btnYes.setText("Ok");
btnNo.setVisibility(View.GONE);
btnYes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(iDialog != null)
iDialog.onSubmitClick();
dialog.dismiss();
}
});
}
dialog.show();
}
} | UTF-8 | Java | 3,062 | java | DialogUtil.java | Java | [
{
"context": "achouri.technovanzahackathon.R;\n\n/**\n * Created by tt-riyaz on 26/10/16.\n */\npublic class DialogUtil {\n\n p",
"end": 239,
"score": 0.9996940493583679,
"start": 231,
"tag": "USERNAME",
"value": "tt-riyaz"
}
] | null | [] | package com.pachouri.technovanzahackathon.widgets;
import android.app.Dialog;
import android.content.Context;
import android.view.View;
import android.widget.Button;
import com.pachouri.technovanzahackathon.R;
/**
* Created by tt-riyaz on 26/10/16.
*/
public class DialogUtil {
public interface IDialog {
void onSubmitClick();
void onCancelClick();
}
public interface IImageSelectionDialog{
void onClickCamera();
void onClickGallery();
}
public interface IInputDialog {
void onSubmitClick(String value);
void onCancelClick();
}
public static void showDialog(Context context, CharSequence displayText, final IDialog iDialog) {
showDialog(context, displayText, "Yes", "No", false, iDialog);
}
public static void showDialog(Context context, CharSequence displayText) {
showDialog(context, displayText, "", "", true, null);
}
public static void showDialog(Context context, CharSequence displayText, String yesBtnText, String noBtnText, final IDialog iDialog) {
showDialog(context, displayText, yesBtnText, noBtnText, false, iDialog);
}
public static void showDialog(Context context, CharSequence displayText, String yesBtnText, String noBtnText,
final boolean shouldShowSingleButtons, final IDialog iDialog) {
final Dialog dialog = new Dialog(context, R.style.dialog_theme);
dialog.setContentView(R.layout.layout_confirmation_dialog);
Button btnNo = (Button) dialog.findViewById(R.id.btn_no);
Button btnYes = (Button) dialog.findViewById(R.id.btn_yes);
btnYes.setText(yesBtnText);
btnNo.setText(noBtnText);
AppTextView txtDialogMsg = (AppTextView) dialog.findViewById(R.id.txt_dialog_msg);
txtDialogMsg.setText(displayText);
if (!shouldShowSingleButtons) {
//Two buttons 'Yes' and 'No'
btnYes.setVisibility(View.VISIBLE);
btnNo.setVisibility(View.VISIBLE);
btnNo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
iDialog.onCancelClick();
}
});
btnYes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
iDialog.onSubmitClick();
dialog.dismiss();
}
});
} else {
//One button 'Ok'
btnYes.setVisibility(View.VISIBLE);
btnYes.setText("Ok");
btnNo.setVisibility(View.GONE);
btnYes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(iDialog != null)
iDialog.onSubmitClick();
dialog.dismiss();
}
});
}
dialog.show();
}
} | 3,062 | 0.600261 | 0.598302 | 90 | 33.033333 | 28.493059 | 138 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.733333 | false | false | 3 |
07a072d963e34bb4b144e061473920c7c513cdbd | 19,756,849,566,485 | d29baa4451aaee733c07677fed4b3b5f36edc055 | /springboot-producer/src/main/java/com/bfxy/springboot/producer/RabbitOrderSender.java | 608c4dc27f4e21d9d06067909edc7cccc5131d2d | [] | no_license | wuxiangge/springboot-rabbitmq-master | https://github.com/wuxiangge/springboot-rabbitmq-master | c43406f8a119843c6166755d148faa3b9930f00e | 31efec9cc6cee06c94132b7f2f22467628a7fb8e | refs/heads/master | 2020-06-05T01:45:12.752000 | 2019-06-17T03:44:23 | 2019-06-17T03:44:23 | 192,270,153 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bfxy.springboot.producer;
import java.util.Date;
import com.bfxy.springboot.constant.Constants;
import com.bfxy.springboot.entity.Order;
import com.bfxy.springboot.mapper.BrokerMessageLogMapper;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class RabbitOrderSender {
@Autowired
private RabbitTemplate rabbitTemplate;
@Autowired
private BrokerMessageLogMapper brokerMessageLogMapper;
//回调函数:confirm确认
private final ConfirmCallback confirmCallback = new ConfirmCallback() {
@Override
public void confirm(CorrelationData correlationData, boolean ack, String cause) {
System.err.println("correlationData:" + correlationData);
String messageId = correlationData.getId();
if (ack) {
//如果confirm返回成功 则进行更新
brokerMessageLogMapper.changeBrokerMessageLogStatus(messageId, Constants.ORDER_SEND_SUCCESS, new Date());
} else {
//失败则进行具体的后续操作:重试或者补偿等手段
System.err.println("异常处理。。。");
}
}
};
//发送消息方法调用:构建自定义对象消息
public void sendOrder(Order order) {
//监听回调函数
rabbitTemplate.setConfirmCallback(confirmCallback);
//消息唯一ID
CorrelationData correlationData = new CorrelationData(order.getMessageId());
rabbitTemplate.convertAndSend("order-exchange",
"order.ABC",
order, //消息体内容
correlationData); //消息唯一ID
}
}
| UTF-8 | Java | 1,954 | java | RabbitOrderSender.java | Java | [] | null | [] | package com.bfxy.springboot.producer;
import java.util.Date;
import com.bfxy.springboot.constant.Constants;
import com.bfxy.springboot.entity.Order;
import com.bfxy.springboot.mapper.BrokerMessageLogMapper;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class RabbitOrderSender {
@Autowired
private RabbitTemplate rabbitTemplate;
@Autowired
private BrokerMessageLogMapper brokerMessageLogMapper;
//回调函数:confirm确认
private final ConfirmCallback confirmCallback = new ConfirmCallback() {
@Override
public void confirm(CorrelationData correlationData, boolean ack, String cause) {
System.err.println("correlationData:" + correlationData);
String messageId = correlationData.getId();
if (ack) {
//如果confirm返回成功 则进行更新
brokerMessageLogMapper.changeBrokerMessageLogStatus(messageId, Constants.ORDER_SEND_SUCCESS, new Date());
} else {
//失败则进行具体的后续操作:重试或者补偿等手段
System.err.println("异常处理。。。");
}
}
};
//发送消息方法调用:构建自定义对象消息
public void sendOrder(Order order) {
//监听回调函数
rabbitTemplate.setConfirmCallback(confirmCallback);
//消息唯一ID
CorrelationData correlationData = new CorrelationData(order.getMessageId());
rabbitTemplate.convertAndSend("order-exchange",
"order.ABC",
order, //消息体内容
correlationData); //消息唯一ID
}
}
| 1,954 | 0.68925 | 0.68925 | 56 | 30.892857 | 28.318771 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.482143 | false | false | 3 |
9be5cfffe0f6d952f003605fbad876b993cbc3b8 | 21,603,685,506,634 | 44465137753c36d0a68de3eead59cd3ceb664126 | /src/by/iba/shimanski/weaponsShop/entity/Stick.java | c02e9fd971848bf387c3da2d2b8bea1dcf72f7c7 | [] | no_license | ShimanskiVlad/weaponsShop | https://github.com/ShimanskiVlad/weaponsShop | 68ef0f6709fc3cc9bfab1ce1322e5be3785ecd8d | a65f2c711022a69d899259ccc3dd38db870bce4c | refs/heads/master | 2021-01-10T15:41:37.947000 | 2016-02-25T07:55:05 | 2016-02-25T07:55:05 | 51,909,369 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package by.iba.shimanski.weaponsShop.entity;
import by.iba.shimanski.weaponsShop.interfaces.Producer;
public class Stick extends Weapon {
private Double weight;
public Stick() {}
public Stick(Double damage, Double size, Double weight, Producer producer) {
super(damage, size, producer);
this.weight = weight;
}
public Double getWeight() {
return weight;
}
public void setWeight(Double weight) {
this.weight = weight;
}
@Override
public Double bit() {
System.out.println("Bit by Stick!");
return super.bit();
}
@Override
public String toString() {
return "Stick [weight=" + weight + ", damage=" + getDamage() + ", size="
+ getSize() + ", producer=" + getProducer() + "]";
}
}
| UTF-8 | Java | 720 | java | Stick.java | Java | [] | null | [] | package by.iba.shimanski.weaponsShop.entity;
import by.iba.shimanski.weaponsShop.interfaces.Producer;
public class Stick extends Weapon {
private Double weight;
public Stick() {}
public Stick(Double damage, Double size, Double weight, Producer producer) {
super(damage, size, producer);
this.weight = weight;
}
public Double getWeight() {
return weight;
}
public void setWeight(Double weight) {
this.weight = weight;
}
@Override
public Double bit() {
System.out.println("Bit by Stick!");
return super.bit();
}
@Override
public String toString() {
return "Stick [weight=" + weight + ", damage=" + getDamage() + ", size="
+ getSize() + ", producer=" + getProducer() + "]";
}
}
| 720 | 0.673611 | 0.673611 | 36 | 19 | 21.399637 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.444444 | false | false | 3 |
a8b55f52b7419971b5a5c6b67feb4e607f035712 | 28,724,741,283,478 | 2a920f5f42c588dad01740da5d8c3d9aecbc2a90 | /src/org/deegree/datatypes/parameter/OperationParameterIm.java | ec9ad39e5ba6e59199464fa73c0605efa18ad9df | [] | no_license | lat-lon/deegree2-rev30957 | https://github.com/lat-lon/deegree2-rev30957 | 40b50297cd28243b09bfd05db051ea4cecc889e4 | 22aa8f8696e50c6e19c22adb505efb0f1fc805d8 | refs/heads/master | 2020-04-06T07:00:21.040000 | 2016-06-28T15:21:56 | 2016-06-28T15:21:56 | 12,290,316 | 0 | 0 | null | false | 2016-06-28T15:21:57 | 2013-08-22T06:49:45 | 2016-05-11T12:35:05 | 2016-06-28T15:21:57 | 36,551 | 0 | 1 | 0 | Java | null | null | // $HeadURL: https://scm.wald.intevation.org/svn/deegree/base/trunk/src/org/deegree/datatypes/parameter/OperationParameterIm.java $
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2009 by:
Department of Geography, University of Bonn
and
lat/lon GmbH
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 2.1 of the License, or (at your option)
any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: info@deegree.org
----------------------------------------------------------------------------*/
package org.deegree.datatypes.parameter;
import java.io.Serializable;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* @author <a href="mailto:poth@lat-lon.de">Andreas Poth </a>
* @author last edited by: $Author: mschneider $
*
* @version $Revision: 18195 $, $Date: 2009-06-18 17:55:39 +0200 (Do, 18. Jun 2009) $
*/
public class OperationParameterIm extends GeneralOperationParameterIm implements Serializable {
private static final long serialVersionUID = -837184501017553294L;
private Comparable<?> maximumValue;
private Comparable<?> minimumValue;
private Set<?> validValues;
private Class<?> valueClass;
private Object defaultValue;
/**
* Convenience constructor.
*
* @param name
* @param validValues
*/
public OperationParameterIm( String name, String[] validValues ) {
this( name, null, 1, 0, null, null, buildSet( validValues ), String.class, null );
}
/**
* Convenience constructor.
*
* @param name
* @param validValues
* @param defaultValue to default to.
*/
public OperationParameterIm( String name, String[] validValues, Object defaultValue ) {
this( name, null, 1, 0, null, null, buildSet( validValues ), defaultValue.getClass(), defaultValue );
}
/**
* @param name
* @param remarks
* @param maximumOccurs
* @param minimumOccurs
* @param maximumValue
* @param minimumValue
* @param validValues
* @param valueClass
* @param defaultValue
*/
public OperationParameterIm( String name, String remarks, int maximumOccurs, int minimumOccurs,
Comparable<?> maximumValue, Comparable<?> minimumValue, Set<?> validValues, Class<?> valueClass,
Object defaultValue ) {
super( name, remarks, maximumOccurs, minimumOccurs );
this.maximumValue = maximumValue;
this.minimumValue = minimumValue;
this.validValues = validValues;
this.valueClass = valueClass;
this.defaultValue = defaultValue;
}
/**
* @return Returns the defaultValue.
*/
public Object getDefaultValue() {
return defaultValue;
}
/**
* @param defaultValue
* The defaultValue to set.
*/
public void setDefaultValue( Object defaultValue ) {
this.defaultValue = defaultValue;
}
/**
* @return Returns the maximumValue.
*
*/
public Comparable<?> getMaximumValue() {
return maximumValue;
}
/**
* @param maximumValue
* The maximumValue to set.
*/
public void setMaximumValue( Comparable<?> maximumValue ) {
this.maximumValue = maximumValue;
}
/**
* @return Returns the minimumValue.
*/
public Comparable<?> getMinimumValue() {
return minimumValue;
}
/**
* @param minimumValue
* The minimumValue to set.
*/
public void setMinimumValue( Comparable<?> minimumValue ) {
this.minimumValue = minimumValue;
}
/**
* @return Returns the validValues.
*/
public Set<?> getValidValues() {
return validValues;
}
/**
* @param validValues
* The validValues to set.
*/
public void setValidValues( Set<?> validValues ) {
this.validValues = validValues;
}
/**
* @return Returns the valueClass.
*/
public Class<?> getValueClass() {
return valueClass;
}
/**
* @param valueClass
* The valueClass to set.
*/
public void setValueClass( Class<?> valueClass ) {
this.valueClass = valueClass;
}
/**
*
* @param values
* @return a set of the given String.
*/
private static Set<String> buildSet( String[] values ) {
Set<String> valueSet = new LinkedHashSet<String>();
if ( values != null ) {
for ( int i = 0; i < values.length; i++ ) {
valueSet.add( values[i] );
}
}
return valueSet;
}
}
| UTF-8 | Java | 5,549 | java | OperationParameterIm.java | Java | [
{
"context": "tp://www.geographie.uni-bonn.de/deegree/\n\n e-mail: info@deegree.org\n-------------------------------------------------",
"end": 1336,
"score": 0.9999197721481323,
"start": 1320,
"tag": "EMAIL",
"value": "info@deegree.org"
},
{
"context": "rt java.util.Set;\n\n/**\n * ... | null | [] | // $HeadURL: https://scm.wald.intevation.org/svn/deegree/base/trunk/src/org/deegree/datatypes/parameter/OperationParameterIm.java $
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2009 by:
Department of Geography, University of Bonn
and
lat/lon GmbH
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 2.1 of the License, or (at your option)
any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: <EMAIL>
----------------------------------------------------------------------------*/
package org.deegree.datatypes.parameter;
import java.io.Serializable;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* @author <a href="mailto:<EMAIL>"><NAME> </a>
* @author last edited by: $Author: mschneider $
*
* @version $Revision: 18195 $, $Date: 2009-06-18 17:55:39 +0200 (Do, 18. Jun 2009) $
*/
public class OperationParameterIm extends GeneralOperationParameterIm implements Serializable {
private static final long serialVersionUID = -837184501017553294L;
private Comparable<?> maximumValue;
private Comparable<?> minimumValue;
private Set<?> validValues;
private Class<?> valueClass;
private Object defaultValue;
/**
* Convenience constructor.
*
* @param name
* @param validValues
*/
public OperationParameterIm( String name, String[] validValues ) {
this( name, null, 1, 0, null, null, buildSet( validValues ), String.class, null );
}
/**
* Convenience constructor.
*
* @param name
* @param validValues
* @param defaultValue to default to.
*/
public OperationParameterIm( String name, String[] validValues, Object defaultValue ) {
this( name, null, 1, 0, null, null, buildSet( validValues ), defaultValue.getClass(), defaultValue );
}
/**
* @param name
* @param remarks
* @param maximumOccurs
* @param minimumOccurs
* @param maximumValue
* @param minimumValue
* @param validValues
* @param valueClass
* @param defaultValue
*/
public OperationParameterIm( String name, String remarks, int maximumOccurs, int minimumOccurs,
Comparable<?> maximumValue, Comparable<?> minimumValue, Set<?> validValues, Class<?> valueClass,
Object defaultValue ) {
super( name, remarks, maximumOccurs, minimumOccurs );
this.maximumValue = maximumValue;
this.minimumValue = minimumValue;
this.validValues = validValues;
this.valueClass = valueClass;
this.defaultValue = defaultValue;
}
/**
* @return Returns the defaultValue.
*/
public Object getDefaultValue() {
return defaultValue;
}
/**
* @param defaultValue
* The defaultValue to set.
*/
public void setDefaultValue( Object defaultValue ) {
this.defaultValue = defaultValue;
}
/**
* @return Returns the maximumValue.
*
*/
public Comparable<?> getMaximumValue() {
return maximumValue;
}
/**
* @param maximumValue
* The maximumValue to set.
*/
public void setMaximumValue( Comparable<?> maximumValue ) {
this.maximumValue = maximumValue;
}
/**
* @return Returns the minimumValue.
*/
public Comparable<?> getMinimumValue() {
return minimumValue;
}
/**
* @param minimumValue
* The minimumValue to set.
*/
public void setMinimumValue( Comparable<?> minimumValue ) {
this.minimumValue = minimumValue;
}
/**
* @return Returns the validValues.
*/
public Set<?> getValidValues() {
return validValues;
}
/**
* @param validValues
* The validValues to set.
*/
public void setValidValues( Set<?> validValues ) {
this.validValues = validValues;
}
/**
* @return Returns the valueClass.
*/
public Class<?> getValueClass() {
return valueClass;
}
/**
* @param valueClass
* The valueClass to set.
*/
public void setValueClass( Class<?> valueClass ) {
this.valueClass = valueClass;
}
/**
*
* @param values
* @return a set of the given String.
*/
private static Set<String> buildSet( String[] values ) {
Set<String> valueSet = new LinkedHashSet<String>();
if ( values != null ) {
for ( int i = 0; i < values.length; i++ ) {
valueSet.add( values[i] );
}
}
return valueSet;
}
}
| 5,526 | 0.613624 | 0.597045 | 195 | 27.456409 | 26.954128 | 131 | false | false | 0 | 0 | 0 | 0 | 83 | 0.014958 | 0.420513 | false | false | 3 |
bdc8bb14fe43e96b6e3da185dad7ff23c92ff7a2 | 26,843,545,608,226 | 47c4f3f39f270737866f0a2849e4fa10115e23ed | /Gym Sign Up/src/controllers/DeleteApplicationServlet.java | 4c51158ec94a30943f783267fdfb38d2f8639054 | [] | no_license | ugack11/Application-Management-System | https://github.com/ugack11/Application-Management-System | 743e04e667eb1b4bb353af1f134425dd287c86d5 | e492a6f754a1d09d9881376419e77b7b559d6d63 | refs/heads/master | 2021-01-10T18:51:41.749000 | 2015-08-31T18:20:25 | 2015-08-31T18:20:25 | 41,459,681 | 0 | 1 | null | false | 2015-08-27T02:47:33 | 2015-08-27T01:52:14 | 2015-08-27T02:08:36 | 2015-08-27T02:08:36 | 0 | 0 | 1 | 1 | Java | null | null | package controllers;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.Profile;
import dbHelpers.UploadQuery;
/**
* Servlet implementation class DeleteResumeServlet
*/
@WebServlet("/DeleteApplicationServlet")
public class DeleteApplicationServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public DeleteApplicationServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
Profile profile = (Profile) session.getAttribute("profile");
profile.setApplication("");
String username = profile.getUsername();
UploadQuery uq = new UploadQuery("application", "root", "", username);
uq.doUpload("");
session.setAttribute("profile", profile);
String url = "/settings.jsp";
RequestDispatcher dispatcher = request.getRequestDispatcher(url);
dispatcher.forward(request, response);
}
}
| UTF-8 | Java | 1,727 | java | DeleteApplicationServlet.java | Java | [] | null | [] | package controllers;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.Profile;
import dbHelpers.UploadQuery;
/**
* Servlet implementation class DeleteResumeServlet
*/
@WebServlet("/DeleteApplicationServlet")
public class DeleteApplicationServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public DeleteApplicationServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
Profile profile = (Profile) session.getAttribute("profile");
profile.setApplication("");
String username = profile.getUsername();
UploadQuery uq = new UploadQuery("application", "root", "", username);
uq.doUpload("");
session.setAttribute("profile", profile);
String url = "/settings.jsp";
RequestDispatcher dispatcher = request.getRequestDispatcher(url);
dispatcher.forward(request, response);
}
}
| 1,727 | 0.75912 | 0.758541 | 59 | 28.271187 | 28.7743 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.338983 | false | false | 3 |
0141bad48090b6594a94485891b77699fc160641 | 10,943,576,684,237 | 311103c854f927801a834b2dd0c14a5d7a1b0b79 | /xproject-common/src/main/java/com/certusnet/xproject/common/initializer/ServletBootingInitializer.java | 9478051e132a589998c5d7d2546cef5074e5aa11 | [
"Apache-2.0"
] | permissive | goodsmile/xproject | https://github.com/goodsmile/xproject | b06f77dfac991f53a7d64388ae089a711fab1357 | 3e124a652af29cf34793efaa64ff73bbca17e4df | refs/heads/master | 2021-08-15T01:51:48.209000 | 2017-11-17T06:10:26 | 2017-11-17T06:10:26 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.certusnet.xproject.common.initializer;
import javax.servlet.ServletContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import com.certusnet.xproject.common.consts.ApplicationConstants;
import com.certusnet.xproject.common.util.FileUtils;
/**
* 应用中依赖于Servlet环境的系统常量初始化
*
* 注:由于该初始化程序中涉及到容器上下文(ServletContext)即需要Servlet容器环境的支持,因此该初始化bean必须配置在springmvc配置文件中
*
* @author pengpeng
* @version 1.0
* @date 2014-07-03 下午3:52:15
*/
public class ServletBootingInitializer extends AbstractApplicationInitializer {
private static final Logger logger = LoggerFactory.getLogger(ServletBootingInitializer.class);
public void initialize(ApplicationContext applicationContext) throws Exception {
WebApplicationContext mvcApplicationContext = null;
if(applicationContext instanceof WebApplicationContext && applicationContext.getParent() != null){
mvcApplicationContext = (WebApplicationContext) applicationContext;
ServletContext servletContext = mvcApplicationContext.getServletContext();
logger.info(">>> 初始化应用中依赖于Servlet环境的系统常量!");
setFinalFieldValue(ApplicationConstants.class, "MVC_APPLICATION_CONTEXT", applicationContext);
setFinalFieldValue(ApplicationConstants.class, "SERVLET_CONTEXT", servletContext);
setFinalFieldValue(ApplicationConstants.class, "CONTEXT_PATH", FileUtils.formatFilePath(servletContext.getContextPath()));
setFinalFieldValue(ApplicationConstants.class, "CONTEXT_REAL_PATH", FileUtils.formatFilePath(servletContext.getRealPath("/")));
}
}
}
| UTF-8 | Java | 1,843 | java | ServletBootingInitializer.java | Java | [
{
"context": "的支持,因此该初始化bean必须配置在springmvc配置文件中\n * \n * @author \tpengpeng\n * @version \t1.0\n * @date \t\t2014-07-03 下午3:52:15\n",
"end": 530,
"score": 0.7025483846664429,
"start": 522,
"tag": "USERNAME",
"value": "pengpeng"
}
] | null | [] | package com.certusnet.xproject.common.initializer;
import javax.servlet.ServletContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import com.certusnet.xproject.common.consts.ApplicationConstants;
import com.certusnet.xproject.common.util.FileUtils;
/**
* 应用中依赖于Servlet环境的系统常量初始化
*
* 注:由于该初始化程序中涉及到容器上下文(ServletContext)即需要Servlet容器环境的支持,因此该初始化bean必须配置在springmvc配置文件中
*
* @author pengpeng
* @version 1.0
* @date 2014-07-03 下午3:52:15
*/
public class ServletBootingInitializer extends AbstractApplicationInitializer {
private static final Logger logger = LoggerFactory.getLogger(ServletBootingInitializer.class);
public void initialize(ApplicationContext applicationContext) throws Exception {
WebApplicationContext mvcApplicationContext = null;
if(applicationContext instanceof WebApplicationContext && applicationContext.getParent() != null){
mvcApplicationContext = (WebApplicationContext) applicationContext;
ServletContext servletContext = mvcApplicationContext.getServletContext();
logger.info(">>> 初始化应用中依赖于Servlet环境的系统常量!");
setFinalFieldValue(ApplicationConstants.class, "MVC_APPLICATION_CONTEXT", applicationContext);
setFinalFieldValue(ApplicationConstants.class, "SERVLET_CONTEXT", servletContext);
setFinalFieldValue(ApplicationConstants.class, "CONTEXT_PATH", FileUtils.formatFilePath(servletContext.getContextPath()));
setFinalFieldValue(ApplicationConstants.class, "CONTEXT_REAL_PATH", FileUtils.formatFilePath(servletContext.getRealPath("/")));
}
}
}
| 1,843 | 0.801187 | 0.791098 | 38 | 43.342106 | 39.67717 | 133 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.236842 | false | false | 3 |
504c5e6ed175b2c8c56863a13fb3f6af81bd3787 | 7,035,156,441,568 | dac4d771b7ec764352da500645179abdb3bf3a9a | /src/sawmill/Condenser.java | bfb119bcfff06d6d0396707b94ad4caa97e16580 | [] | no_license | rmfaller/SawMill | https://github.com/rmfaller/SawMill | 25ddfedb6b95117716f47fab0793fcaf5fdc1257 | e4fc805c3edd8e7ea766dec45d6556c21f1c3836 | refs/heads/master | 2021-07-05T10:13:12.434000 | 2021-05-06T20:49:26 | 2021-05-06T20:49:26 | 99,261,331 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sawmill;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
/**
*
* @author rmfaller
*/
class Condenser {
Condenser(JSONObject config, BufferedReader br) {
}
void condense(JSONObject config, BufferedReader br, long cut, String cfn, boolean showtotals, String lf,
boolean sla, boolean showheader, boolean filltimegap, boolean totalsonly, boolean html, String label,
long startcut, long endcut) {
String timestampformat = config.get("timestampformat").toString();
SimpleDateFormat sdf = new SimpleDateFormat(timestampformat);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String fielddelimiter = config.get("fielddelimiter").toString();
String timestamp = null;
String timescale = null;
String lapsedtimefield = null;
Date operationtime = null;
float etime = 0;
long epochtime = 0;
long oldtime = 0;
long starttime = 0;
long[] slatime;
char fd = 0;
switch (fielddelimiter) {
case "JSON": {
fd = 'J';
}
break;
case "TAB":
fd = '\t';
break;
case "COMMA":
fd = ',';
break;
case "SPACE":
fd = ' ';
break;
default:
break;
}
// String timefield = null;
JSONArray poi = (JSONArray) config.get("poi");
JSONObject[] pois = null;
JSONObject logresponse = null;
String[] brina = null;
JSONArray[] identifiers = null;
JSONParser jp = new JSONParser();
int OPCNT = 0;
int TIMEOP = 1;
int TOTALOPCNT = 2;
int TOTALTIMEOP = 3;
int OPSUNDER = 4;
int OPSOVER = 5;
int TOTALOPSUNDER = 6;
int TOTALOPSOVER = 7;
long opcounter = 0;
float[][] stats;
String brin;
if (!poi.isEmpty()) {
pois = new JSONObject[poi.size()];
identifiers = new JSONArray[poi.size()];
slatime = new long[poi.size()];
stats = new float[poi.size()][8];
for (int i = 0; i < poi.size(); i++) {
pois[i] = (JSONObject) config.get(poi.get(i));
identifiers[i] = (JSONArray) pois[i].get("identifiers");
slatime[i] = (long) pois[i].get("sla");
for (int x = 0; x <= 7; x++) {
stats[i][x] = 0;
}
}
try {
while ((brin = br.readLine()) != null) {
int index = findPoi(brin, identifiers);
opcounter++;
// System.out.println("processing line " + opcounter + " : " + brin);
if (index != -1) {
if (fd == 'J') {
try {
JSONObject logentry = (JSONObject) jp.parse(brin);
logresponse = (JSONObject) logentry.get("response");
timestamp = (String) logentry.get(config.get("timestampfield"));
Long letime = (Long) logresponse.get(pois[index].get("lapsedtimefield"));
// Long letime = (Long) logresponse.get(config.get("lapsedtimefield"));
etime = letime.floatValue();
timescale = (String) logresponse.get(config.get("timescale"));
if (timescale == null) {
timescale = "MILLISECONDS";
}
} catch (ParseException ex) {
Logger.getLogger(Condenser.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
String logentry = brin.replaceAll("\\[", "").replaceAll("\\]", "");
// System.out.println("non-json log = " + logentry);
Long y = (Long) config.get("timestampfield");
brina = logentry.split(String.valueOf(fd));
if (timestampformat.contains(" ")) {
timestamp = brina[y.intValue()] + " " + brina[(y.intValue() + 1)];
} else {
timestamp = brina[y.intValue()];
}
timescale = (String) config.get("timescale");
if (timescale == null) {
timescale = "MILLISECONDS";
}
lapsedtimefield = (String) pois[index].get("lapsedtimefield");
int fi;
String ta = null;
if (lapsedtimefield.matches("[-+]?\\d+(\\.\\d+)?")) {
ta = brina[Integer.parseInt(lapsedtimefield)];
ta = ta.replaceAll("\\\"", "").replaceAll("\\\"", "");
// System.out.println("found: " + lapsedtimefield + "--" + ta);
} else {
fi = brina.length - 1;
while (!brina[fi].contains(lapsedtimefield) && (fi > 0)) {
fi--;
}
if (fi < brina.length) {
ta = brina[fi].substring(lapsedtimefield.length());
} else {
System.out.println("can not find: " + lapsedtimefield);
ta = "0";
}
}
etime = Float.parseFloat(ta);
}
// System.out.println("Pattern: " + sdf.toPattern());
// System.out.println("timestamp ->" + timestamp + "<-");
try {
operationtime = sdf.parse(timestamp.replaceAll("\\[", "").replaceAll("\\]", ""));
// operationtime = sdf.parse(timestamp);
} catch (java.text.ParseException ex) {
Logger.getLogger(Condenser.class.getName()).log(Level.SEVERE, null, ex);
}
float ts = (float) 1.0;
if (etime > 0) {
switch (timescale) {
case "MILLISECONDS":
ts = (float) 1.0;
break;
case "NANOSECONDS":
ts = (float) .000001;
break;
case "SECONDS":
ts = (float) 1000.0;
break;
case "MINUTES":
ts = (float) 60000.0;
break;
default:
ts = 1;
break;
}
}
epochtime = operationtime.getTime();
if ((epochtime >= startcut) && (epochtime <= endcut)) {
if (oldtime == 0) {
oldtime = epochtime;
starttime = epochtime;
if (showheader && !html) {
printHeader(poi, sla);
}
// if (showheader && html) {
// printHTMLHeader(poi, sla);
// }
}
stats[index][OPCNT]++;
stats[index][TOTALOPCNT]++;
slatime[index] = (long) pois[index].get("sla");
etime = (float) etime * ts;
if (etime <= slatime[index]) {
stats[index][OPSUNDER]++;
stats[index][TOTALOPSUNDER]++;
} else {
stats[index][OPSOVER]++;
stats[index][TOTALOPSOVER]++;
}
stats[index][TIMEOP] = stats[index][TIMEOP] + etime;
stats[index][TOTALTIMEOP] = stats[index][TOTALTIMEOP] + etime;
if ((epochtime >= (oldtime + cut)) && (!totalsonly)) {
int x = 1;
if (filltimegap && (epochtime > (oldtime + cut))) {
while ((oldtime + (cut * x)) < epochtime) {
System.out.print(oldtime + (cut * x));
System.out.print("," + timestamp + ",");
System.out.print(lf + ",");
System.out.print(cut + ",");
for (int i = 0; i < stats.length; i++) {
System.out.print("0,0,");
if (sla) {
System.out.print("0,0,0,0,");
}
}
System.out.println();
x++;
}
}
System.out.print(epochtime);
System.out.print("," + timestamp + ",");
System.out.print(lf + ",");
if (filltimegap) {
System.out.print((epochtime - (oldtime + (cut * (x - 1)))) + ",");
} else {
System.out.print((epochtime - oldtime) + ",");
}
oldtime = epochtime;
for (int i = 0; i < stats.length; i++) {
System.out.format("%.0f%s", stats[i][OPCNT], ",");
if (stats[i][OPCNT] > 0) {
System.out.format("%.2f", (stats[i][TIMEOP] / stats[i][OPCNT]));
} else {
System.out.print("0");
}
if (sla) {
System.out.print(",");
System.out.print(slatime[i] + ",");
System.out.format("%.0f%s", stats[i][OPSUNDER], ",");
System.out.format("%.0f%s", stats[i][OPSOVER], ",");
if (stats[i][OPSOVER] > 0) {
System.out.format("%3.1f%s", ((stats[i][OPSUNDER] / stats[i][OPCNT]) * 100),
"%");
} else {
System.out.print("100.0%");
}
System.out.print(",");
}
if (i < (stats.length - 1)) {
System.out.print(",");
}
}
System.out.println();
for (int i = 0; i < stats.length; i++) {
stats[i][OPCNT] = 0;
stats[i][TIMEOP] = 0;
stats[i][OPSUNDER] = 0;
stats[i][OPSOVER] = 0;
}
} // if ((epochtime >= (oldtime + cut)) && (!totalsonly))
} else { // epoch within cut times
oldtime = epochtime;
starttime = epochtime;
}
} // if index != -1
} // while read line
// clean up
if (((epochtime - oldtime) > 0) && (!totalsonly)) {
System.out.print(epochtime);
System.out.print("," + timestamp + ",");
System.out.print(lf + ",");
System.out.print((epochtime - oldtime) + ",");
oldtime = epochtime;
for (int i = 0; i < stats.length; i++) {
System.out.format("%.0f%s", stats[i][OPCNT], ",");
if (stats[i][OPCNT] > 0) {
System.out.format("%.2f", (stats[i][TIMEOP] / stats[i][OPCNT]));
} else {
System.out.print("0");
}
if (sla) {
System.out.print(",");
System.out.print(slatime[i] + ",");
System.out.format("%.0f%s", stats[i][OPSUNDER], ",");
System.out.format("%.0f%s", stats[i][OPSOVER], ",");
if (stats[i][OPSOVER] > 0) {
System.out.format("%3.1f%s", ((stats[i][OPSUNDER] / stats[i][OPCNT]) * 100), "%");
} else {
System.out.print("100.0%");
}
System.out.print(",");
}
if (i < (stats.length - 1)) {
System.out.print(",");
}
}
System.out.println();
}
if (showtotals || totalsonly) {
if (!html) {
if (label != null && !label.isEmpty()) {
System.out.print("Totals, , " + label + ", ");
} else {
System.out.print("Totals, , " + new File(lf).getName() + ", ");
}
System.out.print((epochtime - starttime) + ", ");
for (int i = 0; i < stats.length; i++) {
System.out.format("%.0f%s", stats[i][TOTALOPCNT], ", ");
if (stats[i][TOTALOPCNT] > 0) {
System.out.format("%.2f%s", (stats[i][TOTALTIMEOP] / stats[i][TOTALOPCNT]), ", ");
} else {
System.out.print("0, ");
}
if (sla) {
System.out.print(slatime[i] + ", ");
System.out.format("%.0f%s", stats[i][TOTALOPSUNDER], ", ");
System.out.format("%.0f%s", stats[i][TOTALOPSOVER], ", ");
if (stats[i][TOTALOPSOVER] > 0) {
System.out.format("%3.1f%s",
((stats[i][TOTALOPSUNDER] / stats[i][TOTALOPCNT]) * 100), "%");
} else {
System.out.print("100.0%");
}
System.out.print(", ");
}
}
System.out.println();
} else {
printHTML(sla, epochtime, starttime, stats, slatime, TOTALOPCNT, TOTALOPSOVER, TOTALOPSUNDER,
TOTALTIMEOP, poi);
}
}
} catch (IOException ex) {
Logger.getLogger(Condenser.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private int findPoi(String brin, JSONArray[] identifiers) {
int x = 0;
int index = -1;
int findcount = 0;
boolean found = false;
// System.out.println("brin = " + brin);
while ((x < identifiers.length) && (!found)) {
findcount = 0;
for (int i = 0; i < identifiers[x].size(); i++) {
if (brin.contains((String) identifiers[x].get(i))) {
// System.out.println("id = " + identifiers[x].get(i));
findcount++;
}
}
if (findcount == identifiers[x].size()) {
found = true;
index = x;
}
x++;
}
return (index);
}
private void printHeader(JSONArray poi, boolean sla) {
System.out.print("clock,");
System.out.print("Timestamp,");
System.out.print("Logfile,");
System.out.print("Timespan(ms),");
for (int i = 0; i < poi.size(); i++) {
System.out.print((String) (poi.get(i)) + ".ops,");
System.out.print((String) (poi.get(i)) + ".time-op");
if (sla) {
System.out.print(",");
System.out.print((String) (poi.get(i)) + ".sla,");
System.out.print((String) (poi.get(i)) + ".under,");
System.out.print((String) (poi.get(i)) + ".over,");
System.out.print((String) (poi.get(i)) + ".percent");
}
if (i < (poi.size() - 1)) {
System.out.print(",");
}
}
System.out.println();
}
private void printHTMLHeader(JSONArray poi, boolean sla) {
// System.out.println("clock");
// System.out.println("Timestamp");
// System.out.println("Logfile");
// System.out.println("Timespan(ms)");
System.out.println("<table cellpadding=\"4\" border=\"1\">");
System.out.println("<tbody>");
System.out.println("<tr><font face=\"Consolas\">");
System.out.println("<td align=\"center\">Operation Type</td>");
System.out.println("<td align=\"center\">Operation count</td>");
System.out.println("<td align=\"center\">Average Time per Operation (ms)</td>");
System.out.println("<td align=\"center\">Total time consumed (ms)</td>");
System.out.println("<td align=\"center\">Under threshold count</td>");
System.out.println("<td align=\"center\">Over threshold count</td>");
System.out.println("<td align=\"center\">Threshold (ms)</td>");
System.out.println("<td align=\"center\">Percentage under threshold</td>");
System.out.println("</font></tr>");
}
private void printHTML(boolean sla, long epochtime, long starttime, float[][] stats, long[] slatime, int TOTALOPCNT,
int TOTALOPSOVER, int TOTALOPSUNDER, int TOTALTIMEOP, JSONArray poi) {
Date st = new Date(starttime);
Date et = new Date(epochtime);
SimpleDateFormat tf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.US);
System.out.println("<pre>Time span: " + tf.format(st) + " --> " + tf.format(et) + "</pre>");
System.out.println("<pre>Epoch time: " + starttime + " --> " + epochtime + "</pre>");
System.out
.println("<pre>Length of time = " + (epochtime - starttime) + "ms (" + ((epochtime - starttime) / 1000)
+ " seconds or " + (((epochtime - starttime) / 1000) / 60) + " minutes) </pre>");
System.out.println("<table cellpadding=\"4\" border=\"1\">");
System.out.println("<tbody>");
System.out.println("<tr>");
System.out.println("<td align=\"center\"><pre>Operation Type</pre></td>");
System.out.println("<td align=\"center\"><pre>Operation count</pre></td>");
System.out.println("<td align=\"center\"><pre>Average Time per Operation (ms)</pre></td>");
System.out.println("<td align=\"center\"><pre>Total time consumed (ms)</pre></td>");
System.out.println("<td align=\"center\"><pre>Under threshold count</pre></td>");
System.out.println("<td align=\"center\"><pre>Over threshold count</pre></td>");
System.out.println("<td align=\"center\"><pre>Percentage under threshold</pre></td>");
System.out.println("<td align=\"center\"><pre>Threshold (ms)</pre></td>");
System.out.println("</tr>");
for (int i = 0; i < stats.length; i++) {
System.out.println("<tr>");
System.out.println("<td><pre>" + poi.get(i) + "</pre></td>");
System.out.format("%s%.0f%s", "<td><pre>", stats[i][TOTALOPCNT], "</pre></td>");
if (stats[i][TOTALOPCNT] > 0) {
System.out.format("%s%.2f%s", "<td><pre>", (stats[i][TOTALTIMEOP] / stats[i][TOTALOPCNT]),
"</pre></td>");
System.out.format("%s%.2f%s", "<td><pre>", stats[i][TOTALTIMEOP], "</pre></td>");
} else {
System.out.print("<td><pre>0</pre></td><td><pre>0</pre></td>");
}
if (sla) {
System.out.println("<td><pre>");
System.out.format("%.0f%s", stats[i][TOTALOPSUNDER], "</pre></td>");
if (stats[i][TOTALOPSOVER] > 0) {
System.out.println("<td bgcolor=\"#ff6666\"><pre><b>");
System.out.format("%.0f%s", stats[i][TOTALOPSOVER], "</b></pre></td>");
System.out.format("%s%3.1f%s", "<td bgcolor=\"#ff6666\"><pre><b>",
((stats[i][TOTALOPSUNDER] / stats[i][TOTALOPCNT]) * 100), "%</b></pre></td>");
} else {
System.out.print("<td><pre>0</pre></td>");
System.out.print("<td><pre>100.0%</pre></td>");
}
System.out.print("<td><pre>" + slatime[i] + "</pre></td>");
}
System.out.println("</tr>");
}
System.out.println("</tr></tbody>");
System.out.println("</table><br>");
}
}
| UTF-8 | Java | 23,193 | java | Condenser.java | Java | [
{
"context": "n.simple.parser.ParseException;\n\n/**\n *\n * @author rmfaller\n */\nclass Condenser {\n\n Condenser(JSONObject c",
"end": 642,
"score": 0.9988066554069519,
"start": 634,
"tag": "USERNAME",
"value": "rmfaller"
}
] | null | [] | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sawmill;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
/**
*
* @author rmfaller
*/
class Condenser {
Condenser(JSONObject config, BufferedReader br) {
}
void condense(JSONObject config, BufferedReader br, long cut, String cfn, boolean showtotals, String lf,
boolean sla, boolean showheader, boolean filltimegap, boolean totalsonly, boolean html, String label,
long startcut, long endcut) {
String timestampformat = config.get("timestampformat").toString();
SimpleDateFormat sdf = new SimpleDateFormat(timestampformat);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String fielddelimiter = config.get("fielddelimiter").toString();
String timestamp = null;
String timescale = null;
String lapsedtimefield = null;
Date operationtime = null;
float etime = 0;
long epochtime = 0;
long oldtime = 0;
long starttime = 0;
long[] slatime;
char fd = 0;
switch (fielddelimiter) {
case "JSON": {
fd = 'J';
}
break;
case "TAB":
fd = '\t';
break;
case "COMMA":
fd = ',';
break;
case "SPACE":
fd = ' ';
break;
default:
break;
}
// String timefield = null;
JSONArray poi = (JSONArray) config.get("poi");
JSONObject[] pois = null;
JSONObject logresponse = null;
String[] brina = null;
JSONArray[] identifiers = null;
JSONParser jp = new JSONParser();
int OPCNT = 0;
int TIMEOP = 1;
int TOTALOPCNT = 2;
int TOTALTIMEOP = 3;
int OPSUNDER = 4;
int OPSOVER = 5;
int TOTALOPSUNDER = 6;
int TOTALOPSOVER = 7;
long opcounter = 0;
float[][] stats;
String brin;
if (!poi.isEmpty()) {
pois = new JSONObject[poi.size()];
identifiers = new JSONArray[poi.size()];
slatime = new long[poi.size()];
stats = new float[poi.size()][8];
for (int i = 0; i < poi.size(); i++) {
pois[i] = (JSONObject) config.get(poi.get(i));
identifiers[i] = (JSONArray) pois[i].get("identifiers");
slatime[i] = (long) pois[i].get("sla");
for (int x = 0; x <= 7; x++) {
stats[i][x] = 0;
}
}
try {
while ((brin = br.readLine()) != null) {
int index = findPoi(brin, identifiers);
opcounter++;
// System.out.println("processing line " + opcounter + " : " + brin);
if (index != -1) {
if (fd == 'J') {
try {
JSONObject logentry = (JSONObject) jp.parse(brin);
logresponse = (JSONObject) logentry.get("response");
timestamp = (String) logentry.get(config.get("timestampfield"));
Long letime = (Long) logresponse.get(pois[index].get("lapsedtimefield"));
// Long letime = (Long) logresponse.get(config.get("lapsedtimefield"));
etime = letime.floatValue();
timescale = (String) logresponse.get(config.get("timescale"));
if (timescale == null) {
timescale = "MILLISECONDS";
}
} catch (ParseException ex) {
Logger.getLogger(Condenser.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
String logentry = brin.replaceAll("\\[", "").replaceAll("\\]", "");
// System.out.println("non-json log = " + logentry);
Long y = (Long) config.get("timestampfield");
brina = logentry.split(String.valueOf(fd));
if (timestampformat.contains(" ")) {
timestamp = brina[y.intValue()] + " " + brina[(y.intValue() + 1)];
} else {
timestamp = brina[y.intValue()];
}
timescale = (String) config.get("timescale");
if (timescale == null) {
timescale = "MILLISECONDS";
}
lapsedtimefield = (String) pois[index].get("lapsedtimefield");
int fi;
String ta = null;
if (lapsedtimefield.matches("[-+]?\\d+(\\.\\d+)?")) {
ta = brina[Integer.parseInt(lapsedtimefield)];
ta = ta.replaceAll("\\\"", "").replaceAll("\\\"", "");
// System.out.println("found: " + lapsedtimefield + "--" + ta);
} else {
fi = brina.length - 1;
while (!brina[fi].contains(lapsedtimefield) && (fi > 0)) {
fi--;
}
if (fi < brina.length) {
ta = brina[fi].substring(lapsedtimefield.length());
} else {
System.out.println("can not find: " + lapsedtimefield);
ta = "0";
}
}
etime = Float.parseFloat(ta);
}
// System.out.println("Pattern: " + sdf.toPattern());
// System.out.println("timestamp ->" + timestamp + "<-");
try {
operationtime = sdf.parse(timestamp.replaceAll("\\[", "").replaceAll("\\]", ""));
// operationtime = sdf.parse(timestamp);
} catch (java.text.ParseException ex) {
Logger.getLogger(Condenser.class.getName()).log(Level.SEVERE, null, ex);
}
float ts = (float) 1.0;
if (etime > 0) {
switch (timescale) {
case "MILLISECONDS":
ts = (float) 1.0;
break;
case "NANOSECONDS":
ts = (float) .000001;
break;
case "SECONDS":
ts = (float) 1000.0;
break;
case "MINUTES":
ts = (float) 60000.0;
break;
default:
ts = 1;
break;
}
}
epochtime = operationtime.getTime();
if ((epochtime >= startcut) && (epochtime <= endcut)) {
if (oldtime == 0) {
oldtime = epochtime;
starttime = epochtime;
if (showheader && !html) {
printHeader(poi, sla);
}
// if (showheader && html) {
// printHTMLHeader(poi, sla);
// }
}
stats[index][OPCNT]++;
stats[index][TOTALOPCNT]++;
slatime[index] = (long) pois[index].get("sla");
etime = (float) etime * ts;
if (etime <= slatime[index]) {
stats[index][OPSUNDER]++;
stats[index][TOTALOPSUNDER]++;
} else {
stats[index][OPSOVER]++;
stats[index][TOTALOPSOVER]++;
}
stats[index][TIMEOP] = stats[index][TIMEOP] + etime;
stats[index][TOTALTIMEOP] = stats[index][TOTALTIMEOP] + etime;
if ((epochtime >= (oldtime + cut)) && (!totalsonly)) {
int x = 1;
if (filltimegap && (epochtime > (oldtime + cut))) {
while ((oldtime + (cut * x)) < epochtime) {
System.out.print(oldtime + (cut * x));
System.out.print("," + timestamp + ",");
System.out.print(lf + ",");
System.out.print(cut + ",");
for (int i = 0; i < stats.length; i++) {
System.out.print("0,0,");
if (sla) {
System.out.print("0,0,0,0,");
}
}
System.out.println();
x++;
}
}
System.out.print(epochtime);
System.out.print("," + timestamp + ",");
System.out.print(lf + ",");
if (filltimegap) {
System.out.print((epochtime - (oldtime + (cut * (x - 1)))) + ",");
} else {
System.out.print((epochtime - oldtime) + ",");
}
oldtime = epochtime;
for (int i = 0; i < stats.length; i++) {
System.out.format("%.0f%s", stats[i][OPCNT], ",");
if (stats[i][OPCNT] > 0) {
System.out.format("%.2f", (stats[i][TIMEOP] / stats[i][OPCNT]));
} else {
System.out.print("0");
}
if (sla) {
System.out.print(",");
System.out.print(slatime[i] + ",");
System.out.format("%.0f%s", stats[i][OPSUNDER], ",");
System.out.format("%.0f%s", stats[i][OPSOVER], ",");
if (stats[i][OPSOVER] > 0) {
System.out.format("%3.1f%s", ((stats[i][OPSUNDER] / stats[i][OPCNT]) * 100),
"%");
} else {
System.out.print("100.0%");
}
System.out.print(",");
}
if (i < (stats.length - 1)) {
System.out.print(",");
}
}
System.out.println();
for (int i = 0; i < stats.length; i++) {
stats[i][OPCNT] = 0;
stats[i][TIMEOP] = 0;
stats[i][OPSUNDER] = 0;
stats[i][OPSOVER] = 0;
}
} // if ((epochtime >= (oldtime + cut)) && (!totalsonly))
} else { // epoch within cut times
oldtime = epochtime;
starttime = epochtime;
}
} // if index != -1
} // while read line
// clean up
if (((epochtime - oldtime) > 0) && (!totalsonly)) {
System.out.print(epochtime);
System.out.print("," + timestamp + ",");
System.out.print(lf + ",");
System.out.print((epochtime - oldtime) + ",");
oldtime = epochtime;
for (int i = 0; i < stats.length; i++) {
System.out.format("%.0f%s", stats[i][OPCNT], ",");
if (stats[i][OPCNT] > 0) {
System.out.format("%.2f", (stats[i][TIMEOP] / stats[i][OPCNT]));
} else {
System.out.print("0");
}
if (sla) {
System.out.print(",");
System.out.print(slatime[i] + ",");
System.out.format("%.0f%s", stats[i][OPSUNDER], ",");
System.out.format("%.0f%s", stats[i][OPSOVER], ",");
if (stats[i][OPSOVER] > 0) {
System.out.format("%3.1f%s", ((stats[i][OPSUNDER] / stats[i][OPCNT]) * 100), "%");
} else {
System.out.print("100.0%");
}
System.out.print(",");
}
if (i < (stats.length - 1)) {
System.out.print(",");
}
}
System.out.println();
}
if (showtotals || totalsonly) {
if (!html) {
if (label != null && !label.isEmpty()) {
System.out.print("Totals, , " + label + ", ");
} else {
System.out.print("Totals, , " + new File(lf).getName() + ", ");
}
System.out.print((epochtime - starttime) + ", ");
for (int i = 0; i < stats.length; i++) {
System.out.format("%.0f%s", stats[i][TOTALOPCNT], ", ");
if (stats[i][TOTALOPCNT] > 0) {
System.out.format("%.2f%s", (stats[i][TOTALTIMEOP] / stats[i][TOTALOPCNT]), ", ");
} else {
System.out.print("0, ");
}
if (sla) {
System.out.print(slatime[i] + ", ");
System.out.format("%.0f%s", stats[i][TOTALOPSUNDER], ", ");
System.out.format("%.0f%s", stats[i][TOTALOPSOVER], ", ");
if (stats[i][TOTALOPSOVER] > 0) {
System.out.format("%3.1f%s",
((stats[i][TOTALOPSUNDER] / stats[i][TOTALOPCNT]) * 100), "%");
} else {
System.out.print("100.0%");
}
System.out.print(", ");
}
}
System.out.println();
} else {
printHTML(sla, epochtime, starttime, stats, slatime, TOTALOPCNT, TOTALOPSOVER, TOTALOPSUNDER,
TOTALTIMEOP, poi);
}
}
} catch (IOException ex) {
Logger.getLogger(Condenser.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private int findPoi(String brin, JSONArray[] identifiers) {
int x = 0;
int index = -1;
int findcount = 0;
boolean found = false;
// System.out.println("brin = " + brin);
while ((x < identifiers.length) && (!found)) {
findcount = 0;
for (int i = 0; i < identifiers[x].size(); i++) {
if (brin.contains((String) identifiers[x].get(i))) {
// System.out.println("id = " + identifiers[x].get(i));
findcount++;
}
}
if (findcount == identifiers[x].size()) {
found = true;
index = x;
}
x++;
}
return (index);
}
private void printHeader(JSONArray poi, boolean sla) {
System.out.print("clock,");
System.out.print("Timestamp,");
System.out.print("Logfile,");
System.out.print("Timespan(ms),");
for (int i = 0; i < poi.size(); i++) {
System.out.print((String) (poi.get(i)) + ".ops,");
System.out.print((String) (poi.get(i)) + ".time-op");
if (sla) {
System.out.print(",");
System.out.print((String) (poi.get(i)) + ".sla,");
System.out.print((String) (poi.get(i)) + ".under,");
System.out.print((String) (poi.get(i)) + ".over,");
System.out.print((String) (poi.get(i)) + ".percent");
}
if (i < (poi.size() - 1)) {
System.out.print(",");
}
}
System.out.println();
}
private void printHTMLHeader(JSONArray poi, boolean sla) {
// System.out.println("clock");
// System.out.println("Timestamp");
// System.out.println("Logfile");
// System.out.println("Timespan(ms)");
System.out.println("<table cellpadding=\"4\" border=\"1\">");
System.out.println("<tbody>");
System.out.println("<tr><font face=\"Consolas\">");
System.out.println("<td align=\"center\">Operation Type</td>");
System.out.println("<td align=\"center\">Operation count</td>");
System.out.println("<td align=\"center\">Average Time per Operation (ms)</td>");
System.out.println("<td align=\"center\">Total time consumed (ms)</td>");
System.out.println("<td align=\"center\">Under threshold count</td>");
System.out.println("<td align=\"center\">Over threshold count</td>");
System.out.println("<td align=\"center\">Threshold (ms)</td>");
System.out.println("<td align=\"center\">Percentage under threshold</td>");
System.out.println("</font></tr>");
}
private void printHTML(boolean sla, long epochtime, long starttime, float[][] stats, long[] slatime, int TOTALOPCNT,
int TOTALOPSOVER, int TOTALOPSUNDER, int TOTALTIMEOP, JSONArray poi) {
Date st = new Date(starttime);
Date et = new Date(epochtime);
SimpleDateFormat tf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.US);
System.out.println("<pre>Time span: " + tf.format(st) + " --> " + tf.format(et) + "</pre>");
System.out.println("<pre>Epoch time: " + starttime + " --> " + epochtime + "</pre>");
System.out
.println("<pre>Length of time = " + (epochtime - starttime) + "ms (" + ((epochtime - starttime) / 1000)
+ " seconds or " + (((epochtime - starttime) / 1000) / 60) + " minutes) </pre>");
System.out.println("<table cellpadding=\"4\" border=\"1\">");
System.out.println("<tbody>");
System.out.println("<tr>");
System.out.println("<td align=\"center\"><pre>Operation Type</pre></td>");
System.out.println("<td align=\"center\"><pre>Operation count</pre></td>");
System.out.println("<td align=\"center\"><pre>Average Time per Operation (ms)</pre></td>");
System.out.println("<td align=\"center\"><pre>Total time consumed (ms)</pre></td>");
System.out.println("<td align=\"center\"><pre>Under threshold count</pre></td>");
System.out.println("<td align=\"center\"><pre>Over threshold count</pre></td>");
System.out.println("<td align=\"center\"><pre>Percentage under threshold</pre></td>");
System.out.println("<td align=\"center\"><pre>Threshold (ms)</pre></td>");
System.out.println("</tr>");
for (int i = 0; i < stats.length; i++) {
System.out.println("<tr>");
System.out.println("<td><pre>" + poi.get(i) + "</pre></td>");
System.out.format("%s%.0f%s", "<td><pre>", stats[i][TOTALOPCNT], "</pre></td>");
if (stats[i][TOTALOPCNT] > 0) {
System.out.format("%s%.2f%s", "<td><pre>", (stats[i][TOTALTIMEOP] / stats[i][TOTALOPCNT]),
"</pre></td>");
System.out.format("%s%.2f%s", "<td><pre>", stats[i][TOTALTIMEOP], "</pre></td>");
} else {
System.out.print("<td><pre>0</pre></td><td><pre>0</pre></td>");
}
if (sla) {
System.out.println("<td><pre>");
System.out.format("%.0f%s", stats[i][TOTALOPSUNDER], "</pre></td>");
if (stats[i][TOTALOPSOVER] > 0) {
System.out.println("<td bgcolor=\"#ff6666\"><pre><b>");
System.out.format("%.0f%s", stats[i][TOTALOPSOVER], "</b></pre></td>");
System.out.format("%s%3.1f%s", "<td bgcolor=\"#ff6666\"><pre><b>",
((stats[i][TOTALOPSUNDER] / stats[i][TOTALOPCNT]) * 100), "%</b></pre></td>");
} else {
System.out.print("<td><pre>0</pre></td>");
System.out.print("<td><pre>100.0%</pre></td>");
}
System.out.print("<td><pre>" + slatime[i] + "</pre></td>");
}
System.out.println("</tr>");
}
System.out.println("</tr></tbody>");
System.out.println("</table><br>");
}
}
| 23,193 | 0.388652 | 0.381494 | 460 | 49.419567 | 26.785137 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.967391 | false | false | 3 |
a17c9804476610843f90bc310103d067ba94a4a5 | 23,304,492,560,403 | 18ac8b734b9928e9e74b1395c7b55db2e923895f | /src/test/java/com/delay/DemoApplicationTests.java | df7078a9465ac1c101c0525b9020c61f16a513eb | [] | no_license | jackandyao/delay-study | https://github.com/jackandyao/delay-study | 6e8969e8c60fde668f8cf0e0370d6da63f5de512 | 2b7842a42b675b310d5535789a871b5ac2b02e77 | refs/heads/master | 2020-04-20T18:49:39.137000 | 2019-02-04T05:37:14 | 2019-02-04T05:37:14 | 169,032,421 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.delay;
import com.delay.service.IDelayOrderService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.concurrent.CountDownLatch;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApplication.class)
public class DemoApplicationTests {
@Autowired
private IDelayOrderService delayOrderService;
private CountDownLatch cdl = new CountDownLatch(1);
@Test
public void produce(){
delayOrderService.product();
try {
Thread.sleep(1000);//模拟程序不让其中断
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Test
public void consumer(){
for (int i=0;i<1;i++){
new Thread(new DelayThread()).start();
cdl.countDown();
}
try {
Thread.sleep(100000);//模拟程序不让其中断
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private class DelayThread implements Runnable{
@Override
public void run() {
try {
cdl.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
delayOrderService.consumer();
}
}
}
| UTF-8 | Java | 1,247 | java | DemoApplicationTests.java | Java | [] | null | [] | package com.delay;
import com.delay.service.IDelayOrderService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.concurrent.CountDownLatch;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApplication.class)
public class DemoApplicationTests {
@Autowired
private IDelayOrderService delayOrderService;
private CountDownLatch cdl = new CountDownLatch(1);
@Test
public void produce(){
delayOrderService.product();
try {
Thread.sleep(1000);//模拟程序不让其中断
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Test
public void consumer(){
for (int i=0;i<1;i++){
new Thread(new DelayThread()).start();
cdl.countDown();
}
try {
Thread.sleep(100000);//模拟程序不让其中断
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private class DelayThread implements Runnable{
@Override
public void run() {
try {
cdl.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
delayOrderService.consumer();
}
}
}
| 1,247 | 0.730801 | 0.71924 | 57 | 20.228069 | 18.48377 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.666667 | false | false | 3 |
8814707c3ed4279974f768e3d505010d42dfd3d5 | 22,960,895,180,914 | af8c70f1cf2459a9f7317fbfd8b4edf60f6f3c0d | /tutorials/calculator/server/calculator-server/src/main/java/org/example/http/CalculatorApplication.java | 240001ddf9238f1f8a83c7e78508ec1e7028be73 | [
"Apache-2.0"
] | permissive | OlegDokuka/griffon | https://github.com/OlegDokuka/griffon | cbc23cc7815a2507c8c5c4383330caf60df40fc6 | 30f0433d6e8a0d618511fad8ea36ec673be265ee | refs/heads/development | 2021-01-15T09:15:52.504000 | 2015-11-13T01:30:50 | 2015-11-13T01:30:50 | 46,296,147 | 1 | 0 | null | true | 2015-11-16T19:12:23 | 2015-11-16T19:12:23 | 2015-11-16T19:12:19 | 2015-11-13T01:40:07 | 591,057 | 0 | 0 | 0 | null | null | null | package org.example.http;
import org.example.calculator.pm.CalculatorPMResource;
import org.glassfish.jersey.server.ResourceConfig;
import javax.ws.rs.ApplicationPath;
@ApplicationPath("/")
public class CalculatorApplication extends ResourceConfig {
public CalculatorApplication() {
registerClasses(
CalculatorPMResource.class
);
}
} | UTF-8 | Java | 372 | java | CalculatorApplication.java | Java | [] | null | [] | package org.example.http;
import org.example.calculator.pm.CalculatorPMResource;
import org.glassfish.jersey.server.ResourceConfig;
import javax.ws.rs.ApplicationPath;
@ApplicationPath("/")
public class CalculatorApplication extends ResourceConfig {
public CalculatorApplication() {
registerClasses(
CalculatorPMResource.class
);
}
} | 372 | 0.747312 | 0.747312 | 15 | 23.866667 | 20.142382 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 3 |
2a12c43e8ae5a674ae059b507eff02eaeeca9187 | 29,824,252,906,319 | c972aa36d7d528ee4947af0d5690ef19f114d46f | /Adv/src/adv/Web/DataPackage.java | 1a1d4e96de2e21f499bd221daffab4faeeb0c3f0 | [] | no_license | Carton9/JavaOpenSource | https://github.com/Carton9/JavaOpenSource | ff75e98bf371ee521e6e64bacb983da5995c818a | 0ceaf173acfbb115b6b553c24d65adc09c96787e | refs/heads/master | 2020-12-05T00:00:00.590000 | 2018-09-01T15:30:46 | 2018-09-01T15:30:46 | 83,638,253 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package adv.Web;
//fix
import java.io.Serializable;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
//TODO make a child class for password
/**
* This class use to save data from file, text and image, and carry them to a new device through internet.
* @author Mike Cai
* @version v1.00
*/
public class DataPackage implements Serializable {
private static final long serialVersionUID = 4462539565L;
private transient boolean isBuild;
private transient Cipher cipherEncrypt;
private transient Cipher cipherDecrypt;
boolean isHard=false;
String commend="";//divide commend by $ and /
String description="";//information for user to read, divide by $
String encryption="";//data for know is the file be correct decrypte
ArrayList<byte[]> data;//encrypted data
public DataPackage() {
data=new ArrayList<byte[]>();
isBuild=false;
}
private boolean checkPackage(String signature){
String encryption;
try {
byte[] signatureBuff=signature.getBytes();
Base64.Encoder encoder=Base64.getEncoder();
Base64.Decoder decoder=Base64.getDecoder();
byte[] cipherData = cipherEncrypt.doFinal(signatureBuff);
encryption=encoder.encodeToString(cipherData);
} catch (IllegalBlockSizeException | BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
if(encryption.equals(this.encryption))return true;
return false;
}
private boolean signPackage(String signature){
try {
byte[] signatureBuff=signature.getBytes();
Base64.Encoder encoder=Base64.getEncoder();
Base64.Decoder decoder=Base64.getDecoder();
byte[] cipherData = cipherEncrypt.doFinal(signatureBuff);
encryption=encoder.encodeToString(cipherData);
} catch (IllegalBlockSizeException | BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}
private boolean buildCipher(String id){
if(id.getBytes().length<8)return false;
SecretKey secretKey;
try {
DESKeySpec keySpec = new DESKeySpec(id.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("des");
secretKey = keyFactory.generateSecret(keySpec);
} catch (InvalidKeyException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return false;
}catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
SecureRandom random = new SecureRandom();
try {
cipherEncrypt = Cipher.getInstance("des");
cipherEncrypt.init(Cipher.ENCRYPT_MODE, secretKey, random);
cipherDecrypt = Cipher.getInstance("des");
cipherDecrypt.init(Cipher.DECRYPT_MODE, secretKey, random);
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
isBuild=true;
return true;
}
/******************************/
/**
* This method can get the commend for the package.
* @return A list of commend.
*/
public ArrayList<String[]> getCommend(){
String[] outputBuff= commend.split("$");
ArrayList<String[]> output=new ArrayList<String[]>();
for(int i=0;i<outputBuff.length;i++){
output.add(outputBuff[i].split("/"));
}
return output;
}
/**
* This method can get the description for the package.
* @return A list of description.
*/
public ArrayList<String> getDescription(){
String[] outputBuff= description.split("$");
ArrayList<String> output=new ArrayList<String>();
for(int i=0;i<outputBuff.length;i++){
output.add(outputBuff[i]);
}
return output;
}
/**
* This method can get the data for the package.
* @param pointer-which data in data list user want to get.
* @return the data in position that pointer point to.
*/
public byte[] getData(int pointer){
try {
byte[] dataBuff=data.get(pointer);
byte[] buff=cipherDecrypt.doFinal(dataBuff);
return buff;
} catch (IllegalBlockSizeException | BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
/**
* This method can check the signature and id is valid for this package.
* @param signature-for check the package can or can not be decrypte, id- password for decrypte
* @return A boolean that show the signature and id is valid or not.
*/
public boolean checkSign(String signature,String id){
if(buildCipher(id)&&checkPackage(signature))return true;
else {
cipherEncrypt=null;
cipherDecrypt=null;
if(isHard){
commend="";
description="";
encryption="";
data=null;
}
return false;
}
}
/******************************/
/**
* This method can init a package and wait for input data.
* @param signature-for create a text that will be use later for check this package, id- password for decrypte
* @return is the signature and id valid
*/
public boolean init(String signature,String id){
if(buildCipher(id)&&signPackage(signature))return true;
else return false;
}
/**
* This method can add a commend in the package.
* @param commend-confirm what the data used to, pointer-which data in data list user want to get.
*/
public void addCommend(String commend,int pointer){
this.commend+=commend+"/"+pointer+"$";
}
/**
* This method can add a description in the package.
* @param description-for descrip data.
*/
public void addDescription(String description){
this.description+=description+"$";
}
/**
* This method can add a data in the package.
* @param
* @return A boolean that show the data is valid or not.
*/
public boolean addData(String dataType,byte[] data){
if(isBuild){
try {
addCommend("DataType:"+dataType,this.data.size());
byte[] buff = cipherEncrypt.doFinal(data);
this.data.add(buff);
} catch (IllegalBlockSizeException | BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}
return false;
}
public DataPackage output(){
return this;
}
}
| UTF-8 | Java | 6,817 | java | DataPackage.java | Java | [
{
"context": " them to a new device through internet.\n * @author Mike Cai\n * @version v1.00\n */\npublic class DataPackage im",
"end": 851,
"score": 0.9994596838951111,
"start": 843,
"tag": "NAME",
"value": "Mike Cai"
}
] | null | [] | package adv.Web;
//fix
import java.io.Serializable;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
//TODO make a child class for password
/**
* This class use to save data from file, text and image, and carry them to a new device through internet.
* @author <NAME>
* @version v1.00
*/
public class DataPackage implements Serializable {
private static final long serialVersionUID = 4462539565L;
private transient boolean isBuild;
private transient Cipher cipherEncrypt;
private transient Cipher cipherDecrypt;
boolean isHard=false;
String commend="";//divide commend by $ and /
String description="";//information for user to read, divide by $
String encryption="";//data for know is the file be correct decrypte
ArrayList<byte[]> data;//encrypted data
public DataPackage() {
data=new ArrayList<byte[]>();
isBuild=false;
}
private boolean checkPackage(String signature){
String encryption;
try {
byte[] signatureBuff=signature.getBytes();
Base64.Encoder encoder=Base64.getEncoder();
Base64.Decoder decoder=Base64.getDecoder();
byte[] cipherData = cipherEncrypt.doFinal(signatureBuff);
encryption=encoder.encodeToString(cipherData);
} catch (IllegalBlockSizeException | BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
if(encryption.equals(this.encryption))return true;
return false;
}
private boolean signPackage(String signature){
try {
byte[] signatureBuff=signature.getBytes();
Base64.Encoder encoder=Base64.getEncoder();
Base64.Decoder decoder=Base64.getDecoder();
byte[] cipherData = cipherEncrypt.doFinal(signatureBuff);
encryption=encoder.encodeToString(cipherData);
} catch (IllegalBlockSizeException | BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}
private boolean buildCipher(String id){
if(id.getBytes().length<8)return false;
SecretKey secretKey;
try {
DESKeySpec keySpec = new DESKeySpec(id.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("des");
secretKey = keyFactory.generateSecret(keySpec);
} catch (InvalidKeyException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return false;
}catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
SecureRandom random = new SecureRandom();
try {
cipherEncrypt = Cipher.getInstance("des");
cipherEncrypt.init(Cipher.ENCRYPT_MODE, secretKey, random);
cipherDecrypt = Cipher.getInstance("des");
cipherDecrypt.init(Cipher.DECRYPT_MODE, secretKey, random);
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
isBuild=true;
return true;
}
/******************************/
/**
* This method can get the commend for the package.
* @return A list of commend.
*/
public ArrayList<String[]> getCommend(){
String[] outputBuff= commend.split("$");
ArrayList<String[]> output=new ArrayList<String[]>();
for(int i=0;i<outputBuff.length;i++){
output.add(outputBuff[i].split("/"));
}
return output;
}
/**
* This method can get the description for the package.
* @return A list of description.
*/
public ArrayList<String> getDescription(){
String[] outputBuff= description.split("$");
ArrayList<String> output=new ArrayList<String>();
for(int i=0;i<outputBuff.length;i++){
output.add(outputBuff[i]);
}
return output;
}
/**
* This method can get the data for the package.
* @param pointer-which data in data list user want to get.
* @return the data in position that pointer point to.
*/
public byte[] getData(int pointer){
try {
byte[] dataBuff=data.get(pointer);
byte[] buff=cipherDecrypt.doFinal(dataBuff);
return buff;
} catch (IllegalBlockSizeException | BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
/**
* This method can check the signature and id is valid for this package.
* @param signature-for check the package can or can not be decrypte, id- password for decrypte
* @return A boolean that show the signature and id is valid or not.
*/
public boolean checkSign(String signature,String id){
if(buildCipher(id)&&checkPackage(signature))return true;
else {
cipherEncrypt=null;
cipherDecrypt=null;
if(isHard){
commend="";
description="";
encryption="";
data=null;
}
return false;
}
}
/******************************/
/**
* This method can init a package and wait for input data.
* @param signature-for create a text that will be use later for check this package, id- password for decrypte
* @return is the signature and id valid
*/
public boolean init(String signature,String id){
if(buildCipher(id)&&signPackage(signature))return true;
else return false;
}
/**
* This method can add a commend in the package.
* @param commend-confirm what the data used to, pointer-which data in data list user want to get.
*/
public void addCommend(String commend,int pointer){
this.commend+=commend+"/"+pointer+"$";
}
/**
* This method can add a description in the package.
* @param description-for descrip data.
*/
public void addDescription(String description){
this.description+=description+"$";
}
/**
* This method can add a data in the package.
* @param
* @return A boolean that show the data is valid or not.
*/
public boolean addData(String dataType,byte[] data){
if(isBuild){
try {
addCommend("DataType:"+dataType,this.data.size());
byte[] buff = cipherEncrypt.doFinal(data);
this.data.add(buff);
} catch (IllegalBlockSizeException | BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}
return false;
}
public DataPackage output(){
return this;
}
}
| 6,815 | 0.714244 | 0.708963 | 221 | 29.846153 | 22.099607 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.307692 | false | false | 3 |
d760d8e1e207a56b89ba95760f1c1f4f36c4c68b | 5,016,521,826,068 | 0a27b9dfa15cd048dad641b4730cb81a8e89439e | /example-spring-scheduling/src/main/java/de/bruns/example/spring/scheduling/namespace/ReceiveMailNamespaceService.java | a0d0c587de81a6239a1811bd2be502b02d917948 | [] | no_license | me4bruno/blog-examples | https://github.com/me4bruno/blog-examples | 5c1ef68316b49c49b698dce3d8e6869c2e64dc25 | 4675d470c00ab88a2f04ffebcc349a3888fa5fef | refs/heads/master | 2022-12-21T03:17:51.286000 | 2020-05-31T07:50:31 | 2020-05-31T07:50:31 | 5,798,839 | 4 | 4 | null | false | 2022-12-15T23:59:10 | 2012-09-13T18:12:36 | 2020-05-31T07:50:56 | 2022-12-15T23:59:07 | 14,785 | 2 | 2 | 3 | CSS | false | false | package de.bruns.example.spring.scheduling.namespace;
import de.bruns.example.spring.scheduling.ReceiveMailRunnable;
public class ReceiveMailNamespaceService {
public void receiveMailFixedRate() {
ReceiveMailRunnable.execute(getClass().getSimpleName() + "-FixedRate");
}
public void receiveMailCron() {
ReceiveMailRunnable.execute(getClass().getSimpleName() + "-TimeCron");
}
}
| UTF-8 | Java | 391 | java | ReceiveMailNamespaceService.java | Java | [] | null | [] | package de.bruns.example.spring.scheduling.namespace;
import de.bruns.example.spring.scheduling.ReceiveMailRunnable;
public class ReceiveMailNamespaceService {
public void receiveMailFixedRate() {
ReceiveMailRunnable.execute(getClass().getSimpleName() + "-FixedRate");
}
public void receiveMailCron() {
ReceiveMailRunnable.execute(getClass().getSimpleName() + "-TimeCron");
}
}
| 391 | 0.780051 | 0.780051 | 15 | 25.066668 | 28.174377 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8 | false | false | 3 |
2199d28416913ed5330723c2f9152b957197e66b | 28,355,374,103,761 | 5a0bfac7ad00c079fe8e0bdf1482f4271c46eeab | /app/src/main/wechat6.5.3/android/support/v4/app/Fragment.java | a82ad68dd40316d6ff4869fe9b8c17b5f34f6a9c | [] | no_license | newtonker/wechat6.5.3 | https://github.com/newtonker/wechat6.5.3 | 8af53a870a752bb9e3c92ec92a63c1252cb81c10 | 637a69732afa3a936afc9f4679994b79a9222680 | refs/heads/master | 2020-04-16T03:32:32.230000 | 2017-06-15T09:54:10 | 2017-06-15T09:54:10 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package android.support.v4.app;
import android.app.Activity;
import android.content.ComponentCallbacks;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.Parcelable.Creator;
import android.support.v4.e.c;
import android.support.v4.e.i;
import android.support.v4.view.g;
import android.util.SparseArray;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import com.tencent.mmdb.FileUtils;
import java.io.FileDescriptor;
import java.io.PrintWriter;
public class Fragment implements ComponentCallbacks, OnCreateContextMenuListener {
private static final i<String, Class<?>> oC = new i();
static final Object oD = new Object();
int mIndex = -1;
int mState = 0;
public View mView;
View oE;
int oF;
Bundle oG;
SparseArray<Parcelable> oH;
String oI;
public Bundle oJ;
Fragment oK;
int oL = -1;
int oM;
boolean oN;
public boolean oO;
boolean oP;
boolean oQ;
boolean oR;
int oS;
l oT;
j oU;
l oV;
Fragment oW;
int oX;
int oY;
String oZ;
boolean pa;
boolean pb;
boolean pc;
boolean pd;
boolean pe;
boolean pf = true;
boolean pg;
int ph;
ViewGroup pi;
View pj;
boolean pk;
boolean pl = true;
r pm;
boolean pn;
boolean po;
Object pp = null;
Object pq = oD;
Object pr = null;
Object ps = oD;
Object pt = null;
Object pu = oD;
Boolean pv;
Boolean pw;
ai px = null;
ai py = null;
public static class SavedState implements Parcelable {
public static final Creator<SavedState> CREATOR = new Creator<SavedState>() {
public final /* synthetic */ Object createFromParcel(Parcel parcel) {
return new SavedState(parcel);
}
public final /* bridge */ /* synthetic */ Object[] newArray(int i) {
return new SavedState[i];
}
};
final Bundle pA;
SavedState(Bundle bundle) {
this.pA = bundle;
}
SavedState(Parcel parcel) {
this.pA = parcel.readBundle();
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel parcel, int i) {
parcel.writeBundle(this.pA);
}
}
public static class a extends RuntimeException {
public a(String str, Exception exception) {
super(str, exception);
}
}
public static Fragment b(Context context, String str) {
return a(context, str, null);
}
public static Fragment a(Context context, String str, Bundle bundle) {
try {
Class cls = (Class) oC.get(str);
if (cls == null) {
cls = context.getClassLoader().loadClass(str);
oC.put(str, cls);
}
Fragment fragment = (Fragment) cls.newInstance();
if (bundle != null) {
bundle.setClassLoader(fragment.getClass().getClassLoader());
fragment.oJ = bundle;
}
return fragment;
} catch (Exception e) {
throw new a("Unable to instantiate fragment " + str + ": make sure class name exists, is public, and has an empty constructor that is public", e);
} catch (Exception e2) {
throw new a("Unable to instantiate fragment " + str + ": make sure class name exists, is public, and has an empty constructor that is public", e2);
} catch (Exception e22) {
throw new a("Unable to instantiate fragment " + str + ": make sure class name exists, is public, and has an empty constructor that is public", e22);
}
}
static boolean c(Context context, String str) {
try {
Class cls = (Class) oC.get(str);
if (cls == null) {
cls = context.getClassLoader().loadClass(str);
oC.put(str, cls);
}
return Fragment.class.isAssignableFrom(cls);
} catch (ClassNotFoundException e) {
return false;
}
}
final void c(int i, Fragment fragment) {
this.mIndex = i;
if (fragment != null) {
this.oI = fragment.oI + ":" + this.mIndex;
} else {
this.oI = "android:fragment:" + this.mIndex;
}
}
public final boolean equals(Object obj) {
return super.equals(obj);
}
public final int hashCode() {
return super.hashCode();
}
public String toString() {
StringBuilder stringBuilder = new StringBuilder(FileUtils.S_IWUSR);
c.a(this, stringBuilder);
if (this.mIndex >= 0) {
stringBuilder.append(" #");
stringBuilder.append(this.mIndex);
}
if (this.oX != 0) {
stringBuilder.append(" id=0x");
stringBuilder.append(Integer.toHexString(this.oX));
}
if (this.oZ != null) {
stringBuilder.append(" ");
stringBuilder.append(this.oZ);
}
stringBuilder.append('}');
return stringBuilder.toString();
}
public final void setArguments(Bundle bundle) {
if (this.mIndex >= 0) {
throw new IllegalStateException("Fragment already active");
}
this.oJ = bundle;
}
public Context getContext() {
return this.oU == null ? null : this.oU.mContext;
}
public final FragmentActivity aG() {
return this.oU == null ? null : (FragmentActivity) this.oU.pP;
}
public final Resources getResources() {
if (this.oU != null) {
return this.oU.mContext.getResources();
}
throw new IllegalStateException("Fragment " + this + " not attached to Activity");
}
public final String getString(int i) {
return getResources().getString(i);
}
public final String getString(int i, Object... objArr) {
return getResources().getString(i, objArr);
}
public final boolean isAdded() {
return this.oU != null && this.oN;
}
public static void aH() {
}
public final void aI() {
if (!this.pe) {
this.pe = true;
if (isAdded() && !this.pa) {
this.oU.aU();
}
}
}
public final void setMenuVisibility(boolean z) {
if (this.pf != z) {
this.pf = z;
if (this.pe && isAdded() && !this.pa) {
this.oU.aU();
}
}
}
public void setUserVisibleHint(boolean z) {
if (!this.pl && z && this.mState < 4) {
this.oT.f(this);
}
this.pl = z;
this.pk = !z;
}
public final q aJ() {
if (this.pm != null) {
return this.pm;
}
if (this.oU == null) {
throw new IllegalStateException("Fragment " + this + " not attached to Activity");
}
this.po = true;
this.pm = this.oU.a(this.oI, this.pn, true);
return this.pm;
}
public void startActivity(Intent intent) {
if (this.oU == null) {
throw new IllegalStateException("Fragment " + this + " not attached to Activity");
}
this.oU.b(this, intent, -1, null);
}
public final void startActivityForResult(Intent intent, int i) {
if (this.oU == null) {
throw new IllegalStateException("Fragment " + this + " not attached to Activity");
}
this.oU.b(this, intent, i, null);
}
public void onActivityResult(int i, int i2, Intent intent) {
}
public static void aK() {
}
public LayoutInflater c(Bundle bundle) {
LayoutInflater onGetLayoutInflater = this.oU.onGetLayoutInflater();
if (this.oV == null) {
aO();
if (this.mState >= 5) {
this.oV.dispatchResume();
} else if (this.mState >= 4) {
this.oV.dispatchStart();
} else if (this.mState >= 2) {
this.oV.dispatchActivityCreated();
} else if (this.mState > 0) {
this.oV.dispatchCreate();
}
}
g.a(onGetLayoutInflater, this.oV);
return onGetLayoutInflater;
}
public final void aL() {
this.pg = true;
if ((this.oU == null ? null : this.oU.pP) != null) {
this.pg = false;
this.pg = true;
}
}
@Deprecated
public void onAttach(Activity activity) {
this.pg = true;
}
public static Animation aM() {
return null;
}
public void onCreate(Bundle bundle) {
this.pg = true;
}
public View onCreateView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle bundle) {
return null;
}
public void aN() {
}
public void onActivityCreated(Bundle bundle) {
this.pg = true;
}
public void onStart() {
this.pg = true;
if (!this.pn) {
this.pn = true;
if (!this.po) {
this.po = true;
this.pm = this.oU.a(this.oI, this.pn, false);
}
if (this.pm != null) {
this.pm.be();
}
}
}
public void onResume() {
this.pg = true;
}
public void onSaveInstanceState(Bundle bundle) {
}
public void onConfigurationChanged(Configuration configuration) {
this.pg = true;
}
public void onPause() {
this.pg = true;
}
public void onStop() {
this.pg = true;
}
public void onLowMemory() {
this.pg = true;
}
public void onDestroyView() {
this.pg = true;
}
public void onDestroy() {
this.pg = true;
if (!this.po) {
this.po = true;
this.pm = this.oU.a(this.oI, this.pn, false);
}
if (this.pm != null) {
this.pm.bj();
}
}
public void onDetach() {
this.pg = true;
}
public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
}
public void onPrepareOptionsMenu(Menu menu) {
}
public static void onDestroyOptionsMenu() {
}
public boolean onOptionsItemSelected(MenuItem menuItem) {
return false;
}
public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenuInfo contextMenuInfo) {
aG().onCreateContextMenu(contextMenu, view, contextMenuInfo);
}
public boolean onContextItemSelected(MenuItem menuItem) {
return false;
}
public void dump(String str, FileDescriptor fileDescriptor, PrintWriter printWriter, String[] strArr) {
printWriter.print(str);
printWriter.print("mFragmentId=#");
printWriter.print(Integer.toHexString(this.oX));
printWriter.print(" mContainerId=#");
printWriter.print(Integer.toHexString(this.oY));
printWriter.print(" mTag=");
printWriter.println(this.oZ);
printWriter.print(str);
printWriter.print("mState=");
printWriter.print(this.mState);
printWriter.print(" mIndex=");
printWriter.print(this.mIndex);
printWriter.print(" mWho=");
printWriter.print(this.oI);
printWriter.print(" mBackStackNesting=");
printWriter.println(this.oS);
printWriter.print(str);
printWriter.print("mAdded=");
printWriter.print(this.oN);
printWriter.print(" mRemoving=");
printWriter.print(this.oO);
printWriter.print(" mFromLayout=");
printWriter.print(this.oP);
printWriter.print(" mInLayout=");
printWriter.println(this.oQ);
printWriter.print(str);
printWriter.print("mHidden=");
printWriter.print(this.pa);
printWriter.print(" mDetached=");
printWriter.print(this.pb);
printWriter.print(" mMenuVisible=");
printWriter.print(this.pf);
printWriter.print(" mHasMenu=");
printWriter.println(this.pe);
printWriter.print(str);
printWriter.print("mRetainInstance=");
printWriter.print(this.pc);
printWriter.print(" mRetaining=");
printWriter.print(this.pd);
printWriter.print(" mUserVisibleHint=");
printWriter.println(this.pl);
if (this.oT != null) {
printWriter.print(str);
printWriter.print("mFragmentManager=");
printWriter.println(this.oT);
}
if (this.oU != null) {
printWriter.print(str);
printWriter.print("mHost=");
printWriter.println(this.oU);
}
if (this.oW != null) {
printWriter.print(str);
printWriter.print("mParentFragment=");
printWriter.println(this.oW);
}
if (this.oJ != null) {
printWriter.print(str);
printWriter.print("mArguments=");
printWriter.println(this.oJ);
}
if (this.oG != null) {
printWriter.print(str);
printWriter.print("mSavedFragmentState=");
printWriter.println(this.oG);
}
if (this.oH != null) {
printWriter.print(str);
printWriter.print("mSavedViewState=");
printWriter.println(this.oH);
}
if (this.oK != null) {
printWriter.print(str);
printWriter.print("mTarget=");
printWriter.print(this.oK);
printWriter.print(" mTargetRequestCode=");
printWriter.println(this.oM);
}
if (this.ph != 0) {
printWriter.print(str);
printWriter.print("mNextAnim=");
printWriter.println(this.ph);
}
if (this.pi != null) {
printWriter.print(str);
printWriter.print("mContainer=");
printWriter.println(this.pi);
}
if (this.mView != null) {
printWriter.print(str);
printWriter.print("mView=");
printWriter.println(this.mView);
}
if (this.pj != null) {
printWriter.print(str);
printWriter.print("mInnerView=");
printWriter.println(this.mView);
}
if (this.oE != null) {
printWriter.print(str);
printWriter.print("mAnimatingAway=");
printWriter.println(this.oE);
printWriter.print(str);
printWriter.print("mStateAfterAnimating=");
printWriter.println(this.oF);
}
if (this.pm != null) {
printWriter.print(str);
printWriter.println("Loader Manager:");
this.pm.dump(str + " ", fileDescriptor, printWriter, strArr);
}
if (this.oV != null) {
printWriter.print(str);
printWriter.println("Child " + this.oV + ":");
this.oV.dump(str + " ", fileDescriptor, printWriter, strArr);
}
}
final void aO() {
this.oV = new l();
this.oV.a(this.oU, new h(this) {
final /* synthetic */ Fragment pz;
{
this.pz = r1;
}
public final View onFindViewById(int i) {
if (this.pz.mView != null) {
return this.pz.mView.findViewById(i);
}
throw new IllegalStateException("Fragment does not have a view");
}
public final boolean onHasView() {
return this.pz.mView != null;
}
}, this);
}
final View a(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle bundle) {
if (this.oV != null) {
this.oV.qk = false;
}
return onCreateView(layoutInflater, viewGroup, bundle);
}
final void d(Bundle bundle) {
onSaveInstanceState(bundle);
if (this.oV != null) {
Parcelable saveAllState = this.oV.saveAllState();
if (saveAllState != null) {
bundle.putParcelable("android:support:fragments", saveAllState);
}
}
}
final void aP() {
if (this.oV != null) {
this.oV.G(2);
}
this.mState = 2;
if (this.pn) {
this.pn = false;
if (!this.po) {
this.po = true;
this.pm = this.oU.a(this.oI, this.pn, false);
}
if (this.pm == null) {
return;
}
if (this.oU.pS) {
this.pm.bg();
} else {
this.pm.bf();
}
}
}
}
| UTF-8 | Java | 17,129 | java | Fragment.java | Java | [] | null | [] | package android.support.v4.app;
import android.app.Activity;
import android.content.ComponentCallbacks;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.Parcelable.Creator;
import android.support.v4.e.c;
import android.support.v4.e.i;
import android.support.v4.view.g;
import android.util.SparseArray;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import com.tencent.mmdb.FileUtils;
import java.io.FileDescriptor;
import java.io.PrintWriter;
public class Fragment implements ComponentCallbacks, OnCreateContextMenuListener {
private static final i<String, Class<?>> oC = new i();
static final Object oD = new Object();
int mIndex = -1;
int mState = 0;
public View mView;
View oE;
int oF;
Bundle oG;
SparseArray<Parcelable> oH;
String oI;
public Bundle oJ;
Fragment oK;
int oL = -1;
int oM;
boolean oN;
public boolean oO;
boolean oP;
boolean oQ;
boolean oR;
int oS;
l oT;
j oU;
l oV;
Fragment oW;
int oX;
int oY;
String oZ;
boolean pa;
boolean pb;
boolean pc;
boolean pd;
boolean pe;
boolean pf = true;
boolean pg;
int ph;
ViewGroup pi;
View pj;
boolean pk;
boolean pl = true;
r pm;
boolean pn;
boolean po;
Object pp = null;
Object pq = oD;
Object pr = null;
Object ps = oD;
Object pt = null;
Object pu = oD;
Boolean pv;
Boolean pw;
ai px = null;
ai py = null;
public static class SavedState implements Parcelable {
public static final Creator<SavedState> CREATOR = new Creator<SavedState>() {
public final /* synthetic */ Object createFromParcel(Parcel parcel) {
return new SavedState(parcel);
}
public final /* bridge */ /* synthetic */ Object[] newArray(int i) {
return new SavedState[i];
}
};
final Bundle pA;
SavedState(Bundle bundle) {
this.pA = bundle;
}
SavedState(Parcel parcel) {
this.pA = parcel.readBundle();
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel parcel, int i) {
parcel.writeBundle(this.pA);
}
}
public static class a extends RuntimeException {
public a(String str, Exception exception) {
super(str, exception);
}
}
public static Fragment b(Context context, String str) {
return a(context, str, null);
}
public static Fragment a(Context context, String str, Bundle bundle) {
try {
Class cls = (Class) oC.get(str);
if (cls == null) {
cls = context.getClassLoader().loadClass(str);
oC.put(str, cls);
}
Fragment fragment = (Fragment) cls.newInstance();
if (bundle != null) {
bundle.setClassLoader(fragment.getClass().getClassLoader());
fragment.oJ = bundle;
}
return fragment;
} catch (Exception e) {
throw new a("Unable to instantiate fragment " + str + ": make sure class name exists, is public, and has an empty constructor that is public", e);
} catch (Exception e2) {
throw new a("Unable to instantiate fragment " + str + ": make sure class name exists, is public, and has an empty constructor that is public", e2);
} catch (Exception e22) {
throw new a("Unable to instantiate fragment " + str + ": make sure class name exists, is public, and has an empty constructor that is public", e22);
}
}
static boolean c(Context context, String str) {
try {
Class cls = (Class) oC.get(str);
if (cls == null) {
cls = context.getClassLoader().loadClass(str);
oC.put(str, cls);
}
return Fragment.class.isAssignableFrom(cls);
} catch (ClassNotFoundException e) {
return false;
}
}
final void c(int i, Fragment fragment) {
this.mIndex = i;
if (fragment != null) {
this.oI = fragment.oI + ":" + this.mIndex;
} else {
this.oI = "android:fragment:" + this.mIndex;
}
}
public final boolean equals(Object obj) {
return super.equals(obj);
}
public final int hashCode() {
return super.hashCode();
}
public String toString() {
StringBuilder stringBuilder = new StringBuilder(FileUtils.S_IWUSR);
c.a(this, stringBuilder);
if (this.mIndex >= 0) {
stringBuilder.append(" #");
stringBuilder.append(this.mIndex);
}
if (this.oX != 0) {
stringBuilder.append(" id=0x");
stringBuilder.append(Integer.toHexString(this.oX));
}
if (this.oZ != null) {
stringBuilder.append(" ");
stringBuilder.append(this.oZ);
}
stringBuilder.append('}');
return stringBuilder.toString();
}
public final void setArguments(Bundle bundle) {
if (this.mIndex >= 0) {
throw new IllegalStateException("Fragment already active");
}
this.oJ = bundle;
}
public Context getContext() {
return this.oU == null ? null : this.oU.mContext;
}
public final FragmentActivity aG() {
return this.oU == null ? null : (FragmentActivity) this.oU.pP;
}
public final Resources getResources() {
if (this.oU != null) {
return this.oU.mContext.getResources();
}
throw new IllegalStateException("Fragment " + this + " not attached to Activity");
}
public final String getString(int i) {
return getResources().getString(i);
}
public final String getString(int i, Object... objArr) {
return getResources().getString(i, objArr);
}
public final boolean isAdded() {
return this.oU != null && this.oN;
}
public static void aH() {
}
public final void aI() {
if (!this.pe) {
this.pe = true;
if (isAdded() && !this.pa) {
this.oU.aU();
}
}
}
public final void setMenuVisibility(boolean z) {
if (this.pf != z) {
this.pf = z;
if (this.pe && isAdded() && !this.pa) {
this.oU.aU();
}
}
}
public void setUserVisibleHint(boolean z) {
if (!this.pl && z && this.mState < 4) {
this.oT.f(this);
}
this.pl = z;
this.pk = !z;
}
public final q aJ() {
if (this.pm != null) {
return this.pm;
}
if (this.oU == null) {
throw new IllegalStateException("Fragment " + this + " not attached to Activity");
}
this.po = true;
this.pm = this.oU.a(this.oI, this.pn, true);
return this.pm;
}
public void startActivity(Intent intent) {
if (this.oU == null) {
throw new IllegalStateException("Fragment " + this + " not attached to Activity");
}
this.oU.b(this, intent, -1, null);
}
public final void startActivityForResult(Intent intent, int i) {
if (this.oU == null) {
throw new IllegalStateException("Fragment " + this + " not attached to Activity");
}
this.oU.b(this, intent, i, null);
}
public void onActivityResult(int i, int i2, Intent intent) {
}
public static void aK() {
}
public LayoutInflater c(Bundle bundle) {
LayoutInflater onGetLayoutInflater = this.oU.onGetLayoutInflater();
if (this.oV == null) {
aO();
if (this.mState >= 5) {
this.oV.dispatchResume();
} else if (this.mState >= 4) {
this.oV.dispatchStart();
} else if (this.mState >= 2) {
this.oV.dispatchActivityCreated();
} else if (this.mState > 0) {
this.oV.dispatchCreate();
}
}
g.a(onGetLayoutInflater, this.oV);
return onGetLayoutInflater;
}
public final void aL() {
this.pg = true;
if ((this.oU == null ? null : this.oU.pP) != null) {
this.pg = false;
this.pg = true;
}
}
@Deprecated
public void onAttach(Activity activity) {
this.pg = true;
}
public static Animation aM() {
return null;
}
public void onCreate(Bundle bundle) {
this.pg = true;
}
public View onCreateView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle bundle) {
return null;
}
public void aN() {
}
public void onActivityCreated(Bundle bundle) {
this.pg = true;
}
public void onStart() {
this.pg = true;
if (!this.pn) {
this.pn = true;
if (!this.po) {
this.po = true;
this.pm = this.oU.a(this.oI, this.pn, false);
}
if (this.pm != null) {
this.pm.be();
}
}
}
public void onResume() {
this.pg = true;
}
public void onSaveInstanceState(Bundle bundle) {
}
public void onConfigurationChanged(Configuration configuration) {
this.pg = true;
}
public void onPause() {
this.pg = true;
}
public void onStop() {
this.pg = true;
}
public void onLowMemory() {
this.pg = true;
}
public void onDestroyView() {
this.pg = true;
}
public void onDestroy() {
this.pg = true;
if (!this.po) {
this.po = true;
this.pm = this.oU.a(this.oI, this.pn, false);
}
if (this.pm != null) {
this.pm.bj();
}
}
public void onDetach() {
this.pg = true;
}
public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
}
public void onPrepareOptionsMenu(Menu menu) {
}
public static void onDestroyOptionsMenu() {
}
public boolean onOptionsItemSelected(MenuItem menuItem) {
return false;
}
public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenuInfo contextMenuInfo) {
aG().onCreateContextMenu(contextMenu, view, contextMenuInfo);
}
public boolean onContextItemSelected(MenuItem menuItem) {
return false;
}
public void dump(String str, FileDescriptor fileDescriptor, PrintWriter printWriter, String[] strArr) {
printWriter.print(str);
printWriter.print("mFragmentId=#");
printWriter.print(Integer.toHexString(this.oX));
printWriter.print(" mContainerId=#");
printWriter.print(Integer.toHexString(this.oY));
printWriter.print(" mTag=");
printWriter.println(this.oZ);
printWriter.print(str);
printWriter.print("mState=");
printWriter.print(this.mState);
printWriter.print(" mIndex=");
printWriter.print(this.mIndex);
printWriter.print(" mWho=");
printWriter.print(this.oI);
printWriter.print(" mBackStackNesting=");
printWriter.println(this.oS);
printWriter.print(str);
printWriter.print("mAdded=");
printWriter.print(this.oN);
printWriter.print(" mRemoving=");
printWriter.print(this.oO);
printWriter.print(" mFromLayout=");
printWriter.print(this.oP);
printWriter.print(" mInLayout=");
printWriter.println(this.oQ);
printWriter.print(str);
printWriter.print("mHidden=");
printWriter.print(this.pa);
printWriter.print(" mDetached=");
printWriter.print(this.pb);
printWriter.print(" mMenuVisible=");
printWriter.print(this.pf);
printWriter.print(" mHasMenu=");
printWriter.println(this.pe);
printWriter.print(str);
printWriter.print("mRetainInstance=");
printWriter.print(this.pc);
printWriter.print(" mRetaining=");
printWriter.print(this.pd);
printWriter.print(" mUserVisibleHint=");
printWriter.println(this.pl);
if (this.oT != null) {
printWriter.print(str);
printWriter.print("mFragmentManager=");
printWriter.println(this.oT);
}
if (this.oU != null) {
printWriter.print(str);
printWriter.print("mHost=");
printWriter.println(this.oU);
}
if (this.oW != null) {
printWriter.print(str);
printWriter.print("mParentFragment=");
printWriter.println(this.oW);
}
if (this.oJ != null) {
printWriter.print(str);
printWriter.print("mArguments=");
printWriter.println(this.oJ);
}
if (this.oG != null) {
printWriter.print(str);
printWriter.print("mSavedFragmentState=");
printWriter.println(this.oG);
}
if (this.oH != null) {
printWriter.print(str);
printWriter.print("mSavedViewState=");
printWriter.println(this.oH);
}
if (this.oK != null) {
printWriter.print(str);
printWriter.print("mTarget=");
printWriter.print(this.oK);
printWriter.print(" mTargetRequestCode=");
printWriter.println(this.oM);
}
if (this.ph != 0) {
printWriter.print(str);
printWriter.print("mNextAnim=");
printWriter.println(this.ph);
}
if (this.pi != null) {
printWriter.print(str);
printWriter.print("mContainer=");
printWriter.println(this.pi);
}
if (this.mView != null) {
printWriter.print(str);
printWriter.print("mView=");
printWriter.println(this.mView);
}
if (this.pj != null) {
printWriter.print(str);
printWriter.print("mInnerView=");
printWriter.println(this.mView);
}
if (this.oE != null) {
printWriter.print(str);
printWriter.print("mAnimatingAway=");
printWriter.println(this.oE);
printWriter.print(str);
printWriter.print("mStateAfterAnimating=");
printWriter.println(this.oF);
}
if (this.pm != null) {
printWriter.print(str);
printWriter.println("Loader Manager:");
this.pm.dump(str + " ", fileDescriptor, printWriter, strArr);
}
if (this.oV != null) {
printWriter.print(str);
printWriter.println("Child " + this.oV + ":");
this.oV.dump(str + " ", fileDescriptor, printWriter, strArr);
}
}
final void aO() {
this.oV = new l();
this.oV.a(this.oU, new h(this) {
final /* synthetic */ Fragment pz;
{
this.pz = r1;
}
public final View onFindViewById(int i) {
if (this.pz.mView != null) {
return this.pz.mView.findViewById(i);
}
throw new IllegalStateException("Fragment does not have a view");
}
public final boolean onHasView() {
return this.pz.mView != null;
}
}, this);
}
final View a(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle bundle) {
if (this.oV != null) {
this.oV.qk = false;
}
return onCreateView(layoutInflater, viewGroup, bundle);
}
final void d(Bundle bundle) {
onSaveInstanceState(bundle);
if (this.oV != null) {
Parcelable saveAllState = this.oV.saveAllState();
if (saveAllState != null) {
bundle.putParcelable("android:support:fragments", saveAllState);
}
}
}
final void aP() {
if (this.oV != null) {
this.oV.G(2);
}
this.mState = 2;
if (this.pn) {
this.pn = false;
if (!this.po) {
this.po = true;
this.pm = this.oU.a(this.oI, this.pn, false);
}
if (this.pm == null) {
return;
}
if (this.oU.pS) {
this.pm.bg();
} else {
this.pm.bf();
}
}
}
}
| 17,129 | 0.546909 | 0.545216 | 596 | 27.739933 | 22.427687 | 160 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.595638 | false | false | 3 |
b40fbd76da0d55a520c326e6d7a89eac8513fede | 3,272,765,084,661 | 3d68925c049930cfa5bc00d4313d66f3ba4b6233 | /lambdaExpression/src/main/java/tutorial/lambdaExpression/_03RunnableLambda/RunnableExample.java | d9f880aefe5c132e20ae6467484861f8c08cffa7 | [] | no_license | tremors0/learning-java | https://github.com/tremors0/learning-java | 272e62bef4fb6641b170255bba14d5c5315d5c4e | 2339ca8680a3bdf8468c9adf4353cd0bd1a34457 | refs/heads/master | 2021-06-24T02:41:22.619000 | 2017-09-10T14:58:02 | 2017-09-10T14:58:02 | 103,028,847 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package tutorial.lambdaExpression._03RunnableLambda;
public class RunnableExample {
public static void main(String[] args) {
//Thread musi mit jako parametr instanci Runnable
Thread myThread = new Thread(new Runnable() {
public void run() {
System.out.println("Printed inside Runnable");
}
});
Thread secondThread = new Thread(()->System.out.println("Printed using lambda"));
myThread.run();
secondThread.run();
}
} | UTF-8 | Java | 519 | java | RunnableExample.java | Java | [] | null | [] | package tutorial.lambdaExpression._03RunnableLambda;
public class RunnableExample {
public static void main(String[] args) {
//Thread musi mit jako parametr instanci Runnable
Thread myThread = new Thread(new Runnable() {
public void run() {
System.out.println("Printed inside Runnable");
}
});
Thread secondThread = new Thread(()->System.out.println("Printed using lambda"));
myThread.run();
secondThread.run();
}
} | 519 | 0.606936 | 0.603083 | 18 | 27.888889 | 25.726961 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 3 |
77b5fabbb2db7e92db5e6bca4559682a1dafd76a | 14,499,809,659,888 | c709be4b586ffcc3ad75ab2d1591f3141fe6176a | /src/main/java/uk/co/iyana/asserts/service/test/ServiceTester.java | f55b96736776aee51c05230ff926f690ecd9f424 | [] | no_license | Iyana/iyana-asserts | https://github.com/Iyana/iyana-asserts | 5a45ab2e9acdab6a439302dff01a7f68662f5b5f | 8e8161241304f680b1175dacfa92e0df338566e2 | refs/heads/master | 2020-06-14T12:54:32.049000 | 2016-12-04T23:27:38 | 2016-12-04T23:27:38 | 75,021,986 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package uk.co.iyana.asserts.service.test;
import org.testng.Assert;
import uk.co.iyana.asserts.test.Assert2;
import uk.co.iyana.asserts.testdata.CreateTestData;
import uk.co.iyana.commons.usererror.UserErrorException;
import uk.co.iyana.commons.usererror.UserErrors;
import uk.co.iyana.json.io.JsonHelper;
/**
*
* @author fgyara
*/
public class ServiceTester {
public static <T> T testCreate(CreateTestData<T> testData, IServiceCreateTestHarness<T> harness) {
System.out.println( "Test " + testData.getTestName() + " started");
T result;
try {
result = harness.doTest(testData);
System.out.println( "Test " + testData.getTestName() + " completed without exception");
System.out.println( "\tResult: " );
JsonHelper.write(result).to(System.out);
} catch (Exception t) {
System.out.println( "Test " + testData.getTestName() + " completed with exception " + t.getClass() + "(" + t.getMessage() + ")");
if (t.getClass().equals( UserErrorException.class)) {
System.out.println( "\tUserException:");
JsonHelper.write(t).to(System.out);
}
if (testData.getExpectServiceException() == null) {
Assert.fail("Unexpected exception", t);
} else {
// exception was expected
Assert.assertEquals(t.getClass().getName(), testData.getExpectServiceException(), "Incorrect exception thrown");
if (t.getClass().equals( UserErrorException.class)) {
UserErrors expectedUserErrors = testData.getExpectUserErrors();
UserErrors actualUserErrors = ((UserErrorException)t).getUserErrors();
Assert2.assertEquals( actualUserErrors, expectedUserErrors, "Incorrect user errors");
}
}
return null;
}
if (testData.getExpectServiceException() != null) {
// was expecting an exception
Assert.fail("Was expecting exception " + testData.getExpectException() + " to be thrown");
}
// ensure that result is not null
Assert.assertNotNull(result, "Result was null");
// ensure that the record was created in the db
T requeriedResult = harness.find(result, testData);
Assert.assertNotNull(requeriedResult, "Create did not persist a record.");
return requeriedResult;
}
}
| UTF-8 | Java | 2,840 | java | ServiceTester.java | Java | [
{
"context": "o.iyana.json.io.JsonHelper;\r\n\r\n/**\r\n *\r\n * @author fgyara\r\n */\r\npublic class ServiceTester {\r\n \r\n pub",
"end": 533,
"score": 0.9995735287666321,
"start": 527,
"tag": "USERNAME",
"value": "fgyara"
}
] | null | [] | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package uk.co.iyana.asserts.service.test;
import org.testng.Assert;
import uk.co.iyana.asserts.test.Assert2;
import uk.co.iyana.asserts.testdata.CreateTestData;
import uk.co.iyana.commons.usererror.UserErrorException;
import uk.co.iyana.commons.usererror.UserErrors;
import uk.co.iyana.json.io.JsonHelper;
/**
*
* @author fgyara
*/
public class ServiceTester {
public static <T> T testCreate(CreateTestData<T> testData, IServiceCreateTestHarness<T> harness) {
System.out.println( "Test " + testData.getTestName() + " started");
T result;
try {
result = harness.doTest(testData);
System.out.println( "Test " + testData.getTestName() + " completed without exception");
System.out.println( "\tResult: " );
JsonHelper.write(result).to(System.out);
} catch (Exception t) {
System.out.println( "Test " + testData.getTestName() + " completed with exception " + t.getClass() + "(" + t.getMessage() + ")");
if (t.getClass().equals( UserErrorException.class)) {
System.out.println( "\tUserException:");
JsonHelper.write(t).to(System.out);
}
if (testData.getExpectServiceException() == null) {
Assert.fail("Unexpected exception", t);
} else {
// exception was expected
Assert.assertEquals(t.getClass().getName(), testData.getExpectServiceException(), "Incorrect exception thrown");
if (t.getClass().equals( UserErrorException.class)) {
UserErrors expectedUserErrors = testData.getExpectUserErrors();
UserErrors actualUserErrors = ((UserErrorException)t).getUserErrors();
Assert2.assertEquals( actualUserErrors, expectedUserErrors, "Incorrect user errors");
}
}
return null;
}
if (testData.getExpectServiceException() != null) {
// was expecting an exception
Assert.fail("Was expecting exception " + testData.getExpectException() + " to be thrown");
}
// ensure that result is not null
Assert.assertNotNull(result, "Result was null");
// ensure that the record was created in the db
T requeriedResult = harness.find(result, testData);
Assert.assertNotNull(requeriedResult, "Create did not persist a record.");
return requeriedResult;
}
}
| 2,840 | 0.588028 | 0.587324 | 71 | 38 | 33.679935 | 141 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.549296 | false | false | 3 |
caf54b3aa2ad88419c28cecceeca923ce882b81d | 3,942,779,985,570 | 816d8f7afb3aadf363ec3e59c6bbad805125a3d4 | /client/src/calc/Calc.java | 3db34bc025688f8db0089db20d1ae1b59541cb0f | [] | no_license | GaetanMartin/uqac-java-8inf843-devoir1-server | https://github.com/GaetanMartin/uqac-java-8inf843-devoir1-server | d52c863d6d581f41af9ec46d27a5675e294d48f2 | c10626121d1d092aa7826b412ae5c520e075b29c | refs/heads/master | 2021-07-09T15:38:29.149000 | 2017-10-03T20:39:10 | 2017-10-03T20:39:10 | 103,783,743 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package calc;
import java.io.Serializable;
import java.util.Arrays;
/**
* Class to send and remoteCallCalc to the server
* @author Gaetan
*/
public class Calc implements Serializable {
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
/**
* Parse and add an array of strings
* @param stringsToAdd array of strings to add
* @return String result
*/
public String add(String[] stringsToAdd){
int result = 0;
for (String s : stringsToAdd) {
result += Integer.parseInt(s);
}
return String.valueOf(result);
}
}
| UTF-8 | Java | 831 | java | Calc.java | Java | [
{
"context": "o send and remoteCallCalc to the server\n * @author Gaetan\n */\npublic class Calc implements Serializable {\n\n",
"end": 141,
"score": 0.9993919730186462,
"start": 135,
"tag": "NAME",
"value": "Gaetan"
}
] | null | [] | package calc;
import java.io.Serializable;
import java.util.Arrays;
/**
* Class to send and remoteCallCalc to the server
* @author Gaetan
*/
public class Calc implements Serializable {
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
/**
* Parse and add an array of strings
* @param stringsToAdd array of strings to add
* @return String result
*/
public String add(String[] stringsToAdd){
int result = 0;
for (String s : stringsToAdd) {
result += Integer.parseInt(s);
}
return String.valueOf(result);
}
}
| 831 | 0.616125 | 0.614922 | 39 | 20.307692 | 17.727501 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.230769 | false | false | 3 |
d9eb9f80bf3873c0bbec895f4fd96ec4390e204c | 13,941,463,851,511 | 1f23f3d9c2ea958e3e0d25c11b4ed984e96ec219 | /src/main/java/com/cs56fitnessapp/models/workout/Swimming.java | ecefd247277213a979315ebd9e22222eb2dc3a40 | [
"MIT"
] | permissive | kseniacold/java-fitness-logger | https://github.com/kseniacold/java-fitness-logger | b1c6e9610bb456f2af1fef2b70cd42e17c70d3b7 | 475bb7a62e60f9e13655045cde683246e03e6b47 | refs/heads/master | 2021-10-10T07:01:34.422000 | 2019-01-07T23:28:49 | 2019-01-07T23:28:49 | 102,977,713 | 0 | 0 | null | false | 2017-12-09T20:22:24 | 2017-09-09T18:50:27 | 2017-12-09T02:56:43 | 2017-12-09T20:22:24 | 16,485 | 1 | 3 | 0 | Java | false | null | package com.cs56fitnessapp.models.workout;
import com.cs56fitnessapp.models.FitnessFormulas;
import com.cs56fitnessapp.models.User;
import java.time.LocalDateTime;
/**
* @author Ksenia Koldaeva
* Created: 10/10/17
* Last Updated: 10/11/17
*/
public class Swimming extends Endurance {
private SwimmingStroke swimmingStroke;
private boolean training;
/**
* Constructs Swimming object with provided parameters
* Training is assumed to be false (can be set later) for all except Butterfly - in this case training is true
* @param user user performing swimming
* @param date date of swimming workout
* @param distanceKm distance of swimming workout
* @param timePerformingHours duration of swimming workout
* @param swimmingStroke one of 4 swimming strokes or mixed
*/
public Swimming(Long id, User user, LocalDateTime date, double distanceKm, double timePerformingHours, SwimmingStroke swimmingStroke) {
super(id, user, date, distanceKm, timePerformingHours);
this.swimmingStroke = swimmingStroke;
this.training = swimmingStroke.equals(SwimmingStroke.BUTTERFLY);
}
// Start getters and setters
public SwimmingStroke getSwimmingStroke() {
return swimmingStroke;
}
public void setSwimmingStroke(SwimmingStroke swimmingStroke) {
this.swimmingStroke = swimmingStroke;
}
public boolean isTraining() {
return training;
}
public void setTraining(boolean training) {
this.training = training;
}
// End getters and setters
/**
*
* @return calories out based on the stroke type and if training or recreational
*/
@Override
public int getCaloriesOut() {
int caloriesOut = 0;
switch (swimmingStroke) {
case FREESTYLE:
if (training) {
caloriesOut = FitnessFormulas.caloriesOutByMET(FitnessFormulas.MET_SWIMMING_CRAWL_TRAINING, this.getUser().getBodyMassKg(), this.getTimePerformingHours());
} else {
caloriesOut = FitnessFormulas.caloriesOutByMET(FitnessFormulas.MET_SWIMMING_CRAWL_RECREATIONAL, this.getUser().getBodyMassKg(), this.getTimePerformingHours());
}
break;
case BREASTSTROKE:
if (training) {
caloriesOut = FitnessFormulas.caloriesOutByMET(FitnessFormulas.MET_SWIMMING_BREASTSTROKE_TRAINING, this.getUser().getBodyMassKg(), this.getTimePerformingHours());
} else {
caloriesOut = FitnessFormulas.caloriesOutByMET(FitnessFormulas.MET_SWIMMING_BREASTSTROKE_RECREATIONAL, this.getUser().getBodyMassKg(), this.getTimePerformingHours());
}
break;
case BACKSTROKE:
if (training) {
caloriesOut = FitnessFormulas.caloriesOutByMET(FitnessFormulas.MET_SWIMMING_CRAWL_TRAINING, this.getUser().getBodyMassKg(), this.getTimePerformingHours());
} else {
caloriesOut = FitnessFormulas.caloriesOutByMET(FitnessFormulas.MET_SWIMMING_CRAWL_TRAINING, this.getUser().getBodyMassKg(), this.getTimePerformingHours());
}
break;
case BUTTERFLY:
caloriesOut = FitnessFormulas.caloriesOutByMET(FitnessFormulas.MET_SWIMMING_BUTTERFLY_GENERAL, this.getUser().getBodyMassKg(), this.getTimePerformingHours());
break;
case MIXED:
if (training) {
caloriesOut = FitnessFormulas.caloriesOutByMET(FitnessFormulas.MET_SWIMMING_MIXED_TRAINING, this.getUser().getBodyMassKg(), this.getTimePerformingHours());
} else {
caloriesOut = FitnessFormulas.caloriesOutByMET(FitnessFormulas.MET_SWIMMING_MIXED_RECREATIONAL, this.getUser().getBodyMassKg(), this.getTimePerformingHours());
}
break;
}
return caloriesOut;
}
}
| UTF-8 | Java | 4,012 | java | Swimming.java | Java | [
{
"context": "r;\nimport java.time.LocalDateTime;\n\n/**\n * @author Ksenia Koldaeva\n * Created: 10/10/17\n * Last Updated: 10/11/17\n *",
"end": 196,
"score": 0.9998685717582703,
"start": 181,
"tag": "NAME",
"value": "Ksenia Koldaeva"
}
] | null | [] | package com.cs56fitnessapp.models.workout;
import com.cs56fitnessapp.models.FitnessFormulas;
import com.cs56fitnessapp.models.User;
import java.time.LocalDateTime;
/**
* @author <NAME>
* Created: 10/10/17
* Last Updated: 10/11/17
*/
public class Swimming extends Endurance {
private SwimmingStroke swimmingStroke;
private boolean training;
/**
* Constructs Swimming object with provided parameters
* Training is assumed to be false (can be set later) for all except Butterfly - in this case training is true
* @param user user performing swimming
* @param date date of swimming workout
* @param distanceKm distance of swimming workout
* @param timePerformingHours duration of swimming workout
* @param swimmingStroke one of 4 swimming strokes or mixed
*/
public Swimming(Long id, User user, LocalDateTime date, double distanceKm, double timePerformingHours, SwimmingStroke swimmingStroke) {
super(id, user, date, distanceKm, timePerformingHours);
this.swimmingStroke = swimmingStroke;
this.training = swimmingStroke.equals(SwimmingStroke.BUTTERFLY);
}
// Start getters and setters
public SwimmingStroke getSwimmingStroke() {
return swimmingStroke;
}
public void setSwimmingStroke(SwimmingStroke swimmingStroke) {
this.swimmingStroke = swimmingStroke;
}
public boolean isTraining() {
return training;
}
public void setTraining(boolean training) {
this.training = training;
}
// End getters and setters
/**
*
* @return calories out based on the stroke type and if training or recreational
*/
@Override
public int getCaloriesOut() {
int caloriesOut = 0;
switch (swimmingStroke) {
case FREESTYLE:
if (training) {
caloriesOut = FitnessFormulas.caloriesOutByMET(FitnessFormulas.MET_SWIMMING_CRAWL_TRAINING, this.getUser().getBodyMassKg(), this.getTimePerformingHours());
} else {
caloriesOut = FitnessFormulas.caloriesOutByMET(FitnessFormulas.MET_SWIMMING_CRAWL_RECREATIONAL, this.getUser().getBodyMassKg(), this.getTimePerformingHours());
}
break;
case BREASTSTROKE:
if (training) {
caloriesOut = FitnessFormulas.caloriesOutByMET(FitnessFormulas.MET_SWIMMING_BREASTSTROKE_TRAINING, this.getUser().getBodyMassKg(), this.getTimePerformingHours());
} else {
caloriesOut = FitnessFormulas.caloriesOutByMET(FitnessFormulas.MET_SWIMMING_BREASTSTROKE_RECREATIONAL, this.getUser().getBodyMassKg(), this.getTimePerformingHours());
}
break;
case BACKSTROKE:
if (training) {
caloriesOut = FitnessFormulas.caloriesOutByMET(FitnessFormulas.MET_SWIMMING_CRAWL_TRAINING, this.getUser().getBodyMassKg(), this.getTimePerformingHours());
} else {
caloriesOut = FitnessFormulas.caloriesOutByMET(FitnessFormulas.MET_SWIMMING_CRAWL_TRAINING, this.getUser().getBodyMassKg(), this.getTimePerformingHours());
}
break;
case BUTTERFLY:
caloriesOut = FitnessFormulas.caloriesOutByMET(FitnessFormulas.MET_SWIMMING_BUTTERFLY_GENERAL, this.getUser().getBodyMassKg(), this.getTimePerformingHours());
break;
case MIXED:
if (training) {
caloriesOut = FitnessFormulas.caloriesOutByMET(FitnessFormulas.MET_SWIMMING_MIXED_TRAINING, this.getUser().getBodyMassKg(), this.getTimePerformingHours());
} else {
caloriesOut = FitnessFormulas.caloriesOutByMET(FitnessFormulas.MET_SWIMMING_MIXED_RECREATIONAL, this.getUser().getBodyMassKg(), this.getTimePerformingHours());
}
break;
}
return caloriesOut;
}
}
| 4,003 | 0.65678 | 0.651795 | 96 | 40.791668 | 49.973309 | 186 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583333 | false | false | 3 |
0d5fdfd99472c2df8ba953def20755b4e0a1d2a2 | 32,976,758,918,830 | dc02578ae54df3015add368089ea8e6cf2154370 | /src/test/java/steps/LogInSteps.java | ff35ccd979efe81787a0fc94d86dc9075cfbb4b6 | [] | no_license | mariuszgil91/CucumberProject | https://github.com/mariuszgil91/CucumberProject | f28e266812bf5ce83462e13cd32b16c992857876 | de892befe66e03e5be8bedf2666c5b6a75c2fb2b | refs/heads/main | 2023-02-26T22:12:37.300000 | 2021-02-02T18:36:51 | 2021-02-02T18:36:51 | 334,396,229 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package steps;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class LogInSteps {
WebDriver driver;
@Given("^the user is on landing page$")
public void setup() throws Throwable {
System.setProperty("webdriver.chrome.driver","chromedriver-5");
driver = new ChromeDriver();
driver.get("http://automationpractice.com/index.php?controller=authentication&back=my-account");
driver.manage().window().maximize();
}
@When("^she provides the email as ([^\"]*)$")
public void she_provides_the_email_as(String email) throws Throwable {
driver.findElement(By.id("email")).sendKeys(email);
}
@And("^she provides the password as ([^\"]*)$")
public void she_provides_the_password_as(String password) throws Throwable {
driver.findElement(By.id("passwd")).sendKeys(password);
}
@And("^she signs-up$")
public void she_signs_up() throws Throwable {
driver.findElement(By.id("SubmitLogin")).click();
}
@Then("^she should be logged in to the application$")
public void she_should_be_logged_in_to_the_application() throws Throwable {
String actualTitle = driver.getTitle();
Assert.assertEquals("My account - My Store", actualTitle);
driver.quit();
}
}
| UTF-8 | Java | 1,520 | java | LogInSteps.java | Java | [] | null | [] | package steps;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class LogInSteps {
WebDriver driver;
@Given("^the user is on landing page$")
public void setup() throws Throwable {
System.setProperty("webdriver.chrome.driver","chromedriver-5");
driver = new ChromeDriver();
driver.get("http://automationpractice.com/index.php?controller=authentication&back=my-account");
driver.manage().window().maximize();
}
@When("^she provides the email as ([^\"]*)$")
public void she_provides_the_email_as(String email) throws Throwable {
driver.findElement(By.id("email")).sendKeys(email);
}
@And("^she provides the password as ([^\"]*)$")
public void she_provides_the_password_as(String password) throws Throwable {
driver.findElement(By.id("passwd")).sendKeys(password);
}
@And("^she signs-up$")
public void she_signs_up() throws Throwable {
driver.findElement(By.id("SubmitLogin")).click();
}
@Then("^she should be logged in to the application$")
public void she_should_be_logged_in_to_the_application() throws Throwable {
String actualTitle = driver.getTitle();
Assert.assertEquals("My account - My Store", actualTitle);
driver.quit();
}
}
| 1,520 | 0.678947 | 0.678289 | 45 | 32.777779 | 26.811182 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.488889 | false | false | 3 |
1a2791aa27d81ef40a9040cd523efa79afe12c3f | 11,089,605,574,163 | 152d2d3db03ee733b8208dff8f49acb4aeb4837e | /problem-solving-practice/src/leetcode/LengthOfShortestSubarray.java | fd2cefa6b1eba8c5a6ed3868d85ff4b9823b5325 | [] | no_license | samygerges/problem-solving | https://github.com/samygerges/problem-solving | ab84cbc282d8cc7ab2d3201b5819f2297a301866 | ed943ec1e82634040e107b90d3bf3504d6706bc4 | refs/heads/master | 2022-02-04T10:41:50.336000 | 2022-01-14T10:50:19 | 2022-01-14T10:50:19 | 208,576,933 | 0 | 1 | null | false | 2020-10-16T20:19:00 | 2019-09-15T10:25:33 | 2020-10-16T20:18:35 | 2020-10-16T20:18:59 | 465 | 0 | 0 | 1 | Java | false | false | package leetcode;
public class LengthOfShortestSubarray
{
public static void main(String[] args)
{
LengthOfShortestSubarray a = new LengthOfShortestSubarray();
//System.out.println(a.findLengthOfShortestSubarray(new int[] { 1, 2, 3, 10, 4, 2, 3, 5 }));
//System.out.println(a.findLengthOfShortestSubarray(new int[] { 5, 4, 3, 2, 1 }));
System.out.println(a.findLengthOfShortestSubarray(new int[] { 0, 16, 3, 13, 14, 11, 1, 24, 20, 20, 18, 15, 20 }));
//System.out.println(a.findLengthOfShortestSubarray(new int[] { 10, 13, 17, 21, 15, 15, 9, 17, 22, 22, 13 }));
}
public int findLengthOfShortestSubarray(int[] arr)
{
int[] dp = new int[arr.length];
int max = -1;
int index = -1;
int maxIndex = -1;
for (int i = 1; i < arr.length; i++)
{
if (arr[i] < arr[i - 1] && max == -1)
{
max = arr[i - 1];
index = i - 1;
dp[i] = 1;
}
else
{
if (arr[i] < max && index - 1 >= 0 && arr[i] >= arr[index - 1])
{
max = arr[index - 1];
dp[index] = 1;
maxIndex = i;
}
if (maxIndex != -1 && arr[i] > arr[maxIndex])
{
maxIndex = i;
}
if (arr[i] < arr[i - 1] && dp[i - 1] == 0)
{
dp[i - 1] = 1;
}
if (arr[i] < max)
{
dp[i] = 1;
}
}
}
int start = -1;
int end = -1;
for (int i = 0; i < dp.length; i++)
{
if (dp[i] == 1 && start == -1)
{
start = i;
end = i;
}
else if (dp[i] == 1)
{
end = i;
}
}
if (maxIndex < end && maxIndex != -1)
{
end--;
}
return start != -1 && end != -1 ? end - start + 1 : 0;
}
}
| UTF-8 | Java | 1,648 | java | LengthOfShortestSubarray.java | Java | [] | null | [] | package leetcode;
public class LengthOfShortestSubarray
{
public static void main(String[] args)
{
LengthOfShortestSubarray a = new LengthOfShortestSubarray();
//System.out.println(a.findLengthOfShortestSubarray(new int[] { 1, 2, 3, 10, 4, 2, 3, 5 }));
//System.out.println(a.findLengthOfShortestSubarray(new int[] { 5, 4, 3, 2, 1 }));
System.out.println(a.findLengthOfShortestSubarray(new int[] { 0, 16, 3, 13, 14, 11, 1, 24, 20, 20, 18, 15, 20 }));
//System.out.println(a.findLengthOfShortestSubarray(new int[] { 10, 13, 17, 21, 15, 15, 9, 17, 22, 22, 13 }));
}
public int findLengthOfShortestSubarray(int[] arr)
{
int[] dp = new int[arr.length];
int max = -1;
int index = -1;
int maxIndex = -1;
for (int i = 1; i < arr.length; i++)
{
if (arr[i] < arr[i - 1] && max == -1)
{
max = arr[i - 1];
index = i - 1;
dp[i] = 1;
}
else
{
if (arr[i] < max && index - 1 >= 0 && arr[i] >= arr[index - 1])
{
max = arr[index - 1];
dp[index] = 1;
maxIndex = i;
}
if (maxIndex != -1 && arr[i] > arr[maxIndex])
{
maxIndex = i;
}
if (arr[i] < arr[i - 1] && dp[i - 1] == 0)
{
dp[i - 1] = 1;
}
if (arr[i] < max)
{
dp[i] = 1;
}
}
}
int start = -1;
int end = -1;
for (int i = 0; i < dp.length; i++)
{
if (dp[i] == 1 && start == -1)
{
start = i;
end = i;
}
else if (dp[i] == 1)
{
end = i;
}
}
if (maxIndex < end && maxIndex != -1)
{
end--;
}
return start != -1 && end != -1 ? end - start + 1 : 0;
}
}
| 1,648 | 0.479369 | 0.424757 | 74 | 20.270269 | 25.470861 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.405406 | false | false | 3 |
61fb989b25ab880e322dfab8423b5aa2e60f40da | 4,587,025,078,988 | fc4142b7d34ab39889a058bc5b9c5124585d5a59 | /src/main/java/fr/afpa/user/registration/controller/UserController.java | 3f1044e2f508d79b9aae7898187a693b31aba205 | [] | no_license | ludovic-arnaud/UserRegistrationWithSpringSecurity | https://github.com/ludovic-arnaud/UserRegistrationWithSpringSecurity | 2dee4897b528374a825963a8559feb4cbd1c61f3 | 40fab0f452d43f25e17f828a563117496dc4544f | refs/heads/master | 2022-11-21T19:12:51.257000 | 2020-06-26T08:52:29 | 2020-06-26T08:52:29 | 274,936,658 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package fr.afpa.user.registration.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import fr.afpa.user.registration.model.Utilisateur;
import fr.afpa.user.registration.service.SecurityService;
import fr.afpa.user.registration.service.UserService;
import fr.afpa.user.registration.validator.UserValidator;
// TODO: Auto-generated Javadoc
/**
* The Class UserController.
*/
@Controller
public class UserController {
/** The user service. */
@Autowired
private UserService userService;
/** The security service. */
@Autowired
private SecurityService securityService;
/** The user validator. */
@Autowired
private UserValidator userValidator;
/**
* Registration.
*
* @param model the model
* @return the string
*/
@GetMapping("/registration")
public String registration(Model model) {
model.addAttribute("userForm", new Utilisateur());
return "registration";
}
/**
* Registration.
*
* @param userForm the user form
* @param bindingResult the binding result
* @return the string
*/
@PostMapping("/registration")
public String registration(@ModelAttribute("userForm") Utilisateur userForm, BindingResult bindingResult) {
userValidator.validate(userForm, bindingResult);
if (bindingResult.hasErrors()) {
return "registration";
}
userService.save(userForm);
securityService.autoLogin(userForm.getUsername(), userForm.getPasswordConfirm());
return "redirect:/welcome";
}
/**
* Login.
*
* @param model the model
* @param error the error
* @param logout the logout
* @return the string
*/
@GetMapping("/login")
public String login(Model model, String error, String logout) {
if (error != null)
model.addAttribute("error", "Your username and password is invalid.");
if (logout != null)
model.addAttribute("message", "You have been logged out successfully.");
return "login";
}
/**
* Welcome.
*
* @param model the model
* @return the string
*/
@GetMapping({"/", "/welcome"})
public String welcome(Model model) {
return "welcome";
}
}
| UTF-8 | Java | 2,741 | java | UserController.java | Java | [] | null | [] | package fr.afpa.user.registration.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import fr.afpa.user.registration.model.Utilisateur;
import fr.afpa.user.registration.service.SecurityService;
import fr.afpa.user.registration.service.UserService;
import fr.afpa.user.registration.validator.UserValidator;
// TODO: Auto-generated Javadoc
/**
* The Class UserController.
*/
@Controller
public class UserController {
/** The user service. */
@Autowired
private UserService userService;
/** The security service. */
@Autowired
private SecurityService securityService;
/** The user validator. */
@Autowired
private UserValidator userValidator;
/**
* Registration.
*
* @param model the model
* @return the string
*/
@GetMapping("/registration")
public String registration(Model model) {
model.addAttribute("userForm", new Utilisateur());
return "registration";
}
/**
* Registration.
*
* @param userForm the user form
* @param bindingResult the binding result
* @return the string
*/
@PostMapping("/registration")
public String registration(@ModelAttribute("userForm") Utilisateur userForm, BindingResult bindingResult) {
userValidator.validate(userForm, bindingResult);
if (bindingResult.hasErrors()) {
return "registration";
}
userService.save(userForm);
securityService.autoLogin(userForm.getUsername(), userForm.getPasswordConfirm());
return "redirect:/welcome";
}
/**
* Login.
*
* @param model the model
* @param error the error
* @param logout the logout
* @return the string
*/
@GetMapping("/login")
public String login(Model model, String error, String logout) {
if (error != null)
model.addAttribute("error", "Your username and password is invalid.");
if (logout != null)
model.addAttribute("message", "You have been logged out successfully.");
return "login";
}
/**
* Welcome.
*
* @param model the model
* @return the string
*/
@GetMapping({"/", "/welcome"})
public String welcome(Model model) {
return "welcome";
}
}
| 2,741 | 0.641007 | 0.641007 | 99 | 25.686869 | 23.259035 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.383838 | false | false | 3 |
e000928d3610b5574c9d5cae197a108a5b8955e8 | 21,560,735,826,285 | 1489658cccc8c9826ca833f922fcdd0401ad0d1d | /Qmyd/src/com/ak/qmyd/bean/AreaList.java | bd00604d7ba27ffb03c00e7730eef2d489d05586 | [] | no_license | paulzeng/qmyd | https://github.com/paulzeng/qmyd | b9386dae0ef277679fba3ebd180d7fa31c93279d | 16d2183d3ef1d1dbdf0636b575c3794330a62e7f | refs/heads/master | 2021-01-10T05:30:36.952000 | 2015-11-10T12:38:18 | 2015-11-10T12:38:18 | 45,910,835 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ak.qmyd.bean;
import java.io.Serializable;
public class AreaList implements Serializable {
String areaCode;
String areaName;
public String getAreaCode() {
return areaCode;
}
public void setAreaCode(String areaCode) {
this.areaCode = areaCode;
}
public String getAreaName() {
return areaName;
}
public void setAreaName(String areaName) {
this.areaName = areaName;
}
}
| UTF-8 | Java | 434 | java | AreaList.java | Java | [] | null | [] | package com.ak.qmyd.bean;
import java.io.Serializable;
public class AreaList implements Serializable {
String areaCode;
String areaName;
public String getAreaCode() {
return areaCode;
}
public void setAreaCode(String areaCode) {
this.areaCode = areaCode;
}
public String getAreaName() {
return areaName;
}
public void setAreaName(String areaName) {
this.areaName = areaName;
}
}
| 434 | 0.684332 | 0.684332 | 27 | 14.074074 | 15.479798 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 3 |
02d6af8b6ace7c2402d1126d030ae9123f9aa448 | 6,476,810,716,085 | 0b858ddad33675beb1e18fa8389e948d74484a49 | /src/main/java/me/k1005/web/config/WebMvcConfiguration.java | 9d1f62fcb1d906d24d1221e33d5d1b031173b72a | [] | no_license | erim1005/spring-boot-hibernate | https://github.com/erim1005/spring-boot-hibernate | 43be3210a4e2bba9ca0760d6bbf94154011c7200 | cfc9f9072be6b59fe6589103fcfeb25104d82ded | refs/heads/master | 2020-01-22T17:29:32.813000 | 2014-12-05T09:35:29 | 2014-12-05T09:35:29 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package me.k1005.web.config;
import me.k1005.web.exception.WebAppRuntimeException;
import me.k1005.web.exception.WebAppRuntimeExceptionView;
import me.k1005.web.interceptor.XSSHandlerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import java.util.Properties;
@Configuration
@EnableWebMvc
@EnableAspectJAutoProxy
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources");
registry.addResourceHandler("/js/**").addResourceLocations("classpath:/js/");
registry.addResourceHandler("/css/**").addResourceLocations("classpath:/css/");
registry.addResourceHandler("/image/**").addResourceLocations("classpath:/image/");
registry.addResourceHandler("/html/**").addResourceLocations("classpath:/html/");
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new XSSHandlerInterceptor())
.addPathPatterns("/**")
;
super.addInterceptors(registry);
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
@Bean
public ViewResolver getJspViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
viewResolver.setOrder(2);
return viewResolver;
}
@Bean(name="simpleMappingExceptionResolver")
public SimpleMappingExceptionResolver createSimpleMappingExceptionResolver() {
SimpleMappingExceptionResolver r = new SimpleMappingExceptionResolver();
Properties mappings = new Properties();
mappings.setProperty(WebAppRuntimeException.class.getName(), "WebAppRuntimeExceptionView");
r.setExceptionMappings(mappings); // None by default
r.setDefaultErrorView("error/500"); // No default
r.setExceptionAttribute("exception"); // Default is "exception"
return r;
}
@Bean(name="WebAppRuntimeExceptionView")
public WebAppRuntimeExceptionView webAppRuntimeExceptionView() {
return new WebAppRuntimeExceptionView();
}
}
| UTF-8 | Java | 2,690 | java | WebMvcConfiguration.java | Java | [] | null | [] | package me.k1005.web.config;
import me.k1005.web.exception.WebAppRuntimeException;
import me.k1005.web.exception.WebAppRuntimeExceptionView;
import me.k1005.web.interceptor.XSSHandlerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import java.util.Properties;
@Configuration
@EnableWebMvc
@EnableAspectJAutoProxy
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources");
registry.addResourceHandler("/js/**").addResourceLocations("classpath:/js/");
registry.addResourceHandler("/css/**").addResourceLocations("classpath:/css/");
registry.addResourceHandler("/image/**").addResourceLocations("classpath:/image/");
registry.addResourceHandler("/html/**").addResourceLocations("classpath:/html/");
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new XSSHandlerInterceptor())
.addPathPatterns("/**")
;
super.addInterceptors(registry);
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
@Bean
public ViewResolver getJspViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
viewResolver.setOrder(2);
return viewResolver;
}
@Bean(name="simpleMappingExceptionResolver")
public SimpleMappingExceptionResolver createSimpleMappingExceptionResolver() {
SimpleMappingExceptionResolver r = new SimpleMappingExceptionResolver();
Properties mappings = new Properties();
mappings.setProperty(WebAppRuntimeException.class.getName(), "WebAppRuntimeExceptionView");
r.setExceptionMappings(mappings); // None by default
r.setDefaultErrorView("error/500"); // No default
r.setExceptionAttribute("exception"); // Default is "exception"
return r;
}
@Bean(name="WebAppRuntimeExceptionView")
public WebAppRuntimeExceptionView webAppRuntimeExceptionView() {
return new WebAppRuntimeExceptionView();
}
}
| 2,690 | 0.804833 | 0.797398 | 76 | 34.394737 | 30.18935 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.513158 | false | false | 3 |
3d578bdfa07cfb8a7af40912da993bc133e1afdc | 20,255,065,769,022 | be25b2c018dbacd8147a8fbfbc66f257b050ea1f | /languages/languageDesign/editor/source_gen/jetbrains/mps/lang/editor/structure/QueryFunction_ParametersList.java | 046ab3b3166c4a9b4775637d87dee1cdfc9ce680 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | blutkind/MPS | https://github.com/blutkind/MPS | f5bef8c27c3cb65940ba74a5d1942fdab35ee096 | cac72cce91d98dec40bbadf7a049ed9dbbc18231 | refs/heads/master | 2020-04-08T01:22:10.782000 | 2011-12-09T20:58:07 | 2011-12-09T20:58:07 | 2,950,220 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package jetbrains.mps.lang.editor.structure;
/*Generated by MPS */
import jetbrains.mps.baseLanguage.structure.ConceptFunction;
import jetbrains.mps.smodel.SNode;
import jetbrains.mps.smodel.SModel;
import jetbrains.mps.smodel.SModelUtil_new;
import jetbrains.mps.project.GlobalScope;
public class QueryFunction_ParametersList extends ConceptFunction {
public static final String concept = "jetbrains.mps.lang.editor.structure.QueryFunction_ParametersList";
public QueryFunction_ParametersList(SNode node) {
super(node);
}
public static QueryFunction_ParametersList newInstance(SModel sm, boolean init) {
return (QueryFunction_ParametersList) SModelUtil_new.instantiateConceptDeclaration("jetbrains.mps.lang.editor.structure.QueryFunction_ParametersList", sm, GlobalScope.getInstance(), init).getAdapter();
}
public static QueryFunction_ParametersList newInstance(SModel sm) {
return QueryFunction_ParametersList.newInstance(sm, false);
}
}
| UTF-8 | Java | 973 | java | QueryFunction_ParametersList.java | Java | [] | null | [] | package jetbrains.mps.lang.editor.structure;
/*Generated by MPS */
import jetbrains.mps.baseLanguage.structure.ConceptFunction;
import jetbrains.mps.smodel.SNode;
import jetbrains.mps.smodel.SModel;
import jetbrains.mps.smodel.SModelUtil_new;
import jetbrains.mps.project.GlobalScope;
public class QueryFunction_ParametersList extends ConceptFunction {
public static final String concept = "jetbrains.mps.lang.editor.structure.QueryFunction_ParametersList";
public QueryFunction_ParametersList(SNode node) {
super(node);
}
public static QueryFunction_ParametersList newInstance(SModel sm, boolean init) {
return (QueryFunction_ParametersList) SModelUtil_new.instantiateConceptDeclaration("jetbrains.mps.lang.editor.structure.QueryFunction_ParametersList", sm, GlobalScope.getInstance(), init).getAdapter();
}
public static QueryFunction_ParametersList newInstance(SModel sm) {
return QueryFunction_ParametersList.newInstance(sm, false);
}
}
| 973 | 0.807811 | 0.807811 | 25 | 37.919998 | 45.691944 | 205 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.