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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e01bb380bc9b7bd6d18ad885dd2dea6aef28a2f
| 22,832,046,163,110 |
445f6f39486724f9b1b6d668b00e26c734c9c0e9
|
/hw2.java
|
c4e35e4d80304fbfe0f5e4b6ce65b4060ce00c95
|
[] |
no_license
|
GyeongJinMin/hw2
|
https://github.com/GyeongJinMin/hw2
|
1c1fa6557f7dd09a19531090060d35596f0aaad0
|
311dbc5d6d17dff4a0e0c21e71583d4254754e7e
|
refs/heads/master
| 2020-09-21T15:41:42.422000 | 2019-11-29T11:17:17 | 2019-11-29T11:17:17 | 224,835,027 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class hw2 {
public static void main(String[] args) {
System.out.println("This is A.");
System.out.println("This is F.");
}
}
|
UTF-8
|
Java
| 156 |
java
|
hw2.java
|
Java
|
[] | null |
[] |
public class hw2 {
public static void main(String[] args) {
System.out.println("This is A.");
System.out.println("This is F.");
}
}
| 156 | 0.576923 | 0.570513 | 6 | 25 | 17.785763 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false |
13
|
910a8f8dc33b0e07a6fdae38c95e62ff9b7c503e
| 26,448,408,663,419 |
a3e96f29fe53be3236342170a6e0dd36b116c656
|
/CSecondHand/src/main/java/com/secondhand/widget/autoscrollviewpager/ImagePagerBannerAdapter.java
|
826f8b1918e5c0ff5f85b3c71a232482fa07d468
|
[] |
no_license
|
chayZeng/SecondHand
|
https://github.com/chayZeng/SecondHand
|
780d5867613c2d434169fb83371714a1f444a239
|
31f8cc3b48d1c5e7e243be91f88a3bdd928961a3
|
refs/heads/master
| 2016-06-07T13:58:37.354000 | 2016-04-27T03:59:24 | 2016-04-27T03:59:24 | 48,550,379 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.secondhand.widget.autoscrollviewpager;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.secondhand.R;
import com.secondhand.http.image.glide.GlideManager;
import com.secondhand.bean.Banner;
import java.util.ArrayList;
import java.util.List;
/**
* ImagePagerBannerAdapter
*/
public class ImagePagerBannerAdapter extends RecyclingPagerAdapter {
private Context context;
private List<Banner> bannerList;
private int size;
private boolean isInfiniteLoop;
private OnBannerClickListener mBannerClickListener = null;
public ImagePagerBannerAdapter(Context context) {
this.context = context;
this.bannerList = new ArrayList<>();
this.size = bannerList.size();
isInfiniteLoop = false;
}
public void setData(List<Banner> banners) {
if (this.bannerList == null) {
bannerList = new ArrayList<>();
}
bannerList.clear();
bannerList.addAll(banners);
this.size = banners.size();
notifyDataSetChanged();
}
@Override
public int getCount() {
return isInfiniteLoop ? Integer.MAX_VALUE : bannerList.size();
}
@Override
public int getRealCount() {
return bannerList.size();
}
private int getRealPosition(int position) {
return isInfiniteLoop ? position % size : position;
}
@Override
public View getView(final int position, View convertView, ViewGroup container) {
if (convertView == null) {
convertView = LayoutInflater.from(container.getContext())
.inflate(R.layout.item_viewpager_imageview, container, false);
}
ImageView imageView = (ImageView) convertView.findViewById(R.id.item_imageview);
GlideManager.getGlideLoader().loadImage(imageView, bannerList.get(getRealPosition(position)).getbPic(), R.color.pic_loading);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mBannerClickListener.onClick(v, getRealPosition(position));
}
});
return convertView;
}
public void setBannerClickListener(OnBannerClickListener mBannerClickListener) {
this.mBannerClickListener = mBannerClickListener;
}
/**
* 设置是否无限轮播
*/
public ImagePagerBannerAdapter setInfiniteLoop(boolean isInfiniteLoop) {
this.isInfiniteLoop = isInfiniteLoop;
return this;
}
public interface OnBannerClickListener {
void onClick(View v, int position);
}
}
|
UTF-8
|
Java
| 2,718 |
java
|
ImagePagerBannerAdapter.java
|
Java
|
[] | null |
[] |
package com.secondhand.widget.autoscrollviewpager;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.secondhand.R;
import com.secondhand.http.image.glide.GlideManager;
import com.secondhand.bean.Banner;
import java.util.ArrayList;
import java.util.List;
/**
* ImagePagerBannerAdapter
*/
public class ImagePagerBannerAdapter extends RecyclingPagerAdapter {
private Context context;
private List<Banner> bannerList;
private int size;
private boolean isInfiniteLoop;
private OnBannerClickListener mBannerClickListener = null;
public ImagePagerBannerAdapter(Context context) {
this.context = context;
this.bannerList = new ArrayList<>();
this.size = bannerList.size();
isInfiniteLoop = false;
}
public void setData(List<Banner> banners) {
if (this.bannerList == null) {
bannerList = new ArrayList<>();
}
bannerList.clear();
bannerList.addAll(banners);
this.size = banners.size();
notifyDataSetChanged();
}
@Override
public int getCount() {
return isInfiniteLoop ? Integer.MAX_VALUE : bannerList.size();
}
@Override
public int getRealCount() {
return bannerList.size();
}
private int getRealPosition(int position) {
return isInfiniteLoop ? position % size : position;
}
@Override
public View getView(final int position, View convertView, ViewGroup container) {
if (convertView == null) {
convertView = LayoutInflater.from(container.getContext())
.inflate(R.layout.item_viewpager_imageview, container, false);
}
ImageView imageView = (ImageView) convertView.findViewById(R.id.item_imageview);
GlideManager.getGlideLoader().loadImage(imageView, bannerList.get(getRealPosition(position)).getbPic(), R.color.pic_loading);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mBannerClickListener.onClick(v, getRealPosition(position));
}
});
return convertView;
}
public void setBannerClickListener(OnBannerClickListener mBannerClickListener) {
this.mBannerClickListener = mBannerClickListener;
}
/**
* 设置是否无限轮播
*/
public ImagePagerBannerAdapter setInfiniteLoop(boolean isInfiniteLoop) {
this.isInfiniteLoop = isInfiniteLoop;
return this;
}
public interface OnBannerClickListener {
void onClick(View v, int position);
}
}
| 2,718 | 0.673575 | 0.673575 | 94 | 27.74468 | 26.534977 | 133 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.489362 | false | false |
13
|
979f80de57d510be016bd38410c4978ce9f5cb92
| 15,848,429,340,158 |
cffa526ad8f33ffc22e8a37c40e4807c87e8328b
|
/nm-web/src/main/java/tiger/web/controller/utils/FileController.java
|
c30329f0f8b8f510dd7ea4392f132830f8fcdd6e
|
[] |
no_license
|
KrisCheng/ExperimentForDotNet
|
https://github.com/KrisCheng/ExperimentForDotNet
|
8e24b32fe74db03611fa5d0d9e16e00e527a35a3
|
3f10930215d7b2377d1ed23e49ad1bc1d798240c
|
refs/heads/master
| 2016-09-16T12:49:18.807000 | 2016-06-13T10:51:15 | 2016-06-13T10:51:15 | 61,028,277 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* 404 Studio Inc.
* Copyright (c) 2014-2015 All Rights Reserved.
*/
package tiger.web.controller.utils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tiger.biz.attach.support.AttachManager;
import tiger.common.dal.annotation.Permission;
import tiger.core.base.BaseResult;
import tiger.core.domain.AttachDomain;
import tiger.core.enums.ErrorCodeEnum;
import tiger.core.exception.AppException;
import tiger.core.service.AttachService;
import tiger.web.controller.BaseController;
/**
* @author yiliang.gyl
* @version $ID: v 0.1 12:43 AM yiliang.gyl Exp $
*/
@RestController
@RequestMapping(value = "/api/file")
public class FileController extends BaseController {
private static Logger logger = Logger.getLogger(FileController.class);
@Autowired
AttachManager attachManager;
@Autowired
AttachService attachService;
/**
* 上传文件
*
* @param file
* @return
*/
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@Permission
public BaseResult<?> uploadFileTest(MultipartFile file) {
return attachManager.uploadAttach(currentAccount().getId(), file);
}
/**
* 获取文件
*
* @param id
* @return
*/
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@Permission
public BaseResult<AttachDomain> read(@PathVariable("id") Long id) {
return attachManager.readById(id);
}
/**
* 删除附件
*
* @param id the id
* @return the base result
*/
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
@ResponseBody
@Permission
public BaseResult<Boolean> deleteAttachById(@PathVariable long id) {
return new BaseResult<>(attachService.deleteAttachById(id));
}
// ~ private methods
public void checkFile(Long id) {
if (!attachService.isOwner(id, currentAccount().getId())) {
throw new AppException(ErrorCodeEnum.UNAUTHORIZED, "没有权限访问该文件");
}
}
}
|
UTF-8
|
Java
| 2,185 |
java
|
FileController.java
|
Java
|
[
{
"context": "ger.web.controller.BaseController;\n\n/**\n * @author yiliang.gyl\n * @version $ID: v 0.1 12:43 AM yiliang.gyl Exp $",
"end": 674,
"score": 0.9916653633117676,
"start": 663,
"tag": "USERNAME",
"value": "yiliang.gyl"
}
] | null |
[] |
/**
* 404 Studio Inc.
* Copyright (c) 2014-2015 All Rights Reserved.
*/
package tiger.web.controller.utils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tiger.biz.attach.support.AttachManager;
import tiger.common.dal.annotation.Permission;
import tiger.core.base.BaseResult;
import tiger.core.domain.AttachDomain;
import tiger.core.enums.ErrorCodeEnum;
import tiger.core.exception.AppException;
import tiger.core.service.AttachService;
import tiger.web.controller.BaseController;
/**
* @author yiliang.gyl
* @version $ID: v 0.1 12:43 AM yiliang.gyl Exp $
*/
@RestController
@RequestMapping(value = "/api/file")
public class FileController extends BaseController {
private static Logger logger = Logger.getLogger(FileController.class);
@Autowired
AttachManager attachManager;
@Autowired
AttachService attachService;
/**
* 上传文件
*
* @param file
* @return
*/
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@Permission
public BaseResult<?> uploadFileTest(MultipartFile file) {
return attachManager.uploadAttach(currentAccount().getId(), file);
}
/**
* 获取文件
*
* @param id
* @return
*/
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@Permission
public BaseResult<AttachDomain> read(@PathVariable("id") Long id) {
return attachManager.readById(id);
}
/**
* 删除附件
*
* @param id the id
* @return the base result
*/
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
@ResponseBody
@Permission
public BaseResult<Boolean> deleteAttachById(@PathVariable long id) {
return new BaseResult<>(attachService.deleteAttachById(id));
}
// ~ private methods
public void checkFile(Long id) {
if (!attachService.isOwner(id, currentAccount().getId())) {
throw new AppException(ErrorCodeEnum.UNAUTHORIZED, "没有权限访问该文件");
}
}
}
| 2,185 | 0.685488 | 0.677088 | 79 | 26.126583 | 23.56374 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.329114 | false | false |
13
|
07f1c1b7b67c34f74075b369ac8f4597768d9553
| 17,557,826,332,159 |
b27f2e0c123c25753796d6c31770e801749111d3
|
/Project03/src/main/java/in/co/rays/project3/util/DataUtility.java
|
cdd6c168471001a00493d692a7113de77df4836c
|
[] |
no_license
|
Vaishali-Patidar/Project_3
|
https://github.com/Vaishali-Patidar/Project_3
|
fe469788792b818c2f28e9f479c2cc98c54e4c89
|
2cd8afe5b35391b32441197d4206aa9289504227
|
refs/heads/main
| 2023-05-19T12:23:03.252000 | 2021-06-09T15:47:59 | 2021-06-09T15:47:59 | 374,576,929 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package in.co.rays.project3.util;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
// TODO: Auto-generated Javadoc
/**
* Data Utility class to format data from one format to another
*
* @author Vaishali
*/
public class DataUtility {
/** Application Date Format. */
public static final String APP_DATE_FORMAT = "dd-MM-yy";
/** The Constant APP_TIME_FORMAT. */
public static final String APP_TIME_FORMAT = "MM/dd/yyyy HH:mm:ss";
/** Date formatter. */
private static final SimpleDateFormat formatter = new SimpleDateFormat(
APP_DATE_FORMAT);
/** The Constant timeFormatter. */
private static final SimpleDateFormat timeFormatter = new SimpleDateFormat(
APP_TIME_FORMAT);
/**
* Trims and trailing and leading spaces of a String
*
*
* @param val the val
* @return the string
*/
public static String getString(String val){
if(DataValidator.isNotNull(val)){
return val.trim();
}else{
return val;
}
}
/**
* Gets the string data.
*
* @param val the val
* @return the string data
*/
public static String getStringData(Object val){
if(val!=null){
return val.toString();
}else{
return "";
}
}
/**
* Gets the int.
*
* @param val the val
* @return the int
*/
public static int getInt(String val){
if(DataValidator.isInteger(val)){
return Integer.parseInt(val);
}else{
return 0;
}
}
/**
* Gets the long.
*
* @param val the val
* @return the long
*/
public static Long getLong(String val){
if(DataValidator.isLong(val)){
return Long.parseLong(val);
}else{
return (long) 0;
}
}
/**
* Gets the date.
*
* @param val the val
* @return the date
*/
public static Date getDate(String val){
Date date=null;
try{
date=formatter.parse(val);
}catch(Exception e){
}
return date;
}
/**
* Gets the date string.
*
* @param date the date
* @return the date string
*/
public static String getDateString(Date date){
try{
return formatter.format(date);
}catch(Exception e){
}
return "";
}
/**
* Gets the date.
*
* @param date the date
* @param day the day
* @return the date
*/
public static Date getDate(Date date,int day){
return null;
}
/**
* Ge timestamp.
*
* @param val the val
* @return the timestamp
*/
public static Timestamp geTimestamp(String val){
Timestamp timeStamp=null;
try{
timeStamp=new Timestamp(timeFormatter.parse(val).getTime());
}catch(Exception e){
return null;
}
return timeStamp;
}
/**
* Gets the time stamp.
*
* @param l the l
* @return the time stamp
*/
public static Timestamp getTimeStamp(long l){
Timestamp timeStamp=null;
try{
timeStamp=new Timestamp(l);
}catch(Exception e){
return null;
}
return timeStamp;
}
/**
* Gets the current time stamp.
*
* @return the current time stamp
*/
public static Timestamp getCurrentTimeStamp(){
Timestamp timeStamp=null;
try{
timeStamp=new Timestamp(new Date().getTime());
}catch(Exception e){
}return timeStamp;
}
/**
* Gets the timestamp.
*
* @param tm the tm
* @return the timestamp
*/
public static long getTimestamp(Timestamp tm) {
try {
return tm.getTime();
} catch (Exception e) {
return 0;
}
}
}
|
UTF-8
|
Java
| 3,443 |
java
|
DataUtility.java
|
Java
|
[
{
"context": "at data from one format to another\n * \n * @author Vaishali\n */\n \npublic class DataUtility {\n \n /** Applic",
"end": 245,
"score": 0.9996833205223083,
"start": 237,
"tag": "NAME",
"value": "Vaishali"
}
] | null |
[] |
package in.co.rays.project3.util;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
// TODO: Auto-generated Javadoc
/**
* Data Utility class to format data from one format to another
*
* @author Vaishali
*/
public class DataUtility {
/** Application Date Format. */
public static final String APP_DATE_FORMAT = "dd-MM-yy";
/** The Constant APP_TIME_FORMAT. */
public static final String APP_TIME_FORMAT = "MM/dd/yyyy HH:mm:ss";
/** Date formatter. */
private static final SimpleDateFormat formatter = new SimpleDateFormat(
APP_DATE_FORMAT);
/** The Constant timeFormatter. */
private static final SimpleDateFormat timeFormatter = new SimpleDateFormat(
APP_TIME_FORMAT);
/**
* Trims and trailing and leading spaces of a String
*
*
* @param val the val
* @return the string
*/
public static String getString(String val){
if(DataValidator.isNotNull(val)){
return val.trim();
}else{
return val;
}
}
/**
* Gets the string data.
*
* @param val the val
* @return the string data
*/
public static String getStringData(Object val){
if(val!=null){
return val.toString();
}else{
return "";
}
}
/**
* Gets the int.
*
* @param val the val
* @return the int
*/
public static int getInt(String val){
if(DataValidator.isInteger(val)){
return Integer.parseInt(val);
}else{
return 0;
}
}
/**
* Gets the long.
*
* @param val the val
* @return the long
*/
public static Long getLong(String val){
if(DataValidator.isLong(val)){
return Long.parseLong(val);
}else{
return (long) 0;
}
}
/**
* Gets the date.
*
* @param val the val
* @return the date
*/
public static Date getDate(String val){
Date date=null;
try{
date=formatter.parse(val);
}catch(Exception e){
}
return date;
}
/**
* Gets the date string.
*
* @param date the date
* @return the date string
*/
public static String getDateString(Date date){
try{
return formatter.format(date);
}catch(Exception e){
}
return "";
}
/**
* Gets the date.
*
* @param date the date
* @param day the day
* @return the date
*/
public static Date getDate(Date date,int day){
return null;
}
/**
* Ge timestamp.
*
* @param val the val
* @return the timestamp
*/
public static Timestamp geTimestamp(String val){
Timestamp timeStamp=null;
try{
timeStamp=new Timestamp(timeFormatter.parse(val).getTime());
}catch(Exception e){
return null;
}
return timeStamp;
}
/**
* Gets the time stamp.
*
* @param l the l
* @return the time stamp
*/
public static Timestamp getTimeStamp(long l){
Timestamp timeStamp=null;
try{
timeStamp=new Timestamp(l);
}catch(Exception e){
return null;
}
return timeStamp;
}
/**
* Gets the current time stamp.
*
* @return the current time stamp
*/
public static Timestamp getCurrentTimeStamp(){
Timestamp timeStamp=null;
try{
timeStamp=new Timestamp(new Date().getTime());
}catch(Exception e){
}return timeStamp;
}
/**
* Gets the timestamp.
*
* @param tm the tm
* @return the timestamp
*/
public static long getTimestamp(Timestamp tm) {
try {
return tm.getTime();
} catch (Exception e) {
return 0;
}
}
}
| 3,443 | 0.616033 | 0.614871 | 194 | 16.747423 | 16.490957 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.381443 | false | false |
13
|
86aa5b51904ef09bf0b27ae38ace0c843b6ac5e7
| 7,730,941,145,525 |
40dec2daad60dca19c9593ca808de0071392153b
|
/src/main/java/io/github/vpavic/traintracker/config/HttpClientConfiguration.java
|
57ff34b8b45f41b98a9ec90ae7628473728421b0
|
[
"Apache-2.0"
] |
permissive
|
vpavic/voznired
|
https://github.com/vpavic/voznired
|
0de19698737e6e79257ceeae65a7b8008d381bbf
|
0e781c74f89fcaf481ec9c3a16a3142e3dfc3369
|
refs/heads/master
| 2021-01-24T10:27:29.003000 | 2020-11-13T19:27:50 | 2020-11-13T19:27:50 | 9,300,845 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.vpavic.traintracker.config;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration(proxyBeanMethods = false)
public class HttpClientConfiguration {
@Bean
public CloseableHttpClient httpClient() {
// @formatter:off
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(5000)
.setConnectTimeout(5000)
.setSocketTimeout(5000)
.build();
// @formatter:on
// @formatter:off
return HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig)
.useSystemProperties()
.build();
// @formatter:on
}
}
|
UTF-8
|
Java
| 1,569 |
java
|
HttpClientConfiguration.java
|
Java
|
[
{
"context": "tations under the License.\n */\n\npackage io.github.vpavic.traintracker.config;\n\nimport org.apache.http.clie",
"end": 640,
"score": 0.7506322860717773,
"start": 634,
"tag": "USERNAME",
"value": "vpavic"
}
] | null |
[] |
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.vpavic.traintracker.config;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration(proxyBeanMethods = false)
public class HttpClientConfiguration {
@Bean
public CloseableHttpClient httpClient() {
// @formatter:off
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(5000)
.setConnectTimeout(5000)
.setSocketTimeout(5000)
.build();
// @formatter:on
// @formatter:off
return HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig)
.useSystemProperties()
.build();
// @formatter:on
}
}
| 1,569 | 0.697897 | 0.68515 | 45 | 33.866665 | 23.954216 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.288889 | false | false |
13
|
9c48d365d75d8e3ec17ec0e5775220441e87117e
| 27,771,258,551,724 |
54bb39be9e94065549673d5e43416d24132d1f85
|
/app/src/main/java/com/ml/songsearchapp/ui/home/HomeFragment.java
|
d5d9ee121109c4fc9eb80389a776c1cdef50a7f0
|
[] |
no_license
|
JoeYada/SongSearchApp-master
|
https://github.com/JoeYada/SongSearchApp-master
|
edc7a9cf6724f410e17c75000e17508d1cbc5313
|
5f298fcd92ef7742b5fbe4fbe210a582f3d59685
|
refs/heads/master
| 2023-08-11T18:46:46.842000 | 2021-09-16T18:51:51 | 2021-09-16T18:51:51 | 407,280,274 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.ml.songsearchapp.ui.home;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import com.google.android.material.snackbar.Snackbar;
import com.ml.songsearchapp.R;
import com.ml.songsearchapp.databinding.FragmentHomeBinding;
import com.ml.songsearchapp.domain.Song;
import com.ml.songsearchapp.domain.SongMatches;
import com.ml.songsearchapp.ui.home.adapter.SearchAdapter;
import com.ml.songsearchapp.viewmodel.SearchSongViewModel;
import dagger.hilt.android.AndroidEntryPoint;
import static com.ml.songsearchapp.ui.home.adapter.SearchAdapter.*;
@AndroidEntryPoint
public class HomeFragment extends Fragment implements SearchAdapterDelegate {
private SearchAdapter searchAdapter;
private FragmentHomeBinding binding;
SearchSongViewModel viewModel;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
binding = FragmentHomeBinding.inflate(inflater);
return binding.getRoot();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
viewModel = new ViewModelProvider(this).get(SearchSongViewModel.class);
viewModel.retrieveStoredSongs();
setupRecyclerView();
setupObserver();
setupListeners();
}
private void setupRecyclerView() {
searchAdapter = new SearchAdapter(this);
binding.searchResultsRecycler.setAdapter(searchAdapter);
}
private void setupObserver() {
viewModel.songMatchesLiveData.observe(getViewLifecycleOwner(), this::handleSongMatches);
}
private void setupListeners() {
binding.searchButton.setOnClickListener(v -> {
if(binding.searchEdittext.getText().toString().isEmpty())
showSnackBar(getString(R.string.please_enter_song_title_text));
else viewModel.retrieveSongs(binding.searchEdittext.getText().toString());
});
}
private void showSnackBar(String message) {
Snackbar sb = Snackbar.make(requireView(), message, Snackbar.LENGTH_SHORT);
sb.setAnchorView(binding.searchCardview);
sb.show();
}
private void handleSongMatches(SongMatches songMatches) {
if(songMatches != null) searchAdapter.submitList(songMatches.songList);
}
@Override
public void songClick(Song song) {
NavController navController = Navigation.findNavController(requireActivity(), R.id.nav_host_fragment);
navController.navigate(HomeFragmentDirections.toDetailsFragment(song, null));
}
}
|
UTF-8
|
Java
| 2,971 |
java
|
HomeFragment.java
|
Java
|
[] | null |
[] |
package com.ml.songsearchapp.ui.home;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import com.google.android.material.snackbar.Snackbar;
import com.ml.songsearchapp.R;
import com.ml.songsearchapp.databinding.FragmentHomeBinding;
import com.ml.songsearchapp.domain.Song;
import com.ml.songsearchapp.domain.SongMatches;
import com.ml.songsearchapp.ui.home.adapter.SearchAdapter;
import com.ml.songsearchapp.viewmodel.SearchSongViewModel;
import dagger.hilt.android.AndroidEntryPoint;
import static com.ml.songsearchapp.ui.home.adapter.SearchAdapter.*;
@AndroidEntryPoint
public class HomeFragment extends Fragment implements SearchAdapterDelegate {
private SearchAdapter searchAdapter;
private FragmentHomeBinding binding;
SearchSongViewModel viewModel;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
binding = FragmentHomeBinding.inflate(inflater);
return binding.getRoot();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
viewModel = new ViewModelProvider(this).get(SearchSongViewModel.class);
viewModel.retrieveStoredSongs();
setupRecyclerView();
setupObserver();
setupListeners();
}
private void setupRecyclerView() {
searchAdapter = new SearchAdapter(this);
binding.searchResultsRecycler.setAdapter(searchAdapter);
}
private void setupObserver() {
viewModel.songMatchesLiveData.observe(getViewLifecycleOwner(), this::handleSongMatches);
}
private void setupListeners() {
binding.searchButton.setOnClickListener(v -> {
if(binding.searchEdittext.getText().toString().isEmpty())
showSnackBar(getString(R.string.please_enter_song_title_text));
else viewModel.retrieveSongs(binding.searchEdittext.getText().toString());
});
}
private void showSnackBar(String message) {
Snackbar sb = Snackbar.make(requireView(), message, Snackbar.LENGTH_SHORT);
sb.setAnchorView(binding.searchCardview);
sb.show();
}
private void handleSongMatches(SongMatches songMatches) {
if(songMatches != null) searchAdapter.submitList(songMatches.songList);
}
@Override
public void songClick(Song song) {
NavController navController = Navigation.findNavController(requireActivity(), R.id.nav_host_fragment);
navController.navigate(HomeFragmentDirections.toDetailsFragment(song, null));
}
}
| 2,971 | 0.74756 | 0.74756 | 84 | 34.369049 | 30.07086 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.619048 | false | false |
13
|
3987cbc0e535d69b2ad540a29692a6481c51a3dc
| 33,114,197,889,219 |
1c9d6e9a0d6b3e11e62fd7df64dbc70ff4f3efdd
|
/src/test/java/org/springframework/samples/travel/JpaBookingServiceTests.java
|
19f846a17693fd3d5979e780db60b7c5c0bf2e9f
|
[] |
no_license
|
GolfenGuo/java-mysql-travel-sample
|
https://github.com/GolfenGuo/java-mysql-travel-sample
|
c1d3870f92d67a3e8811a70540c4277071bcc37b
|
53aeca62d677c0c72338dfd5ae076317afa47d42
|
refs/heads/master
| 2021-05-02T05:50:03.181000 | 2016-09-29T10:09:48 | 2016-09-29T10:09:48 | 33,064,359 | 2 | 11 | null | false | 2016-01-29T05:44:29 | 2015-03-29T06:48:46 | 2015-09-28T09:44:21 | 2015-10-10T12:36:34 | 1,214 | 1 | 4 | 1 |
JavaScript
| null | null |
package org.springframework.samples.travel;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.samples.travel.domain.Booking;
import org.springframework.samples.travel.domain.Hotel;
import org.springframework.samples.travel.services.JpaBookingService;
import org.springframework.samples.travel.services.SearchCriteria;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
import java.util.List;
import java.util.Set;
public class JpaBookingServiceTests {
public static void main(String[] args) throws Throwable {
ApplicationContext annotationConfigApplicationContext
= new ClassPathXmlApplicationContext("/services.xml");
PlatformTransactionManager transactionManager = annotationConfigApplicationContext.getBean(PlatformTransactionManager.class);
TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
transactionTemplate.afterPropertiesSet();
final JpaBookingService jpaBookingService = annotationConfigApplicationContext.getBean(JpaBookingService.class);
final SearchCriteria searchCriteria = new SearchCriteria();
searchCriteria.setPage(0);
searchCriteria.setPageSize(100);
searchCriteria.setSearchString("standard");
searchCriteria.setMaximumPrice(43);
transactionTemplate.execute(new TransactionCallback<Object>() {
@Override
public Object doInTransaction(TransactionStatus status) {
List<Hotel> hotels = jpaBookingService.findHotels(searchCriteria);
for (Hotel h : hotels) {
System.out.println("-------------------------------");
System.out.println(h.toString());
Set<Booking> bookings = h.getReservations();
for (Booking b : bookings) {
System.out.println(b.toString());
}
}
return null;
}
});
}
}
|
UTF-8
|
Java
| 2,046 |
java
|
JpaBookingServiceTests.java
|
Java
|
[] | null |
[] |
package org.springframework.samples.travel;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.samples.travel.domain.Booking;
import org.springframework.samples.travel.domain.Hotel;
import org.springframework.samples.travel.services.JpaBookingService;
import org.springframework.samples.travel.services.SearchCriteria;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
import java.util.List;
import java.util.Set;
public class JpaBookingServiceTests {
public static void main(String[] args) throws Throwable {
ApplicationContext annotationConfigApplicationContext
= new ClassPathXmlApplicationContext("/services.xml");
PlatformTransactionManager transactionManager = annotationConfigApplicationContext.getBean(PlatformTransactionManager.class);
TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
transactionTemplate.afterPropertiesSet();
final JpaBookingService jpaBookingService = annotationConfigApplicationContext.getBean(JpaBookingService.class);
final SearchCriteria searchCriteria = new SearchCriteria();
searchCriteria.setPage(0);
searchCriteria.setPageSize(100);
searchCriteria.setSearchString("standard");
searchCriteria.setMaximumPrice(43);
transactionTemplate.execute(new TransactionCallback<Object>() {
@Override
public Object doInTransaction(TransactionStatus status) {
List<Hotel> hotels = jpaBookingService.findHotels(searchCriteria);
for (Hotel h : hotels) {
System.out.println("-------------------------------");
System.out.println(h.toString());
Set<Booking> bookings = h.getReservations();
for (Booking b : bookings) {
System.out.println(b.toString());
}
}
return null;
}
});
}
}
| 2,046 | 0.797165 | 0.794233 | 51 | 39.117645 | 30.661753 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.27451 | false | false |
13
|
9dd29265686e5cbe38e80442d0ba3b328a3567de
| 19,980,187,892,229 |
23655ec191f68010839970cb2184708e9ed12762
|
/src/main/java/jorn/hiel/helpers/PropReader.java
|
d0f279cb2ab1b4a40ea57006a3f33c6d41f4f0fd
|
[] |
no_license
|
jorn-fa/werkUren
|
https://github.com/jorn-fa/werkUren
|
c6d8367886f83be460e5090311081642b4aa31a3
|
a312a0c7bdf06864f96ea93754eba626e33cdab1
|
refs/heads/master
| 2020-03-20T07:35:33.599000 | 2018-08-26T19:00:15 | 2018-08-26T19:00:15 | 137,285,630 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package jorn.hiel.helpers;
import org.apache.log4j.Logger;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
/**
* @author Hiel Jorn
* @version 1.0, jan 2018
* @since 1.0
*/
public abstract class PropReader {
/**
* @param bestand Requires property file
* @return Property file
*/
public static Properties ReadProperties(String bestand) {
Logger logger = Logger.getLogger("dbase");
Properties eigenschappen = new Properties();
try {
FileInputStream in = new FileInputStream(bestand);
eigenschappen.load(in);
logger.debug("loaded from config file: " + bestand );
}
catch (IOException ioe)
{
logger.error("File not found: " + bestand);
}
return eigenschappen;
}
}
|
UTF-8
|
Java
| 856 |
java
|
PropReader.java
|
Java
|
[
{
"context": "tion;\nimport java.util.Properties;\n\n/**\n * @author Hiel Jorn\n * @version 1.0, jan 2018\n * @since 1.0\n */\n\npubl",
"end": 176,
"score": 0.999882698059082,
"start": 167,
"tag": "NAME",
"value": "Hiel Jorn"
}
] | null |
[] |
package jorn.hiel.helpers;
import org.apache.log4j.Logger;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
/**
* @author <NAME>
* @version 1.0, jan 2018
* @since 1.0
*/
public abstract class PropReader {
/**
* @param bestand Requires property file
* @return Property file
*/
public static Properties ReadProperties(String bestand) {
Logger logger = Logger.getLogger("dbase");
Properties eigenschappen = new Properties();
try {
FileInputStream in = new FileInputStream(bestand);
eigenschappen.load(in);
logger.debug("loaded from config file: " + bestand );
}
catch (IOException ioe)
{
logger.error("File not found: " + bestand);
}
return eigenschappen;
}
}
| 853 | 0.613318 | 0.602804 | 43 | 18.906977 | 20.121508 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.302326 | false | false |
13
|
4507cca9c50b3b08befc20194b7477cc2e9c2550
| 23,845,658,452,847 |
5e4ecb92f1fc30924fb75cb4010b901465245e58
|
/Hibernate/T1/25田苗星/上机作业/HBT1/test/com/qhit/lh/g4/tmx/t1/UserTest.java
|
bb9e41c8412c38a927bdf40f5ad37e54d79e6537
|
[] |
no_license
|
1787418735/163G4G
|
https://github.com/1787418735/163G4G
|
413ad4d3119370126a8648473c481683f07c4b27
|
232867ec5da12ab439a7e060e7e084d9cb4d070a
|
refs/heads/master
| 2021-09-09T14:26:39.388000 | 2018-03-17T02:12:37 | 2018-03-17T02:12:37 | 111,653,946 | 0 | 0 | null | true | 2017-11-22T08:01:44 | 2017-11-22T08:01:44 | 2017-11-21T07:56:07 | 2017-11-22T06:13:38 | 3,953 | 0 | 0 | 0 | null | false | null |
package com.qhit.lh.g4.tmx.t1;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
import com.qhit.lh.g4.tmx.t1.bean.User;
import com.qhit.lh.g4.tmx.t1.utils.HibernateSessionFactory;
public class UserTest {
@Test
public void addUser(){
//声明实例化User对象
User user = new User();
user.setUname("xia");
user.setUpwd("123456");
user.setBirthday("2000-5-05");
user.setSex("M");
user.setEnable(1);
//2,获取session对象
Session session = (Session) HibernateSessionFactory.getSession();
//3,开启事务
Transaction ts = session.beginTransaction();
//4,操作对象-->完成数据的CRUD
session.save(user);
//5,提交事务
ts.commit();
//6,关闭session释放资源
HibernateSessionFactory.closeSession();
}
}
|
UTF-8
|
Java
| 795 |
java
|
UserTest.java
|
Java
|
[
{
"context": "User对象\n\t\tUser user = new User();\n\t\tuser.setUname(\"xia\");\n\t\tuser.setUpwd(\"123456\");\n\t\tuser.setBirthday(\"",
"end": 338,
"score": 0.9727420210838318,
"start": 335,
"tag": "USERNAME",
"value": "xia"
},
{
"context": "w User();\n\t\tuser.setUname(\"xia\");\n\t\tuser.setUpwd(\"123456\");\n\t\tuser.setBirthday(\"2000-5-05\");\n\t\tuser.setSex",
"end": 364,
"score": 0.9968817234039307,
"start": 358,
"tag": "PASSWORD",
"value": "123456"
}
] | null |
[] |
package com.qhit.lh.g4.tmx.t1;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
import com.qhit.lh.g4.tmx.t1.bean.User;
import com.qhit.lh.g4.tmx.t1.utils.HibernateSessionFactory;
public class UserTest {
@Test
public void addUser(){
//声明实例化User对象
User user = new User();
user.setUname("xia");
user.setUpwd("<PASSWORD>");
user.setBirthday("2000-5-05");
user.setSex("M");
user.setEnable(1);
//2,获取session对象
Session session = (Session) HibernateSessionFactory.getSession();
//3,开启事务
Transaction ts = session.beginTransaction();
//4,操作对象-->完成数据的CRUD
session.save(user);
//5,提交事务
ts.commit();
//6,关闭session释放资源
HibernateSessionFactory.closeSession();
}
}
| 799 | 0.712517 | 0.678129 | 32 | 21.71875 | 16.173347 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.90625 | false | false |
13
|
7e3dfab380946b61b71192742ffc7ea689e9335d
| 25,615,184,955,671 |
e647d1eaa8f9ae27c8d17c7e7dbcdfa24f819d25
|
/src/test/java/redlaboratory/jvjoyinterface/test/JvJoyTest.java
|
254f32ec7385d58afd0aad4e5dbbf20c5c7d8f85
|
[] |
no_license
|
rlj1202/JvJoyInterface
|
https://github.com/rlj1202/JvJoyInterface
|
b807dc6ec3084c89237f2ebccf65d882c8f4cefb
|
dcffe21ef91479cb65ec84aca4bc949a7e3c0c0e
|
refs/heads/master
| 2021-01-12T09:11:52.096000 | 2017-02-18T08:15:17 | 2017-02-18T08:15:17 | 76,790,340 | 7 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package redlaboratory.jvjoyinterface.test;
import static org.junit.Assert.*;
import org.junit.Test;
import redlaboratory.jvjoyinterface.VJoy;
import redlaboratory.jvjoyinterface.VjdStat;
public class JvJoyTest {
@Test
public void vJoyTest() {
VJoy vJoy = new VJoy();
int rID = 1;
assertTrue(vJoy.vJoyEnabled());
if (!vJoy.vJoyEnabled()) {
System.out.println("vJoy driver not enabled: Failed Getting vJoy attributes.");
return;
} else {
System.out.println("Vender: " + vJoy.getvJoyManufacturerString());
System.out.println("Product: " + vJoy.getvJoyProductString());
System.out.println("Version Number: " + vJoy.getvJoyVersion());
}
assertTrue(vJoy.driverMatch());
if (vJoy.driverMatch()) {
System.out.println("Version of Driver Matches DLL Version {0}");
} else {
System.out.println("Version of Driver {0} does NOT match DLL Version {1}");
}
VjdStat status = vJoy.getVJDStatus(rID);
if ((status == VjdStat.VJD_STAT_OWN) ||
((status == VjdStat.VJD_STAT_FREE) && (!vJoy.acquireVJD(rID)))) {
System.out.println("Failed to acquire vJoy device number " + rID);
} else {
System.out.println("Acquired: vJoy device number "+ rID);
}
System.out.println("number of buttons: " + vJoy.getVJDButtonNumber(rID));
assertTrue(vJoy.setAxis(0, rID, VJoy.HID_USAGE_X));
assertTrue(vJoy.setAxis(16384, rID, VJoy.HID_USAGE_Y));
assertTrue(vJoy.setAxis(32768, rID, VJoy.HID_USAGE_Z));
assertTrue(vJoy.setAxis(0, rID, VJoy.HID_USAGE_RX));
assertTrue(vJoy.setAxis(16384, rID, VJoy.HID_USAGE_RY));
assertTrue(vJoy.setAxis(32768, rID, VJoy.HID_USAGE_RZ));
assertTrue(vJoy.setAxis(0, rID, VJoy.HID_USAGE_SL0));
assertTrue(vJoy.setAxis(16384, rID, VJoy.HID_USAGE_SL1));
for (int i = 1; i <= 32; i++) vJoy.setBtn(Math.random() > 0.5 ? true : false, rID, i);
return;
}
}
|
UTF-8
|
Java
| 1,925 |
java
|
JvJoyTest.java
|
Java
|
[] | null |
[] |
package redlaboratory.jvjoyinterface.test;
import static org.junit.Assert.*;
import org.junit.Test;
import redlaboratory.jvjoyinterface.VJoy;
import redlaboratory.jvjoyinterface.VjdStat;
public class JvJoyTest {
@Test
public void vJoyTest() {
VJoy vJoy = new VJoy();
int rID = 1;
assertTrue(vJoy.vJoyEnabled());
if (!vJoy.vJoyEnabled()) {
System.out.println("vJoy driver not enabled: Failed Getting vJoy attributes.");
return;
} else {
System.out.println("Vender: " + vJoy.getvJoyManufacturerString());
System.out.println("Product: " + vJoy.getvJoyProductString());
System.out.println("Version Number: " + vJoy.getvJoyVersion());
}
assertTrue(vJoy.driverMatch());
if (vJoy.driverMatch()) {
System.out.println("Version of Driver Matches DLL Version {0}");
} else {
System.out.println("Version of Driver {0} does NOT match DLL Version {1}");
}
VjdStat status = vJoy.getVJDStatus(rID);
if ((status == VjdStat.VJD_STAT_OWN) ||
((status == VjdStat.VJD_STAT_FREE) && (!vJoy.acquireVJD(rID)))) {
System.out.println("Failed to acquire vJoy device number " + rID);
} else {
System.out.println("Acquired: vJoy device number "+ rID);
}
System.out.println("number of buttons: " + vJoy.getVJDButtonNumber(rID));
assertTrue(vJoy.setAxis(0, rID, VJoy.HID_USAGE_X));
assertTrue(vJoy.setAxis(16384, rID, VJoy.HID_USAGE_Y));
assertTrue(vJoy.setAxis(32768, rID, VJoy.HID_USAGE_Z));
assertTrue(vJoy.setAxis(0, rID, VJoy.HID_USAGE_RX));
assertTrue(vJoy.setAxis(16384, rID, VJoy.HID_USAGE_RY));
assertTrue(vJoy.setAxis(32768, rID, VJoy.HID_USAGE_RZ));
assertTrue(vJoy.setAxis(0, rID, VJoy.HID_USAGE_SL0));
assertTrue(vJoy.setAxis(16384, rID, VJoy.HID_USAGE_SL1));
for (int i = 1; i <= 32; i++) vJoy.setBtn(Math.random() > 0.5 ? true : false, rID, i);
return;
}
}
| 1,925 | 0.658701 | 0.638442 | 61 | 29.557377 | 27.461761 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.606557 | false | false |
13
|
62b4c624a7d0ce081e71b64802dde4fbd8b934c0
| 13,417,477,845,130 |
dc04abd1ba621ac7e4f0bf67ec61201728203e6c
|
/Composition/src/com/faithefm/Monitor.java
|
90e3e4e6830a5e586838c5c8ac86545906579bb4
|
[] |
no_license
|
faithfem/JavaMasterClassU
|
https://github.com/faithfem/JavaMasterClassU
|
4607253f971f34bc7733176020d43863a634aac4
|
96fa9cc836ccc0ff10401e8bfce9da50f5737389
|
refs/heads/master
| 2021-05-03T23:05:38.462000 | 2018-02-24T18:10:20 | 2018-02-24T18:10:20 | 120,397,844 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.faithefm;
public class Monitor {
//First thing after creating a class is to create the variables
//We'll add variables of model, manufacturer, size and resolution
//Start variable creation with "private" since we don't want them publicly accessible, then int or string etc as needed
private String model;
private String manufacturer;
private int size;
private Resolution nativeResolution;
//After creating variables, create a CONSTRUCTOR for each variable.
//CONSTRUCTORS start with "public" then the Class name, then brackets() and inside those brackets, enter
//the variable part after "private", then squigly brackets, then
//this.variable name = variable name;
public Monitor(String model, String manufacturer, int size, Resolution nativeResolution){
this.model = model;
this.manufacturer = manufacturer;
this.size = size;
this.nativeResolution = nativeResolution;
}
//After the Constructor, create a METHOD
//METHODS start with "public void" then give it a method name, then enter the params inside (), then
//SOUT to print and whatever you want to print.
public void drawPixelAt(int x, int y, String color){ //THIS IS READING FROM THE RESOLUTION CLASS
System.out.println("Drawing pixel at " + x + "," + y + "," + "in color " + color );
}
//After the Method, create GETTERS for each variable.
//GETTERS start with "public".
//If a variable was a string, then it would be public String getVariableName(){ return variableName;}
//If a variable was an int, it would be public int getVariableName(){ return variableName;}
public String getModel() {
return model;
}
public String getManufacturer(){
return manufacturer;
}
public int getSize() {
return size;
}
public Resolution getNativeResolution() {
return nativeResolution;
}
}
|
UTF-8
|
Java
| 1,949 |
java
|
Monitor.java
|
Java
|
[] | null |
[] |
package com.faithefm;
public class Monitor {
//First thing after creating a class is to create the variables
//We'll add variables of model, manufacturer, size and resolution
//Start variable creation with "private" since we don't want them publicly accessible, then int or string etc as needed
private String model;
private String manufacturer;
private int size;
private Resolution nativeResolution;
//After creating variables, create a CONSTRUCTOR for each variable.
//CONSTRUCTORS start with "public" then the Class name, then brackets() and inside those brackets, enter
//the variable part after "private", then squigly brackets, then
//this.variable name = variable name;
public Monitor(String model, String manufacturer, int size, Resolution nativeResolution){
this.model = model;
this.manufacturer = manufacturer;
this.size = size;
this.nativeResolution = nativeResolution;
}
//After the Constructor, create a METHOD
//METHODS start with "public void" then give it a method name, then enter the params inside (), then
//SOUT to print and whatever you want to print.
public void drawPixelAt(int x, int y, String color){ //THIS IS READING FROM THE RESOLUTION CLASS
System.out.println("Drawing pixel at " + x + "," + y + "," + "in color " + color );
}
//After the Method, create GETTERS for each variable.
//GETTERS start with "public".
//If a variable was a string, then it would be public String getVariableName(){ return variableName;}
//If a variable was an int, it would be public int getVariableName(){ return variableName;}
public String getModel() {
return model;
}
public String getManufacturer(){
return manufacturer;
}
public int getSize() {
return size;
}
public Resolution getNativeResolution() {
return nativeResolution;
}
}
| 1,949 | 0.686506 | 0.686506 | 56 | 33.80357 | 34.817081 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.678571 | false | false |
13
|
d82fd9dda4bbe973bb7b4824b938398edabbf9a2
| 11,656,541,244,813 |
73c9961b3882ee446ff019839654039b774140b4
|
/Mid-Central USA Programming Contest 2016 - Dry Run 2/H.java
|
3a6100f3ae002db72b67e52526537a6a2ac5c96d
|
[] |
no_license
|
derrowap/ACM-ICPC
|
https://github.com/derrowap/ACM-ICPC
|
192f14db33bfd08a9e183eb3e3f1cd68f85c17c8
|
01aedac2b7bb73294fe23dceb34d95e89cbe4b3a
|
refs/heads/master
| 2021-01-10T22:19:26.729000 | 2016-11-06T21:08:26 | 2016-11-06T21:08:26 | 69,139,989 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;
// https://open.kattis.com/problems/sheldon
public class H {
public static void solve(long d1, long d2) {
int limit = Long.toBinaryString(d2).length();
HashSet<Long> sheldons = new HashSet<>();
// 1^n(0^m 1^n)^k
for (int n = 1; n <= limit; n++) {
for (int m = 0; m <= limit - n; m++) {
for (int k = 0; n + k*(m + n) <= limit; k++) {
StringBuilder instance = new StringBuilder();
instance.append(repeatChar('1', n));
for (int i = 0; i < k; i++) {
instance.append(repeatChar('0', m));
instance.append(repeatChar('1', n));
}
Long num = (long)-1;
try {
num = Long.parseLong(instance.toString(), 2);
} catch(NumberFormatException e) {
// System.out.println("EXCEPTION --> " + instance.toString());
}
if ((num <= d2) && (num >= d1)) {
sheldons.add(num);
}
// 1^n(0^m 1^n)^k 0^m
if (n + (k * (m + n)) + m <= limit) {
instance.append(repeatChar('0', m));
try {
num = Long.parseLong(instance.toString(), 2);
} catch(NumberFormatException e) {
// System.out.println("EXCEPTION --> " + instance.toString());
}
if ((num <= d2) && (num >= d1)) {
sheldons.add(num);
}
}
}
}
}
// for (Long number : sheldons) {
// System.out.println(number + " --> " + Long.toBinaryString(number));
// }
System.out.println(sheldons.size());
}
public static String repeatChar(char c, int n) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < n; i++) {
b.append(c);
}
return b.toString();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] line = sc.nextLine().split("\\s+");
long d1 = Long.parseLong(line[0]);
long d2 = Long.parseLong(line[1]);
sc.close();
solve(d1, d2);
}
}
|
UTF-8
|
Java
| 1,973 |
java
|
H.java
|
Java
|
[] | null |
[] |
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;
// https://open.kattis.com/problems/sheldon
public class H {
public static void solve(long d1, long d2) {
int limit = Long.toBinaryString(d2).length();
HashSet<Long> sheldons = new HashSet<>();
// 1^n(0^m 1^n)^k
for (int n = 1; n <= limit; n++) {
for (int m = 0; m <= limit - n; m++) {
for (int k = 0; n + k*(m + n) <= limit; k++) {
StringBuilder instance = new StringBuilder();
instance.append(repeatChar('1', n));
for (int i = 0; i < k; i++) {
instance.append(repeatChar('0', m));
instance.append(repeatChar('1', n));
}
Long num = (long)-1;
try {
num = Long.parseLong(instance.toString(), 2);
} catch(NumberFormatException e) {
// System.out.println("EXCEPTION --> " + instance.toString());
}
if ((num <= d2) && (num >= d1)) {
sheldons.add(num);
}
// 1^n(0^m 1^n)^k 0^m
if (n + (k * (m + n)) + m <= limit) {
instance.append(repeatChar('0', m));
try {
num = Long.parseLong(instance.toString(), 2);
} catch(NumberFormatException e) {
// System.out.println("EXCEPTION --> " + instance.toString());
}
if ((num <= d2) && (num >= d1)) {
sheldons.add(num);
}
}
}
}
}
// for (Long number : sheldons) {
// System.out.println(number + " --> " + Long.toBinaryString(number));
// }
System.out.println(sheldons.size());
}
public static String repeatChar(char c, int n) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < n; i++) {
b.append(c);
}
return b.toString();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] line = sc.nextLine().split("\\s+");
long d1 = Long.parseLong(line[0]);
long d2 = Long.parseLong(line[1]);
sc.close();
solve(d1, d2);
}
}
| 1,973 | 0.532184 | 0.515966 | 73 | 25.027397 | 19.574217 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.712329 | false | false |
13
|
714c3236a8c51fa3604465455d89728b266f9460
| 19,292,993,102,755 |
6d88aa4ddb31cb77e6dce7c5830c6fa085445303
|
/itheima-git-test01/src/com/itheima/demo/Demo04.java
|
ca5ec7607904a7c6cc3231d0726d1df962be0400
|
[] |
no_license
|
tgl-bug/idea-git-test
|
https://github.com/tgl-bug/idea-git-test
|
575c04b57b769fc70bf2ea1a25df2c6af7589b85
|
b307e64f70801c29c4cb4c64c7fb1daf823bf195
|
refs/heads/master
| 2023-02-17T07:34:00.328000 | 2021-01-19T14:20:36 | 2021-01-19T14:20:36 | 330,877,988 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.itheima.demo;
import java.util.Properties;
public class Demo04 {
public static void main(String[] args) {
Properties properties = new Properties();
properties.put(1,5);
System.out.println(properties);
}
}
|
UTF-8
|
Java
| 251 |
java
|
Demo04.java
|
Java
|
[] | null |
[] |
package com.itheima.demo;
import java.util.Properties;
public class Demo04 {
public static void main(String[] args) {
Properties properties = new Properties();
properties.put(1,5);
System.out.println(properties);
}
}
| 251 | 0.661355 | 0.645418 | 11 | 21.818182 | 17.272249 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.545455 | false | false |
13
|
70dac51984a2f958d9ff2956c9ba2b960056bd8b
| 19,292,993,102,747 |
b7f201b9b63036590bce034ad454cb5a6e8057bf
|
/10 juegos/NuevoBob/src/nuevobob/Actor.java
|
679ea638131beda6174c18aeb155a60e9bc1bf06
|
[] |
no_license
|
luis13711/TutorialJavaEE
|
https://github.com/luis13711/TutorialJavaEE
|
42bba3fc473b07832784cde6b03ee649e70407de
|
ba695479b5113c36b07c45b8d67393e30b9397fe
|
refs/heads/master
| 2018-09-18T07:03:21.346000 | 2018-08-05T21:05:19 | 2018-08-05T21:05:19 | 121,621,253 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package nuevobob;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
public class Actor extends java.awt.Rectangle{
protected String spriteName;
protected Stage stage;
protected SpriteCache spriteCache;
protected boolean markedForRemoval=false;
public Actor(Stage stage) {
this.stage = stage;
spriteCache = stage.getSpriteCache();
}
public void paint(Graphics2D g){
g.drawImage( spriteCache.getSprite(spriteName), x,y, stage );
}
public void setX(int i) { x = i; }
public void setY(int i) { y = i; }
public String getSpriteName() { return spriteName; }
public void setSpriteName(String string) {
spriteName = string;
BufferedImage image = spriteCache.getSprite(spriteName);
height = image.getHeight();
width = image.getWidth();
}
public void setHeight(int i) {height = i; }
public void setWidth(int i) { width = i; }
public void act() { }
public void remove() {
markedForRemoval = true;
}
public boolean isMarkedForRemoval() {
return markedForRemoval;
}
}
|
UTF-8
|
Java
| 1,128 |
java
|
Actor.java
|
Java
|
[] | null |
[] |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package nuevobob;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
public class Actor extends java.awt.Rectangle{
protected String spriteName;
protected Stage stage;
protected SpriteCache spriteCache;
protected boolean markedForRemoval=false;
public Actor(Stage stage) {
this.stage = stage;
spriteCache = stage.getSpriteCache();
}
public void paint(Graphics2D g){
g.drawImage( spriteCache.getSprite(spriteName), x,y, stage );
}
public void setX(int i) { x = i; }
public void setY(int i) { y = i; }
public String getSpriteName() { return spriteName; }
public void setSpriteName(String string) {
spriteName = string;
BufferedImage image = spriteCache.getSprite(spriteName);
height = image.getHeight();
width = image.getWidth();
}
public void setHeight(int i) {height = i; }
public void setWidth(int i) { width = i; }
public void act() { }
public void remove() {
markedForRemoval = true;
}
public boolean isMarkedForRemoval() {
return markedForRemoval;
}
}
| 1,128 | 0.713652 | 0.711879 | 44 | 24.636364 | 18.308084 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.681818 | false | false |
13
|
cb4f6bd07ea87a3ea5546d0089b5aca431a247f3
| 22,943,715,328,272 |
daa052ecb7e40f27ead3140ee593a9dcfc1b243d
|
/src/main/java/sde/application/test/action/RunWebAction.java
|
cf98fa992f2c12dffcd27e45a113ecd49b0ceddd
|
[] |
no_license
|
kilwaz/SDE3
|
https://github.com/kilwaz/SDE3
|
5c3c45a1f47f76297025f80da8decf0bb6d2568d
|
f300cb995f2893fccb43fbbae498b4596e1437a5
|
refs/heads/master
| 2021-04-15T11:17:34.779000 | 2017-07-20T12:10:15 | 2017-07-20T12:10:15 | 24,239,197 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package sde.application.test.action;
import sde.application.gui.Program;
import sde.application.test.TestParameter;
import sde.application.test.action.helpers.LoopedWebElement;
import sde.application.test.action.helpers.Variable;
import sde.application.utils.NodeRunParams;
import org.apache.log4j.Logger;
/**
* This action is used to run another Node, generally a logic node.
* <p>
* You can pass variables into the NodeRunParams object
*/
public class RunWebAction extends WebAction {
private static Logger log = Logger.getLogger(RunWebAction.class);
public RunWebAction() {
}
/**
* Run by {@link WebAction} to handle this action.
*/
public void performAction() {
try {
TestParameter nodeToRun = getTestCommand().getParameterByName("node");
NodeRunParams nodeRunParams = new NodeRunParams();
for (String parameters : getTestCommand().getParameters().keySet()) {
TestParameter testParameter = getTestCommand().getParameters().get(parameters);
if (!"node".equals(parameters)) {
// If a variable is being passed in we handle this here
if (testParameter.getChildParameter() != null && testParameter.getChildParameter().exists() && "var".equals(testParameter.getChildParameter().getParameterName())) {
TestParameter childVariable = testParameter.getChildParameter();
// Converts the variable name into the variable itself
Variable variable = getVariableTracker().getVariable(childVariable.getParameterValue());
if (variable != null) {
nodeRunParams.addVariable(parameters, variable.getVariableValue());
}
} else if ("loop".equals(testParameter.getParameterName())) {
TestParameter loopElement = getParameterByName("loop");
if (loopElement.exists()) {
LoopedWebElement loopedWebElement = (LoopedWebElement) getLoopTracker().getLoop(loopElement.getParameterValue()).getCurrentLoopObject();
if (loopedWebElement != null) {
nodeRunParams.addVariable(parameters, loopedWebElement.getWebElement(getDriver()));
}
}
} else { // Otherwise just do whatever was passed in with names and straight string values
nodeRunParams.addVariable(parameters, testParameter.getParameterValue());
}
}
}
Program.runHelper(nodeToRun.getParameterValue(), getProgram().getFlowController().getReferenceID(), null, true, true, null, nodeRunParams);
} catch (Exception ex) {
log.error(ex);
}
}
}
|
UTF-8
|
Java
| 2,917 |
java
|
RunWebAction.java
|
Java
|
[] | null |
[] |
package sde.application.test.action;
import sde.application.gui.Program;
import sde.application.test.TestParameter;
import sde.application.test.action.helpers.LoopedWebElement;
import sde.application.test.action.helpers.Variable;
import sde.application.utils.NodeRunParams;
import org.apache.log4j.Logger;
/**
* This action is used to run another Node, generally a logic node.
* <p>
* You can pass variables into the NodeRunParams object
*/
public class RunWebAction extends WebAction {
private static Logger log = Logger.getLogger(RunWebAction.class);
public RunWebAction() {
}
/**
* Run by {@link WebAction} to handle this action.
*/
public void performAction() {
try {
TestParameter nodeToRun = getTestCommand().getParameterByName("node");
NodeRunParams nodeRunParams = new NodeRunParams();
for (String parameters : getTestCommand().getParameters().keySet()) {
TestParameter testParameter = getTestCommand().getParameters().get(parameters);
if (!"node".equals(parameters)) {
// If a variable is being passed in we handle this here
if (testParameter.getChildParameter() != null && testParameter.getChildParameter().exists() && "var".equals(testParameter.getChildParameter().getParameterName())) {
TestParameter childVariable = testParameter.getChildParameter();
// Converts the variable name into the variable itself
Variable variable = getVariableTracker().getVariable(childVariable.getParameterValue());
if (variable != null) {
nodeRunParams.addVariable(parameters, variable.getVariableValue());
}
} else if ("loop".equals(testParameter.getParameterName())) {
TestParameter loopElement = getParameterByName("loop");
if (loopElement.exists()) {
LoopedWebElement loopedWebElement = (LoopedWebElement) getLoopTracker().getLoop(loopElement.getParameterValue()).getCurrentLoopObject();
if (loopedWebElement != null) {
nodeRunParams.addVariable(parameters, loopedWebElement.getWebElement(getDriver()));
}
}
} else { // Otherwise just do whatever was passed in with names and straight string values
nodeRunParams.addVariable(parameters, testParameter.getParameterValue());
}
}
}
Program.runHelper(nodeToRun.getParameterValue(), getProgram().getFlowController().getReferenceID(), null, true, true, null, nodeRunParams);
} catch (Exception ex) {
log.error(ex);
}
}
}
| 2,917 | 0.609873 | 0.60953 | 61 | 46.737705 | 43.094215 | 184 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.491803 | false | false |
13
|
9c385f7f7a0bddced8ebd72609645aab213d89fb
| 14,396,730,378,178 |
6baf1fe00541560788e78de5244ae17a7a2b375a
|
/hollywood/com.oculus.linefrequencyservice-LineFrequencyService/sources/oculus/internal/ThermalPowerLevelStatusInterface.java
|
248190cc3aa526957a1a0d8c0ab4f6b5d6b5922c
|
[] |
no_license
|
phwd/quest-tracker
|
https://github.com/phwd/quest-tracker
|
286e605644fc05f00f4904e51f73d77444a78003
|
3d46fbb467ba11bee5827f7cae7dfeabeb1fd2ba
|
refs/heads/main
| 2023-03-29T20:33:10.959000 | 2021-04-10T22:14:11 | 2021-04-10T22:14:11 | 357,185,040 | 4 | 2 | null | true | 2021-04-12T12:28:09 | 2021-04-12T12:28:08 | 2021-04-10T22:15:44 | 2021-04-10T22:15:39 | 116,441 | 0 | 0 | 0 | null | false | false |
package oculus.internal;
public interface ThermalPowerLevelStatusInterface {
public interface ThermalPowerLevelStatusUpdateCallback {
void powerLevelStatusUpdate(int i);
}
boolean isSupported();
void onDestroy();
void registerCallback(ThermalPowerLevelStatusUpdateCallback thermalPowerLevelStatusUpdateCallback);
}
|
UTF-8
|
Java
| 348 |
java
|
ThermalPowerLevelStatusInterface.java
|
Java
|
[] | null |
[] |
package oculus.internal;
public interface ThermalPowerLevelStatusInterface {
public interface ThermalPowerLevelStatusUpdateCallback {
void powerLevelStatusUpdate(int i);
}
boolean isSupported();
void onDestroy();
void registerCallback(ThermalPowerLevelStatusUpdateCallback thermalPowerLevelStatusUpdateCallback);
}
| 348 | 0.79023 | 0.79023 | 14 | 23.857143 | 29.772608 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.357143 | false | false |
13
|
32954eee6f9b78e8d071968a8c3cb0edd41ef5c7
| 6,554,120,157,507 |
488c74bf97574547d01ce6c330f51bc8f78352d3
|
/src/java_study_0130/OldSystem.java
|
41dec6bb791a2d437d52c50c56452765fa54fbf8
|
[] |
no_license
|
hiwony7933/JavaApp
|
https://github.com/hiwony7933/JavaApp
|
365b8a74354f658504d89233e05a04a51272e564
|
36b6ca58be0308f9378621184dc7dc88e4e2c0ae
|
refs/heads/master
| 2021-03-30T01:28:52.387000 | 2020-03-18T07:37:33 | 2020-03-18T07:37:33 | 248,001,856 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package java_study_0130;
public class OldSystem {
public void process() {
System.out.println("Old System");
}
}
|
UTF-8
|
Java
| 117 |
java
|
OldSystem.java
|
Java
|
[] | null |
[] |
package java_study_0130;
public class OldSystem {
public void process() {
System.out.println("Old System");
}
}
| 117 | 0.700855 | 0.666667 | 7 | 15.714286 | 13.252647 | 35 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.857143 | false | false |
13
|
5dcb9100020967f7f58c7fa75c4b9ff32a992eb7
| 11,175,504,908,127 |
95d20c83d8aff34e314c56a3ecb2b87c9fa9fc86
|
/Ghidra/Framework/Docking/src/main/java/docking/widgets/table/constraint/ColumnData.java
|
374a67e005402def9be84e54ed77410d79067ea6
|
[
"GPL-1.0-or-later",
"GPL-3.0-only",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"LGPL-2.1-only",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
NationalSecurityAgency/ghidra
|
https://github.com/NationalSecurityAgency/ghidra
|
969fe0d2ca25cb8ac72f66f0f90fc7fb2dbfa68d
|
7cc135eb6bfabd166cbc23f7951dae09a7e03c39
|
refs/heads/master
| 2023-08-31T21:20:23.376000 | 2023-08-29T23:08:54 | 2023-08-29T23:08:54 | 173,228,436 | 45,212 | 6,204 |
Apache-2.0
| false | 2023-09-14T18:00:39 | 2019-03-01T03:27:48 | 2023-09-14T16:08:34 | 2023-09-14T18:00:38 | 315,176 | 42,614 | 5,179 | 1,427 |
Java
| false | false |
/* ###
* IP: GHIDRA
*
* 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 docking.widgets.table.constraint;
/**
* Interface for providing column data and a table's DataSource to a constraint editor. Some editors
* require access to the table column data. One example is a String "Starts With" column might
* pre-process the data to provide an autocompletion feature in the editor.
*
* @param <T> the column data type.
*/
public interface ColumnData<T> {
/**
* Returns the name of the column being filtered.
*
* @return the name of the column being filtered.
*/
public String getColumnName();
/**
* Returns the number of column values (unfiltered table row count)
*
* @return the number of column values (unfiltered table row count)
*/
public int getCount();
/**
* Returns the column value for the given row.
* @param row the row for which to get the column value.
* @return the column value for the given row.
*/
public T getColumnValue(int row);
/**
* Returns the table's DataSource.
* @return the table's DataSource.
*/
public Object getTableDataSource();
}
|
UTF-8
|
Java
| 1,634 |
java
|
ColumnData.java
|
Java
|
[
{
"context": "/* ###\n * IP: GHIDRA\n *\n * Licensed under the Apache License, Ver",
"end": 15,
"score": 0.5747861266136169,
"start": 14,
"tag": "NAME",
"value": "G"
}
] | null |
[] |
/* ###
* IP: GHIDRA
*
* 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 docking.widgets.table.constraint;
/**
* Interface for providing column data and a table's DataSource to a constraint editor. Some editors
* require access to the table column data. One example is a String "Starts With" column might
* pre-process the data to provide an autocompletion feature in the editor.
*
* @param <T> the column data type.
*/
public interface ColumnData<T> {
/**
* Returns the name of the column being filtered.
*
* @return the name of the column being filtered.
*/
public String getColumnName();
/**
* Returns the number of column values (unfiltered table row count)
*
* @return the number of column values (unfiltered table row count)
*/
public int getCount();
/**
* Returns the column value for the given row.
* @param row the row for which to get the column value.
* @return the column value for the given row.
*/
public T getColumnValue(int row);
/**
* Returns the table's DataSource.
* @return the table's DataSource.
*/
public Object getTableDataSource();
}
| 1,634 | 0.71175 | 0.709302 | 54 | 29.25926 | 29.08556 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.611111 | false | false |
13
|
614c495e566920585165992cf9d1925aac416fed
| 11,622,181,504,421 |
66a1e0aeafe2fc745a86ad84233b2e4682c75e96
|
/build-area/src/org/kepler/build/Tag.java
|
341c00dd542b8d68b063733e79a362d7a656896c
|
[] |
no_license
|
Elblonko/kepler
|
https://github.com/Elblonko/kepler
|
1b1e13d1c5dfda0b7196c5c44f3aeca0ba07e688
|
48618dc2233781656e63c40f1f2b99123b8bd396
|
refs/heads/master
| 2021-01-10T18:25:40.356000 | 2014-08-19T03:17:59 | 2014-08-19T03:17:59 | 23,061,792 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* Copyright (c) 2009 The Regents of the University of California.
* All rights reserved.
*
* Permission is hereby granted, without written agreement and without
* license or royalty fees, to use, copy, modify, and distribute this
* software and its documentation for any purpose, provided that the above
* copyright notice and the following two paragraphs appear in all copies
* of this software.
*
* IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
* FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
* THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
* PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
* CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
* ENHANCEMENTS, OR MODIFICATIONS.
*
*/
package org.kepler.build;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.kepler.build.modules.ModulesTask;
import org.kepler.build.project.PrintError;
import org.kepler.build.project.RepositoryLocations;
import org.kepler.build.util.CommandLine;
/**
* class to tag a module
*
* @author berkley
*/
public class Tag extends ModulesTask
{
protected String module;
protected String name;
/**
* set the module to tag
*
* @param module
*/
public void setModule(String module)
{
this.module = module;
}
/**
* set the tag name
*
* @param name
*/
public void setName(String name)
{
this.name = name;
}
/**
* run the task
*/
@Override
public void run() throws Exception
{
if (module.equals("undefined"))
{
PrintError.moduleNotDefined();
return;
}
String[] infoCommand = {"svn", "info", RepositoryLocations.MODULES};
Process p = Runtime.getRuntime().exec(infoCommand);
BufferedReader br = new BufferedReader(new InputStreamReader(p
.getInputStream()));
String line = null;
int revision = 0;
while ((line = br.readLine()) != null)
{
if (line.startsWith("Revision:"))
{
revision = Integer.parseInt((line.split("\\s+")[1])) + 1;
break;
}
}
String tagName = !name.equals("undefined") ? module + "-" + name + "-"
+ revision + "-tag" : module + "-" + revision + "-tag";
String[] tagCommand = {"svn", "copy",
RepositoryLocations.MODULES + "/" + module,
RepositoryLocations.REPO + "/tags/" + tagName, "-m",
"\"Tagging " + module + " as " + tagName + "\""};
CommandLine.exec(tagCommand);
}
}
|
UTF-8
|
Java
| 3,031 |
java
|
Tag.java
|
Java
|
[
{
"context": "dLine;\n\n/**\n * class to tag a module\n *\n * @author berkley\n */\npublic class Tag extends ModulesTask\n{\n pr",
"end": 1432,
"score": 0.9993969798088074,
"start": 1425,
"tag": "USERNAME",
"value": "berkley"
}
] | null |
[] |
/*
* Copyright (c) 2009 The Regents of the University of California.
* All rights reserved.
*
* Permission is hereby granted, without written agreement and without
* license or royalty fees, to use, copy, modify, and distribute this
* software and its documentation for any purpose, provided that the above
* copyright notice and the following two paragraphs appear in all copies
* of this software.
*
* IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
* FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
* THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
* PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
* CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
* ENHANCEMENTS, OR MODIFICATIONS.
*
*/
package org.kepler.build;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.kepler.build.modules.ModulesTask;
import org.kepler.build.project.PrintError;
import org.kepler.build.project.RepositoryLocations;
import org.kepler.build.util.CommandLine;
/**
* class to tag a module
*
* @author berkley
*/
public class Tag extends ModulesTask
{
protected String module;
protected String name;
/**
* set the module to tag
*
* @param module
*/
public void setModule(String module)
{
this.module = module;
}
/**
* set the tag name
*
* @param name
*/
public void setName(String name)
{
this.name = name;
}
/**
* run the task
*/
@Override
public void run() throws Exception
{
if (module.equals("undefined"))
{
PrintError.moduleNotDefined();
return;
}
String[] infoCommand = {"svn", "info", RepositoryLocations.MODULES};
Process p = Runtime.getRuntime().exec(infoCommand);
BufferedReader br = new BufferedReader(new InputStreamReader(p
.getInputStream()));
String line = null;
int revision = 0;
while ((line = br.readLine()) != null)
{
if (line.startsWith("Revision:"))
{
revision = Integer.parseInt((line.split("\\s+")[1])) + 1;
break;
}
}
String tagName = !name.equals("undefined") ? module + "-" + name + "-"
+ revision + "-tag" : module + "-" + revision + "-tag";
String[] tagCommand = {"svn", "copy",
RepositoryLocations.MODULES + "/" + module,
RepositoryLocations.REPO + "/tags/" + tagName, "-m",
"\"Tagging " + module + " as " + tagName + "\""};
CommandLine.exec(tagCommand);
}
}
| 3,031 | 0.625536 | 0.623227 | 104 | 28.14423 | 25.81868 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.471154 | false | false |
13
|
6559b995541608ea342c2717c2a1f568436c45ae
| 32,323,923,880,977 |
8a1cb61dd1201a444b2f6a1fe5e8a027634836a9
|
/dojosandninjas/src/main/java/com/project/dojosandninjas/controllers/DojosNinjasController.java
|
ca0db9228d65d8e53bd38e12645ce47a96b27b53
|
[] |
no_license
|
DestaWork21/Java
|
https://github.com/DestaWork21/Java
|
d48360c2a1a14afd9c5b9be2168fa15b127949c4
|
d4ca4ad6db3bd258512ad4d48fc139076e2ffc65
|
refs/heads/master
| 2021-09-06T05:17:46.933000 | 2018-02-02T17:46:07 | 2018-02-02T17:46:07 | 117,911,583 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.project.dojosandninjas.controllers;
import com.project.dojosandninjas.services.DojoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/")
public class DojosNinjasController{
@Autowired
private DojoService dojoService;
@RequestMapping("")
public String index(Model model){
model.addAttribute("dojos",dojoService.all());
return "index";
}
}
|
UTF-8
|
Java
| 566 |
java
|
DojosNinjasController.java
|
Java
|
[] | null |
[] |
package com.project.dojosandninjas.controllers;
import com.project.dojosandninjas.services.DojoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/")
public class DojosNinjasController{
@Autowired
private DojoService dojoService;
@RequestMapping("")
public String index(Model model){
model.addAttribute("dojos",dojoService.all());
return "index";
}
}
| 566 | 0.809187 | 0.809187 | 23 | 23.608696 | 21.779007 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.826087 | false | false |
13
|
0ea99b8d062fb2d4b42f958315adbcec11cfaa1d
| 29,781,303,244,899 |
6b059494db2108476febe27815159c634fe19091
|
/src/test/java/com/jeya/testng/spring/SpringTestNGDependencyInjectionExample.java
|
fb4f1287310bfea9a635335a37cb7fac21013082
|
[] |
no_license
|
Jeyatharsini24/TestNGSpringExample
|
https://github.com/Jeyatharsini24/TestNGSpringExample
|
31382d971577500834f730a135def5b01cbd64ca
|
8f91b0adb7cc820a10cb95fb74d31d829d196129
|
refs/heads/master
| 2020-03-30T01:18:51.580000 | 2018-10-01T14:20:32 | 2018-10-01T14:20:32 | 150,569,924 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.jeya.testng.spring;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* Context file is provided using the type annotation @ContextConfiguration wuth file name context.xml as the value.
* Context is loaded by this and then set to the protected member application context.
* @author JJeyatharsini
*/
@ContextConfiguration("context.xml")
public class SpringTestNGDependencyInjectionExample extends AbstractTestNGSpringContextTests
/**
* Through the extends AbstractTestNGSpringContextTests, dependencies are injected into our test instance.
*/
{
/**
* Spring automatically injects BeanFactory bean into it.
*/
@Autowired
private BeanFactory beanFactory;
/**
* Bean foo is injected
*/
@Autowired
private Foo foo;
/**
* verifies that the foo bean is injected and its name is same as the one set in the context file
*/
@Test
public void verifyFooName() {
System.out.println("verifyFooName: Is foo not null? " + (foo != null));
Assert.assertNotNull(foo);
System.out.println("verifyFooName: Foo name is '" + foo.getName() + "'");
Assert.assertEquals(foo.getName(), "TestNG Spring");
}
/**
* verifies that the bean factory is injected
*/
@Test
public void verifyBeanFactory()
{
System.out.println("verifyBeanFactory: Is bean factory not null? " + (beanFactory != null));
Assert.assertNotNull(beanFactory);
}
}
|
UTF-8
|
Java
| 1,659 |
java
|
SpringTestNGDependencyInjectionExample.java
|
Java
|
[
{
"context": "e protected member application context.\n * @author JJeyatharsini\n */\n@ContextConfiguration(\"context.xml\")\npublic c",
"end": 588,
"score": 0.928856372833252,
"start": 575,
"tag": "NAME",
"value": "JJeyatharsini"
}
] | null |
[] |
package com.jeya.testng.spring;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* Context file is provided using the type annotation @ContextConfiguration wuth file name context.xml as the value.
* Context is loaded by this and then set to the protected member application context.
* @author JJeyatharsini
*/
@ContextConfiguration("context.xml")
public class SpringTestNGDependencyInjectionExample extends AbstractTestNGSpringContextTests
/**
* Through the extends AbstractTestNGSpringContextTests, dependencies are injected into our test instance.
*/
{
/**
* Spring automatically injects BeanFactory bean into it.
*/
@Autowired
private BeanFactory beanFactory;
/**
* Bean foo is injected
*/
@Autowired
private Foo foo;
/**
* verifies that the foo bean is injected and its name is same as the one set in the context file
*/
@Test
public void verifyFooName() {
System.out.println("verifyFooName: Is foo not null? " + (foo != null));
Assert.assertNotNull(foo);
System.out.println("verifyFooName: Foo name is '" + foo.getName() + "'");
Assert.assertEquals(foo.getName(), "TestNG Spring");
}
/**
* verifies that the bean factory is injected
*/
@Test
public void verifyBeanFactory()
{
System.out.println("verifyBeanFactory: Is bean factory not null? " + (beanFactory != null));
Assert.assertNotNull(beanFactory);
}
}
| 1,659 | 0.75226 | 0.75226 | 53 | 30.301888 | 33.42329 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.962264 | false | false |
13
|
ca7f41e7010a8726a2291ed0ecc77d429f3b7968
| 21,096,879,376,128 |
2a84b73dd3c6f70f72c5019efdabb229374a3c99
|
/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/jmx/EndpointMBeanExporterTests.java
|
b0b041113cff569ba1904b32a144072d81032b0f
|
[] |
no_license
|
rohitdhingra/spring-boot
|
https://github.com/rohitdhingra/spring-boot
|
35daad60d873127409b208c18d03890e4b51b745
|
75af18df7d466d19674465f95e0a2dd914905b1d
|
refs/heads/master
| 2018-02-06T19:45:02.273000 | 2013-12-18T22:22:18 | 2013-12-19T17:11:01 | 15,318,146 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.actuate.endpoint.jmx;
import java.util.Collections;
import javax.management.MBeanInfo;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import org.junit.After;
import org.junit.Test;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.boot.actuate.endpoint.AbstractEndpoint;
import org.springframework.boot.actuate.endpoint.Endpoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.jmx.export.MBeanExporter;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* Tests for {@link EndpointMBeanExporter}
*
* @author Christian Dupuis
*/
public class EndpointMBeanExporterTests {
GenericApplicationContext context = null;
@After
public void close() {
if (this.context != null) {
this.context.close();
}
}
@Test
public void testRegistrationOfOneEndpoint() throws Exception {
this.context = new GenericApplicationContext();
this.context.registerBeanDefinition("endpointMbeanExporter",
new RootBeanDefinition(EndpointMBeanExporter.class));
this.context.registerBeanDefinition("endpoint1", new RootBeanDefinition(
TestEndpoint.class));
this.context.registerBeanDefinition(
"mbeanExporter",
new RootBeanDefinition(MBeanExporter.class, null,
new MutablePropertyValues(Collections.singletonMap(
"ensureUniqueRuntimeObjectNames", "false"))));
this.context.refresh();
MBeanExporter mbeanExporter = this.context.getBean(MBeanExporter.class);
MBeanInfo mbeanInfo = mbeanExporter.getServer().getMBeanInfo(
getObjectName("endpoint1", this.context));
assertNotNull(mbeanInfo);
assertEquals(5, mbeanInfo.getOperations().length);
assertEquals(5, mbeanInfo.getAttributes().length);
}
@Test
public void testRegistrationTwoEndpoints() throws Exception {
this.context = new GenericApplicationContext();
this.context.registerBeanDefinition("endpointMbeanExporter",
new RootBeanDefinition(EndpointMBeanExporter.class));
this.context.registerBeanDefinition("endpoint1", new RootBeanDefinition(
TestEndpoint.class));
this.context.registerBeanDefinition("endpoint2", new RootBeanDefinition(
TestEndpoint.class));
this.context.registerBeanDefinition(
"mbeanExporter",
new RootBeanDefinition(MBeanExporter.class, null,
new MutablePropertyValues(Collections.singletonMap(
"ensureUniqueRuntimeObjectNames", "false"))));
this.context.refresh();
MBeanExporter mbeanExporter = this.context.getBean(MBeanExporter.class);
assertNotNull(mbeanExporter.getServer().getMBeanInfo(
getObjectName("endpoint1", this.context)));
assertNotNull(mbeanExporter.getServer().getMBeanInfo(
getObjectName("endpoint2", this.context)));
}
@Test
public void testRegistrationWithParentContext() throws Exception {
this.context = new GenericApplicationContext();
this.context.registerBeanDefinition("endpointMbeanExporter",
new RootBeanDefinition(EndpointMBeanExporter.class));
this.context.registerBeanDefinition("endpoint1", new RootBeanDefinition(
TestEndpoint.class));
this.context.registerBeanDefinition(
"mbeanExporter",
new RootBeanDefinition(MBeanExporter.class, null,
new MutablePropertyValues(Collections.singletonMap(
"ensureUniqueRuntimeObjectNames", "false"))));
GenericApplicationContext parent = new GenericApplicationContext();
this.context.setParent(parent);
parent.refresh();
this.context.refresh();
MBeanExporter mbeanExporter = this.context.getBean(MBeanExporter.class);
assertNotNull(mbeanExporter.getServer().getMBeanInfo(
getObjectName("endpoint1", this.context)));
parent.close();
}
private ObjectName getObjectName(String beanKey, ApplicationContext applicationContext)
throws MalformedObjectNameException {
return new DataEndpointMBean(beanKey,
(Endpoint<?>) applicationContext.getBean(beanKey)).getObjectName();
}
public static class TestEndpoint extends AbstractEndpoint<String> {
public TestEndpoint() {
super("test");
}
@Override
public String invoke() {
return "hello world";
}
}
}
|
UTF-8
|
Java
| 4,939 |
java
|
EndpointMBeanExporterTests.java
|
Java
|
[
{
"context": "s for {@link EndpointMBeanExporter}\n * \n * @author Christian Dupuis\n */\npublic class EndpointMBeanExporterTests {\n\n\tG",
"end": 1477,
"score": 0.9998459219932556,
"start": 1461,
"tag": "NAME",
"value": "Christian Dupuis"
}
] | null |
[] |
/*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.actuate.endpoint.jmx;
import java.util.Collections;
import javax.management.MBeanInfo;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import org.junit.After;
import org.junit.Test;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.boot.actuate.endpoint.AbstractEndpoint;
import org.springframework.boot.actuate.endpoint.Endpoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.jmx.export.MBeanExporter;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* Tests for {@link EndpointMBeanExporter}
*
* @author <NAME>
*/
public class EndpointMBeanExporterTests {
GenericApplicationContext context = null;
@After
public void close() {
if (this.context != null) {
this.context.close();
}
}
@Test
public void testRegistrationOfOneEndpoint() throws Exception {
this.context = new GenericApplicationContext();
this.context.registerBeanDefinition("endpointMbeanExporter",
new RootBeanDefinition(EndpointMBeanExporter.class));
this.context.registerBeanDefinition("endpoint1", new RootBeanDefinition(
TestEndpoint.class));
this.context.registerBeanDefinition(
"mbeanExporter",
new RootBeanDefinition(MBeanExporter.class, null,
new MutablePropertyValues(Collections.singletonMap(
"ensureUniqueRuntimeObjectNames", "false"))));
this.context.refresh();
MBeanExporter mbeanExporter = this.context.getBean(MBeanExporter.class);
MBeanInfo mbeanInfo = mbeanExporter.getServer().getMBeanInfo(
getObjectName("endpoint1", this.context));
assertNotNull(mbeanInfo);
assertEquals(5, mbeanInfo.getOperations().length);
assertEquals(5, mbeanInfo.getAttributes().length);
}
@Test
public void testRegistrationTwoEndpoints() throws Exception {
this.context = new GenericApplicationContext();
this.context.registerBeanDefinition("endpointMbeanExporter",
new RootBeanDefinition(EndpointMBeanExporter.class));
this.context.registerBeanDefinition("endpoint1", new RootBeanDefinition(
TestEndpoint.class));
this.context.registerBeanDefinition("endpoint2", new RootBeanDefinition(
TestEndpoint.class));
this.context.registerBeanDefinition(
"mbeanExporter",
new RootBeanDefinition(MBeanExporter.class, null,
new MutablePropertyValues(Collections.singletonMap(
"ensureUniqueRuntimeObjectNames", "false"))));
this.context.refresh();
MBeanExporter mbeanExporter = this.context.getBean(MBeanExporter.class);
assertNotNull(mbeanExporter.getServer().getMBeanInfo(
getObjectName("endpoint1", this.context)));
assertNotNull(mbeanExporter.getServer().getMBeanInfo(
getObjectName("endpoint2", this.context)));
}
@Test
public void testRegistrationWithParentContext() throws Exception {
this.context = new GenericApplicationContext();
this.context.registerBeanDefinition("endpointMbeanExporter",
new RootBeanDefinition(EndpointMBeanExporter.class));
this.context.registerBeanDefinition("endpoint1", new RootBeanDefinition(
TestEndpoint.class));
this.context.registerBeanDefinition(
"mbeanExporter",
new RootBeanDefinition(MBeanExporter.class, null,
new MutablePropertyValues(Collections.singletonMap(
"ensureUniqueRuntimeObjectNames", "false"))));
GenericApplicationContext parent = new GenericApplicationContext();
this.context.setParent(parent);
parent.refresh();
this.context.refresh();
MBeanExporter mbeanExporter = this.context.getBean(MBeanExporter.class);
assertNotNull(mbeanExporter.getServer().getMBeanInfo(
getObjectName("endpoint1", this.context)));
parent.close();
}
private ObjectName getObjectName(String beanKey, ApplicationContext applicationContext)
throws MalformedObjectNameException {
return new DataEndpointMBean(beanKey,
(Endpoint<?>) applicationContext.getBean(beanKey)).getObjectName();
}
public static class TestEndpoint extends AbstractEndpoint<String> {
public TestEndpoint() {
super("test");
}
@Override
public String invoke() {
return "hello world";
}
}
}
| 4,929 | 0.778295 | 0.774651 | 146 | 32.828766 | 26.204767 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.068493 | false | false |
13
|
41c9bb49818b92cb985c4711f618859b5f83331b
| 32,323,923,884,962 |
de19bbc56e412a896e0cbe757e1be2737131a00d
|
/app/src/main/java/com/stream/wangxiang/adapter/SubscribeCategoryAdapter.java
|
85df41ac16da6430a0ebb0683138721af96aa7dd
|
[
"Apache-2.0"
] |
permissive
|
zhangchuanchuan/Wanxiang
|
https://github.com/zhangchuanchuan/Wanxiang
|
00092f28404524973fda46896411b6eef5a0086a
|
9530b8a059c70cc363ef8e27544d431f12af34fa
|
refs/heads/master
| 2016-09-14T19:27:00.632000 | 2016-05-05T06:03:03 | 2016-05-05T06:03:03 | 56,388,395 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.stream.wangxiang.adapter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.stream.wangxiang.utils.AppUtils;
import com.stream.wangxiang.vo.CategoryVo;
import com.stream.wanxiang.R;
import java.util.List;
/**
*
* Created by 张川川 on 2016/5/1.
*/
public class SubscribeCategoryAdapter extends RecyclerView.Adapter<SubscribeCategoryAdapter.CategoryItemViewHolder> {
private List<CategoryVo> mCateList ;
private ClickCategoryListener mListener;
public SubscribeCategoryAdapter(List<CategoryVo> cateList, ClickCategoryListener listener){
mCateList = cateList;
mListener = listener;
}
@Override
public CategoryItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new CategoryItemViewHolder(LayoutInflater.from(AppUtils.context).inflate(R.layout.item_subscribe_category, parent, false));
}
@Override
public void onBindViewHolder(final CategoryItemViewHolder holder, int position) {
CategoryVo cateVo = mCateList.get(position);
holder.textView.setText(cateVo.getTname());
if(cateVo.isSelected()){
// 设置背景颜色
holder.textView.setTextColor(AppUtils.getColor(R.color.text_brick_red_color));
holder.view.setVisibility(View.VISIBLE);
}else{
holder.textView.setTextColor(AppUtils.getColor(R.color.gray));
holder.view.setVisibility(View.GONE);
}
holder.textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mListener.clickThis(holder.getAdapterPosition());
notifyDataSetChanged();
}
});
}
@Override
public int getItemCount() {
return mCateList.size();
}
class CategoryItemViewHolder extends RecyclerView.ViewHolder{
private TextView textView;
private View view;
public CategoryItemViewHolder(View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.category_item);
view = itemView.findViewById(R.id.base_line);
}
}
public interface ClickCategoryListener{
void clickThis(int position);
}
}
|
UTF-8
|
Java
| 2,409 |
java
|
SubscribeCategoryAdapter.java
|
Java
|
[
{
"context": ".R;\n\nimport java.util.List;\n\n/**\n *\n * Created by 张川川 on 2016/5/1.\n */\npublic class SubscribeCategoryAd",
"end": 378,
"score": 0.9997536540031433,
"start": 375,
"tag": "NAME",
"value": "张川川"
}
] | null |
[] |
package com.stream.wangxiang.adapter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.stream.wangxiang.utils.AppUtils;
import com.stream.wangxiang.vo.CategoryVo;
import com.stream.wanxiang.R;
import java.util.List;
/**
*
* Created by 张川川 on 2016/5/1.
*/
public class SubscribeCategoryAdapter extends RecyclerView.Adapter<SubscribeCategoryAdapter.CategoryItemViewHolder> {
private List<CategoryVo> mCateList ;
private ClickCategoryListener mListener;
public SubscribeCategoryAdapter(List<CategoryVo> cateList, ClickCategoryListener listener){
mCateList = cateList;
mListener = listener;
}
@Override
public CategoryItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new CategoryItemViewHolder(LayoutInflater.from(AppUtils.context).inflate(R.layout.item_subscribe_category, parent, false));
}
@Override
public void onBindViewHolder(final CategoryItemViewHolder holder, int position) {
CategoryVo cateVo = mCateList.get(position);
holder.textView.setText(cateVo.getTname());
if(cateVo.isSelected()){
// 设置背景颜色
holder.textView.setTextColor(AppUtils.getColor(R.color.text_brick_red_color));
holder.view.setVisibility(View.VISIBLE);
}else{
holder.textView.setTextColor(AppUtils.getColor(R.color.gray));
holder.view.setVisibility(View.GONE);
}
holder.textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mListener.clickThis(holder.getAdapterPosition());
notifyDataSetChanged();
}
});
}
@Override
public int getItemCount() {
return mCateList.size();
}
class CategoryItemViewHolder extends RecyclerView.ViewHolder{
private TextView textView;
private View view;
public CategoryItemViewHolder(View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.category_item);
view = itemView.findViewById(R.id.base_line);
}
}
public interface ClickCategoryListener{
void clickThis(int position);
}
}
| 2,409 | 0.684651 | 0.681723 | 83 | 27.807228 | 29.884298 | 138 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.433735 | false | false |
13
|
b969f9cf2e6cf6ababb451990a7b09ed76244842
| 15,393,162,811,311 |
d5d121fcdeb98439fa48c8cf07bd7199d5de1914
|
/OOPM exp 4.java
|
4369380fc2db632d50afa199f77e080251d5c4b6
|
[] |
no_license
|
RushikeshRizviClg/JavaProgram
|
https://github.com/RushikeshRizviClg/JavaProgram
|
8c9fc2fa0a1d03ef8ae7d5f7a0040d106513c285
|
c55efbc1d9488d16e06b9de52fe7295e5390703c
|
refs/heads/main
| 2023-07-04T06:26:03.844000 | 2021-08-11T10:14:42 | 2021-08-11T10:14:42 | 394,945,692 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
EXPERIMENT NO.04
Aim: Write a Program to Perform Matrix Addition.
import java.util.*;
class Matrixadd
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int a[][]=new int[3][3];
int b[][]=new int[3][3];
int c[][]=new int[3][3];
int i,j;
System.out.println("Enter matrix A");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
a[i][j]=sc.nextInt();
}
}
System.out.println("Matrix A is");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
System.out.print(a[i][j]+"\t");
}
System.out.println();
}
System.out.println("Enter matrix B");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
b[i][j]=sc.nextInt();
}
}
System.out.println("Matrix B is");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
System.out.print(b[i][j]+"\t");
}
System.out.println();
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
System.out.println("Sum of matrix is");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
System.out.print(c[i][j]+"\t");
}
System.out.println();
}
}
}
|
ISO-8859-1
|
Java
| 1,012 |
java
|
OOPM exp 4.java
|
Java
|
[] | null |
[] |
EXPERIMENT NO.04
Aim: Write a Program to Perform Matrix Addition.
import java.util.*;
class Matrixadd
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int a[][]=new int[3][3];
int b[][]=new int[3][3];
int c[][]=new int[3][3];
int i,j;
System.out.println("Enter matrix A");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
a[i][j]=sc.nextInt();
}
}
System.out.println("Matrix A is");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
System.out.print(a[i][j]+"\t");
}
System.out.println();
}
System.out.println("Enter matrix B");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
b[i][j]=sc.nextInt();
}
}
System.out.println("Matrix B is");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
System.out.print(b[i][j]+"\t");
}
System.out.println();
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
System.out.println("Sum of matrix is");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
System.out.print(c[i][j]+"\t");
}
System.out.println();
}
}
}
| 1,012 | 0.539604 | 0.507921 | 66 | 13.30303 | 13.06623 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.681818 | false | false |
13
|
417bacaa28da739685e0b3905142c673d12f732b
| 1,606,317,793,307 |
56667ac2a899655c15184a7853e34ea1c353120f
|
/src/good/panda/SignUp.java
|
1a73f12fddb1cf7e74bc31ee9914d4392f9e118b
|
[] |
no_license
|
fahimrayhan/Good-Panda
|
https://github.com/fahimrayhan/Good-Panda
|
25dda022d225580b28c2c15227229869ab37e7a5
|
15d06f594a2ccb472e858cc3b3047cea821916a4
|
refs/heads/master
| 2022-12-16T14:37:02.291000 | 2020-10-04T06:25:38 | 2020-10-04T06:25:38 | 300,947,619 | 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 good.panda;
import java.awt.HeadlessException;
import javax.swing.JOptionPane;
/**
*
* @author fahim
*/
public class SignUp extends javax.swing.JFrame {
/**
* Creates new form SignUp
*/
//Ending OF File Operations
public SignUp() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jPanel7 = new javax.swing.JPanel();
icon = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jLabel4 = new javax.swing.JLabel();
Field1 = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
Field2 = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
Field3 = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
Field4 = new javax.swing.JTextField();
SignUp = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel3.setText(" ©2050 | All Rights Reserved By Alien Corp.");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel3)
.addContainerGap(354, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(15, 15, 15)
.addComponent(jLabel3)
.addContainerGap(15, Short.MAX_VALUE))
);
jPanel7.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
icon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/icon2.jpg"))); // NOI18N
jLabel1.setFont(new java.awt.Font("Tekton Pro Ext", 1, 36)); // NOI18N
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("GOOD PANDA");
jLabel2.setFont(new java.awt.Font("Tekton Pro", 1, 18)); // NOI18N
jLabel2.setText("Eat Healthy, Stay Safe");
javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
jPanel7.setLayout(jPanel7Layout);
jPanel7Layout.setHorizontalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addGap(32, 32, 32)
.addComponent(icon)
.addGap(152, 152, 152)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(jLabel2)
.addComponent(jLabel1))
.addContainerGap(41, Short.MAX_VALUE))
);
jPanel7Layout.setVerticalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addContainerGap()
.addComponent(icon))
.addGroup(jPanel7Layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jLabel4.setText("Enter Your Name:");
jLabel5.setText("Enter Email Address:");
jLabel6.setText("Enter Password");
Field3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Field3ActionPerformed(evt);
}
});
jLabel7.setText("Re-enter Password");
Field4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Field4ActionPerformed(evt);
}
});
SignUp.setText("Sign Up");
SignUp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SignUpActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(41, 41, 41)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel7)
.addComponent(Field4, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6)
.addComponent(Field3, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5)
.addComponent(Field2, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4)
.addComponent(Field1, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(112, 112, 112)
.addComponent(SignUp, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(44, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(47, 47, 47)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Field1, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Field2, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Field3, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Field4, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(SignUp, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(72, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(161, 161, 161)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void SignUpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SignUpActionPerformed
try{
if(evt.getSource()==SignUp){
Users us = new Users();
us.createFolder();
us.readFile();
us.countLines();
String name = Field1.getText();
String email = Field2.getText();
String pass;
if((Field3.getText()).equals(Field4.getText())){
pass = Field3.getText();
us.addData(name, pass, email);
JOptionPane.showMessageDialog(null, "Successfully Registerd");
}
else{
JOptionPane.showMessageDialog(null,"Password Not Matched");
}
}
}
catch(HeadlessException e){
}
}//GEN-LAST:event_SignUpActionPerformed
private void Field3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Field3ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_Field3ActionPerformed
private void Field4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Field4ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_Field4ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(SignUp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SignUp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SignUp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SignUp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new SignUp().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField Field1;
private javax.swing.JTextField Field2;
private javax.swing.JTextField Field3;
private javax.swing.JTextField Field4;
private javax.swing.JButton SignUp;
private javax.swing.JLabel icon;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel7;
// End of variables declaration//GEN-END:variables
}
|
UTF-8
|
Java
| 15,039 |
java
|
SignUp.java
|
Java
|
[
{
"context": "import javax.swing.JOptionPane;\n\n/**\n *\n * @author fahim\n */\npublic class SignUp extends javax.swing.JFram",
"end": 298,
"score": 0.9924653768539429,
"start": 293,
"tag": "USERNAME",
"value": "fahim"
}
] | 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 good.panda;
import java.awt.HeadlessException;
import javax.swing.JOptionPane;
/**
*
* @author fahim
*/
public class SignUp extends javax.swing.JFrame {
/**
* Creates new form SignUp
*/
//Ending OF File Operations
public SignUp() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jPanel7 = new javax.swing.JPanel();
icon = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jLabel4 = new javax.swing.JLabel();
Field1 = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
Field2 = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
Field3 = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
Field4 = new javax.swing.JTextField();
SignUp = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel3.setText(" ©2050 | All Rights Reserved By Alien Corp.");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel3)
.addContainerGap(354, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(15, 15, 15)
.addComponent(jLabel3)
.addContainerGap(15, Short.MAX_VALUE))
);
jPanel7.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
icon.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/icon2.jpg"))); // NOI18N
jLabel1.setFont(new java.awt.Font("Tekton Pro Ext", 1, 36)); // NOI18N
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("GOOD PANDA");
jLabel2.setFont(new java.awt.Font("Tekton Pro", 1, 18)); // NOI18N
jLabel2.setText("Eat Healthy, Stay Safe");
javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
jPanel7.setLayout(jPanel7Layout);
jPanel7Layout.setHorizontalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addGap(32, 32, 32)
.addComponent(icon)
.addGap(152, 152, 152)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(jLabel2)
.addComponent(jLabel1))
.addContainerGap(41, Short.MAX_VALUE))
);
jPanel7Layout.setVerticalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addContainerGap()
.addComponent(icon))
.addGroup(jPanel7Layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jLabel4.setText("Enter Your Name:");
jLabel5.setText("Enter Email Address:");
jLabel6.setText("Enter Password");
Field3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Field3ActionPerformed(evt);
}
});
jLabel7.setText("Re-enter Password");
Field4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Field4ActionPerformed(evt);
}
});
SignUp.setText("Sign Up");
SignUp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SignUpActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(41, 41, 41)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel7)
.addComponent(Field4, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6)
.addComponent(Field3, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5)
.addComponent(Field2, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4)
.addComponent(Field1, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(112, 112, 112)
.addComponent(SignUp, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(44, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(47, 47, 47)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Field1, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Field2, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Field3, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Field4, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(SignUp, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(72, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(161, 161, 161)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void SignUpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SignUpActionPerformed
try{
if(evt.getSource()==SignUp){
Users us = new Users();
us.createFolder();
us.readFile();
us.countLines();
String name = Field1.getText();
String email = Field2.getText();
String pass;
if((Field3.getText()).equals(Field4.getText())){
pass = Field3.getText();
us.addData(name, pass, email);
JOptionPane.showMessageDialog(null, "Successfully Registerd");
}
else{
JOptionPane.showMessageDialog(null,"Password Not Matched");
}
}
}
catch(HeadlessException e){
}
}//GEN-LAST:event_SignUpActionPerformed
private void Field3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Field3ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_Field3ActionPerformed
private void Field4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Field4ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_Field4ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(SignUp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SignUp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SignUp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SignUp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new SignUp().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField Field1;
private javax.swing.JTextField Field2;
private javax.swing.JTextField Field3;
private javax.swing.JTextField Field4;
private javax.swing.JButton SignUp;
private javax.swing.JLabel icon;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel7;
// End of variables declaration//GEN-END:variables
}
| 15,039 | 0.626679 | 0.610055 | 320 | 45.993752 | 36.16827 | 180 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.615625 | false | false |
13
|
ed106986a331e1a900f2ca293a1404ab1445b704
| 8,761,733,291,805 |
fdc33b52db9a35f63b74e572548aadcd0d3b2b6a
|
/src/com/bloom/runtime/compiler/exprs/IndexExpr.java
|
6f462a41f97405475cf08df65b8caa758606b38c
|
[] |
no_license
|
theseusyang/BSP
|
https://github.com/theseusyang/BSP
|
bc11bd46016acd1661613e9b1ea79e187c89261d
|
4d46a7da243b935f61cc2a05a2bc54e9b9dcd5af
|
refs/heads/master
| 2016-09-13T04:37:15.065000 | 2016-08-29T06:13:00 | 2016-08-29T06:13:00 | 65,086,656 | 5 | 6 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.bloom.runtime.compiler.exprs;
import com.bloom.runtime.compiler.AST;
import com.bloom.runtime.compiler.visitors.ExpressionVisitor;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.List;
public class IndexExpr
extends Operation
{
public IndexExpr(ValueExpr index, ValueExpr expr)
{
super(ExprCmd.INDEX, AST.NewList(expr, index));
}
public ValueExpr getExpr()
{
return (ValueExpr)this.args.get(0);
}
public ValueExpr getIndex()
{
return (ValueExpr)this.args.get(1);
}
public void setIndex(ValueExpr index)
{
this.args.set(1, index);
}
public <T> Expr visit(ExpressionVisitor<T> visitor, T params)
{
return visitor.visitIndexExpr(this, params);
}
public String toString()
{
return exprToString() + getExpr() + "[" + getIndex() + "]";
}
private Class<?> getBaseType()
{
return getExpr().getType();
}
public Class<?> getType()
{
if (baseIsJsonNode()) {
return JsonNode.class;
}
Class<?> ta = getBaseType();
Class<?> t = ta == null ? null : ta.getComponentType();
return t;
}
public boolean baseIsJsonNode()
{
Class<?> t = getBaseType();
return JsonNode.class.isAssignableFrom(t);
}
public boolean baseIsArray()
{
Class<?> t = getBaseType();
return (t.isArray()) || (JsonNode.class.isAssignableFrom(t));
}
}
|
UTF-8
|
Java
| 1,392 |
java
|
IndexExpr.java
|
Java
|
[] | null |
[] |
package com.bloom.runtime.compiler.exprs;
import com.bloom.runtime.compiler.AST;
import com.bloom.runtime.compiler.visitors.ExpressionVisitor;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.List;
public class IndexExpr
extends Operation
{
public IndexExpr(ValueExpr index, ValueExpr expr)
{
super(ExprCmd.INDEX, AST.NewList(expr, index));
}
public ValueExpr getExpr()
{
return (ValueExpr)this.args.get(0);
}
public ValueExpr getIndex()
{
return (ValueExpr)this.args.get(1);
}
public void setIndex(ValueExpr index)
{
this.args.set(1, index);
}
public <T> Expr visit(ExpressionVisitor<T> visitor, T params)
{
return visitor.visitIndexExpr(this, params);
}
public String toString()
{
return exprToString() + getExpr() + "[" + getIndex() + "]";
}
private Class<?> getBaseType()
{
return getExpr().getType();
}
public Class<?> getType()
{
if (baseIsJsonNode()) {
return JsonNode.class;
}
Class<?> ta = getBaseType();
Class<?> t = ta == null ? null : ta.getComponentType();
return t;
}
public boolean baseIsJsonNode()
{
Class<?> t = getBaseType();
return JsonNode.class.isAssignableFrom(t);
}
public boolean baseIsArray()
{
Class<?> t = getBaseType();
return (t.isArray()) || (JsonNode.class.isAssignableFrom(t));
}
}
| 1,392 | 0.646552 | 0.644397 | 68 | 19.470589 | 19.960602 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.411765 | false | false |
13
|
76d7fadb674468ba393bea9e65c977a3c25910d6
| 33,973,191,315,088 |
3233482183bfaee1f3ee6b63d4a5b4af594d9e6c
|
/src/main/java/net/say2you/filter/JWTAuthFilter.java
|
db993b3c56783c2089521f0b15edde1567f4cfae
|
[] |
no_license
|
say2you/chenjj
|
https://github.com/say2you/chenjj
|
69d91a65f0c7e46c1bf22ff637ee9dabf785fac7
|
e019101ffd89559348f900668bc315b41966d65c
|
refs/heads/master
| 2021-01-01T04:42:33.904000 | 2019-01-08T04:28:14 | 2019-01-08T04:28:14 | 97,230,674 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package net.say2you.filter;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import net.say2you.util.ApplicationProperty;
import net.say2you.util.JWTUtil;
import net.say2you.util.JsonTools;
import net.say2you.util.MessageValue;
import net.say2you.util.PropertyUtil;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Component;
@Component
public class JWTAuthFilter implements Filter {
private FilterConfig filterConfig;
private String[] urlPass = {"/auth/","/user/registerUser"};
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest)request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
HttpSession session = ((HttpServletRequest) request).getSession(true);
PrintWriter pr=null;
// 获取客户请求的页面
String userUrl = httpRequest.getRequestURL().toString();
try{
//取出所有的初始化参数,如果过滤器关闭,则不执行任何关闭动作
String initToggle = filterConfig.getInitParameter("toggle");
if(initToggle.equals("off")){
chain.doFilter(request, response);
return;
}
// 这些url不签权
if (isUrlPass(userUrl, urlPass)) {
chain.doFilter(httpRequest, httpResponse);
return;
}
//检查session
if(session.getAttribute("sessionid")!=null ){
String au=(String)session.getAttribute("sessionid");
if(au.equals(session.getId())){
//从header里取得客户端的操作请求,此动作需要客户端在header中进行设置
String sessionAction = httpRequest.getHeader("Action");
//客户端请求销毁session
if(sessionAction!=null && sessionAction.equals(PropertyUtil.getProperty("audience.sessionAction"))){
session.removeAttribute("sessionid");
session.invalidate();
return;
}
chain.doFilter(request, response);
return;
}
}
//校验 tgt
String auth = httpRequest.getParameter("tgt");
if ((auth != null) && (auth.length() > 7)){
String headStr = auth.substring(0, 6).toLowerCase();
if (headStr.compareTo("bearer") == 0){
auth = auth.substring(6, auth.length());
Claims claim=JWTUtil.parseJWT(auth, ApplicationProperty.getProperty("audience.base64Secret"));
if (claim!= null){
// System.out.println("从auth设置session并访问接口:"+session.getId());
session.setAttribute("sessionid", session.getId());
//设置默认session时长30分钟
session.setMaxInactiveInterval(Integer.parseInt(ApplicationProperty.getProperty("audience.sessionSecond")));
chain.doFilter(request, response);
return;
}
}
}
httpResponse.setCharacterEncoding("UTF-8");
httpResponse.setContentType("application/json; charset=utf-8");
httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
Map<String,Object> map=new HashMap<String,Object>();
map.put("status",false);
map.put("messagecode",MessageValue.TGT_UNDEFINED_CODE);
map.put("message", PropertyUtil.getProperty(MessageValue.TGT_UNDEFINED_CODE));
String str=JsonTools.Object2Json(map);
pr=httpResponse.getWriter();
pr.write(str);
pr.close();
}catch(SignatureException|MalformedJwtException e){
Map<String,Object> map=new HashMap<String,Object>();
map.put("status",false);
map.put("messagecode",MessageValue.TGT_ERROR_CODE);
map.put("message", PropertyUtil.getProperty(MessageValue.TGT_ERROR_CODE));
String str=JsonTools.Object2Json(map);
pr=httpResponse.getWriter();
pr.write(str);
pr.close();
}catch(ExpiredJwtException e){
//token超时
Map<String,Object> map=new HashMap<String,Object>();
map.put("status",false);
map.put("messagecode",MessageValue.TGT_TIMEOUT_CODE);
map.put("message", PropertyUtil.getProperty(MessageValue.TGT_TIMEOUT_CODE));
String str=JsonTools.Object2Json(map);
pr=httpResponse.getWriter();
pr.write(str);
pr.close();
}finally{
if(pr!=null){
pr.close();
}
}
return;
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig=filterConfig;
}
/**
* 检查url是否在指定的数组中
* @param reqUrl
* @param urlGroup
* @return
*/
private boolean isUrlPass(String reqUrl, String[] urlGroup) {
boolean isPass = false;
for (String userUrl : urlGroup) {
if (reqUrl.indexOf(userUrl) >= 0) {
isPass = true;
break;
}
}
return isPass;
}
}
|
UTF-8
|
Java
| 5,804 |
java
|
JWTAuthFilter.java
|
Java
|
[] | null |
[] |
package net.say2you.filter;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import net.say2you.util.ApplicationProperty;
import net.say2you.util.JWTUtil;
import net.say2you.util.JsonTools;
import net.say2you.util.MessageValue;
import net.say2you.util.PropertyUtil;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Component;
@Component
public class JWTAuthFilter implements Filter {
private FilterConfig filterConfig;
private String[] urlPass = {"/auth/","/user/registerUser"};
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest)request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
HttpSession session = ((HttpServletRequest) request).getSession(true);
PrintWriter pr=null;
// 获取客户请求的页面
String userUrl = httpRequest.getRequestURL().toString();
try{
//取出所有的初始化参数,如果过滤器关闭,则不执行任何关闭动作
String initToggle = filterConfig.getInitParameter("toggle");
if(initToggle.equals("off")){
chain.doFilter(request, response);
return;
}
// 这些url不签权
if (isUrlPass(userUrl, urlPass)) {
chain.doFilter(httpRequest, httpResponse);
return;
}
//检查session
if(session.getAttribute("sessionid")!=null ){
String au=(String)session.getAttribute("sessionid");
if(au.equals(session.getId())){
//从header里取得客户端的操作请求,此动作需要客户端在header中进行设置
String sessionAction = httpRequest.getHeader("Action");
//客户端请求销毁session
if(sessionAction!=null && sessionAction.equals(PropertyUtil.getProperty("audience.sessionAction"))){
session.removeAttribute("sessionid");
session.invalidate();
return;
}
chain.doFilter(request, response);
return;
}
}
//校验 tgt
String auth = httpRequest.getParameter("tgt");
if ((auth != null) && (auth.length() > 7)){
String headStr = auth.substring(0, 6).toLowerCase();
if (headStr.compareTo("bearer") == 0){
auth = auth.substring(6, auth.length());
Claims claim=JWTUtil.parseJWT(auth, ApplicationProperty.getProperty("audience.base64Secret"));
if (claim!= null){
// System.out.println("从auth设置session并访问接口:"+session.getId());
session.setAttribute("sessionid", session.getId());
//设置默认session时长30分钟
session.setMaxInactiveInterval(Integer.parseInt(ApplicationProperty.getProperty("audience.sessionSecond")));
chain.doFilter(request, response);
return;
}
}
}
httpResponse.setCharacterEncoding("UTF-8");
httpResponse.setContentType("application/json; charset=utf-8");
httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
Map<String,Object> map=new HashMap<String,Object>();
map.put("status",false);
map.put("messagecode",MessageValue.TGT_UNDEFINED_CODE);
map.put("message", PropertyUtil.getProperty(MessageValue.TGT_UNDEFINED_CODE));
String str=JsonTools.Object2Json(map);
pr=httpResponse.getWriter();
pr.write(str);
pr.close();
}catch(SignatureException|MalformedJwtException e){
Map<String,Object> map=new HashMap<String,Object>();
map.put("status",false);
map.put("messagecode",MessageValue.TGT_ERROR_CODE);
map.put("message", PropertyUtil.getProperty(MessageValue.TGT_ERROR_CODE));
String str=JsonTools.Object2Json(map);
pr=httpResponse.getWriter();
pr.write(str);
pr.close();
}catch(ExpiredJwtException e){
//token超时
Map<String,Object> map=new HashMap<String,Object>();
map.put("status",false);
map.put("messagecode",MessageValue.TGT_TIMEOUT_CODE);
map.put("message", PropertyUtil.getProperty(MessageValue.TGT_TIMEOUT_CODE));
String str=JsonTools.Object2Json(map);
pr=httpResponse.getWriter();
pr.write(str);
pr.close();
}finally{
if(pr!=null){
pr.close();
}
}
return;
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig=filterConfig;
}
/**
* 检查url是否在指定的数组中
* @param reqUrl
* @param urlGroup
* @return
*/
private boolean isUrlPass(String reqUrl, String[] urlGroup) {
boolean isPass = false;
for (String userUrl : urlGroup) {
if (reqUrl.indexOf(userUrl) >= 0) {
isPass = true;
break;
}
}
return isPass;
}
}
| 5,804 | 0.639148 | 0.635387 | 157 | 33.566879 | 24.972666 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.764331 | false | false |
13
|
768837694afbd6e415991dfb6778664487bb500d
| 18,923,625,941,710 |
f0358eeabef5039272e7e14b69fc51119736a85f
|
/src/main/java/com/yvette/gym/service/GymClassService.java
|
8b80982405e7bd533ecc64816b9e8c175af7bdbe
|
[] |
no_license
|
yuwibambe/TheGym
|
https://github.com/yuwibambe/TheGym
|
f089ffe85d61e8662c6eb03078121e5fe897adcf
|
56ef9126f03e28e10c4a407b7d9725e0cecb30d9
|
refs/heads/master
| 2021-01-06T22:46:00.389000 | 2020-02-29T07:06:56 | 2020-02-29T07:06:56 | 241,503,610 | 0 | 0 | null | false | 2020-02-19T02:55:00 | 2020-02-19T01:12:38 | 2020-02-19T02:54:41 | 2020-02-19T02:54:59 | 0 | 0 | 0 | 1 |
Java
| false | false |
package com.yvette.gym.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yvette.gym.domain.GymClass;
import com.yvette.gym.domain.Member;
import com.yvette.gym.repository.IGymClassRepository;
@Service
public class GymClassService {
@Autowired
private IGymClassRepository iGymClassRepository;
public GymClass save (GymClass gymClass) {
GymClass savedGymClass = iGymClassRepository.save(gymClass);
return savedGymClass;
}
public GymClass getGymClass(Long id) {
return iGymClassRepository.getOne(id);
}
public List<GymClass> getGymClassesByMember(Member member){
return iGymClassRepository.findByStudents(member);
}
public List<GymClass> getAllGymClasses(){
return iGymClassRepository.findAll();
}
}
|
UTF-8
|
Java
| 837 |
java
|
GymClassService.java
|
Java
|
[] | null |
[] |
package com.yvette.gym.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yvette.gym.domain.GymClass;
import com.yvette.gym.domain.Member;
import com.yvette.gym.repository.IGymClassRepository;
@Service
public class GymClassService {
@Autowired
private IGymClassRepository iGymClassRepository;
public GymClass save (GymClass gymClass) {
GymClass savedGymClass = iGymClassRepository.save(gymClass);
return savedGymClass;
}
public GymClass getGymClass(Long id) {
return iGymClassRepository.getOne(id);
}
public List<GymClass> getGymClassesByMember(Member member){
return iGymClassRepository.findByStudents(member);
}
public List<GymClass> getAllGymClasses(){
return iGymClassRepository.findAll();
}
}
| 837 | 0.796894 | 0.796894 | 35 | 22.914286 | 22.115763 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.114286 | false | false |
13
|
ae193ffbe077f680ae4699fdb569aca47a425246
| 27,204,322,867,307 |
b05796ebb5643a044917e7da43f3a4e4e43c4163
|
/src/main/java/com/example/innoventesProject/service/EmployeeDetailsImpl.java
|
20bf8d159f49287377f4d6775c599a928d94456a
|
[] |
no_license
|
Aartigiri/innoventesProject
|
https://github.com/Aartigiri/innoventesProject
|
240d67c6f93d697381e447721603b82fb1c5d404
|
40f42aeb1edcdcce4c6c0505bfa34cdef4ffd91a
|
refs/heads/master
| 2022-12-02T22:48:02.638000 | 2020-08-17T05:41:20 | 2020-08-17T05:41:20 | 288,091,161 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.innoventesProject.service;
import com.example.innoventesProject.dto.*;
import com.example.innoventesProject.entity.Address;
import com.example.innoventesProject.entity.Employee;
import com.example.innoventesProject.entity.EmployeeAddress;
import com.example.innoventesProject.repository.AddressRead;
import com.example.innoventesProject.repository.EmployeeAddressRead;
import com.example.innoventesProject.repository.EmployeeRead;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
public class EmployeeDetailsImpl implements EmployeeDetailsService {
private static final Logger LOG = LoggerFactory.getLogger(EmployeeDetailsImpl.class);
@Autowired
EmployeeAddressRead employeeAddressRead;
@Autowired
AddressRead addressRead;
@Autowired
EmployeeRead employeeRead;
@Override
public ResponseObject<EmployeeAddressResponse> insertData(EmployeeAddressDto employeeAddressDto){
LOG.trace(" -->ENTRY-->CreateUser() :: {}", employeeAddressDto);
EmployeeAddressResponse employeeAddressResponse=new EmployeeAddressResponse();
Optional<EmployeeAddress> employeeAddress = Optional.empty();
try{
employeeAddress = employeeAddressRead.findByemployeeAddressId(employeeAddressDto.getEmployeeAddressId());
}
catch (Exception ex){
ex.printStackTrace();
}
if (!employeeAddress.isPresent()){
// employeeAddress1.setEmployeeAddressId();
EmployeeAddress employeeAddress1=new EmployeeAddress();
Employee employee=new Employee();
employee.setEmployeeName(employeeAddressDto.getEmployeeDto().getEmployeeName());
employee.setDob(employeeAddressDto.getEmployeeDto().getDob());
employeeAddress1.setEmployee(employee);
Address address=new Address();
address.setAddrLineOne(employeeAddressDto.getAddressDto().getAddrLineOne());
address.setCity(employeeAddressDto.getAddressDto().getCity());
employeeAddress1.setAddress(address);
employeeAddress1.setAddressType(employeeAddressDto.getAddressType());
addressRead.save(address);
employeeRead.save(employee);
employeeAddressRead.save(employeeAddress1);
employeeAddressResponse.setAddressType(employeeAddress1.getAddressType());
}
return ResponseObject.success(employeeAddressResponse);
}
@Override
public ResponseObject<EmployeeAddressResponse1> findAllData() {
Iterable<EmployeeAddress> entityOptional = null;
List<EmployeeAddressResponse> employeeAddressResponse1=new ArrayList<>();
EmployeeAddressResponse1 employeeAddressResponse11=new EmployeeAddressResponse1();
try{
entityOptional= employeeAddressRead.findAll();
}
catch (Exception ex){
ex.getMessage();
}
entityOptional.forEach(eventEntity -> {
EmployeeAddressResponse employeeAddressResponse=new EmployeeAddressResponse();
employeeAddressResponse.setAddressType(eventEntity.getAddressType());
EmployeeResponse employeeResponse=new EmployeeResponse();
AddressResponse addressResponse=new AddressResponse();
employeeAddressResponse.setEmployeeAddressId(eventEntity.getEmployeeAddressId());
employeeResponse.setEmployeeName(eventEntity.getEmployee().getEmployeeName());
employeeResponse.setEmployeeId(eventEntity.getEmployee().getEmployeeId());
addressResponse.setAddrLineOne(eventEntity.getAddress().getAddrLineOne());
addressResponse.setCity(eventEntity.getAddress().getCity());
addressResponse.setAddressId(eventEntity.getAddress().getAddressId());
employeeAddressResponse.setAddressResponse(addressResponse);
employeeAddressResponse.setEmployeeResponse(employeeResponse);
employeeAddressResponse1.add(employeeAddressResponse);
});
employeeAddressResponse11.setEmployeeAddressResponse( employeeAddressResponse1);
return ResponseObject.success(employeeAddressResponse11);
}
@Override
public ResponseObject<EmployeeAddressResponse> updateData(EmployeeAddressDto employeeAddressDto){
EmployeeAddressResponse employeeAddressResponse11=new EmployeeAddressResponse();
EmployeeAddress employeeAddress1=new EmployeeAddress();
Address address1=new Address();
Employee employee1=new Employee();
Optional<EmployeeAddress> employeeAddress=Optional.empty();
Optional<Address> address=Optional.empty();
Optional<Employee> employee=Optional.empty();
try {
employeeAddress=employeeAddressRead.findByemployeeAddressId(employeeAddressDto.getEmployeeAddressId());
address= addressRead.findByaddressId(employeeAddressDto.getAddressDto().getAddressId());
employee = employeeRead.findByemployeeId(employeeAddressDto.getEmployeeDto().getEmployeeId());
}
catch (Exception ex){
ex.printStackTrace();
}
employeeAddress1= employeeAddress.get();
address1=address.get();
employee1= employee.get();
employeeAddress1.setAddressType(employeeAddressDto.getAddressType());
address1.setAddrLineOne(employeeAddressDto.getAddressDto().getAddrLineOne());
address1.setCity(employeeAddressDto.getAddressDto().getCity());
employee1.setDob(employeeAddressDto.getEmployeeDto().getDob());
employee1.setEmployeeName(employeeAddressDto.getEmployeeDto().getEmployeeName());
addressRead.save(address1);
employeeRead.save(employee1);
employeeAddressRead.save(employeeAddress1);
return ResponseObject.success(employeeAddressResponse11);
}
@Override
public ResponseObject<EmployeeAddressResponse> deleteData(Long employeeaddressId){
LOG.trace("-->>ENTRY>> deleteData() :: {}", employeeaddressId);
EmployeeAddressResponse employeeAddressResponse=new EmployeeAddressResponse();
Optional<EmployeeAddress> employeeAddress=Optional.empty();
Optional<Address> address=Optional.empty();
Optional<Employee> employee=Optional.empty();
try {
employeeAddress=employeeAddressRead.findByemployeeAddressId(employeeaddressId);
address= addressRead.findByaddressId(employeeAddress.get().getAddress().getAddressId());
employee = employeeRead.findByemployeeId(employeeAddress.get().getEmployee().getEmployeeId());
}
catch (Exception ex){
ex.printStackTrace();
}
Address address11=address.get();
addressRead.delete(address11);
Employee employee1=employee.get();
employeeRead.delete(employee1);
EmployeeAddress employeeAddress11=employeeAddress.get();
employeeAddressRead.delete(employeeAddress11);
return ResponseObject.success(employeeAddressResponse);
}
@Override
public ResponseObject<EmployeeAddressResponse> findByemployeeName(String employeeName){
EmployeeAddressResponse employeeAddressResponse=new EmployeeAddressResponse();
Optional<Employee> employee=Optional.empty();
Optional<Address> address=Optional.empty();
Optional<EmployeeAddress> employeeAddress=Optional.empty();
try {
employee = employeeRead.findByemployeeName(employeeName);
employeeAddress=employeeAddressRead.findByemployeeAddressId(employee.get().getEmployeeId());
address= addressRead.findByaddressId(employeeAddress.get().getAddress().getAddressId());
}
catch (Exception ex){
ex.printStackTrace();
}
if (employee.isPresent()){
EmployeeResponse employeeResponse=new EmployeeResponse();
AddressResponse addressResponse=new AddressResponse();
employeeResponse.setEmployeeName(employee.get().getEmployeeName());
employeeResponse.setEmployeeId(employee.get().getEmployeeId());
employeeAddressResponse.setAddressResponse(addressResponse);
employeeAddressResponse.setEmployeeResponse(employeeResponse);
}
return ResponseObject.success(employeeAddressResponse);
}
@Override
public ResponseObject<EmployeeAddressResponse> updateDataAddress(EmployeeAddressDto employeeAddressDto){
EmployeeAddressResponse employeeAddressResponse11=new EmployeeAddressResponse();
EmployeeAddress employeeAddress1=new EmployeeAddress();
Address address1=new Address();
Employee employee1=new Employee();
Optional<EmployeeAddress> employeeAddress=Optional.empty();
Optional<Address> address=Optional.empty();
Optional<Employee> employee=Optional.empty();
try {
employeeAddress=employeeAddressRead.findByemployeeAddressId(employeeAddressDto.getEmployeeAddressId());
address= addressRead.findByaddressId(employeeAddressDto.getAddressDto().getAddressId());
}
catch (Exception ex){
ex.printStackTrace();
}
employeeAddress1= employeeAddress.get();
address1=address.get();
address1.setAddrLineOne(employeeAddressDto.getAddressDto().getAddrLineOne());
address1.setCity(employeeAddressDto.getAddressDto().getCity());
employeeAddress1.setAddressType(employeeAddressDto.getAddressType());
addressRead.save(address1);
employeeAddressRead.save(employeeAddress1);
return ResponseObject.success(employeeAddressResponse11);
}
}
|
UTF-8
|
Java
| 9,851 |
java
|
EmployeeDetailsImpl.java
|
Java
|
[
{
"context": " employee = employeeRead.findByemployeeName(employeeName);\n employeeAddress=employeeAddress",
"end": 7696,
"score": 0.980375349521637,
"start": 7688,
"tag": "NAME",
"value": "employee"
},
{
"context": "mployee = employeeRead.findByemployeeName(employeeName);\n employeeAddress=employeeAddressRead",
"end": 7700,
"score": 0.8354302644729614,
"start": 7696,
"tag": "NAME",
"value": "Name"
}
] | null |
[] |
package com.example.innoventesProject.service;
import com.example.innoventesProject.dto.*;
import com.example.innoventesProject.entity.Address;
import com.example.innoventesProject.entity.Employee;
import com.example.innoventesProject.entity.EmployeeAddress;
import com.example.innoventesProject.repository.AddressRead;
import com.example.innoventesProject.repository.EmployeeAddressRead;
import com.example.innoventesProject.repository.EmployeeRead;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
public class EmployeeDetailsImpl implements EmployeeDetailsService {
private static final Logger LOG = LoggerFactory.getLogger(EmployeeDetailsImpl.class);
@Autowired
EmployeeAddressRead employeeAddressRead;
@Autowired
AddressRead addressRead;
@Autowired
EmployeeRead employeeRead;
@Override
public ResponseObject<EmployeeAddressResponse> insertData(EmployeeAddressDto employeeAddressDto){
LOG.trace(" -->ENTRY-->CreateUser() :: {}", employeeAddressDto);
EmployeeAddressResponse employeeAddressResponse=new EmployeeAddressResponse();
Optional<EmployeeAddress> employeeAddress = Optional.empty();
try{
employeeAddress = employeeAddressRead.findByemployeeAddressId(employeeAddressDto.getEmployeeAddressId());
}
catch (Exception ex){
ex.printStackTrace();
}
if (!employeeAddress.isPresent()){
// employeeAddress1.setEmployeeAddressId();
EmployeeAddress employeeAddress1=new EmployeeAddress();
Employee employee=new Employee();
employee.setEmployeeName(employeeAddressDto.getEmployeeDto().getEmployeeName());
employee.setDob(employeeAddressDto.getEmployeeDto().getDob());
employeeAddress1.setEmployee(employee);
Address address=new Address();
address.setAddrLineOne(employeeAddressDto.getAddressDto().getAddrLineOne());
address.setCity(employeeAddressDto.getAddressDto().getCity());
employeeAddress1.setAddress(address);
employeeAddress1.setAddressType(employeeAddressDto.getAddressType());
addressRead.save(address);
employeeRead.save(employee);
employeeAddressRead.save(employeeAddress1);
employeeAddressResponse.setAddressType(employeeAddress1.getAddressType());
}
return ResponseObject.success(employeeAddressResponse);
}
@Override
public ResponseObject<EmployeeAddressResponse1> findAllData() {
Iterable<EmployeeAddress> entityOptional = null;
List<EmployeeAddressResponse> employeeAddressResponse1=new ArrayList<>();
EmployeeAddressResponse1 employeeAddressResponse11=new EmployeeAddressResponse1();
try{
entityOptional= employeeAddressRead.findAll();
}
catch (Exception ex){
ex.getMessage();
}
entityOptional.forEach(eventEntity -> {
EmployeeAddressResponse employeeAddressResponse=new EmployeeAddressResponse();
employeeAddressResponse.setAddressType(eventEntity.getAddressType());
EmployeeResponse employeeResponse=new EmployeeResponse();
AddressResponse addressResponse=new AddressResponse();
employeeAddressResponse.setEmployeeAddressId(eventEntity.getEmployeeAddressId());
employeeResponse.setEmployeeName(eventEntity.getEmployee().getEmployeeName());
employeeResponse.setEmployeeId(eventEntity.getEmployee().getEmployeeId());
addressResponse.setAddrLineOne(eventEntity.getAddress().getAddrLineOne());
addressResponse.setCity(eventEntity.getAddress().getCity());
addressResponse.setAddressId(eventEntity.getAddress().getAddressId());
employeeAddressResponse.setAddressResponse(addressResponse);
employeeAddressResponse.setEmployeeResponse(employeeResponse);
employeeAddressResponse1.add(employeeAddressResponse);
});
employeeAddressResponse11.setEmployeeAddressResponse( employeeAddressResponse1);
return ResponseObject.success(employeeAddressResponse11);
}
@Override
public ResponseObject<EmployeeAddressResponse> updateData(EmployeeAddressDto employeeAddressDto){
EmployeeAddressResponse employeeAddressResponse11=new EmployeeAddressResponse();
EmployeeAddress employeeAddress1=new EmployeeAddress();
Address address1=new Address();
Employee employee1=new Employee();
Optional<EmployeeAddress> employeeAddress=Optional.empty();
Optional<Address> address=Optional.empty();
Optional<Employee> employee=Optional.empty();
try {
employeeAddress=employeeAddressRead.findByemployeeAddressId(employeeAddressDto.getEmployeeAddressId());
address= addressRead.findByaddressId(employeeAddressDto.getAddressDto().getAddressId());
employee = employeeRead.findByemployeeId(employeeAddressDto.getEmployeeDto().getEmployeeId());
}
catch (Exception ex){
ex.printStackTrace();
}
employeeAddress1= employeeAddress.get();
address1=address.get();
employee1= employee.get();
employeeAddress1.setAddressType(employeeAddressDto.getAddressType());
address1.setAddrLineOne(employeeAddressDto.getAddressDto().getAddrLineOne());
address1.setCity(employeeAddressDto.getAddressDto().getCity());
employee1.setDob(employeeAddressDto.getEmployeeDto().getDob());
employee1.setEmployeeName(employeeAddressDto.getEmployeeDto().getEmployeeName());
addressRead.save(address1);
employeeRead.save(employee1);
employeeAddressRead.save(employeeAddress1);
return ResponseObject.success(employeeAddressResponse11);
}
@Override
public ResponseObject<EmployeeAddressResponse> deleteData(Long employeeaddressId){
LOG.trace("-->>ENTRY>> deleteData() :: {}", employeeaddressId);
EmployeeAddressResponse employeeAddressResponse=new EmployeeAddressResponse();
Optional<EmployeeAddress> employeeAddress=Optional.empty();
Optional<Address> address=Optional.empty();
Optional<Employee> employee=Optional.empty();
try {
employeeAddress=employeeAddressRead.findByemployeeAddressId(employeeaddressId);
address= addressRead.findByaddressId(employeeAddress.get().getAddress().getAddressId());
employee = employeeRead.findByemployeeId(employeeAddress.get().getEmployee().getEmployeeId());
}
catch (Exception ex){
ex.printStackTrace();
}
Address address11=address.get();
addressRead.delete(address11);
Employee employee1=employee.get();
employeeRead.delete(employee1);
EmployeeAddress employeeAddress11=employeeAddress.get();
employeeAddressRead.delete(employeeAddress11);
return ResponseObject.success(employeeAddressResponse);
}
@Override
public ResponseObject<EmployeeAddressResponse> findByemployeeName(String employeeName){
EmployeeAddressResponse employeeAddressResponse=new EmployeeAddressResponse();
Optional<Employee> employee=Optional.empty();
Optional<Address> address=Optional.empty();
Optional<EmployeeAddress> employeeAddress=Optional.empty();
try {
employee = employeeRead.findByemployeeName(employeeName);
employeeAddress=employeeAddressRead.findByemployeeAddressId(employee.get().getEmployeeId());
address= addressRead.findByaddressId(employeeAddress.get().getAddress().getAddressId());
}
catch (Exception ex){
ex.printStackTrace();
}
if (employee.isPresent()){
EmployeeResponse employeeResponse=new EmployeeResponse();
AddressResponse addressResponse=new AddressResponse();
employeeResponse.setEmployeeName(employee.get().getEmployeeName());
employeeResponse.setEmployeeId(employee.get().getEmployeeId());
employeeAddressResponse.setAddressResponse(addressResponse);
employeeAddressResponse.setEmployeeResponse(employeeResponse);
}
return ResponseObject.success(employeeAddressResponse);
}
@Override
public ResponseObject<EmployeeAddressResponse> updateDataAddress(EmployeeAddressDto employeeAddressDto){
EmployeeAddressResponse employeeAddressResponse11=new EmployeeAddressResponse();
EmployeeAddress employeeAddress1=new EmployeeAddress();
Address address1=new Address();
Employee employee1=new Employee();
Optional<EmployeeAddress> employeeAddress=Optional.empty();
Optional<Address> address=Optional.empty();
Optional<Employee> employee=Optional.empty();
try {
employeeAddress=employeeAddressRead.findByemployeeAddressId(employeeAddressDto.getEmployeeAddressId());
address= addressRead.findByaddressId(employeeAddressDto.getAddressDto().getAddressId());
}
catch (Exception ex){
ex.printStackTrace();
}
employeeAddress1= employeeAddress.get();
address1=address.get();
address1.setAddrLineOne(employeeAddressDto.getAddressDto().getAddrLineOne());
address1.setCity(employeeAddressDto.getAddressDto().getCity());
employeeAddress1.setAddressType(employeeAddressDto.getAddressType());
addressRead.save(address1);
employeeAddressRead.save(employeeAddress1);
return ResponseObject.success(employeeAddressResponse11);
}
}
| 9,851 | 0.723784 | 0.717389 | 232 | 41.452587 | 33.733582 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.581897 | false | false |
13
|
e12aa3496481f4b616aa633f5ea4d1461a12cc73
| 27,204,322,868,250 |
f995a9885e223c9548b44d9cb924443c8e303c8f
|
/src/main/java/com/hq/bm/mapper/FacilityPhotoMapper.java
|
0b094f8f1608e915b0072b5493fd9470a208ac9a
|
[] |
no_license
|
BearXiongGuan/obd
|
https://github.com/BearXiongGuan/obd
|
9e52435bc0698e7b717d4a23b5c2dd7379cc94d7
|
cf419766257a5ab6552271a57d5c5f53a1b8ea57
|
refs/heads/master
| 2021-01-15T12:59:18.965000 | 2017-08-08T07:38:50 | 2017-08-08T07:38:50 | 99,662,826 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.hq.bm.mapper;
import org.springframework.stereotype.Repository;
import com.hq.bm.entity.FacilityPhoto;
import com.hq.bm.exception.ServiceException;
/**
* Created by Administrator on 2017/3/9.
*/
@Repository
public interface FacilityPhotoMapper extends BaseMapper<FacilityPhoto> {
public void add(FacilityPhoto facility) throws ServiceException;
}
|
UTF-8
|
Java
| 365 |
java
|
FacilityPhotoMapper.java
|
Java
|
[
{
"context": ".bm.exception.ServiceException;\n\n/**\n * Created by Administrator on 2017/3/9.\n */\n@Repository\npublic interface Fac",
"end": 194,
"score": 0.6903032064437866,
"start": 181,
"tag": "USERNAME",
"value": "Administrator"
}
] | null |
[] |
package com.hq.bm.mapper;
import org.springframework.stereotype.Repository;
import com.hq.bm.entity.FacilityPhoto;
import com.hq.bm.exception.ServiceException;
/**
* Created by Administrator on 2017/3/9.
*/
@Repository
public interface FacilityPhotoMapper extends BaseMapper<FacilityPhoto> {
public void add(FacilityPhoto facility) throws ServiceException;
}
| 365 | 0.805479 | 0.789041 | 14 | 25.071428 | 25.00704 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false |
13
|
34b4580fe0728cafcb3faa5d8816b229b2c68341
| 27,487,790,754,373 |
ff320fb97961d7a9ea5bb6668e5e67912a26db5e
|
/app/src/main/java/com/aboesmail/omar/pharma/Api/order/Order.java
|
91e32df1745e61c49313dd4a81cf6368be6d079d
|
[] |
no_license
|
amor21010/E-Commerce-pharmacy-android
|
https://github.com/amor21010/E-Commerce-pharmacy-android
|
ce5705949c316a6c977261aef654301e5b4388c1
|
50079b29d73eed09bf4e200872a8eb1b6cea6e78
|
refs/heads/master
| 2022-10-08T09:23:45.239000 | 2020-06-07T14:57:31 | 2020-06-07T14:57:31 | 270,342,623 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.aboesmail.omar.pharma.Api.order;
import com.google.gson.JsonArray;
import com.google.gson.annotations.SerializedName;
public class Order {
@SerializedName("_id")
private String Id;
private String time;
private String owner;
private String status;
@SerializedName("totalPrice")
private String totalPrice;
private String seller;
private String delivary;
private JsonArray products;
public Order(String owner, String status, String totalPrice) {
this.totalPrice = totalPrice;
this.owner = owner;
this.status = status;
}
public JsonArray getProduct() {
return products;
}
public String getTotalPrice() {
return totalPrice;
}
public String getId() {
return Id;
}
public String getSeller() {
return seller;
}
public String getDelivary() {
return delivary;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
|
UTF-8
|
Java
| 1,341 |
java
|
Order.java
|
Java
|
[] | null |
[] |
package com.aboesmail.omar.pharma.Api.order;
import com.google.gson.JsonArray;
import com.google.gson.annotations.SerializedName;
public class Order {
@SerializedName("_id")
private String Id;
private String time;
private String owner;
private String status;
@SerializedName("totalPrice")
private String totalPrice;
private String seller;
private String delivary;
private JsonArray products;
public Order(String owner, String status, String totalPrice) {
this.totalPrice = totalPrice;
this.owner = owner;
this.status = status;
}
public JsonArray getProduct() {
return products;
}
public String getTotalPrice() {
return totalPrice;
}
public String getId() {
return Id;
}
public String getSeller() {
return seller;
}
public String getDelivary() {
return delivary;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
| 1,341 | 0.612975 | 0.612975 | 74 | 17.121622 | 15.669692 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.364865 | false | false |
13
|
267494fc5bd73f3f7769cd9190150974a9e9a046
| 7,859,790,214,657 |
f50613190c1c731afdd67d9f325ee5fb258a0120
|
/BinaryTreePaths/src/Main.java
|
fe475a0d7043806c8130dd8998cc461fc300e85f
|
[] |
no_license
|
victornani07/data_structures_algorithms
|
https://github.com/victornani07/data_structures_algorithms
|
adcc877b8ca18fe03945a4ca43235221395d97f4
|
d07aea983e81adecffe4cf921009695b11f5260c
|
refs/heads/main
| 2023-07-10T15:54:12.214000 | 2021-08-11T16:06:16 | 2021-08-11T16:06:16 | 383,177,664 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class Main {
public static void main(String[] args) {
Solution solution = new Solution();
TreeNode root = new TreeNode(1, null, null);
TreeNode node1 = new TreeNode(2, null, null);
TreeNode node2 = new TreeNode(3, null, null);
TreeNode node3 = new TreeNode(5, null, null);
root.left = node1;
root.right = node2;
node1.right = node3;
for(String path : solution.binaryTreePaths(root))
System.out.println(path);
}
}
|
UTF-8
|
Java
| 534 |
java
|
Main.java
|
Java
|
[] | null |
[] |
public class Main {
public static void main(String[] args) {
Solution solution = new Solution();
TreeNode root = new TreeNode(1, null, null);
TreeNode node1 = new TreeNode(2, null, null);
TreeNode node2 = new TreeNode(3, null, null);
TreeNode node3 = new TreeNode(5, null, null);
root.left = node1;
root.right = node2;
node1.right = node3;
for(String path : solution.binaryTreePaths(root))
System.out.println(path);
}
}
| 534 | 0.571161 | 0.550562 | 18 | 27.666666 | 21.514853 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.944444 | false | false |
13
|
16747dbc7f6110eb6ebea3c22f0c7f5f7cf50f37
| 20,873,541,072,519 |
79f2ae81f5725c049ddd9be6b4c8d1d9cb5cf02a
|
/crm/src/main/java/com/liliangyu/crm/service/impl/SystemDictionaryServiceImpl.java
|
bdd5f9864518a30d8f24231340a7f7475e066e23
|
[] |
no_license
|
lliyuu520/root
|
https://github.com/lliyuu520/root
|
d0aeb1b63969bba18c632b8b21954e6c5e046214
|
9d0ea3fa842d52e415bbecfe90bbde3438144686
|
refs/heads/master
| 2016-08-09T22:48:22.926000 | 2016-04-07T13:35:20 | 2016-04-07T13:35:20 | 55,340,477 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.liliangyu.crm.service.impl;
import com.liliangyu.crm.domain.SystemDictionary;
import com.liliangyu.crm.mapper.SystemDictionaryMapper;
import com.liliangyu.crm.service.ISystemDictionaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class SystemDictionaryServiceImpl implements ISystemDictionaryService {
@Qualifier("systemDictionaryMapper")
@Autowired
private SystemDictionaryMapper systemDictionaryMapper;
@Override
public SystemDictionary get(Long id) {
return systemDictionaryMapper.get(id);
}
@Override
public void insert(SystemDictionary item) {
systemDictionaryMapper.insert(item);
}
@Override
public void delete(Long id) {
systemDictionaryMapper.delete(id);
}
@Override
public void update(SystemDictionary item) {
}
@Override
public List<SystemDictionary> getAll() {
return systemDictionaryMapper.getAll();
}
@Override
public List<SystemDictionary> getBySn(String sn) {
return systemDictionaryMapper.getBySn(sn);
}
}
|
UTF-8
|
Java
| 1,244 |
java
|
SystemDictionaryServiceImpl.java
|
Java
|
[] | null |
[] |
package com.liliangyu.crm.service.impl;
import com.liliangyu.crm.domain.SystemDictionary;
import com.liliangyu.crm.mapper.SystemDictionaryMapper;
import com.liliangyu.crm.service.ISystemDictionaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class SystemDictionaryServiceImpl implements ISystemDictionaryService {
@Qualifier("systemDictionaryMapper")
@Autowired
private SystemDictionaryMapper systemDictionaryMapper;
@Override
public SystemDictionary get(Long id) {
return systemDictionaryMapper.get(id);
}
@Override
public void insert(SystemDictionary item) {
systemDictionaryMapper.insert(item);
}
@Override
public void delete(Long id) {
systemDictionaryMapper.delete(id);
}
@Override
public void update(SystemDictionary item) {
}
@Override
public List<SystemDictionary> getAll() {
return systemDictionaryMapper.getAll();
}
@Override
public List<SystemDictionary> getBySn(String sn) {
return systemDictionaryMapper.getBySn(sn);
}
}
| 1,244 | 0.745981 | 0.745981 | 48 | 24.916666 | 23.237751 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.291667 | false | false |
13
|
3d9e7e6feed5384bdd149c840a8373800a67f456
| 28,810,640,679,926 |
12fc369cbd144228d7d778b4cf5643deebcf1e32
|
/src/main/java/com/jluque/w2m/exception/custom/FieldExistCustomException.java
|
30503dfbefe35ee46a0854a9db18615b7ff40046
|
[] |
no_license
|
julioluque/superhero
|
https://github.com/julioluque/superhero
|
89465e0eaaf656abc82712e3928543f18c3e08c6
|
3b58edea51636b59efdef1c5f0767a5a2b188652
|
refs/heads/main
| 2023-06-02T15:17:48.206000 | 2021-06-15T19:14:17 | 2021-06-15T19:14:17 | 376,064,467 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.jluque.w2m.exception.custom;
public class FieldExistCustomException extends ConflictCustomException {
private static final long serialVersionUID = 1L;
private static final String DESCRIPTION = "Field Exist Exception";
public FieldExistCustomException(String detail) {
super(DESCRIPTION + ". " + detail);
}
}
|
UTF-8
|
Java
| 332 |
java
|
FieldExistCustomException.java
|
Java
|
[] | null |
[] |
package com.jluque.w2m.exception.custom;
public class FieldExistCustomException extends ConflictCustomException {
private static final long serialVersionUID = 1L;
private static final String DESCRIPTION = "Field Exist Exception";
public FieldExistCustomException(String detail) {
super(DESCRIPTION + ". " + detail);
}
}
| 332 | 0.78012 | 0.774096 | 13 | 24.538462 | 27.345694 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.846154 | false | false |
13
|
ae7cd332b221248e4cb22124ca0e1e988f3c609f
| 16,286,516,002,197 |
76219b16993e0b130a7bd1eb0acd7a7ae2503ddd
|
/business-service/src/main/java/me/mentoring/service/impl/BusinessServiceImpl.java
|
e83334bf78a89b411a66cc21184551822e15eeb6
|
[] |
no_license
|
AndreiRohau/parent
|
https://github.com/AndreiRohau/parent
|
8e7da96594b06cfe152bddb712ba324fa3af622f
|
18f7d3ec63e6c3e1f1f7b099d7b3ddeeb34084dc
|
refs/heads/master
| 2023-04-04T13:18:23.289000 | 2021-03-29T19:59:56 | 2021-03-29T19:59:56 | 352,758,553 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package me.mentoring.service.impl;
import me.mentoring.service.BusinessService;
import org.springframework.stereotype.Service;
@Service
public class BusinessServiceImpl implements BusinessService {
private static final String ENDING = "-TEST";
@Override
public String test(final String text) {
return text + ENDING;
}
}
|
UTF-8
|
Java
| 348 |
java
|
BusinessServiceImpl.java
|
Java
|
[] | null |
[] |
package me.mentoring.service.impl;
import me.mentoring.service.BusinessService;
import org.springframework.stereotype.Service;
@Service
public class BusinessServiceImpl implements BusinessService {
private static final String ENDING = "-TEST";
@Override
public String test(final String text) {
return text + ENDING;
}
}
| 348 | 0.747126 | 0.747126 | 15 | 22.200001 | 21.426464 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false |
13
|
0b1dad6523039c6af9ea7c5412ad65b6b308e6e0
| 6,923,487,284,326 |
9d8a5cf9ffc942a6d30f23de1706622322db42f9
|
/Project2/src/RGBtoCMYK.java
|
46bad7d5edb09fbeedc602700d0c81beb04b7490
|
[] |
no_license
|
huyviet1995/MCS-178
|
https://github.com/huyviet1995/MCS-178
|
631724018058b0de70fec1a0dcdd9be2740e7a6a
|
4ad8c2826d0ebc076dc06225f59774478d36cc3a
|
refs/heads/master
| 2021-01-10T10:14:13.784000 | 2016-01-27T15:38:42 | 2016-01-27T15:38:42 | 50,517,025 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class RGBtoCMYK {
/*Input values of the level of red, blue and green. Output the corresponding values of white
* cyan, magneta, yellow and black color based on the given formulae*/
public static void main(String[] args) {
double red=Integer.parseInt(args[0]);
double green=Integer.parseInt(args[1]);
double blue=Integer.parseInt(args[2]);
double white,cyan,magneta,yellow,black;
white=Math.max(red/255,Math.max(blue/255, green/255));
//If white is not equal to 0, assign the values of CMYB based on the formulae.
if (white!=0)
{
cyan=(white-red/255)/white;
magneta=(white-green/255)/white;
yellow=(white-blue/255)/white;
black=(1-white);
}
//if level of white is 0 then assign the values of cyan, magneta, yellow and black to be 0,0,0 and 1 respectively.
else
{
cyan=0.0;
magneta=0.0;
yellow=0.0;
black=1.0;
}
System.out.println("cyan = "+cyan+"\nmagneta = "+magneta+"\nyellow = "+yellow+"\nblack = "+black);
}
}
|
UTF-8
|
Java
| 1,008 |
java
|
RGBtoCMYK.java
|
Java
|
[] | null |
[] |
public class RGBtoCMYK {
/*Input values of the level of red, blue and green. Output the corresponding values of white
* cyan, magneta, yellow and black color based on the given formulae*/
public static void main(String[] args) {
double red=Integer.parseInt(args[0]);
double green=Integer.parseInt(args[1]);
double blue=Integer.parseInt(args[2]);
double white,cyan,magneta,yellow,black;
white=Math.max(red/255,Math.max(blue/255, green/255));
//If white is not equal to 0, assign the values of CMYB based on the formulae.
if (white!=0)
{
cyan=(white-red/255)/white;
magneta=(white-green/255)/white;
yellow=(white-blue/255)/white;
black=(1-white);
}
//if level of white is 0 then assign the values of cyan, magneta, yellow and black to be 0,0,0 and 1 respectively.
else
{
cyan=0.0;
magneta=0.0;
yellow=0.0;
black=1.0;
}
System.out.println("cyan = "+cyan+"\nmagneta = "+magneta+"\nyellow = "+yellow+"\nblack = "+black);
}
}
| 1,008 | 0.662698 | 0.625992 | 29 | 32.827587 | 31.593397 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.965517 | false | false |
13
|
e295052e2e59526eee1e1c3c4056d1facae08def
| 16,406,775,079,929 |
57d050a1ea481c4ed22174ca4ea30b3365a1d0ae
|
/SpringBoot/sampleProject/src/main/java/src/com/sample/sampleProject/SampleMain.java
|
219ad353ff3b0a387367a8e9a01291c89e043490
|
[] |
no_license
|
priynata/Learning
|
https://github.com/priynata/Learning
|
72d4c885b84edb25afc8176c50763c6d56abb43b
|
1bc697a167901bdcb70e4cb6824a6ddab83daa29
|
refs/heads/master
| 2022-12-29T15:14:52.177000 | 2020-10-16T08:34:57 | 2020-10-16T08:38:05 | 304,536,007 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package src.com.sample.sampleProject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Hello world!
*
*/
@SpringBootApplication
public class SampleMain {
@Autowired()
DemoController restController;
public static void main( String[] args )
{
SpringApplication.run(SampleMain.class, args);
System.out.println( "Hello World!" );
}
}
|
UTF-8
|
Java
| 508 |
java
|
SampleMain.java
|
Java
|
[] | null |
[] |
package src.com.sample.sampleProject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Hello world!
*
*/
@SpringBootApplication
public class SampleMain {
@Autowired()
DemoController restController;
public static void main( String[] args )
{
SpringApplication.run(SampleMain.class, args);
System.out.println( "Hello World!" );
}
}
| 508 | 0.744094 | 0.744094 | 23 | 20.173914 | 21.846603 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.73913 | false | false |
13
|
0a12c894395d3ecaad1988e3b8486a28dc021f5c
| 30,245,159,717,561 |
0b0a780c234892ab31d94e30738c9183e4bbc4be
|
/UD2/T8/Tarea8_ej7.java
|
85b969f8c0027678ae5ae2bafe4a0ce0b8c8aecc
|
[] |
no_license
|
Gabrielkarajallo/Programacion
|
https://github.com/Gabrielkarajallo/Programacion
|
5b2ea6a261e7a9a8bbf627dab64a4bcb64744bed
|
b8a6204309bed20d686cc576a707da1d65c31561
|
refs/heads/master
| 2023-01-02T08:38:22.722000 | 2020-10-29T17:06:57 | 2020-10-29T17:06:57 | 298,010,765 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package UD2.T8;
// Diseñar un programa que muestre el producto de los 10 primeros números impares.
public class Tarea8_ej7 {
public static void main(String[] args){
System.out.println("producto de los 10 primeros numeros impares");
double producto = 1.0D;
for(int i = 1; i < 10; i += 2) {
producto *= (double)i;
}
System.out.println("El producto de los 10 primeros impares es de: " + producto);
}
}
|
UTF-8
|
Java
| 464 |
java
|
Tarea8_ej7.java
|
Java
|
[] | null |
[] |
package UD2.T8;
// Diseñar un programa que muestre el producto de los 10 primeros números impares.
public class Tarea8_ej7 {
public static void main(String[] args){
System.out.println("producto de los 10 primeros numeros impares");
double producto = 1.0D;
for(int i = 1; i < 10; i += 2) {
producto *= (double)i;
}
System.out.println("El producto de los 10 primeros impares es de: " + producto);
}
}
| 464 | 0.619048 | 0.584416 | 15 | 29.799999 | 29.604504 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.466667 | false | false |
13
|
75add6cf19def2995fea072591aac3ac02589e23
| 35,338,990,930,187 |
8fa879e0db7e849c4439f5567385ca6184b8c7aa
|
/src/unitTesting/TestStringHandler.java
|
e02cb14f0cd31544ad179f4c36afcc50abd37d6f
|
[] |
no_license
|
kinosker/CS2103-CE2
|
https://github.com/kinosker/CS2103-CE2
|
37ce4fc919f0e6c9b8e1f421ce5c3ee009887cf4
|
414d66a9553bea920d7cc184b3a0a1dd129fe9d5
|
refs/heads/master
| 2021-05-27T14:12:12.758000 | 2014-09-18T05:59:37 | 2014-09-18T05:59:37 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package unitTesting;
import static org.junit.Assert.*;
import org.junit.Test;
import command.StringHandler;
public class TestStringHandler {
@Test
public void test() {
assertEquals("add", StringHandler.getFirstWord("add Pizza"));
assertEquals(null, StringHandler.getFirstWord(""));
assertEquals(null, StringHandler.getFirstWord(" "));
assertEquals(null, StringHandler.getFirstWord(null));
assertEquals("greedIsGood", StringHandler.getFirstWord("greedIsGood"));
assertEquals("Pig", StringHandler.getFirstWord("Pig is flying !!!"));
assertEquals("Pizza", StringHandler.removeFirstMatched("add Pizza", "add"));
assertEquals("pig eat me", StringHandler.removeFirstMatched("pig eat me","add"));
assertEquals("pig eat me", StringHandler.removeFirstMatched("pig eat me",null));
assertEquals(null, StringHandler.removeFirstMatched(null,"add"));
assertEquals(null, StringHandler.removeFirstMatched(null,null));
}
}
|
UTF-8
|
Java
| 1,049 |
java
|
TestStringHandler.java
|
Java
|
[] | null |
[] |
package unitTesting;
import static org.junit.Assert.*;
import org.junit.Test;
import command.StringHandler;
public class TestStringHandler {
@Test
public void test() {
assertEquals("add", StringHandler.getFirstWord("add Pizza"));
assertEquals(null, StringHandler.getFirstWord(""));
assertEquals(null, StringHandler.getFirstWord(" "));
assertEquals(null, StringHandler.getFirstWord(null));
assertEquals("greedIsGood", StringHandler.getFirstWord("greedIsGood"));
assertEquals("Pig", StringHandler.getFirstWord("Pig is flying !!!"));
assertEquals("Pizza", StringHandler.removeFirstMatched("add Pizza", "add"));
assertEquals("pig eat me", StringHandler.removeFirstMatched("pig eat me","add"));
assertEquals("pig eat me", StringHandler.removeFirstMatched("pig eat me",null));
assertEquals(null, StringHandler.removeFirstMatched(null,"add"));
assertEquals(null, StringHandler.removeFirstMatched(null,null));
}
}
| 1,049 | 0.678742 | 0.678742 | 29 | 35.172413 | 32.504715 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.068966 | false | false |
13
|
dc478d48b3d34d12040a6e0e366c85742c4e7c89
| 25,185,688,279,055 |
cb1673fff6f95f025a411df43d69e9bf2a9342bd
|
/src/com/PhoneMaker/PhoneComponentHandler.java
|
5218c2a8ab975ea6b52d5b97bc0689a3cabf8c54
|
[] |
no_license
|
AkshayRawalGoodOne/PhoneProductDesigner
|
https://github.com/AkshayRawalGoodOne/PhoneProductDesigner
|
15bfb48166fc8aa524f3b33972eaea4977d104cf
|
04661a18d0de962eee76024b54393bf0c99b022d
|
refs/heads/master
| 2020-03-27T19:30:28.942000 | 2018-08-31T15:22:18 | 2018-08-31T15:22:18 | 146,908,314 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.PhoneMaker;
import java.util.LinkedList;
import java.awt.Graphics;
public class PhoneComponentHandler {
protected LinkedList<PhoneComponent> CompHandler = new LinkedList<PhoneComponent>();
protected String HandlerName;
protected boolean selected;
protected boolean bought;
PhoneComponentHandler(String HandlerName)
{
setHandlerName(HandlerName);
selected = false;
}
void addComponent(PhoneComponent pcomp)
{
CompHandler.add(pcomp);
}
void removeComponent(PhoneComponent pcomp)
{
CompHandler.remove(pcomp);
}
void renderComponents(Graphics g)
{
for(int i = 0; i < CompHandler.size(); i++)
{
PhoneComponent comp = CompHandler.get(i);
comp.render(g);
}
}
public String getHandlerName() {
return HandlerName;
}
public void setHandlerName(String HandlerName) {
this.HandlerName = HandlerName;
}
}
|
UTF-8
|
Java
| 897 |
java
|
PhoneComponentHandler.java
|
Java
|
[] | null |
[] |
package com.PhoneMaker;
import java.util.LinkedList;
import java.awt.Graphics;
public class PhoneComponentHandler {
protected LinkedList<PhoneComponent> CompHandler = new LinkedList<PhoneComponent>();
protected String HandlerName;
protected boolean selected;
protected boolean bought;
PhoneComponentHandler(String HandlerName)
{
setHandlerName(HandlerName);
selected = false;
}
void addComponent(PhoneComponent pcomp)
{
CompHandler.add(pcomp);
}
void removeComponent(PhoneComponent pcomp)
{
CompHandler.remove(pcomp);
}
void renderComponents(Graphics g)
{
for(int i = 0; i < CompHandler.size(); i++)
{
PhoneComponent comp = CompHandler.get(i);
comp.render(g);
}
}
public String getHandlerName() {
return HandlerName;
}
public void setHandlerName(String HandlerName) {
this.HandlerName = HandlerName;
}
}
| 897 | 0.71126 | 0.710145 | 42 | 19.357143 | 19.201714 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.47619 | false | false |
13
|
c51d9c2573497de2037381d2ff46a92016d42cbe
| 34,548,716,950,474 |
43fb255e11cae0b8441bc15ca9ed63c8c44c0a1e
|
/src/main/java/winasia/eventbus/objectmessage/Sender.java
|
32316e5ea8f85bebd31a8f52bed90b4a58a8514e
|
[
"MIT"
] |
permissive
|
hz594556878/Winasia-Vert.x
|
https://github.com/hz594556878/Winasia-Vert.x
|
a2150cdcf6e0acc9acc0cb1ffc291cd4aa15ea47
|
0ca4ebc59abbd81922d03c44ebee748fabbf6b67
|
refs/heads/master
| 2020-12-31T00:30:37.894000 | 2017-03-30T01:24:18 | 2017-03-30T01:24:18 | 86,551,172 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package winasia.eventbus.objectmessage;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.VertxOptions;
import io.vertx.core.eventbus.EventBus;
import winasia.staticresource.StaticData;
import winasia.util.Runner;
/**
* Created by WinAsia on 2017/3/29.
*/
public class Sender extends AbstractVerticle {
public static void main(String[] args) {
Runner.runExample();
}
@Override
public void start() throws Exception {
EventBus eb = getVertx().eventBus();
eb.registerDefaultCodec(MessageEntity.class, new CustomMessageCodec());
MessageEntity entity = new MessageEntity();
entity.setName("zhong");
entity.setPwd("123");
eb.publish(StaticData.OBJECTADDRESS, entity);
}
}
|
UTF-8
|
Java
| 758 |
java
|
Sender.java
|
Java
|
[
{
"context": "ta;\nimport winasia.util.Runner;\n\n/**\n * Created by WinAsia on 2017/3/29.\n */\npublic class Sender extends Abs",
"end": 251,
"score": 0.9995797872543335,
"start": 244,
"tag": "USERNAME",
"value": "WinAsia"
},
{
"context": "ty = new MessageEntity();\n entity.setName(\"zhong\");\n entity.setPwd(\"123\");\n eb.publi",
"end": 662,
"score": 0.9101318120956421,
"start": 657,
"tag": "USERNAME",
"value": "zhong"
},
{
"context": " entity.setName(\"zhong\");\n entity.setPwd(\"123\");\n eb.publish(StaticData.OBJECTADDRESS, e",
"end": 692,
"score": 0.9992244243621826,
"start": 689,
"tag": "PASSWORD",
"value": "123"
}
] | null |
[] |
package winasia.eventbus.objectmessage;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.VertxOptions;
import io.vertx.core.eventbus.EventBus;
import winasia.staticresource.StaticData;
import winasia.util.Runner;
/**
* Created by WinAsia on 2017/3/29.
*/
public class Sender extends AbstractVerticle {
public static void main(String[] args) {
Runner.runExample();
}
@Override
public void start() throws Exception {
EventBus eb = getVertx().eventBus();
eb.registerDefaultCodec(MessageEntity.class, new CustomMessageCodec());
MessageEntity entity = new MessageEntity();
entity.setName("zhong");
entity.setPwd("123");
eb.publish(StaticData.OBJECTADDRESS, entity);
}
}
| 758 | 0.701847 | 0.688654 | 27 | 27.074074 | 20.884029 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false |
13
|
d1482d1fc98afe2b81ad7f0bdb2efde059177f97
| 18,519,899,033,647 |
a0cd546101594e679544d24f92ae8fcc17013142
|
/refactorit-netbeans/src/main/java/net/sf/refactorit/netbeans/common/vfs/NBSourcePath.java
|
6d9b4ae1dfecc1bb3940e9cdf435834e42acb9c0
|
[] |
no_license
|
svn2github/RefactorIT
|
https://github.com/svn2github/RefactorIT
|
f65198bb64f6c11e20d35ace5f9563d781b7fe5c
|
4b1fc1ebd06c8e192af9ccd94eb5c2d96f79f94c
|
refs/heads/master
| 2021-01-10T03:09:28.310000 | 2008-09-18T10:17:56 | 2008-09-18T10:17:56 | 47,540,746 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* Copyright 2001-2008 Aqris Software AS. All rights reserved.
*
* This program is dual-licensed under both the Common Development
* and Distribution License ("CDDL") and the GNU General Public
* License ("GPL"). You may elect to use one or the other of these
* licenses.
*/
package net.sf.refactorit.netbeans.common.vfs;
import net.sf.refactorit.common.util.WildcardPattern;
import net.sf.refactorit.loader.MultiFileChangeMonitor;
import net.sf.refactorit.netbeans.common.projectoptions.NBFileUtil;
import net.sf.refactorit.netbeans.common.projectoptions.PathItemReference;
import net.sf.refactorit.netbeans.common.projectoptions.PathUtil;
import net.sf.refactorit.vfs.AbstractSourcePath;
import net.sf.refactorit.vfs.FileChangeMonitor;
import net.sf.refactorit.vfs.Source;
import net.sf.refactorit.vfs.SourcePathFilter;
import net.sf.refactorit.vfs.local.LocalFileChangeMonitor;
import org.openide.filesystems.FileObject;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Implementation of SourcePath VFS for netbeans/forte
*
* @author Igor Malinin
*/
public class NBSourcePath extends AbstractSourcePath {
private static SourcePathFilter filter = new SourcePathFilter();
private WeakReference ideProjectRef;
public NBSourcePath(Object ideProject) {
this.ideProjectRef = new WeakReference(ideProject);
}
public WeakReference getIdeProjectReference() {
return ideProjectRef;
}
// public Object getIdeProject() {
// return null;
// }
public Source[] getAutodetectedElements() {
final Object ideProject = ideProjectRef.get();
if(ideProject == null) {
return new Source[]{};
} else {
return getSourcesFromFileObjects(PathUtil.getInstance()
.getAutodetectedSourcepath(ideProject, false));
}
}
public void setValidExtensions(String[] extensions) {
super.setValidExtensions(extensions);
NBFileUtil.setValidExtensions(extensions); // set valid extensions for
// static NB filters also
}
public FileChangeMonitor getFileChangeMonitor() {
if (fileChangeMonitor == null) {
final PathItemReference[] paths;
final Object ideProject = ideProjectRef.get();
if(ideProject != null) {
paths = PathUtil.getInstance().getSourcepath(ideProject);
} else {
paths = new PathItemReference[]{};
}
List nbPaths = new ArrayList();
boolean localFound = false;
for (int i = 0; i < paths.length; i++) {
if (paths[i].isFileObject()) {
nbPaths.add(paths[i].getFileObject());
} else {
localFound = true;
}
}
NBFileChangeMonitor m1 = new NBFileChangeMonitor(this,
(FileObject[]) nbPaths.toArray(new FileObject[0]));
if (localFound) {
HashSet currentLocalSources = new HashSet(200);
collectLocalSources(currentLocalSources);
LocalFileChangeMonitor m2 = new LocalFileChangeMonitor(
currentLocalSources) {
protected void collectSources(Collection result) {
collectLocalSources(result);
}
};
fileChangeMonitor = new MultiFileChangeMonitor(new FileChangeMonitor[]{
m1, m2});
} else {
fileChangeMonitor = m1;
}
}
return fileChangeMonitor;
}
void collectLocalSources(Collection result) {
final Object ideProject = ideProjectRef.get();
if (ideProject == null) {
return;
}
PathItemReference[] paths = PathUtil.getInstance().getSourcepath(
ideProject);
PathUtil.IgnoreListFilter filter = PathUtil.getInstance()
.getIgnoreListFilter(ideProject);
for (int i = 0; i < paths.length; i++) {
if (paths[i].isValid() && paths[i].isLocalFile()) {
iterateDirectory(paths[i].getSource(), result, filter, null);
}
}
}
public Source[] getRootSources() {
final Object ideProject = ideProjectRef.get();
if(ideProject == null) {
return new Source[] {};
}
PathItemReference[] items = PathUtil.getInstance().getSourcepath(ideProject);
return getSourcesFromFileObjects(items);
}
public List getIgnoredSources() {
final Object ideProject = ideProjectRef.get();
if(ideProject == null) {
return new ArrayList(0);
}
PathItemReference[] items = PathUtil.getInstance().getIgnoredSourceDirectories(ideProject);
List result = new ArrayList();
for (int i = 0; i < items.length; i++) {
result.add(items[i].getAbsolutePath());
}
return result;
}
private Source[] getSourcesFromFileObjects(
PathItemReference[] pathItemReferences) {
final Object ideProject = ideProjectRef.get();
if(ideProject == null) {
return new Source[] {};
}
PathUtil.IgnoreListFilter filter = PathUtil.getInstance()
.getIgnoreListFilter(ideProject);
List sources = new ArrayList(pathItemReferences.length);
for (int i = 0; i < pathItemReferences.length; i++) {
if (pathItemReferences[i].isValid()) {
Source source = pathItemReferences[i].getSource();
// Checking entire filesystem at a time here
if (!filter.inIgnoreList(source)
&& (source.isFile() || source.isDirectory())) {
sources.add(source);
}
}
}
return (Source[]) sources.toArray(new Source[sources.size()]);
}
public List getAllSources() {
return getAllSources(null);
}
public List getAllSources(WildcardPattern[] patterns) {
final Object ideProject = ideProjectRef.get();
if(ideProject == null) {
return new ArrayList(0);
}
PathUtil.IgnoreListFilter ignoreListFilter = PathUtil.getInstance()
.getIgnoreListFilter(ideProject);
filter.initialize();
ArrayList result = new ArrayList(200);
Source[] sources = getRootSources();
for (int i = 0; i < sources.length; ++i) {
iterateDirectory(sources[i], result, ignoreListFilter, patterns);
}
// FIXME: it should be slow, better filter out original paths
final Set uniqueSourcesSet = new HashSet();
uniqueSourcesSet.addAll(result);
final List uniqueSources = new ArrayList(uniqueSourcesSet.size());
uniqueSources.addAll(uniqueSourcesSet);
return uniqueSources;
}
void iterateDirectory(Source parent, Collection result,
PathUtil.IgnoreListFilter filter, WildcardPattern[] patterns) {
if (!parent.isDirectory()) {
return;
}
Source children[] = parent.getChildren();
if (children == null) {
return;
}
for (int i = 0; i < children.length; ++i) {
Source curSource = children[i];
if (curSource.isFile() && fileInSourcepath(curSource, patterns)) {
result.add(curSource);
} else if (curSource.isDirectory()
&& shouldIterateInto(curSource, filter)) {
iterateDirectory(curSource, result, filter, patterns);
}
}
}
void collectDirectories(FileObject parent, Set result,
PathUtil.IgnoreListFilter filter) {
if (shouldIterateInto(NBSource.getSource(parent), filter)) {
result.add(parent);
Enumeration e = parent.getFolders(true);
while (e.hasMoreElements()) {
FileObject dir = (FileObject) e.nextElement();
if (shouldIterateInto(NBSource.getSource(dir), filter)) {
result.add(dir);
}
}
}
}
/** Note: does not check parent folders */
boolean fileInSourcepath(Source file, WildcardPattern[] patterns) {
if (patterns == null) {
return fileAcceptedByName(file);
} else {
return fileAcceptedByPattern(file.getName(), patterns);
}
}
/** Note: does not check parent folders */
boolean shouldIterateInto(Source folder, PathUtil.IgnoreListFilter filter) {
boolean result = directoryAcceptedByName(folder)
&& (!filter.inIgnoreList(folder));
return result;
}
boolean fileAcceptedByName(Source file) {
if (file == null) {
return false;
}
return isValidSource(file.getName());
}
private boolean directoryAcceptedByName(Source folder) {
return filter.acceptDirectoryByName(folder.getName().toLowerCase());
}
public boolean sourceAcceptedIfNotIgnored(Source source) {
if (source.isFile()) {
return fileAcceptedByName(source);
} else {
return directoryAcceptedByName(source);
}
}
public List getNonJavaSources(WildcardPattern[] patterns) {
return getAllSources(patterns);
}
}
|
UTF-8
|
Java
| 8,931 |
java
|
NBSourcePath.java
|
Java
|
[
{
"context": " SourcePath VFS for netbeans/forte\r\n *\r\n * @author Igor Malinin\r\n */\r\npublic class NBSourcePath extends AbstractSou",
"end": 1253,
"score": 0.9944804906845093,
"start": 1241,
"tag": "NAME",
"value": "Igor Malinin"
}
] | null |
[] |
/*
* Copyright 2001-2008 Aqris Software AS. All rights reserved.
*
* This program is dual-licensed under both the Common Development
* and Distribution License ("CDDL") and the GNU General Public
* License ("GPL"). You may elect to use one or the other of these
* licenses.
*/
package net.sf.refactorit.netbeans.common.vfs;
import net.sf.refactorit.common.util.WildcardPattern;
import net.sf.refactorit.loader.MultiFileChangeMonitor;
import net.sf.refactorit.netbeans.common.projectoptions.NBFileUtil;
import net.sf.refactorit.netbeans.common.projectoptions.PathItemReference;
import net.sf.refactorit.netbeans.common.projectoptions.PathUtil;
import net.sf.refactorit.vfs.AbstractSourcePath;
import net.sf.refactorit.vfs.FileChangeMonitor;
import net.sf.refactorit.vfs.Source;
import net.sf.refactorit.vfs.SourcePathFilter;
import net.sf.refactorit.vfs.local.LocalFileChangeMonitor;
import org.openide.filesystems.FileObject;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Implementation of SourcePath VFS for netbeans/forte
*
* @author <NAME>
*/
public class NBSourcePath extends AbstractSourcePath {
private static SourcePathFilter filter = new SourcePathFilter();
private WeakReference ideProjectRef;
public NBSourcePath(Object ideProject) {
this.ideProjectRef = new WeakReference(ideProject);
}
public WeakReference getIdeProjectReference() {
return ideProjectRef;
}
// public Object getIdeProject() {
// return null;
// }
public Source[] getAutodetectedElements() {
final Object ideProject = ideProjectRef.get();
if(ideProject == null) {
return new Source[]{};
} else {
return getSourcesFromFileObjects(PathUtil.getInstance()
.getAutodetectedSourcepath(ideProject, false));
}
}
public void setValidExtensions(String[] extensions) {
super.setValidExtensions(extensions);
NBFileUtil.setValidExtensions(extensions); // set valid extensions for
// static NB filters also
}
public FileChangeMonitor getFileChangeMonitor() {
if (fileChangeMonitor == null) {
final PathItemReference[] paths;
final Object ideProject = ideProjectRef.get();
if(ideProject != null) {
paths = PathUtil.getInstance().getSourcepath(ideProject);
} else {
paths = new PathItemReference[]{};
}
List nbPaths = new ArrayList();
boolean localFound = false;
for (int i = 0; i < paths.length; i++) {
if (paths[i].isFileObject()) {
nbPaths.add(paths[i].getFileObject());
} else {
localFound = true;
}
}
NBFileChangeMonitor m1 = new NBFileChangeMonitor(this,
(FileObject[]) nbPaths.toArray(new FileObject[0]));
if (localFound) {
HashSet currentLocalSources = new HashSet(200);
collectLocalSources(currentLocalSources);
LocalFileChangeMonitor m2 = new LocalFileChangeMonitor(
currentLocalSources) {
protected void collectSources(Collection result) {
collectLocalSources(result);
}
};
fileChangeMonitor = new MultiFileChangeMonitor(new FileChangeMonitor[]{
m1, m2});
} else {
fileChangeMonitor = m1;
}
}
return fileChangeMonitor;
}
void collectLocalSources(Collection result) {
final Object ideProject = ideProjectRef.get();
if (ideProject == null) {
return;
}
PathItemReference[] paths = PathUtil.getInstance().getSourcepath(
ideProject);
PathUtil.IgnoreListFilter filter = PathUtil.getInstance()
.getIgnoreListFilter(ideProject);
for (int i = 0; i < paths.length; i++) {
if (paths[i].isValid() && paths[i].isLocalFile()) {
iterateDirectory(paths[i].getSource(), result, filter, null);
}
}
}
public Source[] getRootSources() {
final Object ideProject = ideProjectRef.get();
if(ideProject == null) {
return new Source[] {};
}
PathItemReference[] items = PathUtil.getInstance().getSourcepath(ideProject);
return getSourcesFromFileObjects(items);
}
public List getIgnoredSources() {
final Object ideProject = ideProjectRef.get();
if(ideProject == null) {
return new ArrayList(0);
}
PathItemReference[] items = PathUtil.getInstance().getIgnoredSourceDirectories(ideProject);
List result = new ArrayList();
for (int i = 0; i < items.length; i++) {
result.add(items[i].getAbsolutePath());
}
return result;
}
private Source[] getSourcesFromFileObjects(
PathItemReference[] pathItemReferences) {
final Object ideProject = ideProjectRef.get();
if(ideProject == null) {
return new Source[] {};
}
PathUtil.IgnoreListFilter filter = PathUtil.getInstance()
.getIgnoreListFilter(ideProject);
List sources = new ArrayList(pathItemReferences.length);
for (int i = 0; i < pathItemReferences.length; i++) {
if (pathItemReferences[i].isValid()) {
Source source = pathItemReferences[i].getSource();
// Checking entire filesystem at a time here
if (!filter.inIgnoreList(source)
&& (source.isFile() || source.isDirectory())) {
sources.add(source);
}
}
}
return (Source[]) sources.toArray(new Source[sources.size()]);
}
public List getAllSources() {
return getAllSources(null);
}
public List getAllSources(WildcardPattern[] patterns) {
final Object ideProject = ideProjectRef.get();
if(ideProject == null) {
return new ArrayList(0);
}
PathUtil.IgnoreListFilter ignoreListFilter = PathUtil.getInstance()
.getIgnoreListFilter(ideProject);
filter.initialize();
ArrayList result = new ArrayList(200);
Source[] sources = getRootSources();
for (int i = 0; i < sources.length; ++i) {
iterateDirectory(sources[i], result, ignoreListFilter, patterns);
}
// FIXME: it should be slow, better filter out original paths
final Set uniqueSourcesSet = new HashSet();
uniqueSourcesSet.addAll(result);
final List uniqueSources = new ArrayList(uniqueSourcesSet.size());
uniqueSources.addAll(uniqueSourcesSet);
return uniqueSources;
}
void iterateDirectory(Source parent, Collection result,
PathUtil.IgnoreListFilter filter, WildcardPattern[] patterns) {
if (!parent.isDirectory()) {
return;
}
Source children[] = parent.getChildren();
if (children == null) {
return;
}
for (int i = 0; i < children.length; ++i) {
Source curSource = children[i];
if (curSource.isFile() && fileInSourcepath(curSource, patterns)) {
result.add(curSource);
} else if (curSource.isDirectory()
&& shouldIterateInto(curSource, filter)) {
iterateDirectory(curSource, result, filter, patterns);
}
}
}
void collectDirectories(FileObject parent, Set result,
PathUtil.IgnoreListFilter filter) {
if (shouldIterateInto(NBSource.getSource(parent), filter)) {
result.add(parent);
Enumeration e = parent.getFolders(true);
while (e.hasMoreElements()) {
FileObject dir = (FileObject) e.nextElement();
if (shouldIterateInto(NBSource.getSource(dir), filter)) {
result.add(dir);
}
}
}
}
/** Note: does not check parent folders */
boolean fileInSourcepath(Source file, WildcardPattern[] patterns) {
if (patterns == null) {
return fileAcceptedByName(file);
} else {
return fileAcceptedByPattern(file.getName(), patterns);
}
}
/** Note: does not check parent folders */
boolean shouldIterateInto(Source folder, PathUtil.IgnoreListFilter filter) {
boolean result = directoryAcceptedByName(folder)
&& (!filter.inIgnoreList(folder));
return result;
}
boolean fileAcceptedByName(Source file) {
if (file == null) {
return false;
}
return isValidSource(file.getName());
}
private boolean directoryAcceptedByName(Source folder) {
return filter.acceptDirectoryByName(folder.getName().toLowerCase());
}
public boolean sourceAcceptedIfNotIgnored(Source source) {
if (source.isFile()) {
return fileAcceptedByName(source);
} else {
return directoryAcceptedByName(source);
}
}
public List getNonJavaSources(WildcardPattern[] patterns) {
return getAllSources(patterns);
}
}
| 8,925 | 0.647968 | 0.644833 | 296 | 28.172297 | 24.31912 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.469595 | false | false |
13
|
b4d82befc50f660966a091f21a050b6b79344a2b
| 15,101,105,048,615 |
ede2acb0c3cce3cfae9df6980a38b34350cc9610
|
/sidc-sits-logical/src/main/java/com/sidc/sits/logical/shopping/ShoppingVendorProcess.java
|
25055b45fc9468e8680b90014d3a729d47f4f663
|
[] |
no_license
|
lmydayuldd/si
|
https://github.com/lmydayuldd/si
|
dd7032588c31cae5c0823a66cc0f84ac85695b4c
|
10272687acae512fa08b42d3f1cb8eaef38bca33
|
refs/heads/master
| 2021-05-14T11:38:14.003000 | 2017-09-15T12:28:28 | 2017-09-15T12:28:28 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.sidc.sits.logical.shopping;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import com.sidc.blackcore.api.sits.shop.request.ShoppingVendorRequest;
import com.sidc.blackcore.api.sits.shop.response.ShoppingVendorResponse;
import com.sidc.common.framework.abs.AbstractAPIProcess;
import com.sidc.dao.sits.manager.ShopManager;
import com.sidc.utils.exception.SiDCException;
import com.sidc.utils.log.LogAction;
import com.sidc.utils.status.APIStatus;
/**
*
* @author Joe
*
*/
public class ShoppingVendorProcess extends AbstractAPIProcess {
private final ShoppingVendorRequest entity;
private final String STEP = "2";
public ShoppingVendorProcess(final ShoppingVendorRequest entity) {
// TODO Auto-generated constructor stub
this.entity = entity;
}
@Override
protected void init() throws SiDCException, Exception {
// TODO Auto-generated method stub
LogAction.getInstance().debug("Request:" + entity);
}
@Override
protected Object process() throws SiDCException, Exception {
int status = -1;
String langCode = null;
switch (entity.getStatus()) {
case "enable":
status = 1;
break;
case "disable":
status = 0;
break;
}
switch (entity.getLangcode()) {
case "all":
break;
default:
langCode = entity.getLangcode();
break;
}
LogAction.getInstance().debug("step 1/" + STEP + " :format request parameter success.");
List<ShoppingVendorResponse> list = new ArrayList<ShoppingVendorResponse>();
if (StringUtils.isBlank(entity.getVendorname())) {
list = ShopManager.getInstance().selectVendor(entity.getVendorid(), status, langCode);
} else {
list = ShopManager.getInstance().selectVendor(entity.getVendorid(), status, entity.getVendorname(),
langCode);
}
LogAction.getInstance().debug("step 2/" + STEP + " :select success(ShopManager|selectItem).");
/*
for (ShoppingVendorResponse responseEntity : list) {
switch (responseEntity.getStatus()) {
case "1":
responseEntity.setStatus("enable");
break;
case "0":
responseEntity.setStatus("disable");
break;
}
}
LogAction.getInstance().debug("step 3/" + STEP + ":transform status success.");
*/
return list;
}
@Override
protected void check() throws SiDCException, Exception {
// TODO Auto-generated method stub
if (entity == null) {
throw new SiDCException(APIStatus.ILLEGAL_ARGUMENT, "illegal of request.");
}
if (entity.getVendorid() < 0) {
throw new SiDCException(APIStatus.ILLEGAL_ARGUMENT, "illegal of request(category id).");
}
if (StringUtils.isBlank(entity.getLangcode())) {
throw new SiDCException(APIStatus.ILLEGAL_ARGUMENT, "illegal of request(langcode).");
}
if (StringUtils.isBlank(entity.getStatus())) {
throw new SiDCException(APIStatus.ILLEGAL_ARGUMENT, "illegal of request(status).");
}
if (!StringUtils.isBlank(entity.getVendorname())) {
if (entity.getLangcode().equals("all")) {
throw new SiDCException(APIStatus.ILLEGAL_ARGUMENT,
"illegal of request(search vendor name ,lange code can not all).");
}
}
}
}
|
UTF-8
|
Java
| 3,109 |
java
|
ShoppingVendorProcess.java
|
Java
|
[
{
"context": "m.sidc.utils.status.APIStatus;\n\n/**\n * \n * @author Joe\n *\n */\npublic class ShoppingVendorProcess extends",
"end": 533,
"score": 0.998526930809021,
"start": 530,
"tag": "NAME",
"value": "Joe"
}
] | null |
[] |
package com.sidc.sits.logical.shopping;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import com.sidc.blackcore.api.sits.shop.request.ShoppingVendorRequest;
import com.sidc.blackcore.api.sits.shop.response.ShoppingVendorResponse;
import com.sidc.common.framework.abs.AbstractAPIProcess;
import com.sidc.dao.sits.manager.ShopManager;
import com.sidc.utils.exception.SiDCException;
import com.sidc.utils.log.LogAction;
import com.sidc.utils.status.APIStatus;
/**
*
* @author Joe
*
*/
public class ShoppingVendorProcess extends AbstractAPIProcess {
private final ShoppingVendorRequest entity;
private final String STEP = "2";
public ShoppingVendorProcess(final ShoppingVendorRequest entity) {
// TODO Auto-generated constructor stub
this.entity = entity;
}
@Override
protected void init() throws SiDCException, Exception {
// TODO Auto-generated method stub
LogAction.getInstance().debug("Request:" + entity);
}
@Override
protected Object process() throws SiDCException, Exception {
int status = -1;
String langCode = null;
switch (entity.getStatus()) {
case "enable":
status = 1;
break;
case "disable":
status = 0;
break;
}
switch (entity.getLangcode()) {
case "all":
break;
default:
langCode = entity.getLangcode();
break;
}
LogAction.getInstance().debug("step 1/" + STEP + " :format request parameter success.");
List<ShoppingVendorResponse> list = new ArrayList<ShoppingVendorResponse>();
if (StringUtils.isBlank(entity.getVendorname())) {
list = ShopManager.getInstance().selectVendor(entity.getVendorid(), status, langCode);
} else {
list = ShopManager.getInstance().selectVendor(entity.getVendorid(), status, entity.getVendorname(),
langCode);
}
LogAction.getInstance().debug("step 2/" + STEP + " :select success(ShopManager|selectItem).");
/*
for (ShoppingVendorResponse responseEntity : list) {
switch (responseEntity.getStatus()) {
case "1":
responseEntity.setStatus("enable");
break;
case "0":
responseEntity.setStatus("disable");
break;
}
}
LogAction.getInstance().debug("step 3/" + STEP + ":transform status success.");
*/
return list;
}
@Override
protected void check() throws SiDCException, Exception {
// TODO Auto-generated method stub
if (entity == null) {
throw new SiDCException(APIStatus.ILLEGAL_ARGUMENT, "illegal of request.");
}
if (entity.getVendorid() < 0) {
throw new SiDCException(APIStatus.ILLEGAL_ARGUMENT, "illegal of request(category id).");
}
if (StringUtils.isBlank(entity.getLangcode())) {
throw new SiDCException(APIStatus.ILLEGAL_ARGUMENT, "illegal of request(langcode).");
}
if (StringUtils.isBlank(entity.getStatus())) {
throw new SiDCException(APIStatus.ILLEGAL_ARGUMENT, "illegal of request(status).");
}
if (!StringUtils.isBlank(entity.getVendorname())) {
if (entity.getLangcode().equals("all")) {
throw new SiDCException(APIStatus.ILLEGAL_ARGUMENT,
"illegal of request(search vendor name ,lange code can not all).");
}
}
}
}
| 3,109 | 0.717272 | 0.713734 | 108 | 27.787037 | 28.179995 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.12963 | false | false |
13
|
571f89baab30a8d565c3072b99bd3944eb827ad7
| 15,101,105,046,879 |
052efb5c7d5179a810fb5ecdc9361b7a3082fd1d
|
/WorkKing/app/src/main/java/com/example/asus/workking/ViewPageFragment/TestFragment.java
|
28a55c018fada97fa4b32dc13eab73354fabf30f
|
[] |
no_license
|
Vikingweirdo/WordKing_Demo
|
https://github.com/Vikingweirdo/WordKing_Demo
|
34a35ee3aac295ccf8fc98203e187742469a9a57
|
e5e3c0b07585f06434fa06e9d3d6a106a0810af9
|
refs/heads/master
| 2021-01-20T00:10:53.251000 | 2017-09-01T13:52:54 | 2017-09-01T13:52:54 | 83,795,101 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.asus.workking.ViewPageFragment;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;
import com.example.asus.workking.GameModel.Listening;
import com.example.asus.workking.GameModel.Pictures;
import com.example.asus.workking.GameModel.Spelling;
import com.example.asus.workking.GameModel.Translation;
import com.example.asus.workking.MainActivity;
import com.example.asus.workking.R;
import com.example.asus.workking.Tools.RandomModel;
import com.example.asus.workking.Tools.Record;
import com.example.asus.workking.Tools.Words;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Created by asus on 2017/2/7.
*/
public class TestFragment extends Fragment implements View.OnClickListener{
private String mTitle = "Defult";
public final static String TITLE = "tilte";
private ImageButton mPictures = null;
private ImageButton mListent = null;
private ImageButton mTranslate = null;
private ImageButton mSpell = null;
private Intent mIntent = null;
private String mTempName = null;//用来保存游戏进度即将要读的表
private int bookNum = 1 ; //默认第一本书
private String[] mTabKey = {
"First1A",
"Second2A",
"Third3A",
"Fourth4A",
"Fifth5A",
"Sixth6A",
"Seventh7A",
"eighth8A",
"First1B",
"Second2B",
"Third3B",
"Fourth4B",
"Fifth5B",
"Sixth6B",
"Seventh7B",
"eighth8B"
}; //所有表的key
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
if(getArguments() != null){
mTitle = getArguments().getString(TITLE);
}
//设置Fragment布局
View view = inflater.inflate(R.layout.testpage, container, false);
initView(view);
return view;
}
private void initView(View view) {
this.mListent = (ImageButton)view.findViewById(R.id.listening);
this.mSpell = (ImageButton)view.findViewById(R.id.spelling);
this.mTranslate = (ImageButton)view.findViewById(R.id.translation);
this.mPictures = (ImageButton)view.findViewById(R.id.pictures);
this.mListent.setOnClickListener(this);
this.mSpell.setOnClickListener(this);
this.mTranslate.setOnClickListener(this);
this.mPictures.setOnClickListener(this);
getTableKey(); //获取游戏记录中的表的key名字
}
//获取Key
private void getTableKey() {
SharedPreferences sharePreference = getActivity().getSharedPreferences(MainActivity.GAMEPROSS,
Activity.MODE_PRIVATE); //获取操作对象
this.mTempName = sharePreference.getString("record_unit","First1A");
this.bookNum = sharePreference.getInt("record_book",1);
setTable();//设置要查询的表
}
private void setTable() {
String file = null;
SharedPreferences sharePre = null;
switch (this.bookNum){
case 1:
file = "book1";
sharePre = getActivity().getSharedPreferences(file,Activity.MODE_PRIVATE);
MainActivity.TABLENAME = sharePre.getString(mTempName,"First1A");
break;
case 2:
file = "book2";
sharePre = getActivity().getSharedPreferences(file,Activity.MODE_PRIVATE);
MainActivity.TABLENAME = sharePre.getString(mTempName,"First1A");
break;
case 3:
file = "book3";
sharePre = getActivity().getSharedPreferences(file,Activity.MODE_PRIVATE);
MainActivity.TABLENAME = sharePre.getString(mTempName,"First1A");
break;
case 4:
file = "book4";
sharePre = getActivity().getSharedPreferences(file,Activity.MODE_PRIVATE);
MainActivity.TABLENAME = sharePre.getString(mTempName,"First1A");
break;
}
}
@Override
public void onClick(View view) {
Record.mGamePross= 1;
Record.mWordCount = Words.getBook1_1A_words().length;//获取所有单词数
RandomModel.mWordCount = Words.getBook1_1A_words().length;//获取所有单词数
switch (view.getId()){
case R.id.listening:
this.mIntent = new Intent(getActivity(), Listening.class);
Bundle bundle = new Bundle();
bundle.putInt("modleFlag",0x111); //判断是否是测试模式
mIntent.putExtras(bundle);
startActivity(mIntent);
getActivity().overridePendingTransition(R.anim.in_anim, R.anim.out_anim);
getActivity().finish();
break;
case R.id.spelling:
this.mIntent = new Intent(getActivity(), Spelling.class);
Bundle bundle1 = new Bundle();
bundle1.putInt("modleFlag",0x111); //判断是否是测试模式
mIntent.putExtras(bundle1);
startActivity(mIntent);
getActivity().overridePendingTransition(R.anim.in_anim, R.anim.out_anim);
getActivity().finish();
break;
case R.id.pictures:
this.mIntent = new Intent(getActivity(), Pictures.class);
Bundle bundle2 = new Bundle();
bundle2.putInt("modleFlag",0x111); //判断是否是测试模式
mIntent.putExtras(bundle2);
startActivity(mIntent);
getActivity().overridePendingTransition(R.anim.in_anim, R.anim.out_anim);
getActivity().finish();
break;
case R.id.translation:
this.mIntent = new Intent(getActivity(), Translation.class);
Bundle bundle3 = new Bundle();
bundle3.putInt("modleFlag",0x111); //判断是否是测试模式
mIntent.putExtras(bundle3);
startActivity(mIntent);
getActivity().overridePendingTransition(R.anim.in_anim, R.anim.out_anim);
getActivity().finish();
break;
}
}
}
|
UTF-8
|
Java
| 6,875 |
java
|
TestFragment.java
|
Java
|
[
{
"context": "til.List;\nimport java.util.Map;\n\n/**\n * Created by asus on 2017/2/7.\n */\n\npublic class TestFragment exten",
"end": 1167,
"score": 0.9609297513961792,
"start": 1163,
"tag": "USERNAME",
"value": "asus"
}
] | null |
[] |
package com.example.asus.workking.ViewPageFragment;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;
import com.example.asus.workking.GameModel.Listening;
import com.example.asus.workking.GameModel.Pictures;
import com.example.asus.workking.GameModel.Spelling;
import com.example.asus.workking.GameModel.Translation;
import com.example.asus.workking.MainActivity;
import com.example.asus.workking.R;
import com.example.asus.workking.Tools.RandomModel;
import com.example.asus.workking.Tools.Record;
import com.example.asus.workking.Tools.Words;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Created by asus on 2017/2/7.
*/
public class TestFragment extends Fragment implements View.OnClickListener{
private String mTitle = "Defult";
public final static String TITLE = "tilte";
private ImageButton mPictures = null;
private ImageButton mListent = null;
private ImageButton mTranslate = null;
private ImageButton mSpell = null;
private Intent mIntent = null;
private String mTempName = null;//用来保存游戏进度即将要读的表
private int bookNum = 1 ; //默认第一本书
private String[] mTabKey = {
"First1A",
"Second2A",
"Third3A",
"Fourth4A",
"Fifth5A",
"Sixth6A",
"Seventh7A",
"eighth8A",
"First1B",
"Second2B",
"Third3B",
"Fourth4B",
"Fifth5B",
"Sixth6B",
"Seventh7B",
"eighth8B"
}; //所有表的key
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
if(getArguments() != null){
mTitle = getArguments().getString(TITLE);
}
//设置Fragment布局
View view = inflater.inflate(R.layout.testpage, container, false);
initView(view);
return view;
}
private void initView(View view) {
this.mListent = (ImageButton)view.findViewById(R.id.listening);
this.mSpell = (ImageButton)view.findViewById(R.id.spelling);
this.mTranslate = (ImageButton)view.findViewById(R.id.translation);
this.mPictures = (ImageButton)view.findViewById(R.id.pictures);
this.mListent.setOnClickListener(this);
this.mSpell.setOnClickListener(this);
this.mTranslate.setOnClickListener(this);
this.mPictures.setOnClickListener(this);
getTableKey(); //获取游戏记录中的表的key名字
}
//获取Key
private void getTableKey() {
SharedPreferences sharePreference = getActivity().getSharedPreferences(MainActivity.GAMEPROSS,
Activity.MODE_PRIVATE); //获取操作对象
this.mTempName = sharePreference.getString("record_unit","First1A");
this.bookNum = sharePreference.getInt("record_book",1);
setTable();//设置要查询的表
}
private void setTable() {
String file = null;
SharedPreferences sharePre = null;
switch (this.bookNum){
case 1:
file = "book1";
sharePre = getActivity().getSharedPreferences(file,Activity.MODE_PRIVATE);
MainActivity.TABLENAME = sharePre.getString(mTempName,"First1A");
break;
case 2:
file = "book2";
sharePre = getActivity().getSharedPreferences(file,Activity.MODE_PRIVATE);
MainActivity.TABLENAME = sharePre.getString(mTempName,"First1A");
break;
case 3:
file = "book3";
sharePre = getActivity().getSharedPreferences(file,Activity.MODE_PRIVATE);
MainActivity.TABLENAME = sharePre.getString(mTempName,"First1A");
break;
case 4:
file = "book4";
sharePre = getActivity().getSharedPreferences(file,Activity.MODE_PRIVATE);
MainActivity.TABLENAME = sharePre.getString(mTempName,"First1A");
break;
}
}
@Override
public void onClick(View view) {
Record.mGamePross= 1;
Record.mWordCount = Words.getBook1_1A_words().length;//获取所有单词数
RandomModel.mWordCount = Words.getBook1_1A_words().length;//获取所有单词数
switch (view.getId()){
case R.id.listening:
this.mIntent = new Intent(getActivity(), Listening.class);
Bundle bundle = new Bundle();
bundle.putInt("modleFlag",0x111); //判断是否是测试模式
mIntent.putExtras(bundle);
startActivity(mIntent);
getActivity().overridePendingTransition(R.anim.in_anim, R.anim.out_anim);
getActivity().finish();
break;
case R.id.spelling:
this.mIntent = new Intent(getActivity(), Spelling.class);
Bundle bundle1 = new Bundle();
bundle1.putInt("modleFlag",0x111); //判断是否是测试模式
mIntent.putExtras(bundle1);
startActivity(mIntent);
getActivity().overridePendingTransition(R.anim.in_anim, R.anim.out_anim);
getActivity().finish();
break;
case R.id.pictures:
this.mIntent = new Intent(getActivity(), Pictures.class);
Bundle bundle2 = new Bundle();
bundle2.putInt("modleFlag",0x111); //判断是否是测试模式
mIntent.putExtras(bundle2);
startActivity(mIntent);
getActivity().overridePendingTransition(R.anim.in_anim, R.anim.out_anim);
getActivity().finish();
break;
case R.id.translation:
this.mIntent = new Intent(getActivity(), Translation.class);
Bundle bundle3 = new Bundle();
bundle3.putInt("modleFlag",0x111); //判断是否是测试模式
mIntent.putExtras(bundle3);
startActivity(mIntent);
getActivity().overridePendingTransition(R.anim.in_anim, R.anim.out_anim);
getActivity().finish();
break;
}
}
}
| 6,875 | 0.616354 | 0.606001 | 191 | 33.895287 | 25.81366 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.795812 | false | false |
13
|
b58839f46805e3cc773db8e202fba6438abb9cc9
| 36,962,488,555,185 |
12112b2429575f1a26cd6bdf23fccc1a59ef9f8a
|
/Users/MFOUNDOU MICHAEL/OpenClassrooms-master/Android/Entrevoisins/app/src/androidTest/java/com/openclassrooms/entrevoisins/ui/neighbour_list/ListNeighbourActivityTest.java
|
a78976f829fe49759938cbd7e5f78e7f12495cd9
|
[] |
no_license
|
Loussemo78/Michael2
|
https://github.com/Loussemo78/Michael2
|
4e5a79006c3607aca1b1e6d875fcfcb35fdca577
|
f79fae5bc1f178abce1e4e3f8121d43e9cadca00
|
refs/heads/master
| 2022-10-30T05:45:51.128000 | 2020-06-11T21:44:19 | 2020-06-11T21:44:19 | 257,067,231 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.openclassrooms.entrevoisins.ui.neighbour_list;
import android.support.test.espresso.ViewInteraction;
import android.support.test.filters.LargeTest;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import com.openclassrooms.entrevoisins.R;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.contrib.RecyclerViewActions.actionOnItemAtPosition;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.core.AllOf.allOf;
@LargeTest
@RunWith(AndroidJUnit4.class)
public class ListNeighbourActivityTest {
@Rule
public ActivityTestRule<ListNeighbourActivity> mActivityTestRule = new ActivityTestRule<>(ListNeighbourActivity.class);
@Test
public void listNeighbourActivityTest() {
onView(allOf(withId(R.id.list_neighbours),isDisplayed())).perform(actionOnItemAtPosition(0,click()));
onView(withId(R.id.txtTitre)).check(matches(withText("Caroline")));
}
}
|
UTF-8
|
Java
| 1,529 |
java
|
ListNeighbourActivityTest.java
|
Java
|
[
{
"context": "ew(withId(R.id.txtTitre)).check(matches(withText(\"Caroline\")));\n\n }\n\n\n}\n",
"end": 1512,
"score": 0.9910163879394531,
"start": 1504,
"tag": "NAME",
"value": "Caroline"
}
] | null |
[] |
package com.openclassrooms.entrevoisins.ui.neighbour_list;
import android.support.test.espresso.ViewInteraction;
import android.support.test.filters.LargeTest;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import com.openclassrooms.entrevoisins.R;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.contrib.RecyclerViewActions.actionOnItemAtPosition;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.core.AllOf.allOf;
@LargeTest
@RunWith(AndroidJUnit4.class)
public class ListNeighbourActivityTest {
@Rule
public ActivityTestRule<ListNeighbourActivity> mActivityTestRule = new ActivityTestRule<>(ListNeighbourActivity.class);
@Test
public void listNeighbourActivityTest() {
onView(allOf(withId(R.id.list_neighbours),isDisplayed())).perform(actionOnItemAtPosition(0,click()));
onView(withId(R.id.txtTitre)).check(matches(withText("Caroline")));
}
}
| 1,529 | 0.814912 | 0.81295 | 45 | 32.977779 | 33.336327 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false |
13
|
82a5ad28951de65632156dd6c1dac2a8dfb21959
| 36,962,488,554,191 |
0ac4adda66cdfd992a1cbda68ab52c6c4cedd594
|
/app/src/main/java/com/fujinbang/ui/activity/MissionDetailActivity.java
|
99c3fa35bb65861f6fc4806af6e77ee31a13b261
|
[] |
no_license
|
fujinbang/FuJInBang
|
https://github.com/fujinbang/FuJInBang
|
aea2456a97209c748a75b7a2760cefc35d299d1f
|
34ed94c1d1a27a5cbc7182a397a12527111b319d
|
refs/heads/master
| 2021-01-09T20:37:08.338000 | 2016-07-10T13:41:52 | 2016-07-10T13:41:52 | 62,877,342 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.fujinbang.ui.activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.fujinbang.R;
import com.fujinbang.global.IMController;
import com.fujinbang.global.MissionDetail;
import com.fujinbang.global.SimpleDataBase;
import com.fujinbang.global.TimeCalculator;
import com.fujinbang.internet.HttpConnRequest;
import com.fujinbang.internet.UrlConstant;
import com.fujinbang.seekhelp.MediaManager;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.widget.CircleTransform;
import org.json.JSONObject;
import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by VITO on 2016/5/18.
* 任务详情界面
*/
public class MissionDetailActivity extends BaseActivity implements View.OnClickListener{
protected static String dir = Environment.getExternalStorageDirectory()+"/fujinbang_vido";
protected static String pushFinish = "您发布的任务已有参与者确认完成,请确认";
protected static String pushDrop = "已有用户放弃您的任务,请确认";
protected ImageView mission_detail_back,announcer_img;
protected TextView announcer_name,txt_desc,start_time,end_time,rest_time,urge,status,bonus,add_bonus,item1_txt,item2_txt;
protected GridLayout attender_list;
protected RelativeLayout item1,item2,item3,item4;
protected int mMinWidth;
protected int mMaxWidth;
protected View animView;
protected FrameLayout play_sound;
protected TextView record_time;
private boolean isAnnouncer;
private String myToken;
private String myid;
HashMap<String, Object> mission;
String announcer;
String announcerId;
List<String> attenders = new ArrayList<>();
List<Integer> attendersId = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mission_detail);
Intent it = this.getIntent();
announcer = it.getExtras().getString("announcer");
announcerId = it.getExtras().getString("announcerId");
attenders = it.getExtras().getStringArrayList("attenders");
attendersId = it.getExtras().getIntegerArrayList("attendersId");
mission = MissionDetail.getInstance().getMission(it.getExtras().getInt("groupPosition"));
isAnnouncer = mission.containsKey("isAnnouncer");
SimpleDataBase simpleDataBase = new SimpleDataBase(this);
myToken = simpleDataBase.getToken();
myid = String.valueOf(simpleDataBase.getClientId());
initView();
}
private void initView() {
mission_detail_back = (ImageView) findViewById(R.id.mission_detail_back);
announcer_img = (ImageView) findViewById(R.id.mission_detail_announcer_img);
announcer_name = (TextView) findViewById(R.id.mission_detail_announcer_name);
attender_list = (GridLayout)findViewById(R.id.mission_detail_attender_list);
txt_desc = (TextView) findViewById(R.id.mission_detail_txt_desc);
start_time = (TextView) findViewById(R.id.mission_detail_starttime);
end_time = (TextView) findViewById(R.id.mission_detail_endtime);
rest_time = (TextView) findViewById(R.id.mission_detail_rest_time);
urge = (TextView) findViewById(R.id.mission_detail_urge);
status = (TextView) findViewById(R.id.mission_detail_status);
bonus = (TextView) findViewById(R.id.mission_detail_bonus);
add_bonus = (TextView) findViewById(R.id.mission_detail_add_bonus);
item1 = (RelativeLayout) findViewById(R.id.mission_detail_item1);
item2 = (RelativeLayout) findViewById(R.id.mission_detail_item2);
item3 = (RelativeLayout) findViewById(R.id.mission_detail_item3);
item4 = (RelativeLayout) findViewById(R.id.mission_detail_item4);
item1_txt = (TextView) findViewById(R.id.mission_detail_item1_txt);
item2_txt = (TextView) findViewById(R.id.mission_detail_item2_txt);
record_time = (TextView) findViewById(R.id.mission_detail_recoder_time);
play_sound = (FrameLayout) findViewById(R.id.mission_detail_recoder_lenght);
animView = findViewById(R.id.mission_detail_recoder_anim);
mission_detail_back.setOnClickListener(this);
item1.setOnClickListener(this);
item2.setOnClickListener(this);
item3.setOnClickListener(this);
item4.setOnClickListener(this);
txt_desc.setText(mission.get("desc").toString());
start_time.setText(mission.get("start_time").toString());
end_time.setText(mission.get("end_time").toString());
bonus.setText(mission.get("bonus").toString());
if (isAnnouncer){
item1_txt.setText("确认完成任务");
item2_txt.setText("取消任务");
urge.setVisibility(View.VISIBLE);
add_bonus.setVisibility(View.VISIBLE);
urge.setOnClickListener(this);
add_bonus.setOnClickListener(this);
} else {
item1_txt.setText("完成任务");
item2_txt.setText("放弃任务");
urge.setVisibility(View.GONE);
add_bonus.setVisibility(View.GONE);
}
//加载昵称与头像
initNickAndAvatar();
if (mission.containsKey("voicelength")){
WindowManager wm = (WindowManager) MissionDetailActivity.this.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
mMaxWidth = (int) (outMetrics.widthPixels * 0.4f);
mMinWidth = (int) (outMetrics.widthPixels * 0.15f);
ViewGroup.LayoutParams lp = play_sound.getLayoutParams();
lp.width = (int) (mMinWidth + (mMaxWidth / 60f) * Integer.parseInt(mission.get("voicelength").toString()));
animView.setBackgroundResource(R.drawable.adj);
txt_desc.setVisibility(View.GONE);
play_sound.setVisibility(View.VISIBLE);
record_time.setVisibility(View.VISIBLE);
record_time.setText(mission.get("voicelength") + "\"");
play_sound.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//播放帧动画
animView.setBackgroundResource(R.drawable.play_anim);
AnimationDrawable animation = (AnimationDrawable) animView.getBackground();
animation.start();
//播放录音
MediaManager.playSound(MissionDetailActivity.this, new File(dir, mission.get("helpid").toString()+".aac").getAbsolutePath(), new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
//停止播放帧动画
animView.setBackgroundResource(R.drawable.adj);
MediaManager.release();
}
});
}
});
}
}
private void initAvatar(String avatar, ImageView imageView){
Glide.with(this)
.load(avatar)
.placeholder(R.drawable.integration)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.transform(new CircleTransform(this))
.into(imageView);
}
private void addViewToGridLayout(String nick, String avatar){
View view = View.inflate(MissionDetailActivity.this, R.layout.item_information, null);
TextView txt = (TextView) view.findViewById(R.id.item_information_name);
ImageView img = (ImageView) view.findViewById(R.id.item_information_img);
txt.setText(nick);
initAvatar(avatar, img);
attender_list.addView(view);
}
private void initNickAndAvatar() {
EaseUser easeUser = IMController.getInstance().getUserInfo(announcer);
announcer_name.setText(easeUser.getNick());
initAvatar(easeUser.getAvatar(), announcer_img);
for (int i = 0;i < attenders.size();i++){
EaseUser easeAttender = IMController.getInstance().getUserInfo(attenders.get(i));
addViewToGridLayout(easeAttender.getNick(), easeAttender.getAvatar());
}
}
public static void startActivity(Context context, int groupPosition, String announcer, ArrayList<String> attenders, ArrayList<Integer> attendersId, String announcerId) {
Intent intent = new Intent(context, MissionDetailActivity.class);
intent.putExtra("groupPosition", groupPosition);
intent.putExtra("announcer", announcer);
intent.putExtra("announcerId", announcerId);
intent.putStringArrayListExtra("attenders", attenders);
intent.putIntegerArrayListExtra("attendersId", attendersId);
context.startActivity(intent);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.mission_detail_back:
finish();
break;
case R.id.mission_detail_urge:
//催促接单者
for (int i = 1;i<attendersId.size();i++){
urgeAttender(attendersId.get(i).toString());
}
break;
case R.id.mission_detail_add_bonus:
//追加奖励
showCustomDia();
break;
case R.id.mission_detail_item1:
if (isAnnouncer){
MissionDetail.missionFinished(myToken, mission.get("helpid").toString(), myid);
} else {
pushMessage(pushFinish, "1", announcerId);
}
break;
case R.id.mission_detail_item2:
//放弃任务
if (isAnnouncer){
pushMessage(pushDrop, "0", null);
} else {
pushMessage(pushDrop, "0", announcerId);
}
break;
case R.id.mission_detail_item3:
//联系客服
FeedbackPhonecallActivity.startActivity(MissionDetailActivity.this);
break;
case R.id.mission_detail_item4:
//举报
FeedbackOnlineActivity.startActivity(MissionDetailActivity.this, true);
break;
default:
break;
}
}
AlertDialog dialog;
private void showCustomDia()
{
AlertDialog.Builder builder = new AlertDialog.Builder(MissionDetailActivity.this, R.style.AudioDialog);
View viewDia= LayoutInflater.from(MissionDetailActivity.this).inflate(R.layout.dialog_add_bonus, null);
builder.setView(viewDia);
final EditText bonus = (EditText) viewDia.findViewById(R.id.dialog_bonus);
Button submit = (Button) viewDia.findViewById(R.id.dialog_submit);
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addBonus(bonus.getText().toString());
if (dialog != null && dialog.isShowing()) dialog.dismiss();
}
});
builder.create();
dialog = builder.show();
}
private void addBonus(String bonus) {
new AsyncTask<String, Integer, String>() {
@Override
protected String doInBackground(String... params) {
String result = null;
try{
JSONObject obj = new JSONObject();
obj.put("token",params[0]);
obj.put("target",Integer.parseInt(params[1]));
obj.put("bonus",Integer.parseInt(params[2]));
result = HttpConnRequest.request(UrlConstant.transferBonus,"POST",obj);
}catch (Exception e){e.printStackTrace();}
return result;
}
@Override
protected void onPostExecute(String result){
if (result!=null){
try{
JSONObject obj = new JSONObject(result);
if (obj.has("code") && obj.getInt("code") == 1){
Toast.makeText(MissionDetailActivity.this,"追加奖励成功!",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MissionDetailActivity.this,"追加奖励失败!",Toast.LENGTH_SHORT).show();
}
}catch (Exception e){e.printStackTrace();}
}
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, myToken, mission.get("helpid").toString(), bonus);
}
protected void pushMessage(String message, String type, String userid){
Toast.makeText(MissionDetailActivity.this,"请稍候...",Toast.LENGTH_SHORT).show();
new AsyncTask<String, Integer, String>() {
@Override
protected String doInBackground(String... params) {
String result = null;
try{
JSONObject obj = new JSONObject();
obj.put("token",params[0]);
obj.put("push_message", params[1]);
obj.put("message", params[2]+","+mission.get("helpid").toString()+","+params[4]);
if (params[3] == null){
obj.put("helpinfoid",Integer.parseInt(mission.get("helpid").toString()));
} else {
obj.put("targetuserid", Integer.parseInt(params[3]));
}
result = HttpConnRequest.request(UrlConstant.transMission,"POST",obj);
}catch (Exception e){e.printStackTrace();}
return result;
}
@Override
protected void onPostExecute(String result){
if (result!=null){
try{
JSONObject obj = new JSONObject(result);
if (obj.getInt("code") == 1){
Toast.makeText(MissionDetailActivity.this,"操作成功,等待对方确认",Toast.LENGTH_SHORT).show();
Intent it = new Intent(MissionDetailActivity.this, MainActivity.class);
it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(it);
}
}catch (Exception e){e.printStackTrace();}
}
}
}.execute(myToken, message, type, userid, myid);
}
int urgeCount = 0;
protected void urgeAttender(String targetid){
new AsyncTask<String, Integer, String>() {
@Override
protected String doInBackground(String... params) {
String result = null;
try{
JSONObject obj = new JSONObject();
obj.put("token",params[0]);
obj.put("helpid",Integer.parseInt(params[1]));
obj.put("targetuser",Integer.parseInt(params[2]));
result = HttpConnRequest.request(UrlConstant.urgeAttender,"POST",obj);
}catch (Exception e){e.printStackTrace();}
return result;
}
@Override
protected void onPostExecute(String result){
if (result!=null){
try{
JSONObject obj = new JSONObject(result);
if (obj.has("code") && obj.getInt("code") == 1){
urgeCount++;
Toast.makeText(MissionDetailActivity.this,"已催促"+ urgeCount +"位接单者",Toast.LENGTH_SHORT).show();
//if (urgeCount == attenderId.size()){
// urgeCount = 0;
//}
}
}catch (Exception e){e.printStackTrace();}
}
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, myToken, mission.get("helpid").toString(), targetid);
}
DecimalFormat df = new DecimalFormat("00");
protected boolean isFinished;
protected Handler missionDetailTimeHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
if (msg.what ==1) {
Log.e("ccc","handle还在跑");
long second = TimeCalculator.getRestTime(mission.get("end_time").toString());
rest_time.setText(second / 3600 + ":" + df.format(second % 3600 / 60) + ":" + df.format(second % 3600 % 60));
if (second / 3600 < 24 && second > 0 && rest_time.getCurrentTextColor()!=0xffff0000){
rest_time.setTextColor(0xffff0000);
}
if (second == 0){
isFinished = true;
}
if (!isFinished){
missionDetailTimeHandler.sendEmptyMessageDelayed(1,1000);
} else {
status.setText("已结束");
}
}
}
};
@Override
public void onPause(){
super.onPause();
isFinished = true;
}
@Override
public void onResume(){
super.onResume();
isFinished = false;
missionDetailTimeHandler.sendEmptyMessageDelayed(1, 1000);
}
}
|
UTF-8
|
Java
| 18,379 |
java
|
MissionDetailActivity.java
|
Java
|
[
{
"context": "HashMap;\nimport java.util.List;\n\n/**\n * Created by VITO on 2016/5/18.\n * 任务详情界面\n */\npublic class MissionD",
"end": 1511,
"score": 0.9984374046325684,
"start": 1507,
"tag": "USERNAME",
"value": "VITO"
}
] | null |
[] |
package com.fujinbang.ui.activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.fujinbang.R;
import com.fujinbang.global.IMController;
import com.fujinbang.global.MissionDetail;
import com.fujinbang.global.SimpleDataBase;
import com.fujinbang.global.TimeCalculator;
import com.fujinbang.internet.HttpConnRequest;
import com.fujinbang.internet.UrlConstant;
import com.fujinbang.seekhelp.MediaManager;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.widget.CircleTransform;
import org.json.JSONObject;
import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by VITO on 2016/5/18.
* 任务详情界面
*/
public class MissionDetailActivity extends BaseActivity implements View.OnClickListener{
protected static String dir = Environment.getExternalStorageDirectory()+"/fujinbang_vido";
protected static String pushFinish = "您发布的任务已有参与者确认完成,请确认";
protected static String pushDrop = "已有用户放弃您的任务,请确认";
protected ImageView mission_detail_back,announcer_img;
protected TextView announcer_name,txt_desc,start_time,end_time,rest_time,urge,status,bonus,add_bonus,item1_txt,item2_txt;
protected GridLayout attender_list;
protected RelativeLayout item1,item2,item3,item4;
protected int mMinWidth;
protected int mMaxWidth;
protected View animView;
protected FrameLayout play_sound;
protected TextView record_time;
private boolean isAnnouncer;
private String myToken;
private String myid;
HashMap<String, Object> mission;
String announcer;
String announcerId;
List<String> attenders = new ArrayList<>();
List<Integer> attendersId = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mission_detail);
Intent it = this.getIntent();
announcer = it.getExtras().getString("announcer");
announcerId = it.getExtras().getString("announcerId");
attenders = it.getExtras().getStringArrayList("attenders");
attendersId = it.getExtras().getIntegerArrayList("attendersId");
mission = MissionDetail.getInstance().getMission(it.getExtras().getInt("groupPosition"));
isAnnouncer = mission.containsKey("isAnnouncer");
SimpleDataBase simpleDataBase = new SimpleDataBase(this);
myToken = simpleDataBase.getToken();
myid = String.valueOf(simpleDataBase.getClientId());
initView();
}
private void initView() {
mission_detail_back = (ImageView) findViewById(R.id.mission_detail_back);
announcer_img = (ImageView) findViewById(R.id.mission_detail_announcer_img);
announcer_name = (TextView) findViewById(R.id.mission_detail_announcer_name);
attender_list = (GridLayout)findViewById(R.id.mission_detail_attender_list);
txt_desc = (TextView) findViewById(R.id.mission_detail_txt_desc);
start_time = (TextView) findViewById(R.id.mission_detail_starttime);
end_time = (TextView) findViewById(R.id.mission_detail_endtime);
rest_time = (TextView) findViewById(R.id.mission_detail_rest_time);
urge = (TextView) findViewById(R.id.mission_detail_urge);
status = (TextView) findViewById(R.id.mission_detail_status);
bonus = (TextView) findViewById(R.id.mission_detail_bonus);
add_bonus = (TextView) findViewById(R.id.mission_detail_add_bonus);
item1 = (RelativeLayout) findViewById(R.id.mission_detail_item1);
item2 = (RelativeLayout) findViewById(R.id.mission_detail_item2);
item3 = (RelativeLayout) findViewById(R.id.mission_detail_item3);
item4 = (RelativeLayout) findViewById(R.id.mission_detail_item4);
item1_txt = (TextView) findViewById(R.id.mission_detail_item1_txt);
item2_txt = (TextView) findViewById(R.id.mission_detail_item2_txt);
record_time = (TextView) findViewById(R.id.mission_detail_recoder_time);
play_sound = (FrameLayout) findViewById(R.id.mission_detail_recoder_lenght);
animView = findViewById(R.id.mission_detail_recoder_anim);
mission_detail_back.setOnClickListener(this);
item1.setOnClickListener(this);
item2.setOnClickListener(this);
item3.setOnClickListener(this);
item4.setOnClickListener(this);
txt_desc.setText(mission.get("desc").toString());
start_time.setText(mission.get("start_time").toString());
end_time.setText(mission.get("end_time").toString());
bonus.setText(mission.get("bonus").toString());
if (isAnnouncer){
item1_txt.setText("确认完成任务");
item2_txt.setText("取消任务");
urge.setVisibility(View.VISIBLE);
add_bonus.setVisibility(View.VISIBLE);
urge.setOnClickListener(this);
add_bonus.setOnClickListener(this);
} else {
item1_txt.setText("完成任务");
item2_txt.setText("放弃任务");
urge.setVisibility(View.GONE);
add_bonus.setVisibility(View.GONE);
}
//加载昵称与头像
initNickAndAvatar();
if (mission.containsKey("voicelength")){
WindowManager wm = (WindowManager) MissionDetailActivity.this.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
mMaxWidth = (int) (outMetrics.widthPixels * 0.4f);
mMinWidth = (int) (outMetrics.widthPixels * 0.15f);
ViewGroup.LayoutParams lp = play_sound.getLayoutParams();
lp.width = (int) (mMinWidth + (mMaxWidth / 60f) * Integer.parseInt(mission.get("voicelength").toString()));
animView.setBackgroundResource(R.drawable.adj);
txt_desc.setVisibility(View.GONE);
play_sound.setVisibility(View.VISIBLE);
record_time.setVisibility(View.VISIBLE);
record_time.setText(mission.get("voicelength") + "\"");
play_sound.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//播放帧动画
animView.setBackgroundResource(R.drawable.play_anim);
AnimationDrawable animation = (AnimationDrawable) animView.getBackground();
animation.start();
//播放录音
MediaManager.playSound(MissionDetailActivity.this, new File(dir, mission.get("helpid").toString()+".aac").getAbsolutePath(), new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
//停止播放帧动画
animView.setBackgroundResource(R.drawable.adj);
MediaManager.release();
}
});
}
});
}
}
private void initAvatar(String avatar, ImageView imageView){
Glide.with(this)
.load(avatar)
.placeholder(R.drawable.integration)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.transform(new CircleTransform(this))
.into(imageView);
}
private void addViewToGridLayout(String nick, String avatar){
View view = View.inflate(MissionDetailActivity.this, R.layout.item_information, null);
TextView txt = (TextView) view.findViewById(R.id.item_information_name);
ImageView img = (ImageView) view.findViewById(R.id.item_information_img);
txt.setText(nick);
initAvatar(avatar, img);
attender_list.addView(view);
}
private void initNickAndAvatar() {
EaseUser easeUser = IMController.getInstance().getUserInfo(announcer);
announcer_name.setText(easeUser.getNick());
initAvatar(easeUser.getAvatar(), announcer_img);
for (int i = 0;i < attenders.size();i++){
EaseUser easeAttender = IMController.getInstance().getUserInfo(attenders.get(i));
addViewToGridLayout(easeAttender.getNick(), easeAttender.getAvatar());
}
}
public static void startActivity(Context context, int groupPosition, String announcer, ArrayList<String> attenders, ArrayList<Integer> attendersId, String announcerId) {
Intent intent = new Intent(context, MissionDetailActivity.class);
intent.putExtra("groupPosition", groupPosition);
intent.putExtra("announcer", announcer);
intent.putExtra("announcerId", announcerId);
intent.putStringArrayListExtra("attenders", attenders);
intent.putIntegerArrayListExtra("attendersId", attendersId);
context.startActivity(intent);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.mission_detail_back:
finish();
break;
case R.id.mission_detail_urge:
//催促接单者
for (int i = 1;i<attendersId.size();i++){
urgeAttender(attendersId.get(i).toString());
}
break;
case R.id.mission_detail_add_bonus:
//追加奖励
showCustomDia();
break;
case R.id.mission_detail_item1:
if (isAnnouncer){
MissionDetail.missionFinished(myToken, mission.get("helpid").toString(), myid);
} else {
pushMessage(pushFinish, "1", announcerId);
}
break;
case R.id.mission_detail_item2:
//放弃任务
if (isAnnouncer){
pushMessage(pushDrop, "0", null);
} else {
pushMessage(pushDrop, "0", announcerId);
}
break;
case R.id.mission_detail_item3:
//联系客服
FeedbackPhonecallActivity.startActivity(MissionDetailActivity.this);
break;
case R.id.mission_detail_item4:
//举报
FeedbackOnlineActivity.startActivity(MissionDetailActivity.this, true);
break;
default:
break;
}
}
AlertDialog dialog;
private void showCustomDia()
{
AlertDialog.Builder builder = new AlertDialog.Builder(MissionDetailActivity.this, R.style.AudioDialog);
View viewDia= LayoutInflater.from(MissionDetailActivity.this).inflate(R.layout.dialog_add_bonus, null);
builder.setView(viewDia);
final EditText bonus = (EditText) viewDia.findViewById(R.id.dialog_bonus);
Button submit = (Button) viewDia.findViewById(R.id.dialog_submit);
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addBonus(bonus.getText().toString());
if (dialog != null && dialog.isShowing()) dialog.dismiss();
}
});
builder.create();
dialog = builder.show();
}
private void addBonus(String bonus) {
new AsyncTask<String, Integer, String>() {
@Override
protected String doInBackground(String... params) {
String result = null;
try{
JSONObject obj = new JSONObject();
obj.put("token",params[0]);
obj.put("target",Integer.parseInt(params[1]));
obj.put("bonus",Integer.parseInt(params[2]));
result = HttpConnRequest.request(UrlConstant.transferBonus,"POST",obj);
}catch (Exception e){e.printStackTrace();}
return result;
}
@Override
protected void onPostExecute(String result){
if (result!=null){
try{
JSONObject obj = new JSONObject(result);
if (obj.has("code") && obj.getInt("code") == 1){
Toast.makeText(MissionDetailActivity.this,"追加奖励成功!",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MissionDetailActivity.this,"追加奖励失败!",Toast.LENGTH_SHORT).show();
}
}catch (Exception e){e.printStackTrace();}
}
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, myToken, mission.get("helpid").toString(), bonus);
}
protected void pushMessage(String message, String type, String userid){
Toast.makeText(MissionDetailActivity.this,"请稍候...",Toast.LENGTH_SHORT).show();
new AsyncTask<String, Integer, String>() {
@Override
protected String doInBackground(String... params) {
String result = null;
try{
JSONObject obj = new JSONObject();
obj.put("token",params[0]);
obj.put("push_message", params[1]);
obj.put("message", params[2]+","+mission.get("helpid").toString()+","+params[4]);
if (params[3] == null){
obj.put("helpinfoid",Integer.parseInt(mission.get("helpid").toString()));
} else {
obj.put("targetuserid", Integer.parseInt(params[3]));
}
result = HttpConnRequest.request(UrlConstant.transMission,"POST",obj);
}catch (Exception e){e.printStackTrace();}
return result;
}
@Override
protected void onPostExecute(String result){
if (result!=null){
try{
JSONObject obj = new JSONObject(result);
if (obj.getInt("code") == 1){
Toast.makeText(MissionDetailActivity.this,"操作成功,等待对方确认",Toast.LENGTH_SHORT).show();
Intent it = new Intent(MissionDetailActivity.this, MainActivity.class);
it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(it);
}
}catch (Exception e){e.printStackTrace();}
}
}
}.execute(myToken, message, type, userid, myid);
}
int urgeCount = 0;
protected void urgeAttender(String targetid){
new AsyncTask<String, Integer, String>() {
@Override
protected String doInBackground(String... params) {
String result = null;
try{
JSONObject obj = new JSONObject();
obj.put("token",params[0]);
obj.put("helpid",Integer.parseInt(params[1]));
obj.put("targetuser",Integer.parseInt(params[2]));
result = HttpConnRequest.request(UrlConstant.urgeAttender,"POST",obj);
}catch (Exception e){e.printStackTrace();}
return result;
}
@Override
protected void onPostExecute(String result){
if (result!=null){
try{
JSONObject obj = new JSONObject(result);
if (obj.has("code") && obj.getInt("code") == 1){
urgeCount++;
Toast.makeText(MissionDetailActivity.this,"已催促"+ urgeCount +"位接单者",Toast.LENGTH_SHORT).show();
//if (urgeCount == attenderId.size()){
// urgeCount = 0;
//}
}
}catch (Exception e){e.printStackTrace();}
}
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, myToken, mission.get("helpid").toString(), targetid);
}
DecimalFormat df = new DecimalFormat("00");
protected boolean isFinished;
protected Handler missionDetailTimeHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
if (msg.what ==1) {
Log.e("ccc","handle还在跑");
long second = TimeCalculator.getRestTime(mission.get("end_time").toString());
rest_time.setText(second / 3600 + ":" + df.format(second % 3600 / 60) + ":" + df.format(second % 3600 % 60));
if (second / 3600 < 24 && second > 0 && rest_time.getCurrentTextColor()!=0xffff0000){
rest_time.setTextColor(0xffff0000);
}
if (second == 0){
isFinished = true;
}
if (!isFinished){
missionDetailTimeHandler.sendEmptyMessageDelayed(1,1000);
} else {
status.setText("已结束");
}
}
}
};
@Override
public void onPause(){
super.onPause();
isFinished = true;
}
@Override
public void onResume(){
super.onResume();
isFinished = false;
missionDetailTimeHandler.sendEmptyMessageDelayed(1, 1000);
}
}
| 18,379 | 0.5939 | 0.587657 | 420 | 42.092857 | 29.127853 | 185 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.82381 | false | false |
13
|
9033e4ad442d4b5dc9036b9cad92403a6d92022c
| 26,946,624,873,948 |
4f4c8a86b26cbe8287c3466ace649015d2e1917f
|
/Liza0.2/src/Liza/LizaProjectile.java
|
dc3c2d790d34b64b5952b913308ae722c5c0815f
|
[] |
no_license
|
geislekj/Liza
|
https://github.com/geislekj/Liza
|
d3372d3c18bc862261ed469a3985926dfeb9334a
|
bbfbcc70237c59c1723f165a8c70813dd3993df2
|
refs/heads/master
| 2021-01-10T22:00:02.959000 | 2012-05-11T03:33:32 | 2012-05-11T03:33:32 | 2,616,422 | 3 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Liza;
import org.bukkit.entity.Projectile;
/**
* LizaProjectile is the Liza interface representation of
* the Bukkit Projectile interface.
*
* @author geislekj
*/
public interface LizaProjectile extends Projectile{
}
|
UTF-8
|
Java
| 237 |
java
|
LizaProjectile.java
|
Java
|
[
{
"context": "* the Bukkit Projectile interface.\n * \n * @author geislekj\n */\npublic interface LizaProjectile extends Proje",
"end": 177,
"score": 0.9995783567428589,
"start": 169,
"tag": "USERNAME",
"value": "geislekj"
}
] | null |
[] |
package Liza;
import org.bukkit.entity.Projectile;
/**
* LizaProjectile is the Liza interface representation of
* the Bukkit Projectile interface.
*
* @author geislekj
*/
public interface LizaProjectile extends Projectile{
}
| 237 | 0.751055 | 0.751055 | 14 | 15.928572 | 19.933691 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.142857 | false | false |
13
|
da1a2754d7cd2df3cde345111590db9477d2aa66
| 29,454,885,772,860 |
14ba89d545d118d09ffaa232939810f97b60f7b6
|
/spring-kata/src/main/java/io/erenkaya/akaldiroglu/_02_example/CalculatorApplication.java
|
85464bdb11e9e4f8153cb60b9dd68aded27d28fe
|
[] |
no_license
|
ErenKaya/code-practices
|
https://github.com/ErenKaya/code-practices
|
dc48ec896d50af6b9dfa88764b7bcba93f8c6d88
|
c21373e6c5a79fd535d1e84270de335f02f9d65a
|
refs/heads/master
| 2022-10-17T22:04:30.331000 | 2022-10-10T03:29:07 | 2022-10-10T03:29:07 | 132,752,781 | 5 | 1 | null | false | 2022-08-01T10:45:05 | 2018-05-09T12:21:17 | 2021-05-31T13:28:41 | 2022-08-01T10:44:24 | 54,535 | 3 | 1 | 0 |
Java
| false | false |
package io.erenkaya.akaldiroglu._02_example;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import io.erenkaya.akaldiroglu._01_example.domain.GreetingRenderer;
public class CalculatorApplication {
public static void main(String[] args) {
String path = "bean1.xml";
ApplicationContext factory = new ClassPathXmlApplicationContext(path);
Calculator calculator = (Calculator) factory.getBean("calculator");
System.out.println(calculator.doCalculation("Sin", 2 * Math.PI * 30 / 360));
System.out.println(calculator.doCalculation("Cos", 2 * Math.PI * 30 / 360));
System.out.println(calculator.doCalculation("Log", 2.71828));
}
}
|
UTF-8
|
Java
| 724 |
java
|
CalculatorApplication.java
|
Java
|
[] | null |
[] |
package io.erenkaya.akaldiroglu._02_example;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import io.erenkaya.akaldiroglu._01_example.domain.GreetingRenderer;
public class CalculatorApplication {
public static void main(String[] args) {
String path = "bean1.xml";
ApplicationContext factory = new ClassPathXmlApplicationContext(path);
Calculator calculator = (Calculator) factory.getBean("calculator");
System.out.println(calculator.doCalculation("Sin", 2 * Math.PI * 30 / 360));
System.out.println(calculator.doCalculation("Cos", 2 * Math.PI * 30 / 360));
System.out.println(calculator.doCalculation("Log", 2.71828));
}
}
| 724 | 0.779006 | 0.747238 | 17 | 41.588234 | 29.962837 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.588235 | false | false |
13
|
f1a0f1f70cbd52b2e4bc5d880142ac0d58cf94fe
| 34,754,875,396,231 |
5d4f06c9c83dd05ef34f3df5207cd4922478f7bd
|
/core/src/com/coffeede/editor/MenuScreen.java
|
d9e9797ce6e57a6db71c64877eeeffd3cee3416a
|
[] |
no_license
|
Ckle/qwerty
|
https://github.com/Ckle/qwerty
|
eee8ae8b90378a0ea2fa7c12bca87f40c96b43f2
|
a4e62da3f794eb5488c15f03ee1add2632704baf
|
refs/heads/master
| 2021-01-18T11:34:10.143000 | 2014-10-12T00:52:26 | 2014-10-12T00:52:26 | 23,484,248 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.coffeede.editor;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.coffeede.engine.screen.BaseScreen;
import com.coffeede.game.QwertyGame;
/**
* @author Byron
*/
public class MenuScreen extends BaseScreen {
protected final EditScreen editScreen;
protected final FileScreen fileScreen;
public MenuScreen(final QwertyGame game) {
super(game);
editScreen = new EditScreen(game, this);
fileScreen = new FileScreen(game, this);
// Build widgets
Table table = game.ui.table().top();
Label titleLabel = game.ui.label("Chapter Editor", 60, Color.YELLOW);
TextButton newButton = game.ui.button("New", 60);
TextButton loadButton = game.ui.button("Load", 60);
TextButton backButton = game.ui.button("Back to Game", 42, game.mainMenuScreen);
int buttonWidth = 400;
table.add(titleLabel).height(500);
table.row();
table.add(newButton).width(buttonWidth);
table.row();
table.add(loadButton).width(buttonWidth);
table.row();
table.add(backButton).width(buttonWidth).padTop(200);
table.row();
stage.addActor(table);
newButton.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
editScreen.makeEmpty();
game.setScreen(editScreen);
}
});
loadButton.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
fileScreen.refresh();
game.setScreen(fileScreen);
}
});
}
}
|
UTF-8
|
Java
| 1,717 |
java
|
MenuScreen.java
|
Java
|
[
{
"context": "port com.coffeede.game.QwertyGame;\n\n/**\n * @author Byron\n */\npublic class MenuScreen extends BaseScreen {\n",
"end": 437,
"score": 0.8891162276268005,
"start": 432,
"tag": "NAME",
"value": "Byron"
}
] | null |
[] |
package com.coffeede.editor;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.coffeede.engine.screen.BaseScreen;
import com.coffeede.game.QwertyGame;
/**
* @author Byron
*/
public class MenuScreen extends BaseScreen {
protected final EditScreen editScreen;
protected final FileScreen fileScreen;
public MenuScreen(final QwertyGame game) {
super(game);
editScreen = new EditScreen(game, this);
fileScreen = new FileScreen(game, this);
// Build widgets
Table table = game.ui.table().top();
Label titleLabel = game.ui.label("Chapter Editor", 60, Color.YELLOW);
TextButton newButton = game.ui.button("New", 60);
TextButton loadButton = game.ui.button("Load", 60);
TextButton backButton = game.ui.button("Back to Game", 42, game.mainMenuScreen);
int buttonWidth = 400;
table.add(titleLabel).height(500);
table.row();
table.add(newButton).width(buttonWidth);
table.row();
table.add(loadButton).width(buttonWidth);
table.row();
table.add(backButton).width(buttonWidth).padTop(200);
table.row();
stage.addActor(table);
newButton.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
editScreen.makeEmpty();
game.setScreen(editScreen);
}
});
loadButton.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
fileScreen.refresh();
game.setScreen(fileScreen);
}
});
}
}
| 1,717 | 0.731508 | 0.718695 | 63 | 26.253969 | 21.905256 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.079365 | false | false |
13
|
b14f4be9ba93c2c0abdc3b29d8d45701b60b4de9
| 25,795,573,639,665 |
3eb60c5eacedfcd5f23131b317e5b923c7b3d38a
|
/src/com/mycompany/myapp/gui/ProduitHomeForm.java
|
728110e05a7a8ec73b14e65d74fe6a254f3f2fae
|
[] |
no_license
|
zeineb0/DebboPiMobile
|
https://github.com/zeineb0/DebboPiMobile
|
e0724542b819a79751d3e403133cc760efc22da0
|
2007055ea1e5fd23a0b5fbacde44e5cc7d8ad2b5
|
refs/heads/master
| 2022-11-10T10:53:09.215000 | 2020-06-19T18:31:57 | 2020-06-19T18:31:57 | 260,089,646 | 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.mycompany.myapp.gui;
import com.codename1.ui.Button;
import com.codename1.ui.FontImage;
import com.codename1.ui.Form;
import com.codename1.ui.Label;
import com.codename1.ui.layouts.BoxLayout;
/**
*
* @author Zeineb_yahiaoui
*/
public class ProduitHomeForm extends Form{
Form current;
public ProduitHomeForm(Form previous) {
current=this;
setTitle("Produit");
setLayout(BoxLayout.y());
add(new Label("Choisissez une option"));
Button btnAddTask = new Button("Ajouter un nouveau produit");
Button btnListTasks = new Button("Afficher la liste des produits");
btnAddTask.addActionListener(e-> new AddProduitForm(current).show());
btnListTasks.addActionListener(e-> new ListProduitForm(current).show());
addAll(btnAddTask,btnListTasks);
getToolbar().addMaterialCommandToLeftBar("", FontImage.MATERIAL_ARROW_BACK, e-> previous.showBack());
}
}
|
UTF-8
|
Java
| 1,168 |
java
|
ProduitHomeForm.java
|
Java
|
[
{
"context": "codename1.ui.layouts.BoxLayout;\n\n/**\n *\n * @author Zeineb_yahiaoui\n */\npublic class ProduitHomeForm extends Form{\n\n ",
"end": 424,
"score": 0.7432023882865906,
"start": 409,
"tag": "USERNAME",
"value": "Zeineb_yahiaoui"
}
] | 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.mycompany.myapp.gui;
import com.codename1.ui.Button;
import com.codename1.ui.FontImage;
import com.codename1.ui.Form;
import com.codename1.ui.Label;
import com.codename1.ui.layouts.BoxLayout;
/**
*
* @author Zeineb_yahiaoui
*/
public class ProduitHomeForm extends Form{
Form current;
public ProduitHomeForm(Form previous) {
current=this;
setTitle("Produit");
setLayout(BoxLayout.y());
add(new Label("Choisissez une option"));
Button btnAddTask = new Button("Ajouter un nouveau produit");
Button btnListTasks = new Button("Afficher la liste des produits");
btnAddTask.addActionListener(e-> new AddProduitForm(current).show());
btnListTasks.addActionListener(e-> new ListProduitForm(current).show());
addAll(btnAddTask,btnListTasks);
getToolbar().addMaterialCommandToLeftBar("", FontImage.MATERIAL_ARROW_BACK, e-> previous.showBack());
}
}
| 1,168 | 0.688356 | 0.684075 | 37 | 30.567568 | 28.71344 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.621622 | false | false |
13
|
9cde1f9fccf27c39e6f2e296a0e7a6bad260cd74
| 1,932,735,332,727 |
3dda8b6d3ac61a99ee5c20245013107f3096401c
|
/nem-infrastructure-server/core/model/t.java
|
6e72d785b8b78da32be4d2c4cf61b493d90818d2
|
[] |
no_license
|
skycontroller/NEM-Alpha-0.0.55
|
https://github.com/skycontroller/NEM-Alpha-0.0.55
|
dd6e3696805b908ec4ff50bf66c6752ff6725080
|
8c66698bfba042e1ebbf8cacf2f4aecc3b6ce80f
|
refs/heads/master
| 2016-09-02T05:52:00.283000 | 2014-06-30T21:41:22 | 2014-06-30T21:41:22 | 21,361,332 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.nem.core.model;
import org.nem.core.model.Account;
import org.nem.core.model.g;
import org.nem.core.model.primitive.Amount;
import org.nem.core.model.primitive.BlockHeight;
import org.nem.core.model.s;
public class t
implements g {
@Override
public void a(BlockHeight blockHeight, Account account, Amount amount) {
account.as().j(blockHeight, amount);
}
@Override
public void b(BlockHeight blockHeight, Account account, Amount amount) {
account.as().h(blockHeight, amount);
}
@Override
public void c(BlockHeight blockHeight, Account account, Amount amount) {
account.as().k(blockHeight, amount);
}
@Override
public void d(BlockHeight blockHeight, Account account, Amount amount) {
account.as().i(blockHeight, amount);
}
}
|
UTF-8
|
Java
| 847 |
java
|
t.java
|
Java
|
[] | null |
[] |
package org.nem.core.model;
import org.nem.core.model.Account;
import org.nem.core.model.g;
import org.nem.core.model.primitive.Amount;
import org.nem.core.model.primitive.BlockHeight;
import org.nem.core.model.s;
public class t
implements g {
@Override
public void a(BlockHeight blockHeight, Account account, Amount amount) {
account.as().j(blockHeight, amount);
}
@Override
public void b(BlockHeight blockHeight, Account account, Amount amount) {
account.as().h(blockHeight, amount);
}
@Override
public void c(BlockHeight blockHeight, Account account, Amount amount) {
account.as().k(blockHeight, amount);
}
@Override
public void d(BlockHeight blockHeight, Account account, Amount amount) {
account.as().i(blockHeight, amount);
}
}
| 847 | 0.672963 | 0.672963 | 30 | 26.299999 | 25.0814 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.733333 | false | false |
13
|
6c0f8ea4581c6f89d444a5f7cf2906e6a37a464d
| 25,907,242,740,928 |
70064914ff0eed77c98332f341f1e897b6025692
|
/Jukebox Server/src/com/ketonax/networking/NamingService.java
|
2acd7f58b01b4376c0fd0b0d5a83f7665e5e26c1
|
[] |
no_license
|
sahpat229/Jukebox-Server
|
https://github.com/sahpat229/Jukebox-Server
|
148771dfb6320649c6405d64243f84d0f93ee5a0
|
b573ed30d3265425f27608d61f225e6d7afaaae1
|
refs/heads/master
| 2021-01-21T22:26:39.620000 | 2014-06-27T16:20:46 | 2014-06-27T16:20:46 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.ketonax.networking;
import edu.rutgers.winlab.jmfapi.GUID;
public class NamingService {
private static int guid = 1;
public static GUID assignGUID() {
GUID id = new GUID(guid);
guid++;//should replace with an algorithm
return id;
}
}
|
UTF-8
|
Java
| 261 |
java
|
NamingService.java
|
Java
|
[] | null |
[] |
package com.ketonax.networking;
import edu.rutgers.winlab.jmfapi.GUID;
public class NamingService {
private static int guid = 1;
public static GUID assignGUID() {
GUID id = new GUID(guid);
guid++;//should replace with an algorithm
return id;
}
}
| 261 | 0.716475 | 0.712644 | 16 | 15.3125 | 16.1273 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.9375 | false | false |
13
|
5cf75992f0bf0e0c70c360917adfd26e89a6fa42
| 33,595,234,200,371 |
e618a9125642c6b14e355192b37d3e960f318be3
|
/spring/spring-security-experiments/spring-security-in-memory/src/test/java/org/farrukh/examples/spring/security/ApplicationIntegrationTests.java
|
d4daafe6de4515aa5f8167b460b54f32622ab3da
|
[] |
no_license
|
Farrukhjon/experimental-samples
|
https://github.com/Farrukhjon/experimental-samples
|
5c062a89ba499ac2223374bcf93b431bb68fae0a
|
cc20db2dc2c1b28aae54933550c89c13e46040ec
|
refs/heads/master
| 2022-07-16T19:23:03.557000 | 2019-07-27T11:34:56 | 2019-07-27T11:34:56 | 61,690,323 | 6 | 9 | null | false | 2022-10-18T18:07:38 | 2016-06-22T05:03:21 | 2020-11-01T06:41:18 | 2022-10-18T18:07:33 | 7,897 | 5 | 7 | 91 |
Java
| false | false |
package org.farrukh.examples.spring.security;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.boot.test.WebIntegrationTest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.util.UriComponentsBuilder;
import static org.junit.Assert.assertEquals;
@RunWith(SpringJUnit4ClassRunner.class)
@WebIntegrationTest(randomPort = true)
@SpringApplicationConfiguration(classes = Application.class)
public class ApplicationIntegrationTests {
private TestRestTemplate restTemplate = new TestRestTemplate();
@Value("${local.server.port}")
private int port;
@Test
public void contextLoads() {
HttpStatus expectedStatusCode = HttpStatus.OK;
ResponseEntity<String> entity = restTemplate.getForEntity(getUrl("/"), String.class);
HttpHeaders headers = entity.getHeaders();
assertEquals(expectedStatusCode, entity.getStatusCode());
}
private String getUrl(final String path) {
return UriComponentsBuilder.newInstance()
.scheme("http")
.host("localhost")
.port(port)
.path(path)
.toUriString();
}
}
|
UTF-8
|
Java
| 1,640 |
java
|
ApplicationIntegrationTests.java
|
Java
|
[] | null |
[] |
package org.farrukh.examples.spring.security;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.boot.test.WebIntegrationTest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.util.UriComponentsBuilder;
import static org.junit.Assert.assertEquals;
@RunWith(SpringJUnit4ClassRunner.class)
@WebIntegrationTest(randomPort = true)
@SpringApplicationConfiguration(classes = Application.class)
public class ApplicationIntegrationTests {
private TestRestTemplate restTemplate = new TestRestTemplate();
@Value("${local.server.port}")
private int port;
@Test
public void contextLoads() {
HttpStatus expectedStatusCode = HttpStatus.OK;
ResponseEntity<String> entity = restTemplate.getForEntity(getUrl("/"), String.class);
HttpHeaders headers = entity.getHeaders();
assertEquals(expectedStatusCode, entity.getStatusCode());
}
private String getUrl(final String path) {
return UriComponentsBuilder.newInstance()
.scheme("http")
.host("localhost")
.port(port)
.path(path)
.toUriString();
}
}
| 1,640 | 0.701219 | 0.69939 | 44 | 36.272728 | 24.458094 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
13
|
afe9e2b3f2d75db69672824a586b6242238d848e
| 25,615,184,970,511 |
39892fea614d28afd88f79d695a446c7929c4c0f
|
/app/src/main/java/com/bubbles/storageinfo/MainActivity.java
|
06508e4774aff7dc7baed13568d38dae4f1a567d
|
[] |
no_license
|
bonnette/AStorageInfo_3_0
|
https://github.com/bonnette/AStorageInfo_3_0
|
ab721a40e2a5bd20851c3bc8853e4c17ad79962c
|
58566bc1cce21a5ccf917ce0a3e005d02e9340c5
|
refs/heads/master
| 2020-04-15T12:49:26.006000 | 2019-01-08T16:16:52 | 2019-01-08T16:16:52 | 164,687,451 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.bubbles.storageinfo;
import android.os.Bundle;
import android.app.ListActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListView;
import android.view.View;
import android.content.Intent;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity extends ListActivity {
String[] hparrays = new String[] { "HPE StoreServ 20000", "HPE StoreServ 9000","HPE StoreServ 8000", "HPE Nimble",
"HPE MSA", "HPE Software Defined Storage", "HPE SimpliVity", "HPE StoreEasy 3000", "HPE StoreEasy 1000", "HPE StoreOnce 6600", "HPE StoreOnce 5000",
"HPE StoreOnce 3000", "HPE TFinity Tape Library", "HPE T950 Tape Library", "HPE StoreEver MSL", "HPE Tape"};
// Array of integers points to images stored in /res/drawable-hdpi/
int[] arrayImg = new int[]{
R.drawable.ss20800,
R.drawable.ss9000,
R.drawable.ss8000,
R.drawable.nimble,
R.drawable.p2000,
R.drawable.sds,
R.drawable.simpliv,
R.drawable.se3000,
R.drawable.se1000,
R.drawable.so6000,
R.drawable.so5000,
R.drawable.so3000,
R.drawable.tfin,
R.drawable.t950,
R.drawable.mslimg,
R.drawable.tapeimg
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
CustomListAdapter adapter=new CustomListAdapter(this,hparrays,arrayImg );
setListAdapter(adapter);
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String product = (String) getListAdapter().getItem(position);
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), ArrayViewItem.class);
// sending data to new activity
i.putExtra("product", product);
i.putExtra("productimg", position);
startActivity(i);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
Intent i = new Intent(getApplicationContext(), AboutPageView.class);
startActivity(i);
return super.onOptionsItemSelected(item);
}
}
|
UTF-8
|
Java
| 2,962 |
java
|
MainActivity.java
|
Java
|
[] | null |
[] |
package com.bubbles.storageinfo;
import android.os.Bundle;
import android.app.ListActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListView;
import android.view.View;
import android.content.Intent;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity extends ListActivity {
String[] hparrays = new String[] { "HPE StoreServ 20000", "HPE StoreServ 9000","HPE StoreServ 8000", "HPE Nimble",
"HPE MSA", "HPE Software Defined Storage", "HPE SimpliVity", "HPE StoreEasy 3000", "HPE StoreEasy 1000", "HPE StoreOnce 6600", "HPE StoreOnce 5000",
"HPE StoreOnce 3000", "HPE TFinity Tape Library", "HPE T950 Tape Library", "HPE StoreEver MSL", "HPE Tape"};
// Array of integers points to images stored in /res/drawable-hdpi/
int[] arrayImg = new int[]{
R.drawable.ss20800,
R.drawable.ss9000,
R.drawable.ss8000,
R.drawable.nimble,
R.drawable.p2000,
R.drawable.sds,
R.drawable.simpliv,
R.drawable.se3000,
R.drawable.se1000,
R.drawable.so6000,
R.drawable.so5000,
R.drawable.so3000,
R.drawable.tfin,
R.drawable.t950,
R.drawable.mslimg,
R.drawable.tapeimg
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
CustomListAdapter adapter=new CustomListAdapter(this,hparrays,arrayImg );
setListAdapter(adapter);
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String product = (String) getListAdapter().getItem(position);
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), ArrayViewItem.class);
// sending data to new activity
i.putExtra("product", product);
i.putExtra("productimg", position);
startActivity(i);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
Intent i = new Intent(getApplicationContext(), AboutPageView.class);
startActivity(i);
return super.onOptionsItemSelected(item);
}
}
| 2,962 | 0.633018 | 0.60736 | 88 | 32.659092 | 29.506889 | 160 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.784091 | false | false |
13
|
3231ac32d90e9b419bad03212ef39fcd96798647
| 2,164,663,532,283 |
f4867294838b82e5679143e0e7ace6c8cfba05a0
|
/src/training/CalculatorTest.java
|
7b884ae38f00de3bff47ad26fcd30b0b335d2f9f
|
[] |
no_license
|
hemanthkumaram-agi/traineearisglobalhemanth
|
https://github.com/hemanthkumaram-agi/traineearisglobalhemanth
|
596240769e3d29c6c336e0dda17b579d3df8962b
|
4213b1100b54601e7125b39ddf9c02656834b538
|
refs/heads/main
| 2023-09-02T02:03:59.125000 | 2021-10-29T05:41:53 | 2021-10-29T05:41:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package training;
public class CalculatorTest {
public static void main(String[] args) {
Calculator cal=new Calculator();
System.out.print(Math.sqrt(Calculator.add(2.0, 3.9,4.0)));
//double sum=cal.add(4.7, 3.5);
}
}
|
UTF-8
|
Java
| 235 |
java
|
CalculatorTest.java
|
Java
|
[] | null |
[] |
package training;
public class CalculatorTest {
public static void main(String[] args) {
Calculator cal=new Calculator();
System.out.print(Math.sqrt(Calculator.add(2.0, 3.9,4.0)));
//double sum=cal.add(4.7, 3.5);
}
}
| 235 | 0.66383 | 0.621277 | 10 | 21.299999 | 19.365175 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.9 | false | false |
13
|
5c6e1e48e1a1b4239a49504f2cd0f389f26af753
| 1,013,612,297,911 |
40d827d593bdaa538a506e782485415f07ba1e2f
|
/ikks-message/src/main/java/com/chintec/ikks/message/service/IUploadFileService.java
|
0ab3ac1e8d1fb98f5c89c373622e468555a3f79f
|
[] |
no_license
|
lvbing92/chintec-ikks
|
https://github.com/lvbing92/chintec-ikks
|
d5147908c9dd989c5b3b98d5cdc7cb8076182a62
|
7f3c26656ed19b121f8b69d21fdfde3f6539adde
|
refs/heads/master
| 2023-02-24T23:26:31.635000 | 2021-01-22T09:40:02 | 2021-01-22T09:40:02 | 293,450,339 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.chintec.ikks.message.service;
import com.chintec.ikks.common.util.ResultResponse;
import org.springframework.web.multipart.MultipartFile;
/**
* @author Jack
* @version 1.0
* @date 2020/7/6 13:08
*/
public interface IUploadFileService {
/**
* 保存图片
*
* @param file
* @return
*/
ResultResponse uploadImg2Oss(MultipartFile file, Integer type);
ResultResponse uploadImgOssToken(Integer type);
}
|
UTF-8
|
Java
| 457 |
java
|
IUploadFileService.java
|
Java
|
[
{
"context": "ework.web.multipart.MultipartFile;\n\n/**\n * @author Jack\n * @version 1.0\n * @date 2020/7/6 13:08\n */\npubli",
"end": 171,
"score": 0.9722891449928284,
"start": 167,
"tag": "NAME",
"value": "Jack"
}
] | null |
[] |
package com.chintec.ikks.message.service;
import com.chintec.ikks.common.util.ResultResponse;
import org.springframework.web.multipart.MultipartFile;
/**
* @author Jack
* @version 1.0
* @date 2020/7/6 13:08
*/
public interface IUploadFileService {
/**
* 保存图片
*
* @param file
* @return
*/
ResultResponse uploadImg2Oss(MultipartFile file, Integer type);
ResultResponse uploadImgOssToken(Integer type);
}
| 457 | 0.690423 | 0.66147 | 24 | 17.708334 | 20.425636 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false |
13
|
000c6ad5f199824338111ad4d667db86293ed03e
| 22,823,456,224,924 |
0e86ddc5a24e74c532a4d4a375a0f2bd9fc4ec47
|
/src/main/java/com/dolojia/admin/manage/service/SysRoleDeptService.java
|
7ccb29172f55e3623afafd047436afa39f373260
|
[] |
no_license
|
dolojia/mis-admin
|
https://github.com/dolojia/mis-admin
|
bfff157fc3de83ffdde146b412cb4f7107bb886d
|
982ce6b02f153856c8490a1c31a88594be366ad6
|
refs/heads/master
| 2020-03-28T09:19:33.180000 | 2018-09-09T13:45:09 | 2018-09-09T13:45:09 | 148,029,098 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.dolojia.admin.manage.service;
import com.baomidou.mybatisplus.service.IService;
import com.dolojia.admin.manage.entity.SysRoleDeptEntity;
import java.util.List;
/**
* 描述: 角色与部门对应关系
* 作者: dolojia
* 修改日期: 2018/9/9 下午2:12
* E-mail: dolojia@gmail.com
**/
public interface SysRoleDeptService extends IService<SysRoleDeptEntity> {
void saveOrUpdate(Long roleId, List<Long> deptIdList);
/**
* 根据角色ID,获取部门ID列表
*/
List<Long> queryDeptIdList(Long[] roleIds);
/**
* 根据角色ID数组,批量删除
*/
int deleteBatch(Long[] roleIds);
}
|
UTF-8
|
Java
| 654 |
java
|
SysRoleDeptService.java
|
Java
|
[
{
"context": "port java.util.List;\n\n\n/**\n * 描述: 角色与部门对应关系\n * 作者: dolojia\n * 修改日期: 2018/9/9 下午2:12\n * E-mail: dolojia@gmail",
"end": 213,
"score": 0.9996086955070496,
"start": 206,
"tag": "USERNAME",
"value": "dolojia"
},
{
"context": " * 作者: dolojia\n * 修改日期: 2018/9/9 下午2:12\n * E-mail: dolojia@gmail.com\n **/\npublic interface SysRoleDeptService extends ",
"end": 267,
"score": 0.9999249577522278,
"start": 250,
"tag": "EMAIL",
"value": "dolojia@gmail.com"
}
] | null |
[] |
package com.dolojia.admin.manage.service;
import com.baomidou.mybatisplus.service.IService;
import com.dolojia.admin.manage.entity.SysRoleDeptEntity;
import java.util.List;
/**
* 描述: 角色与部门对应关系
* 作者: dolojia
* 修改日期: 2018/9/9 下午2:12
* E-mail: <EMAIL>
**/
public interface SysRoleDeptService extends IService<SysRoleDeptEntity> {
void saveOrUpdate(Long roleId, List<Long> deptIdList);
/**
* 根据角色ID,获取部门ID列表
*/
List<Long> queryDeptIdList(Long[] roleIds);
/**
* 根据角色ID数组,批量删除
*/
int deleteBatch(Long[] roleIds);
}
| 644 | 0.690559 | 0.674825 | 28 | 19.392857 | 21.044746 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false |
13
|
3d5e8f5f8cb812ae14d3b728ae54dd90369dabe9
| 32,667,521,268,478 |
b8e3e449651bd64e5c126b5f91853428a595b5d8
|
/domain-model/src/main/java/com/similan/domain/repository/lead/SearchLeadRepository.java
|
8036b29be450fc9014186f4bb02f0ab5582de8be
|
[] |
no_license
|
suparna2702/ServiceFabric
|
https://github.com/suparna2702/ServiceFabric
|
ee5801a346fda63edf0bea75103e693e52037fc4
|
d526376f9530f608726fa6ad1b7912b4ec384a82
|
refs/heads/master
| 2021-03-22T04:40:41.688000 | 2016-12-06T02:06:38 | 2016-12-06T02:06:38 | 75,250,704 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.similan.domain.repository.lead;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.similan.domain.entity.lead.SearchLead;
import com.similan.domain.repository.lead.jpa.JpaSearchLeadRepository;
@Repository
public class SearchLeadRepository {
@Autowired
private JpaSearchLeadRepository repository;
public SearchLead findOne(Long id) {
return repository.findOne(id);
}
public List<SearchLead> findAll() {
return repository.findAll();
}
public List<SearchLead> findLeadsForSocialActor(Long actorId) {
return repository.findLeadsForSocialActor(actorId);
}
public SearchLead save(SearchLead searchLead) {
return repository.save(searchLead);
}
public Long getLeadCountSocialActor(Long actorId) {
return repository.getLeadCountSocialActor(actorId);
}
public List<SearchLead> save(Iterable<SearchLead> searchLead) {
return repository.save(searchLead);
}
public void delete(Long id) {
repository.delete(id);
}
public SearchLead create(){
SearchLead searchLead =
new SearchLead();
return searchLead;
}
public Long getNotViewedLeadCountSocialActor(Long id) {
return repository.getNotViewedLeadCountSocialActor(id);
}
}
|
UTF-8
|
Java
| 1,313 |
java
|
SearchLeadRepository.java
|
Java
|
[] | null |
[] |
package com.similan.domain.repository.lead;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.similan.domain.entity.lead.SearchLead;
import com.similan.domain.repository.lead.jpa.JpaSearchLeadRepository;
@Repository
public class SearchLeadRepository {
@Autowired
private JpaSearchLeadRepository repository;
public SearchLead findOne(Long id) {
return repository.findOne(id);
}
public List<SearchLead> findAll() {
return repository.findAll();
}
public List<SearchLead> findLeadsForSocialActor(Long actorId) {
return repository.findLeadsForSocialActor(actorId);
}
public SearchLead save(SearchLead searchLead) {
return repository.save(searchLead);
}
public Long getLeadCountSocialActor(Long actorId) {
return repository.getLeadCountSocialActor(actorId);
}
public List<SearchLead> save(Iterable<SearchLead> searchLead) {
return repository.save(searchLead);
}
public void delete(Long id) {
repository.delete(id);
}
public SearchLead create(){
SearchLead searchLead =
new SearchLead();
return searchLead;
}
public Long getNotViewedLeadCountSocialActor(Long id) {
return repository.getNotViewedLeadCountSocialActor(id);
}
}
| 1,313 | 0.763899 | 0.763899 | 54 | 23.314816 | 22.812298 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.796296 | false | false |
13
|
bef90d6a7ebaa2f82665dd93f59652b3299c7ffb
| 12,635,793,811,795 |
7691146e5e2868fe6048abcf72dfa1e0ca8f2943
|
/src/main/java/com/dogboy60/NYC146/data/repo/EventModelCustomRepo.java
|
e489f24d80e1b6c273b5d921615d7f8a15f39826
|
[] |
no_license
|
bhagyesh-p/NYC146Main
|
https://github.com/bhagyesh-p/NYC146Main
|
3ef3a1dd81f3186c0d19ca932bc0bfe53f1d9f3d
|
a5a09ca649a37a0699d5c740e27297393c769958
|
refs/heads/master
| 2020-07-21T23:55:56.815000 | 2020-06-30T18:51:22 | 2020-06-30T18:51:22 | 207,006,330 | 2 | 0 | null | false | 2020-06-30T18:51:23 | 2019-09-07T17:59:07 | 2019-12-18T04:04:12 | 2020-06-30T18:51:22 | 42,582 | 1 | 0 | 0 |
Java
| false | false |
package com.dogboy60.NYC146.data.repo;
import com.dogboy60.NYC146.data.model.EventDocument;
import java.util.Collection;
public interface EventModelCustomRepo {
String SUMMER = "summer";
String WINTER = "winter";
String SPRING = "spring";
String FALL = "fall";
String CHEAP = "cheap";
String FAIR = "fair";
String EXPENSIVE = "expensive";
void updateEvent(EventDocument eventDocument);
void removeEvent(String ID);
int addPost(EventDocument eventDocument);
Collection<EventDocument> getPost(String Season, String price);
boolean contains(String id);
boolean contains(EventDocument eventDocument);
EventDocument getPost(String id);
}
|
UTF-8
|
Java
| 701 |
java
|
EventModelCustomRepo.java
|
Java
|
[
{
"context": "package com.dogboy60.NYC146.data.repo;\n\nimport com.dogboy60.NYC146.dat",
"end": 20,
"score": 0.744118869304657,
"start": 15,
"tag": "USERNAME",
"value": "boy60"
},
{
"context": "age com.dogboy60.NYC146.data.repo;\n\nimport com.dogboy60.NYC146.data.model.EventDocument;\n\nimport java.uti",
"end": 59,
"score": 0.9677959084510803,
"start": 54,
"tag": "USERNAME",
"value": "boy60"
}
] | null |
[] |
package com.dogboy60.NYC146.data.repo;
import com.dogboy60.NYC146.data.model.EventDocument;
import java.util.Collection;
public interface EventModelCustomRepo {
String SUMMER = "summer";
String WINTER = "winter";
String SPRING = "spring";
String FALL = "fall";
String CHEAP = "cheap";
String FAIR = "fair";
String EXPENSIVE = "expensive";
void updateEvent(EventDocument eventDocument);
void removeEvent(String ID);
int addPost(EventDocument eventDocument);
Collection<EventDocument> getPost(String Season, String price);
boolean contains(String id);
boolean contains(EventDocument eventDocument);
EventDocument getPost(String id);
}
| 701 | 0.717546 | 0.703281 | 31 | 21.612904 | 20.185715 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.580645 | false | false |
13
|
36cb3f09c6b0ff679ba5a4d9cdc12564a6313438
| 7,945,689,517,487 |
8aad3c75a9eacd2690a5beac0011d0ed349df03d
|
/Maven/Java8FunctionaInterfaces/src/com/MyConsumerDemo.java
|
cf4935463039ec4d1c910d5a103f64619ac1f866
|
[] |
no_license
|
Infyni-Learning/JavaSpringFrameworks
|
https://github.com/Infyni-Learning/JavaSpringFrameworks
|
253c5adef5518dc12e8d81f18037f40ad6d0bcd7
|
5226e6cdb130413827065efcb51a09386fdaddd9
|
refs/heads/master
| 2023-03-06T05:08:58.066000 | 2021-02-19T03:16:07 | 2021-02-19T03:16:07 | 318,397,291 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com;
import java.util.function.Consumer;
class MyConsumer implements Consumer<Float>{
@Override
public void accept(Float t) {
System.out.println(t);
}
}
public class MyConsumerDemo {
public static void main(String[] args) {
Consumer<Float> c1 = new MyConsumer();
c1.accept(10.10f);
c1.accept(20.20f);
Consumer<Integer> c2 = (v)->System.out.println(v);
c2.accept(100);
c2.accept(200);
}
}
|
UTF-8
|
Java
| 415 |
java
|
MyConsumerDemo.java
|
Java
|
[] | null |
[] |
package com;
import java.util.function.Consumer;
class MyConsumer implements Consumer<Float>{
@Override
public void accept(Float t) {
System.out.println(t);
}
}
public class MyConsumerDemo {
public static void main(String[] args) {
Consumer<Float> c1 = new MyConsumer();
c1.accept(10.10f);
c1.accept(20.20f);
Consumer<Integer> c2 = (v)->System.out.println(v);
c2.accept(100);
c2.accept(200);
}
}
| 415 | 0.701205 | 0.653012 | 22 | 17.863636 | 16.234911 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.090909 | false | false |
13
|
c2f10cb4608d231d26193a523dc76edf4b0655a6
| 7,945,689,520,059 |
3b2323ace289dcc9f04b3027dfadf0f8f2aba76f
|
/app/src/main/java/smartshop/co/mz/rv/CustomAdapter.java
|
2060fb35532dccdf140f782b4808bac6bed6e675
|
[] |
no_license
|
Agostinhodossantos/s
|
https://github.com/Agostinhodossantos/s
|
9d54e44b1f62843388980c88e63fe718e6bf771c
|
066b12b0351510815bf751c0031731f3902577e2
|
refs/heads/master
| 2020-12-05T11:21:07.710000 | 2020-01-06T12:03:04 | 2020-01-06T12:03:04 | 232,093,279 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package smartshop.co.mz.rv;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
import smartshop.co.mz.R;
import smartshop.co.mz.model.Descricao;
import smartshop.co.mz.model.Localizacao;
import smartshop.co.mz.model.Usuario;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
private LayoutInflater inflater;
public static ArrayList<Descricao> editModelArrayList;
public CustomAdapter(Context ctx, ArrayList<Descricao> editModelArrayList){
inflater = LayoutInflater.from(ctx);
this.editModelArrayList = editModelArrayList;
}
@Override
public CustomAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.card_row_detalhes, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(final CustomAdapter.MyViewHolder holder, final int position) {
holder.editText.setHint(editModelArrayList.get(position).getConceito());
Log.d("print","yes");
}
@Override
public int getItemCount() {
return editModelArrayList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder{
protected EditText editText;
public MyViewHolder(View itemView) {
super(itemView);
editText = (EditText) itemView.findViewById(R.id.tv_item);
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
editModelArrayList.get(getAdapterPosition()).setDefinicao(editText.getText().toString());
}
@Override
public void afterTextChanged(Editable editable) {
}
});
}
}
}
|
UTF-8
|
Java
| 2,873 |
java
|
CustomAdapter.java
|
Java
|
[] | null |
[] |
package smartshop.co.mz.rv;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
import smartshop.co.mz.R;
import smartshop.co.mz.model.Descricao;
import smartshop.co.mz.model.Localizacao;
import smartshop.co.mz.model.Usuario;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
private LayoutInflater inflater;
public static ArrayList<Descricao> editModelArrayList;
public CustomAdapter(Context ctx, ArrayList<Descricao> editModelArrayList){
inflater = LayoutInflater.from(ctx);
this.editModelArrayList = editModelArrayList;
}
@Override
public CustomAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.card_row_detalhes, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(final CustomAdapter.MyViewHolder holder, final int position) {
holder.editText.setHint(editModelArrayList.get(position).getConceito());
Log.d("print","yes");
}
@Override
public int getItemCount() {
return editModelArrayList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder{
protected EditText editText;
public MyViewHolder(View itemView) {
super(itemView);
editText = (EditText) itemView.findViewById(R.id.tv_item);
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
editModelArrayList.get(getAdapterPosition()).setDefinicao(editText.getText().toString());
}
@Override
public void afterTextChanged(Editable editable) {
}
});
}
}
}
| 2,873 | 0.712496 | 0.711103 | 100 | 27.73 | 27.688934 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.55 | false | false |
13
|
473d26a8a5f3b87326033a44afb6dfd68620d4d6
| 32,813,550,161,736 |
acd4479cc4b8b4152410f8fb14fbd5a341e7daca
|
/app/src/main/java/com/jhjj9158/niupaivideo/wxapi/WXEntryActivity.java
|
4bc936189137b89e42f5eca1c93085bcca1017fc
|
[] |
no_license
|
StonyGround/niupai
|
https://github.com/StonyGround/niupai
|
11be0ac4f9dc2ea037e6f40ab483c4be66690c1a
|
4d0b09a3718be2c33e4f6987ea426122299be9bc
|
refs/heads/master
| 2021-01-15T08:18:44.916000 | 2017-08-07T10:04:51 | 2017-08-07T10:04:51 | 99,564,226 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.jhjj9158.niupaivideo.wxapi;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import com.google.gson.Gson;
import com.jhjj9158.niupaivideo.MyApplication;
import com.jhjj9158.niupaivideo.activity.QuickLoignActivity;
import com.jhjj9158.niupaivideo.bean.LoginResultBean;
import com.jhjj9158.niupaivideo.utils.CacheUtils;
import com.jhjj9158.niupaivideo.utils.CommonUtil;
import com.jhjj9158.niupaivideo.utils.Contact;
import com.jhjj9158.niupaivideo.utils.OkHttpUtils;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.socialize.weixin.view.WXCallbackActivity;
import java.io.IOException;
import okhttp3.Call;
public class WXEntryActivity extends WXCallbackActivity implements IWXAPIEventHandler {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyApplication.api.handleIntent(getIntent(), this);
}
@Override
public void onReq(BaseReq baseReq) {
}
@Override
public void onResp(BaseResp resp) {
switch (resp.getType()) {
case 1://1为第三方登录,2为分享
String code = ((SendAuth.Resp) resp).code;
if (!TextUtils.isEmpty(code)) {
CacheUtils.setString(this, "code_weixin", code);
}
finish();
break;
default:
finish();
break;
}
}
}
|
UTF-8
|
Java
| 1,815 |
java
|
WXEntryActivity.java
|
Java
|
[
{
"context": "l.Log;\n\nimport com.google.gson.Gson;\nimport com.jhjj9158.niupaivideo.MyApplication;\nimport com.jhjj9158.",
"end": 253,
"score": 0.6660274863243103,
"start": 249,
"tag": "USERNAME",
"value": "jj91"
},
{
"context": ";\n\nimport com.google.gson.Gson;\nimport com.jhjj9158.niupaivideo.MyApplication;\nimport com.jhjj9158.ni",
"end": 255,
"score": 0.6215239763259888,
"start": 254,
"tag": "USERNAME",
"value": "8"
},
{
"context": ".jhjj9158.niupaivideo.MyApplication;\nimport com.jhjj9158.niupaivideo.activity.QuickLoignActivity;\nimport c",
"end": 302,
"score": 0.9341684579849243,
"start": 296,
"tag": "USERNAME",
"value": "jj9158"
},
{
"context": "aivideo.activity.QuickLoignActivity;\nimport com.jhjj9158.niupaivideo.bean.LoginResultBean;\nimport com.jhjj",
"end": 363,
"score": 0.925042986869812,
"start": 357,
"tag": "USERNAME",
"value": "jj9158"
},
{
"context": "58.niupaivideo.bean.LoginResultBean;\nimport com.jhjj9158.niupaivideo.utils.CacheUtils;\nimport com.jhjj91",
"end": 415,
"score": 0.6617572903633118,
"start": 411,
"tag": "USERNAME",
"value": "jj91"
},
{
"context": "upaivideo.bean.LoginResultBean;\nimport com.jhjj9158.niupaivideo.utils.CacheUtils;\nimport com.jhjj9158",
"end": 417,
"score": 0.614226758480072,
"start": 416,
"tag": "USERNAME",
"value": "8"
},
{
"context": "jj9158.niupaivideo.utils.CacheUtils;\nimport com.jhjj9158.niupaivideo.utils.CommonUtil;\nimport com.jhjj9158",
"end": 467,
"score": 0.8384519815444946,
"start": 461,
"tag": "USERNAME",
"value": "jj9158"
},
{
"context": "jj9158.niupaivideo.utils.CommonUtil;\nimport com.jhjj9158.niupaivideo.utils.Contact;\nimport com.jhjj9158.ni",
"end": 517,
"score": 0.8660776019096375,
"start": 511,
"tag": "USERNAME",
"value": "jj9158"
},
{
"context": ".jhjj9158.niupaivideo.utils.Contact;\nimport com.jhjj9158.niupaivideo.utils.OkHttpUtils;\nimport com.tencent",
"end": 564,
"score": 0.8544099926948547,
"start": 558,
"tag": "USERNAME",
"value": "jj9158"
}
] | null |
[] |
package com.jhjj9158.niupaivideo.wxapi;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import com.google.gson.Gson;
import com.jhjj9158.niupaivideo.MyApplication;
import com.jhjj9158.niupaivideo.activity.QuickLoignActivity;
import com.jhjj9158.niupaivideo.bean.LoginResultBean;
import com.jhjj9158.niupaivideo.utils.CacheUtils;
import com.jhjj9158.niupaivideo.utils.CommonUtil;
import com.jhjj9158.niupaivideo.utils.Contact;
import com.jhjj9158.niupaivideo.utils.OkHttpUtils;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.socialize.weixin.view.WXCallbackActivity;
import java.io.IOException;
import okhttp3.Call;
public class WXEntryActivity extends WXCallbackActivity implements IWXAPIEventHandler {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyApplication.api.handleIntent(getIntent(), this);
}
@Override
public void onReq(BaseReq baseReq) {
}
@Override
public void onResp(BaseResp resp) {
switch (resp.getType()) {
case 1://1为第三方登录,2为分享
String code = ((SendAuth.Resp) resp).code;
if (!TextUtils.isEmpty(code)) {
CacheUtils.setString(this, "code_weixin", code);
}
finish();
break;
default:
finish();
break;
}
}
}
| 1,815 | 0.711742 | 0.691708 | 58 | 29.982759 | 21.458454 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.62069 | false | false |
13
|
48b982674aa5c1a3171fedc9007613a3c6aaa844
| 31,799,937,917,816 |
16b69e61e7148c88937239a4249f55ffb5518e16
|
/marcher-framework-mvc/src/main/java/xin/marcher/framework/mvc/validation/groups/GroupUpdate.java
|
8ef19f5740991908f7bc09392acb15a2cb8789c6
|
[] |
no_license
|
bellmit/marcher-framework
|
https://github.com/bellmit/marcher-framework
|
c5e2b08c3c92b8fa845a0a6e2f46c3c867199b8f
|
b0c0ac55f68f57fdf1b182335d58901ef1624f33
|
refs/heads/master
| 2023-07-28T18:11:15.839000 | 2021-09-09T03:52:49 | 2021-09-09T03:52:49 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package xin.marcher.framework.mvc.validation.groups;
/**
* 真实的 group update
*
* @author marcher
*/
public interface GroupUpdate {
}
|
UTF-8
|
Java
| 143 |
java
|
GroupUpdate.java
|
Java
|
[
{
"context": "ion.groups;\n\n/**\n * 真实的 group update\n *\n * @author marcher\n */\npublic interface GroupUpdate {\n}\n",
"end": 99,
"score": 0.9987934231758118,
"start": 92,
"tag": "USERNAME",
"value": "marcher"
}
] | null |
[] |
package xin.marcher.framework.mvc.validation.groups;
/**
* 真实的 group update
*
* @author marcher
*/
public interface GroupUpdate {
}
| 143 | 0.715328 | 0.715328 | 9 | 14.222222 | 16.638494 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.111111 | false | false |
13
|
92ed2075cd570a14910b5c888a98dd7d386262e5
| 6,571,300,017,716 |
3473a3c1fbec047e578ab138594be23f3f40e3e4
|
/src/com/orchestra/interfaces/Command.java
|
1b7f219ff4f92cb23ef9e7cae4da8448226380d6
|
[] |
no_license
|
wandermonk/Orchestra
|
https://github.com/wandermonk/Orchestra
|
bca5382bf7e72394b66dcb579ca98af57208c919
|
f6e7863050dd4a7081f1c603141e70088ce3b166
|
refs/heads/master
| 2021-01-01T19:57:25.187000 | 2017-08-01T16:26:54 | 2017-08-01T16:26:54 | 98,727,299 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.orchestra.interfaces;
public interface Command {
}
|
UTF-8
|
Java
| 65 |
java
|
Command.java
|
Java
|
[] | null |
[] |
package com.orchestra.interfaces;
public interface Command {
}
| 65 | 0.784615 | 0.784615 | 5 | 12 | 14.463748 | 33 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false |
13
|
70079d83c96250aa7f296387de197df5df97a43c
| 20,461,224,261,249 |
f5f95d94144175cfd234e1bcc18f383b18efaf00
|
/IPersistence_test/src/main/java/com/szy/io/IPersistenceTest.java
|
24aefd46d2f2d31892d203477c30fa70709e6c50
|
[] |
no_license
|
suzhongyuan55/definepersistence
|
https://github.com/suzhongyuan55/definepersistence
|
44c49f3057c86e3ca1f04e4366b649effb163f70
|
c262f8a2a656c93d93d91e872f7cbc9aea0f5dbf
|
refs/heads/main
| 2022-12-20T02:47:42.088000 | 2020-10-20T15:19:01 | 2020-10-20T15:19:01 | 305,422,444 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.szy.io;
import com.szy.pojo.User;
import com.szy.sqlsession.SqlSession;
import com.szy.sqlsession.SqlSessionFactory;
import com.szy.sqlsession.SqlSessionFactoryBuilder;
import java.io.InputStream;
/**
* @Author Suzy
* @Date 2020-10-18
*/
public class IPersistenceTest {
public void test() throws Exception {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapperConfigure.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = new User();
user.setId(1).setName("李四");
User resultUser = sqlSession.selectOne("user.selectOne", user);
}
}
|
UTF-8
|
Java
| 749 |
java
|
IPersistenceTest.java
|
Java
|
[
{
"context": "lder;\n\nimport java.io.InputStream;\n\n/**\n * @Author Suzy\n * @Date 2020-10-18\n */\npublic class IPersistence",
"end": 231,
"score": 0.99005126953125,
"start": 227,
"tag": "USERNAME",
"value": "Suzy"
},
{
"context": "user = new User();\n user.setId(1).setName(\"李四\");\n User resultUser = sqlSession.selectOne",
"end": 660,
"score": 0.9914135932922363,
"start": 658,
"tag": "NAME",
"value": "李四"
}
] | null |
[] |
package com.szy.io;
import com.szy.pojo.User;
import com.szy.sqlsession.SqlSession;
import com.szy.sqlsession.SqlSessionFactory;
import com.szy.sqlsession.SqlSessionFactoryBuilder;
import java.io.InputStream;
/**
* @Author Suzy
* @Date 2020-10-18
*/
public class IPersistenceTest {
public void test() throws Exception {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapperConfigure.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = new User();
user.setId(1).setName("李四");
User resultUser = sqlSession.selectOne("user.selectOne", user);
}
}
| 749 | 0.728859 | 0.716779 | 26 | 27.653847 | 28.843 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
13
|
8035e19dec420869a89e2043dafaf10b541fcce8
| 20,461,224,261,561 |
cc387597b608be13d34683c551a101f6f7234e35
|
/src/main/java/controlador/ControladorSaludo.java
|
ebdc565936978cc2855cd73324ac46b4b0a49b41
|
[] |
no_license
|
josemelorrieta/Reto3Grupo1
|
https://github.com/josemelorrieta/Reto3Grupo1
|
bb288dec54d2e0c54592e45cbf728614d6f3b5b7
|
bf36b759222fd89a892570c4b65b19e36043190a
|
refs/heads/master
| 2020-04-17T00:07:47.916000 | 2019-02-18T11:01:03 | 2019-02-18T11:01:03 | 166,037,983 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package controlador;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import vista.Ventana;
/**
* Clase que controla el panel de saludo
*
*/
public class ControladorSaludo implements ActionListener {
FuncionesControlador funciones = new FuncionesControlador();
private Ventana miVentana;
/**
* Constructor de la clase
* @param miVentana instancia de la ventana principal
*/
public ControladorSaludo( Ventana miVentana) {
this.miVentana = miVentana;
//Defininicion del listener del boton del panel saludo
miVentana.saludo.btnSaludo.addActionListener(this);
}
/**
* Metodo de las llamadas a los botones de la ventana saludo
*/
@Override
public void actionPerformed(ActionEvent e) {
//Accion del boton del panel saludo
switch (((JButton) e.getSource()).getName()) {
case "btnSaludo": funciones.cambiarDePanel(miVentana.saludo, miVentana.login);
break;
}
}
}
|
UTF-8
|
Java
| 985 |
java
|
ControladorSaludo.java
|
Java
|
[] | null |
[] |
package controlador;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import vista.Ventana;
/**
* Clase que controla el panel de saludo
*
*/
public class ControladorSaludo implements ActionListener {
FuncionesControlador funciones = new FuncionesControlador();
private Ventana miVentana;
/**
* Constructor de la clase
* @param miVentana instancia de la ventana principal
*/
public ControladorSaludo( Ventana miVentana) {
this.miVentana = miVentana;
//Defininicion del listener del boton del panel saludo
miVentana.saludo.btnSaludo.addActionListener(this);
}
/**
* Metodo de las llamadas a los botones de la ventana saludo
*/
@Override
public void actionPerformed(ActionEvent e) {
//Accion del boton del panel saludo
switch (((JButton) e.getSource()).getName()) {
case "btnSaludo": funciones.cambiarDePanel(miVentana.saludo, miVentana.login);
break;
}
}
}
| 985 | 0.722843 | 0.722843 | 51 | 18.313726 | 22.33391 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.196078 | false | false |
13
|
0f16a85598154216e3e4cffc4a42a7919597ef2a
| 8,933,532,037,702 |
70029a48ef902802b5045ae1890de707fffc6da0
|
/enoa-mq/enoa-rabbitmq/src/main/java/io/enoa/mq/rabbitmq/ERabbitMQException.java
|
881bdd8f94d2e5a5d9c21875fb95206c53f72887
|
[
"Apache-2.0"
] |
permissive
|
fewensa/enoa
|
https://github.com/fewensa/enoa
|
dce541bacc060c0475780f0d1d7b0025865ea53d
|
0335b7f9fe858491b0aa341ee8d6129d0b43090f
|
refs/heads/master
| 2022-02-18T02:32:32.941000 | 2019-11-04T01:40:50 | 2019-11-04T01:40:50 | 131,958,137 | 2 | 0 |
Apache-2.0
| false | 2022-02-16T00:55:35 | 2018-05-03T07:29:46 | 2020-11-11T08:44:24 | 2022-02-16T00:55:31 | 3,953 | 2 | 0 | 3 |
Java
| false | false |
package io.enoa.mq.rabbitmq;
public class ERabbitMQException extends RuntimeException {
public ERabbitMQException() {
super();
}
public ERabbitMQException(String message) {
super(message);
}
public ERabbitMQException(String message, Throwable cause) {
super(message, cause);
}
public ERabbitMQException(Throwable cause) {
super(cause);
}
protected ERabbitMQException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
|
UTF-8
|
Java
| 569 |
java
|
ERabbitMQException.java
|
Java
|
[] | null |
[] |
package io.enoa.mq.rabbitmq;
public class ERabbitMQException extends RuntimeException {
public ERabbitMQException() {
super();
}
public ERabbitMQException(String message) {
super(message);
}
public ERabbitMQException(String message, Throwable cause) {
super(message, cause);
}
public ERabbitMQException(Throwable cause) {
super(cause);
}
protected ERabbitMQException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
| 569 | 0.745167 | 0.745167 | 24 | 22.708334 | 29.480896 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583333 | false | false |
13
|
a9d70a323ab9e59fbdb487672bcb6ed93ec76357
| 27,874,337,810,999 |
58487345db4ca1afdca7037d887b7a754b0bb0b9
|
/webbati.parent/webbati.api/src/main/java/webbati/api/dao/interfaces/IMainOeuvreEtudeDao.java
|
9f421c91d47d9c0f79fcd0a42241638813f5ff43
|
[] |
no_license
|
kero31/wb
|
https://github.com/kero31/wb
|
a8fef9634b35a379f05547b9d54182460dc0fd7b
|
c1f4c134b2714f62f9b5a240bfe4c187d3a920b3
|
refs/heads/master
| 2020-12-09T01:48:25.071000 | 2016-10-07T20:54:49 | 2016-10-07T20:54:49 | 67,790,249 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/***********************************************************************
* Module: IMainOeuvreEtudeDao.java Author: Kero Purpose: Defines the Interface IMainOeuvreEtudeDao
***********************************************************************/
package webbati.api.dao.interfaces;
import webbati.api.metier.interfaces.IMainOeuvreEtude;
/**
* Interface <b>IMainOeuvreEtudeDao</b><br/>
*/
public interface IMainOeuvreEtudeDao extends IMainOeuvreDao<IMainOeuvreEtude> {
}
|
UTF-8
|
Java
| 487 |
java
|
IMainOeuvreEtudeDao.java
|
Java
|
[
{
"context": "*****\r\n * Module: IMainOeuvreEtudeDao.java Author: Kero Purpose: Defines the Interface IMainOeuvreEtudeDa",
"end": 122,
"score": 0.8360544443130493,
"start": 118,
"tag": "NAME",
"value": "Kero"
}
] | null |
[] |
/***********************************************************************
* Module: IMainOeuvreEtudeDao.java Author: Kero Purpose: Defines the Interface IMainOeuvreEtudeDao
***********************************************************************/
package webbati.api.dao.interfaces;
import webbati.api.metier.interfaces.IMainOeuvreEtude;
/**
* Interface <b>IMainOeuvreEtudeDao</b><br/>
*/
public interface IMainOeuvreEtudeDao extends IMainOeuvreDao<IMainOeuvreEtude> {
}
| 487 | 0.544148 | 0.544148 | 13 | 35.615383 | 35.258472 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.153846 | false | false |
13
|
04ab79c511aa5c1a7e3e22f4ce02fa24fd9c9122
| 15,960,098,528,410 |
37124a49068d3aa9c1e2669481a85a1e2f20b104
|
/demo/demo-web/src/main/java/com/bageframework/demo/web/service/UserService.java
|
99d882dcda0930dffe8a638ff1559ad62e97f41f
|
[] |
no_license
|
designreuse/bageframework.org
|
https://github.com/designreuse/bageframework.org
|
092ff82dee180b3bcde2fb74eab56919c0a69ac9
|
c174b8029f84e904431bcf5c3c6ed0955c31682a
|
refs/heads/master
| 2021-01-12T14:08:34.609000 | 2016-08-29T15:52:57 | 2016-08-29T15:52:57 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.bageframework.demo.web.service;
import com.bageframework.demo.web.model.User;
import com.bageframework.demo.web.vo.UserVO;
import com.bageframework.demo.web.vo.admin.UserAdminVO;
import com.bageframework.service.IService;
public interface UserService extends IService<User, UserVO, UserAdminVO, String> {
public User login(String username, String password);
}
|
UTF-8
|
Java
| 376 |
java
|
UserService.java
|
Java
|
[] | null |
[] |
package com.bageframework.demo.web.service;
import com.bageframework.demo.web.model.User;
import com.bageframework.demo.web.vo.UserVO;
import com.bageframework.demo.web.vo.admin.UserAdminVO;
import com.bageframework.service.IService;
public interface UserService extends IService<User, UserVO, UserAdminVO, String> {
public User login(String username, String password);
}
| 376 | 0.816489 | 0.816489 | 11 | 33.18182 | 27.004438 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false |
13
|
c32eb9568a2eb2fe6124a0ff9cc925693772f14f
| 30,030,411,346,318 |
77027b7b88167e4f0df456c97c9cd2fb86b02d05
|
/app/src/main/java/bc/otlhd/com/data/SetPriceDao.java
|
06d182c4234c3e030381f3c13c7d74522cd018fe
|
[] |
no_license
|
gamekonglee/leishiHD
|
https://github.com/gamekonglee/leishiHD
|
5253533631a2976632fc249694737d9192f214c3
|
90985aee7ba89d0abbe207963e0127851019977b
|
refs/heads/master
| 2020-06-26T23:47:17.115000 | 2019-08-15T02:36:14 | 2019-08-15T02:36:14 | 199,790,659 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package bc.otlhd.com.data;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.lib.common.hxp.db.DatabaseManager;
import com.lib.common.hxp.db.SQLHelper;
import com.lib.common.hxp.db.SetPriceSQL;
import java.util.ArrayList;
import java.util.List;
import bc.otlhd.com.bean.GoodPrices;
import bc.otlhd.com.cons.Constance;
/**
* @author: Jun
* @date : 2017/4/24 11:05
* @description :
*/
public class SetPriceDao {
private final String TAG = CartDao.class.getSimpleName();
public SetPriceDao(Context context) {
SQLHelper helper = new SQLHelper(context, Constance.DB_NAME, null, Constance.DB_VERSION);
DatabaseManager.initializeInstance(helper);
}
/**
* 添加(或更新)一条记录
*
* @param
* @return -1:添加(更新)失败;否则添加成功
*/
public long replaceOne(GoodPrices bean) {
long result = -1;
try {
SQLiteDatabase db = DatabaseManager.getInstance().openDatabase();
ContentValues values = new ContentValues();
values.put(SetPriceSQL.PID, bean.getId());
values.put(SetPriceSQL.PRICE, bean.getShop_price());
if (db.isOpen()) {
result = db.replace(SetPriceSQL.TABLE_NAME, null, values);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DatabaseManager.getInstance().closeDatabase();
}
return result;
}
/**
* 获取所有记录
*
* @return
*/
public List<GoodPrices> getAll() {
Cursor cursor = null;
List<GoodPrices> beans = new ArrayList<>();
try {
SQLiteDatabase db = DatabaseManager.getInstance().openDatabase();
if (db.isOpen()) {
cursor = db.query(SetPriceSQL.TABLE_NAME, null, null, null, null, null, null);
while (cursor.moveToNext()) {
int pId = cursor.getInt(cursor.getColumnIndex(SetPriceSQL.PID));
float price = cursor.getFloat(cursor.getColumnIndex(SetPriceSQL.PRICE));
GoodPrices bean = new GoodPrices();
bean.setId(pId);
bean.setShop_price(price);
beans.add(bean);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != cursor)
cursor.close();
DatabaseManager.getInstance().closeDatabase();
}
return beans;
}
/**
* 删除一个记录
*
* @param pId 产品id
* @return 删除成功记录数
*/
public int deleteOne(int pId) {
int result = 0;
try {
SQLiteDatabase db = DatabaseManager.getInstance().openDatabase();
if (db.isOpen()) {
result = db.delete(SetPriceSQL.TABLE_NAME, SetPriceSQL.PID + "=?", new String[]{String.valueOf(pId)});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DatabaseManager.getInstance().closeDatabase();
}
return result;
}
public GoodPrices getProductPrice(String id){
Cursor cursor = null;
GoodPrices bean=new GoodPrices();
try {
SQLiteDatabase db = DatabaseManager.getInstance().openDatabase();
if (db.isOpen()) {
cursor=db.query(SetPriceSQL.TABLE_NAME,null, SetPriceSQL.PID + "=?", new String[]{id}, null, null, null);
while (cursor.moveToNext()) {
int pId = cursor.getInt(cursor.getColumnIndex(SetPriceSQL.PID));
float price = cursor.getFloat(cursor.getColumnIndex(SetPriceSQL.PRICE));
bean.setId(pId);
bean.setShop_price(price);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DatabaseManager.getInstance().closeDatabase();
}
return bean;
}
}
|
UTF-8
|
Java
| 4,162 |
java
|
SetPriceDao.java
|
Java
|
[
{
"context": "port bc.otlhd.com.cons.Constance;\n\n/**\n * @author: Jun\n * @date : 2017/4/24 11:05\n * @description :\n */\n",
"end": 452,
"score": 0.996870219707489,
"start": 449,
"tag": "NAME",
"value": "Jun"
}
] | null |
[] |
package bc.otlhd.com.data;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.lib.common.hxp.db.DatabaseManager;
import com.lib.common.hxp.db.SQLHelper;
import com.lib.common.hxp.db.SetPriceSQL;
import java.util.ArrayList;
import java.util.List;
import bc.otlhd.com.bean.GoodPrices;
import bc.otlhd.com.cons.Constance;
/**
* @author: Jun
* @date : 2017/4/24 11:05
* @description :
*/
public class SetPriceDao {
private final String TAG = CartDao.class.getSimpleName();
public SetPriceDao(Context context) {
SQLHelper helper = new SQLHelper(context, Constance.DB_NAME, null, Constance.DB_VERSION);
DatabaseManager.initializeInstance(helper);
}
/**
* 添加(或更新)一条记录
*
* @param
* @return -1:添加(更新)失败;否则添加成功
*/
public long replaceOne(GoodPrices bean) {
long result = -1;
try {
SQLiteDatabase db = DatabaseManager.getInstance().openDatabase();
ContentValues values = new ContentValues();
values.put(SetPriceSQL.PID, bean.getId());
values.put(SetPriceSQL.PRICE, bean.getShop_price());
if (db.isOpen()) {
result = db.replace(SetPriceSQL.TABLE_NAME, null, values);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DatabaseManager.getInstance().closeDatabase();
}
return result;
}
/**
* 获取所有记录
*
* @return
*/
public List<GoodPrices> getAll() {
Cursor cursor = null;
List<GoodPrices> beans = new ArrayList<>();
try {
SQLiteDatabase db = DatabaseManager.getInstance().openDatabase();
if (db.isOpen()) {
cursor = db.query(SetPriceSQL.TABLE_NAME, null, null, null, null, null, null);
while (cursor.moveToNext()) {
int pId = cursor.getInt(cursor.getColumnIndex(SetPriceSQL.PID));
float price = cursor.getFloat(cursor.getColumnIndex(SetPriceSQL.PRICE));
GoodPrices bean = new GoodPrices();
bean.setId(pId);
bean.setShop_price(price);
beans.add(bean);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != cursor)
cursor.close();
DatabaseManager.getInstance().closeDatabase();
}
return beans;
}
/**
* 删除一个记录
*
* @param pId 产品id
* @return 删除成功记录数
*/
public int deleteOne(int pId) {
int result = 0;
try {
SQLiteDatabase db = DatabaseManager.getInstance().openDatabase();
if (db.isOpen()) {
result = db.delete(SetPriceSQL.TABLE_NAME, SetPriceSQL.PID + "=?", new String[]{String.valueOf(pId)});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DatabaseManager.getInstance().closeDatabase();
}
return result;
}
public GoodPrices getProductPrice(String id){
Cursor cursor = null;
GoodPrices bean=new GoodPrices();
try {
SQLiteDatabase db = DatabaseManager.getInstance().openDatabase();
if (db.isOpen()) {
cursor=db.query(SetPriceSQL.TABLE_NAME,null, SetPriceSQL.PID + "=?", new String[]{id}, null, null, null);
while (cursor.moveToNext()) {
int pId = cursor.getInt(cursor.getColumnIndex(SetPriceSQL.PID));
float price = cursor.getFloat(cursor.getColumnIndex(SetPriceSQL.PRICE));
bean.setId(pId);
bean.setShop_price(price);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DatabaseManager.getInstance().closeDatabase();
}
return bean;
}
}
| 4,162 | 0.559676 | 0.556238 | 132 | 29.85606 | 26.081495 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.575758 | false | false |
13
|
9afe02b891e624fe985880e615f766e8d5cc9a5a
| 841,813,659,012 |
f20b919ed02c78634d8aa01bbc65ca7863dc503e
|
/src/main/java/de/uhd/ifi/se/decision/management/jira/rest/ViewRest.java
|
bc095dae5685745c9c3381f6c5f9b4bfd452baa1
|
[
"MIT"
] |
permissive
|
cures-hub/cures-decdoc-jira
|
https://github.com/cures-hub/cures-decdoc-jira
|
4f163dcfc613223cc8b39e62ac5fb00e34ecc1d7
|
b0941604faf232ccf63dfe8e9a1e52c7f05b6af8
|
refs/heads/master
| 2020-12-02T18:41:21.238000 | 2020-11-29T21:28:21 | 2020-11-29T21:28:21 | 96,444,830 | 1 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package de.uhd.ifi.se.decision.management.jira.rest;
import java.util.List;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.user.ApplicationUser;
import com.google.common.collect.ImmutableMap;
import de.uhd.ifi.se.decision.management.jira.config.AuthenticationManager;
import de.uhd.ifi.se.decision.management.jira.decisionguidance.knowledgesources.KnowledgeSource;
import de.uhd.ifi.se.decision.management.jira.decisionguidance.recommender.BaseRecommender;
import de.uhd.ifi.se.decision.management.jira.decisionguidance.recommender.EvaluationRecommender;
import de.uhd.ifi.se.decision.management.jira.decisionguidance.recommender.RecommenderType;
import de.uhd.ifi.se.decision.management.jira.decisionguidance.recommender.factory.RecommenderFactory;
import de.uhd.ifi.se.decision.management.jira.extraction.versioncontrol.CommitMessageToCommentTranscriber;
import de.uhd.ifi.se.decision.management.jira.filtering.FilterSettings;
import de.uhd.ifi.se.decision.management.jira.filtering.FilteringManager;
import de.uhd.ifi.se.decision.management.jira.model.DocumentationLocation;
import de.uhd.ifi.se.decision.management.jira.model.KnowledgeElement;
import de.uhd.ifi.se.decision.management.jira.model.KnowledgeGraph;
import de.uhd.ifi.se.decision.management.jira.model.KnowledgeType;
import de.uhd.ifi.se.decision.management.jira.persistence.ConfigPersistenceManager;
import de.uhd.ifi.se.decision.management.jira.persistence.KnowledgePersistenceManager;
import de.uhd.ifi.se.decision.management.jira.view.decisionguidance.Recommendation;
import de.uhd.ifi.se.decision.management.jira.view.decisionguidance.RecommendationEvaluation;
import de.uhd.ifi.se.decision.management.jira.view.decisiontable.DecisionTable;
import de.uhd.ifi.se.decision.management.jira.view.diffviewer.DiffViewer;
import de.uhd.ifi.se.decision.management.jira.view.matrix.Matrix;
import de.uhd.ifi.se.decision.management.jira.view.treant.Treant;
import de.uhd.ifi.se.decision.management.jira.view.treeviewer.TreeViewer;
import de.uhd.ifi.se.decision.management.jira.view.vis.VisGraph;
import de.uhd.ifi.se.decision.management.jira.view.vis.VisTimeLine;
/**
* REST resource for view
*/
@Path("/view")
public class ViewRest {
private static final Logger LOGGER = LoggerFactory.getLogger(ViewRest.class);
@Path("/elementsFromBranchesOfProject")
@GET
public Response getElementsFromAllBranchesOfProject(@QueryParam("projectKey") String projectKey) {
Response checkIfProjectKeyIsValidResponse = RestParameterChecker.checkIfProjectKeyIsValid(projectKey);
if (checkIfProjectKeyIsValidResponse.getStatus() != Status.OK.getStatusCode()) {
return checkIfProjectKeyIsValidResponse;
}
if (!ConfigPersistenceManager.isKnowledgeExtractedFromGit(projectKey)) {
return Response.status(Status.SERVICE_UNAVAILABLE)
.entity(ImmutableMap.of("error", "Git extraction is disabled in project settings.")).build();
}
return Response.ok(new DiffViewer(projectKey)).build();
}
@Path("/elementsFromBranchesOfJiraIssue")
@GET
public Response getElementsOfFeatureBranchForJiraIssue(@Context HttpServletRequest request,
@QueryParam("issueKey") String issueKey) {
if (request == null || issueKey == null || issueKey.isBlank()) {
return Response.status(Status.BAD_REQUEST).entity(ImmutableMap.of("error",
"Invalid parameters given. Knowledge from feature branch cannot be shown.")).build();
}
String projectKey = getProjectKey(issueKey);
Issue issue = ComponentAccessor.getIssueManager().getIssueObject(issueKey);
if (issue == null) {
return jiraIssueKeyIsInvalid();
}
if (!ConfigPersistenceManager.isKnowledgeExtractedFromGit(projectKey)) {
return Response.status(Status.SERVICE_UNAVAILABLE)
.entity(ImmutableMap.of("error", "Git extraction is disabled in project settings.")).build();
}
new CommitMessageToCommentTranscriber(issue).postCommitsIntoJiraIssueComments();
return Response.ok(new DiffViewer(projectKey, issueKey)).build();
}
/**
* Returns a jstree tree viewer that matches the {@link FilterSettings}. If a
* knowledge element is selected in the {@link FilterSettings}, the tree viewer
* comprises only one tree with the selected element as the root element. If no
* element is selected, the tree viewer contains a list of trees.
*
* @param filterSettings For example, the {@link FilterSettings} cover the selected element
* and the knowledge types to be shown. The selected element can be
* null.
*/
@Path("/getTreeViewer")
@POST
public Response getTreeViewer(@Context HttpServletRequest request, FilterSettings filterSettings) {
if (request == null || filterSettings == null) {
return Response.status(Status.BAD_REQUEST)
.entity(ImmutableMap.of("error", "Invalid parameters given. Tree viewer not be created.")).build();
}
String projectKey = filterSettings.getProjectKey();
Response checkIfProjectKeyIsValidResponse = RestParameterChecker.checkIfProjectKeyIsValid(projectKey);
if (checkIfProjectKeyIsValidResponse.getStatus() != Status.OK.getStatusCode()) {
return checkIfProjectKeyIsValidResponse;
}
TreeViewer treeViewer = new TreeViewer(filterSettings);
return Response.ok(treeViewer).build();
}
@Path("/getEvolutionData")
@POST
@Produces({MediaType.APPLICATION_JSON})
public Response getEvolutionData(@Context HttpServletRequest request, FilterSettings filterSettings,
@QueryParam("isPlacedAtCreationDate") boolean isPlacedAtCreationDate,
@QueryParam("isPlacedAtUpdatingDate") boolean isPlacedAtUpdatingDate) {
if (request == null) {
return Response.status(Status.BAD_REQUEST)
.entity(ImmutableMap.of("error", "HttpServletRequest is null. Timeline could not be created."))
.build();
}
if (filterSettings == null || filterSettings.getProjectKey() == null
|| filterSettings.getProjectKey().isBlank()) {
return Response.status(Status.BAD_REQUEST).entity(ImmutableMap.of("error", "Project key is not valid."))
.build();
}
ApplicationUser user = AuthenticationManager.getUser(request);
VisTimeLine timeLine = new VisTimeLine(user, filterSettings, isPlacedAtCreationDate, isPlacedAtUpdatingDate);
return Response.ok(timeLine).build();
}
@Path("/decisionTable")
@POST
@Produces({MediaType.APPLICATION_JSON})
public Response getDecisionTable(@Context HttpServletRequest request, FilterSettings filterSettings) {
if (request == null || filterSettings == null || filterSettings.getSelectedElement() == null) {
return Response.status(Status.BAD_REQUEST).entity(
ImmutableMap.of("error", "Decision Table cannot be shown due to missing or invalid parameters."))
.build();
}
String projectKey = filterSettings.getProjectKey();
Response checkIfProjectKeyIsValidResponse = RestParameterChecker.checkIfProjectKeyIsValid(projectKey);
if (checkIfProjectKeyIsValidResponse.getStatus() != Status.OK.getStatusCode()) {
return checkIfProjectKeyIsValidResponse;
}
DecisionTable decisionTable = new DecisionTable(projectKey);
ApplicationUser user = AuthenticationManager.getUser(request);
KnowledgeElement issue = filterSettings.getSelectedElement();
decisionTable.setDecisionTableForIssue(issue, user);
return Response.ok(decisionTable.getDecisionTableData()).build();
}
/**
* @return all available criteria (e.g. quality attributes, non-functional
* requirements) for a project.
*/
@Path("/decisionTableCriteria")
@GET
@Produces({MediaType.APPLICATION_JSON})
public Response getDecisionTableCriteria(@Context HttpServletRequest request,
@QueryParam("projectKey") String projectKey) {
if (request == null) {
return Response.status(Status.BAD_REQUEST).entity(
ImmutableMap.of("error", "Decision Table cannot be shown due to missing or invalid parameters."))
.build();
}
Response checkIfProjectKeyIsValidResponse = RestParameterChecker.checkIfProjectKeyIsValid(projectKey);
if (checkIfProjectKeyIsValidResponse.getStatus() != Status.OK.getStatusCode()) {
return checkIfProjectKeyIsValidResponse;
}
DecisionTable decisionTable = new DecisionTable(projectKey);
ApplicationUser user = AuthenticationManager.getUser(request);
return Response.ok(decisionTable.getDecisionTableCriteria(user)).build();
}
@Path("/getTreant")
@POST
@Produces({MediaType.APPLICATION_JSON})
public Response getTreant(@Context HttpServletRequest request, FilterSettings filterSettings) {
if (request == null || filterSettings == null || filterSettings.getSelectedElement() == null
|| filterSettings.getSelectedElement().getKey() == null) {
return Response.status(Status.BAD_REQUEST)
.entity(ImmutableMap.of("error", "Treant cannot be shown since request or element key is invalid."))
.build();
}
String projectKey = filterSettings.getProjectKey();
Response checkIfProjectKeyIsValidResponse = RestParameterChecker.checkIfProjectKeyIsValid(projectKey);
if (checkIfProjectKeyIsValidResponse.getStatus() != Status.OK.getStatusCode()) {
return checkIfProjectKeyIsValidResponse;
}
Treant treant = new Treant(filterSettings);
return Response.ok(treant).build();
}
@Path("/getVis")
@POST
@Produces({MediaType.APPLICATION_JSON})
public Response getVis(@Context HttpServletRequest request, FilterSettings filterSettings) {
if (request == null || filterSettings == null) {
return Response.status(Status.BAD_REQUEST)
.entity(ImmutableMap.of("error",
"The HttpServletRequest or the filter settings are null. Vis graph could not be created."))
.build();
}
String projectKey = filterSettings.getProjectKey();
Response checkIfProjectKeyIsValidResponse = RestParameterChecker.checkIfProjectKeyIsValid(projectKey);
if (checkIfProjectKeyIsValidResponse.getStatus() != Status.OK.getStatusCode()) {
return checkIfProjectKeyIsValidResponse;
}
ApplicationUser user = AuthenticationManager.getUser(request);
VisGraph visGraph = new VisGraph(user, filterSettings);
return Response.ok(visGraph).build();
}
@Path("/getFilterSettings")
@GET
@Produces({MediaType.APPLICATION_JSON})
public Response getFilterSettings(@Context HttpServletRequest request, @QueryParam("searchTerm") String searchTerm,
@QueryParam("elementKey") String elementKey) {
String projectKey;
if (RestParameterChecker.checkIfProjectKeyIsValid(elementKey).getStatus() == Status.OK.getStatusCode()) {
projectKey = elementKey;
} else if (checkIfElementIsValid(elementKey).getStatus() == Status.OK.getStatusCode()) {
projectKey = getProjectKey(elementKey);
} else {
return checkIfElementIsValid(elementKey);
}
ApplicationUser user = AuthenticationManager.getUser(request);
return Response.ok(new FilterSettings(projectKey, searchTerm, user)).build();
}
/**
* @param filterSettings For example, the {@link FilterSettings} cover the
* {@link KnowledgeType}s to be shown.
* @return adjacency matrix of the {@link KnowledgeGraph} or a filtered subgraph
* provided by the {@link FilteringManager}.
*/
@Path("/getMatrix")
@POST
@Produces({MediaType.APPLICATION_JSON})
public Response getMatrix(@Context HttpServletRequest request, FilterSettings filterSettings) {
if (request == null || filterSettings == null) {
return Response.status(Status.BAD_REQUEST)
.entity(ImmutableMap.of("error",
"Matrix cannot be shown since the HttpServletRequest or filter settings are invalid."))
.build();
}
String projectKey = filterSettings.getProjectKey();
Response checkIfProjectKeyIsValidResponse = RestParameterChecker.checkIfProjectKeyIsValid(projectKey);
if (checkIfProjectKeyIsValidResponse.getStatus() != Status.OK.getStatusCode()) {
return checkIfProjectKeyIsValidResponse;
}
Matrix matrix = new Matrix(filterSettings);
return Response.ok(matrix).build();
}
private String getProjectKey(String elementKey) {
return elementKey.split("-")[0].toUpperCase(Locale.ENGLISH);
}
private Response checkIfElementIsValid(String elementKey) {
if (elementKey == null) {
return jiraIssueKeyIsInvalid();
}
String projectKey = getProjectKey(elementKey);
Response checkIfProjectKeyIsValidResponse = RestParameterChecker.checkIfProjectKeyIsValid(projectKey);
if (checkIfProjectKeyIsValidResponse.getStatus() != Status.OK.getStatusCode()) {
return checkIfProjectKeyIsValidResponse;
}
return Response.status(Status.OK).build();
}
private Response jiraIssueKeyIsInvalid() {
String message = "Decision knowledge elements cannot be shown" + " since the Jira issue key is invalid.";
LOGGER.error(message);
return Response.status(Status.BAD_REQUEST).entity(ImmutableMap.of("error", message)).build();
}
@Path("/getRecommendation")
@GET
@Produces({MediaType.APPLICATION_JSON})
public Response getRecommendation(@Context HttpServletRequest request, @QueryParam("projectKey") String projectKey,
@QueryParam("keyword") String keyword, @QueryParam("issueID") int issueID) {
if (request == null) {
return Response.status(Status.BAD_REQUEST).entity(ImmutableMap.of("error", "Request is null!")).build();
}
Response checkIfProjectKeyIsValidResponse = RestParameterChecker.checkIfProjectKeyIsValid(projectKey);
if (checkIfProjectKeyIsValidResponse.getStatus() != Status.OK.getStatusCode()) {
return checkIfProjectKeyIsValidResponse;
}
if (keyword.isBlank()) {
return Response.status(Status.BAD_REQUEST)
.entity(ImmutableMap.of("error", "The keywords should not be empty.")).build();
}
List<KnowledgeSource> allKnowledgeSources = ConfigPersistenceManager.getAllKnowledgeSources(projectKey);
KnowledgeElement knowledgeElement = this.getIssueFromDocumentationLocation(issueID, projectKey);
RecommenderType recommenderType = ConfigPersistenceManager.getRecommendationInput(projectKey);
BaseRecommender recommender = RecommenderFactory.getRecommender(recommenderType);
recommender.addKnowledgeSource(allKnowledgeSources);
if (RecommenderType.KEYWORD.equals(recommenderType))
recommender.setInput(keyword);
else {
if (knowledgeElement == null) {
return Response.status(Status.BAD_REQUEST)
.entity(ImmutableMap.of("error", "The Knowledgeelement could not be found.")).build();
}
recommender.setInput(knowledgeElement);
}
if (checkIfKnowledgeSourceNotConfigured(recommender)) {
return Response.status(Status.BAD_REQUEST).entity(ImmutableMap.of("error",
"There is no knowledge source configured! <a href='/jira/plugins/servlet/condec/settings?projectKey="
+ projectKey + "&category=decisionGuidance'>Configure</a>"))
.build();
}
List<Recommendation> recommendationList = recommender.getRecommendation();
if (ConfigPersistenceManager.getAddRecommendationDirectly(projectKey))
recommender.addToKnowledgeGraph(knowledgeElement, AuthenticationManager.getUser(request), projectKey);
return Response.ok(recommendationList).build();
}
@Path("/getRecommendationEvaluation")
@GET
@Produces({MediaType.APPLICATION_JSON})
public Response getRecommendationEvaluation(@Context HttpServletRequest request,
@QueryParam("projectKey") String projectKey, @QueryParam("keyword") String keyword,
@QueryParam("issueID") int issueID, @QueryParam("knowledgeSource") String knowledgeSourceName, @QueryParam("kResults") int kResults) {
if (request == null) {
return Response.status(Status.BAD_REQUEST).entity(ImmutableMap.of("error", "Request is null!")).build();
}
Response checkIfProjectKeyIsValidResponse = RestParameterChecker.checkIfProjectKeyIsValid(projectKey);
if (checkIfProjectKeyIsValidResponse.getStatus() != Status.OK.getStatusCode()) {
return checkIfProjectKeyIsValidResponse;
}
List<KnowledgeSource> allKnowledgeSources = ConfigPersistenceManager.getAllKnowledgeSources(projectKey);
KnowledgeElement issue = this.getIssueFromDocumentationLocation(issueID, projectKey);
// we use?
if (issue == null) {
return Response.status(Status.NOT_FOUND).entity(ImmutableMap.of("error", "The issue could not be found."))
.build();
}
EvaluationRecommender recommender = new EvaluationRecommender(issue, keyword, kResults);
RecommendationEvaluation recommendationEvaluation = recommender.evaluate(issue)
.withKnowledgeSource(allKnowledgeSources, knowledgeSourceName).execute();
return Response.ok(recommendationEvaluation).build();
}
private KnowledgeElement getIssueFromDocumentationLocation(long id, String projectKey) {
KnowledgePersistenceManager manager = KnowledgePersistenceManager.getOrCreate(projectKey);
KnowledgeElement issue = null;
for (DocumentationLocation location : DocumentationLocation.getAllDocumentationLocations()) {
issue = manager.getKnowledgeElement(id, location);
if (issue != null)
return issue;
}
return issue;
}
private boolean checkIfKnowledgeSourceNotConfigured(BaseRecommender<?> recommender) {
for (KnowledgeSource knowledgeSource : recommender.getKnowledgeSources()) {
if (knowledgeSource.isActivated())
return false;
}
return true;
}
}
|
UTF-8
|
Java
| 17,919 |
java
|
ViewRest.java
|
Java
|
[] | null |
[] |
package de.uhd.ifi.se.decision.management.jira.rest;
import java.util.List;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.user.ApplicationUser;
import com.google.common.collect.ImmutableMap;
import de.uhd.ifi.se.decision.management.jira.config.AuthenticationManager;
import de.uhd.ifi.se.decision.management.jira.decisionguidance.knowledgesources.KnowledgeSource;
import de.uhd.ifi.se.decision.management.jira.decisionguidance.recommender.BaseRecommender;
import de.uhd.ifi.se.decision.management.jira.decisionguidance.recommender.EvaluationRecommender;
import de.uhd.ifi.se.decision.management.jira.decisionguidance.recommender.RecommenderType;
import de.uhd.ifi.se.decision.management.jira.decisionguidance.recommender.factory.RecommenderFactory;
import de.uhd.ifi.se.decision.management.jira.extraction.versioncontrol.CommitMessageToCommentTranscriber;
import de.uhd.ifi.se.decision.management.jira.filtering.FilterSettings;
import de.uhd.ifi.se.decision.management.jira.filtering.FilteringManager;
import de.uhd.ifi.se.decision.management.jira.model.DocumentationLocation;
import de.uhd.ifi.se.decision.management.jira.model.KnowledgeElement;
import de.uhd.ifi.se.decision.management.jira.model.KnowledgeGraph;
import de.uhd.ifi.se.decision.management.jira.model.KnowledgeType;
import de.uhd.ifi.se.decision.management.jira.persistence.ConfigPersistenceManager;
import de.uhd.ifi.se.decision.management.jira.persistence.KnowledgePersistenceManager;
import de.uhd.ifi.se.decision.management.jira.view.decisionguidance.Recommendation;
import de.uhd.ifi.se.decision.management.jira.view.decisionguidance.RecommendationEvaluation;
import de.uhd.ifi.se.decision.management.jira.view.decisiontable.DecisionTable;
import de.uhd.ifi.se.decision.management.jira.view.diffviewer.DiffViewer;
import de.uhd.ifi.se.decision.management.jira.view.matrix.Matrix;
import de.uhd.ifi.se.decision.management.jira.view.treant.Treant;
import de.uhd.ifi.se.decision.management.jira.view.treeviewer.TreeViewer;
import de.uhd.ifi.se.decision.management.jira.view.vis.VisGraph;
import de.uhd.ifi.se.decision.management.jira.view.vis.VisTimeLine;
/**
* REST resource for view
*/
@Path("/view")
public class ViewRest {
private static final Logger LOGGER = LoggerFactory.getLogger(ViewRest.class);
@Path("/elementsFromBranchesOfProject")
@GET
public Response getElementsFromAllBranchesOfProject(@QueryParam("projectKey") String projectKey) {
Response checkIfProjectKeyIsValidResponse = RestParameterChecker.checkIfProjectKeyIsValid(projectKey);
if (checkIfProjectKeyIsValidResponse.getStatus() != Status.OK.getStatusCode()) {
return checkIfProjectKeyIsValidResponse;
}
if (!ConfigPersistenceManager.isKnowledgeExtractedFromGit(projectKey)) {
return Response.status(Status.SERVICE_UNAVAILABLE)
.entity(ImmutableMap.of("error", "Git extraction is disabled in project settings.")).build();
}
return Response.ok(new DiffViewer(projectKey)).build();
}
@Path("/elementsFromBranchesOfJiraIssue")
@GET
public Response getElementsOfFeatureBranchForJiraIssue(@Context HttpServletRequest request,
@QueryParam("issueKey") String issueKey) {
if (request == null || issueKey == null || issueKey.isBlank()) {
return Response.status(Status.BAD_REQUEST).entity(ImmutableMap.of("error",
"Invalid parameters given. Knowledge from feature branch cannot be shown.")).build();
}
String projectKey = getProjectKey(issueKey);
Issue issue = ComponentAccessor.getIssueManager().getIssueObject(issueKey);
if (issue == null) {
return jiraIssueKeyIsInvalid();
}
if (!ConfigPersistenceManager.isKnowledgeExtractedFromGit(projectKey)) {
return Response.status(Status.SERVICE_UNAVAILABLE)
.entity(ImmutableMap.of("error", "Git extraction is disabled in project settings.")).build();
}
new CommitMessageToCommentTranscriber(issue).postCommitsIntoJiraIssueComments();
return Response.ok(new DiffViewer(projectKey, issueKey)).build();
}
/**
* Returns a jstree tree viewer that matches the {@link FilterSettings}. If a
* knowledge element is selected in the {@link FilterSettings}, the tree viewer
* comprises only one tree with the selected element as the root element. If no
* element is selected, the tree viewer contains a list of trees.
*
* @param filterSettings For example, the {@link FilterSettings} cover the selected element
* and the knowledge types to be shown. The selected element can be
* null.
*/
@Path("/getTreeViewer")
@POST
public Response getTreeViewer(@Context HttpServletRequest request, FilterSettings filterSettings) {
if (request == null || filterSettings == null) {
return Response.status(Status.BAD_REQUEST)
.entity(ImmutableMap.of("error", "Invalid parameters given. Tree viewer not be created.")).build();
}
String projectKey = filterSettings.getProjectKey();
Response checkIfProjectKeyIsValidResponse = RestParameterChecker.checkIfProjectKeyIsValid(projectKey);
if (checkIfProjectKeyIsValidResponse.getStatus() != Status.OK.getStatusCode()) {
return checkIfProjectKeyIsValidResponse;
}
TreeViewer treeViewer = new TreeViewer(filterSettings);
return Response.ok(treeViewer).build();
}
@Path("/getEvolutionData")
@POST
@Produces({MediaType.APPLICATION_JSON})
public Response getEvolutionData(@Context HttpServletRequest request, FilterSettings filterSettings,
@QueryParam("isPlacedAtCreationDate") boolean isPlacedAtCreationDate,
@QueryParam("isPlacedAtUpdatingDate") boolean isPlacedAtUpdatingDate) {
if (request == null) {
return Response.status(Status.BAD_REQUEST)
.entity(ImmutableMap.of("error", "HttpServletRequest is null. Timeline could not be created."))
.build();
}
if (filterSettings == null || filterSettings.getProjectKey() == null
|| filterSettings.getProjectKey().isBlank()) {
return Response.status(Status.BAD_REQUEST).entity(ImmutableMap.of("error", "Project key is not valid."))
.build();
}
ApplicationUser user = AuthenticationManager.getUser(request);
VisTimeLine timeLine = new VisTimeLine(user, filterSettings, isPlacedAtCreationDate, isPlacedAtUpdatingDate);
return Response.ok(timeLine).build();
}
@Path("/decisionTable")
@POST
@Produces({MediaType.APPLICATION_JSON})
public Response getDecisionTable(@Context HttpServletRequest request, FilterSettings filterSettings) {
if (request == null || filterSettings == null || filterSettings.getSelectedElement() == null) {
return Response.status(Status.BAD_REQUEST).entity(
ImmutableMap.of("error", "Decision Table cannot be shown due to missing or invalid parameters."))
.build();
}
String projectKey = filterSettings.getProjectKey();
Response checkIfProjectKeyIsValidResponse = RestParameterChecker.checkIfProjectKeyIsValid(projectKey);
if (checkIfProjectKeyIsValidResponse.getStatus() != Status.OK.getStatusCode()) {
return checkIfProjectKeyIsValidResponse;
}
DecisionTable decisionTable = new DecisionTable(projectKey);
ApplicationUser user = AuthenticationManager.getUser(request);
KnowledgeElement issue = filterSettings.getSelectedElement();
decisionTable.setDecisionTableForIssue(issue, user);
return Response.ok(decisionTable.getDecisionTableData()).build();
}
/**
* @return all available criteria (e.g. quality attributes, non-functional
* requirements) for a project.
*/
@Path("/decisionTableCriteria")
@GET
@Produces({MediaType.APPLICATION_JSON})
public Response getDecisionTableCriteria(@Context HttpServletRequest request,
@QueryParam("projectKey") String projectKey) {
if (request == null) {
return Response.status(Status.BAD_REQUEST).entity(
ImmutableMap.of("error", "Decision Table cannot be shown due to missing or invalid parameters."))
.build();
}
Response checkIfProjectKeyIsValidResponse = RestParameterChecker.checkIfProjectKeyIsValid(projectKey);
if (checkIfProjectKeyIsValidResponse.getStatus() != Status.OK.getStatusCode()) {
return checkIfProjectKeyIsValidResponse;
}
DecisionTable decisionTable = new DecisionTable(projectKey);
ApplicationUser user = AuthenticationManager.getUser(request);
return Response.ok(decisionTable.getDecisionTableCriteria(user)).build();
}
@Path("/getTreant")
@POST
@Produces({MediaType.APPLICATION_JSON})
public Response getTreant(@Context HttpServletRequest request, FilterSettings filterSettings) {
if (request == null || filterSettings == null || filterSettings.getSelectedElement() == null
|| filterSettings.getSelectedElement().getKey() == null) {
return Response.status(Status.BAD_REQUEST)
.entity(ImmutableMap.of("error", "Treant cannot be shown since request or element key is invalid."))
.build();
}
String projectKey = filterSettings.getProjectKey();
Response checkIfProjectKeyIsValidResponse = RestParameterChecker.checkIfProjectKeyIsValid(projectKey);
if (checkIfProjectKeyIsValidResponse.getStatus() != Status.OK.getStatusCode()) {
return checkIfProjectKeyIsValidResponse;
}
Treant treant = new Treant(filterSettings);
return Response.ok(treant).build();
}
@Path("/getVis")
@POST
@Produces({MediaType.APPLICATION_JSON})
public Response getVis(@Context HttpServletRequest request, FilterSettings filterSettings) {
if (request == null || filterSettings == null) {
return Response.status(Status.BAD_REQUEST)
.entity(ImmutableMap.of("error",
"The HttpServletRequest or the filter settings are null. Vis graph could not be created."))
.build();
}
String projectKey = filterSettings.getProjectKey();
Response checkIfProjectKeyIsValidResponse = RestParameterChecker.checkIfProjectKeyIsValid(projectKey);
if (checkIfProjectKeyIsValidResponse.getStatus() != Status.OK.getStatusCode()) {
return checkIfProjectKeyIsValidResponse;
}
ApplicationUser user = AuthenticationManager.getUser(request);
VisGraph visGraph = new VisGraph(user, filterSettings);
return Response.ok(visGraph).build();
}
@Path("/getFilterSettings")
@GET
@Produces({MediaType.APPLICATION_JSON})
public Response getFilterSettings(@Context HttpServletRequest request, @QueryParam("searchTerm") String searchTerm,
@QueryParam("elementKey") String elementKey) {
String projectKey;
if (RestParameterChecker.checkIfProjectKeyIsValid(elementKey).getStatus() == Status.OK.getStatusCode()) {
projectKey = elementKey;
} else if (checkIfElementIsValid(elementKey).getStatus() == Status.OK.getStatusCode()) {
projectKey = getProjectKey(elementKey);
} else {
return checkIfElementIsValid(elementKey);
}
ApplicationUser user = AuthenticationManager.getUser(request);
return Response.ok(new FilterSettings(projectKey, searchTerm, user)).build();
}
/**
* @param filterSettings For example, the {@link FilterSettings} cover the
* {@link KnowledgeType}s to be shown.
* @return adjacency matrix of the {@link KnowledgeGraph} or a filtered subgraph
* provided by the {@link FilteringManager}.
*/
@Path("/getMatrix")
@POST
@Produces({MediaType.APPLICATION_JSON})
public Response getMatrix(@Context HttpServletRequest request, FilterSettings filterSettings) {
if (request == null || filterSettings == null) {
return Response.status(Status.BAD_REQUEST)
.entity(ImmutableMap.of("error",
"Matrix cannot be shown since the HttpServletRequest or filter settings are invalid."))
.build();
}
String projectKey = filterSettings.getProjectKey();
Response checkIfProjectKeyIsValidResponse = RestParameterChecker.checkIfProjectKeyIsValid(projectKey);
if (checkIfProjectKeyIsValidResponse.getStatus() != Status.OK.getStatusCode()) {
return checkIfProjectKeyIsValidResponse;
}
Matrix matrix = new Matrix(filterSettings);
return Response.ok(matrix).build();
}
private String getProjectKey(String elementKey) {
return elementKey.split("-")[0].toUpperCase(Locale.ENGLISH);
}
private Response checkIfElementIsValid(String elementKey) {
if (elementKey == null) {
return jiraIssueKeyIsInvalid();
}
String projectKey = getProjectKey(elementKey);
Response checkIfProjectKeyIsValidResponse = RestParameterChecker.checkIfProjectKeyIsValid(projectKey);
if (checkIfProjectKeyIsValidResponse.getStatus() != Status.OK.getStatusCode()) {
return checkIfProjectKeyIsValidResponse;
}
return Response.status(Status.OK).build();
}
private Response jiraIssueKeyIsInvalid() {
String message = "Decision knowledge elements cannot be shown" + " since the Jira issue key is invalid.";
LOGGER.error(message);
return Response.status(Status.BAD_REQUEST).entity(ImmutableMap.of("error", message)).build();
}
@Path("/getRecommendation")
@GET
@Produces({MediaType.APPLICATION_JSON})
public Response getRecommendation(@Context HttpServletRequest request, @QueryParam("projectKey") String projectKey,
@QueryParam("keyword") String keyword, @QueryParam("issueID") int issueID) {
if (request == null) {
return Response.status(Status.BAD_REQUEST).entity(ImmutableMap.of("error", "Request is null!")).build();
}
Response checkIfProjectKeyIsValidResponse = RestParameterChecker.checkIfProjectKeyIsValid(projectKey);
if (checkIfProjectKeyIsValidResponse.getStatus() != Status.OK.getStatusCode()) {
return checkIfProjectKeyIsValidResponse;
}
if (keyword.isBlank()) {
return Response.status(Status.BAD_REQUEST)
.entity(ImmutableMap.of("error", "The keywords should not be empty.")).build();
}
List<KnowledgeSource> allKnowledgeSources = ConfigPersistenceManager.getAllKnowledgeSources(projectKey);
KnowledgeElement knowledgeElement = this.getIssueFromDocumentationLocation(issueID, projectKey);
RecommenderType recommenderType = ConfigPersistenceManager.getRecommendationInput(projectKey);
BaseRecommender recommender = RecommenderFactory.getRecommender(recommenderType);
recommender.addKnowledgeSource(allKnowledgeSources);
if (RecommenderType.KEYWORD.equals(recommenderType))
recommender.setInput(keyword);
else {
if (knowledgeElement == null) {
return Response.status(Status.BAD_REQUEST)
.entity(ImmutableMap.of("error", "The Knowledgeelement could not be found.")).build();
}
recommender.setInput(knowledgeElement);
}
if (checkIfKnowledgeSourceNotConfigured(recommender)) {
return Response.status(Status.BAD_REQUEST).entity(ImmutableMap.of("error",
"There is no knowledge source configured! <a href='/jira/plugins/servlet/condec/settings?projectKey="
+ projectKey + "&category=decisionGuidance'>Configure</a>"))
.build();
}
List<Recommendation> recommendationList = recommender.getRecommendation();
if (ConfigPersistenceManager.getAddRecommendationDirectly(projectKey))
recommender.addToKnowledgeGraph(knowledgeElement, AuthenticationManager.getUser(request), projectKey);
return Response.ok(recommendationList).build();
}
@Path("/getRecommendationEvaluation")
@GET
@Produces({MediaType.APPLICATION_JSON})
public Response getRecommendationEvaluation(@Context HttpServletRequest request,
@QueryParam("projectKey") String projectKey, @QueryParam("keyword") String keyword,
@QueryParam("issueID") int issueID, @QueryParam("knowledgeSource") String knowledgeSourceName, @QueryParam("kResults") int kResults) {
if (request == null) {
return Response.status(Status.BAD_REQUEST).entity(ImmutableMap.of("error", "Request is null!")).build();
}
Response checkIfProjectKeyIsValidResponse = RestParameterChecker.checkIfProjectKeyIsValid(projectKey);
if (checkIfProjectKeyIsValidResponse.getStatus() != Status.OK.getStatusCode()) {
return checkIfProjectKeyIsValidResponse;
}
List<KnowledgeSource> allKnowledgeSources = ConfigPersistenceManager.getAllKnowledgeSources(projectKey);
KnowledgeElement issue = this.getIssueFromDocumentationLocation(issueID, projectKey);
// we use?
if (issue == null) {
return Response.status(Status.NOT_FOUND).entity(ImmutableMap.of("error", "The issue could not be found."))
.build();
}
EvaluationRecommender recommender = new EvaluationRecommender(issue, keyword, kResults);
RecommendationEvaluation recommendationEvaluation = recommender.evaluate(issue)
.withKnowledgeSource(allKnowledgeSources, knowledgeSourceName).execute();
return Response.ok(recommendationEvaluation).build();
}
private KnowledgeElement getIssueFromDocumentationLocation(long id, String projectKey) {
KnowledgePersistenceManager manager = KnowledgePersistenceManager.getOrCreate(projectKey);
KnowledgeElement issue = null;
for (DocumentationLocation location : DocumentationLocation.getAllDocumentationLocations()) {
issue = manager.getKnowledgeElement(id, location);
if (issue != null)
return issue;
}
return issue;
}
private boolean checkIfKnowledgeSourceNotConfigured(BaseRecommender<?> recommender) {
for (KnowledgeSource knowledgeSource : recommender.getKnowledgeSources()) {
if (knowledgeSource.isActivated())
return false;
}
return true;
}
}
| 17,919 | 0.75752 | 0.757353 | 390 | 43.946156 | 36.193562 | 146 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.34359 | false | false |
13
|
68c7c54cc50c301d38d9812cab912b3f1d2aada9
| 3,264,175,212,935 |
13cbb329807224bd736ff0ac38fd731eb6739389
|
/com/sun/xml/internal/ws/client/dispatch/JAXBDispatch.java
|
1c89b41f597fcfb9742cb4c675bc435b02606df5
|
[] |
no_license
|
ZhipingLi/rt-source
|
https://github.com/ZhipingLi/rt-source
|
5e2537ed5f25d9ba9a0f8009ff8eeca33930564c
|
1a70a036a07b2c6b8a2aac6f71964192c89aae3c
|
refs/heads/master
| 2023-07-14T15:00:33.100000 | 2021-09-01T04:49:04 | 2021-09-01T04:49:04 | 401,933,858 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.sun.xml.internal.ws.client.dispatch;
import com.sun.xml.internal.bind.api.JAXBRIContext;
import com.sun.xml.internal.ws.api.addressing.WSEndpointReference;
import com.sun.xml.internal.ws.api.client.WSPortInfo;
import com.sun.xml.internal.ws.api.message.Header;
import com.sun.xml.internal.ws.api.message.Headers;
import com.sun.xml.internal.ws.api.message.Message;
import com.sun.xml.internal.ws.api.message.Messages;
import com.sun.xml.internal.ws.api.message.Packet;
import com.sun.xml.internal.ws.api.pipe.Tube;
import com.sun.xml.internal.ws.binding.BindingImpl;
import com.sun.xml.internal.ws.client.WSServiceDelegate;
import com.sun.xml.internal.ws.message.jaxb.JAXBDispatchMessage;
import com.sun.xml.internal.ws.spi.db.BindingContextFactory;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.namespace.QName;
import javax.xml.transform.Source;
import javax.xml.ws.Service;
import javax.xml.ws.WebServiceException;
public class JAXBDispatch extends DispatchImpl<Object> {
private final JAXBContext jaxbcontext;
private final boolean isContextSupported;
@Deprecated
public JAXBDispatch(QName paramQName, JAXBContext paramJAXBContext, Service.Mode paramMode, WSServiceDelegate paramWSServiceDelegate, Tube paramTube, BindingImpl paramBindingImpl, WSEndpointReference paramWSEndpointReference) {
super(paramQName, paramMode, paramWSServiceDelegate, paramTube, paramBindingImpl, paramWSEndpointReference);
this.jaxbcontext = paramJAXBContext;
this.isContextSupported = BindingContextFactory.isContextSupported(paramJAXBContext);
}
public JAXBDispatch(WSPortInfo paramWSPortInfo, JAXBContext paramJAXBContext, Service.Mode paramMode, BindingImpl paramBindingImpl, WSEndpointReference paramWSEndpointReference) {
super(paramWSPortInfo, paramMode, paramBindingImpl, paramWSEndpointReference);
this.jaxbcontext = paramJAXBContext;
this.isContextSupported = BindingContextFactory.isContextSupported(paramJAXBContext);
}
Object toReturnValue(Packet paramPacket) {
try {
Source source;
Unmarshaller unmarshaller = this.jaxbcontext.createUnmarshaller();
Message message = paramPacket.getMessage();
switch (this.mode) {
case PAYLOAD:
return message.readPayloadAsJAXB(unmarshaller);
case MESSAGE:
source = message.readEnvelopeAsSource();
return unmarshaller.unmarshal(source);
}
throw new WebServiceException("Unrecognized dispatch mode");
} catch (JAXBException jAXBException) {
throw new WebServiceException(jAXBException);
}
}
Packet createPacket(Object paramObject) {
Message message;
assert this.jaxbcontext != null;
if (this.mode == Service.Mode.MESSAGE) {
message = this.isContextSupported ? new JAXBDispatchMessage(BindingContextFactory.create(this.jaxbcontext), paramObject, this.soapVersion) : new JAXBDispatchMessage(this.jaxbcontext, paramObject, this.soapVersion);
} else if (paramObject == null) {
message = Messages.createEmpty(this.soapVersion);
} else {
message = this.isContextSupported ? Messages.create(this.jaxbcontext, paramObject, this.soapVersion) : Messages.createRaw(this.jaxbcontext, paramObject, this.soapVersion);
}
return new Packet(message);
}
public void setOutboundHeaders(Object... paramVarArgs) {
if (paramVarArgs == null)
throw new IllegalArgumentException();
Header[] arrayOfHeader = new Header[paramVarArgs.length];
for (byte b = 0; b < arrayOfHeader.length; b++) {
if (paramVarArgs[b] == null)
throw new IllegalArgumentException();
arrayOfHeader[b] = Headers.create((JAXBRIContext)this.jaxbcontext, paramVarArgs[b]);
}
setOutboundHeaders(arrayOfHeader);
}
}
/* Location: D:\software\jd-gui\jd-gui-windows-1.6.3\rt.jar!\com\sun\xml\internal\ws\client\dispatch\JAXBDispatch.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.0.7
*/
|
UTF-8
|
Java
| 4,050 |
java
|
JAXBDispatch.java
|
Java
|
[] | null |
[] |
package com.sun.xml.internal.ws.client.dispatch;
import com.sun.xml.internal.bind.api.JAXBRIContext;
import com.sun.xml.internal.ws.api.addressing.WSEndpointReference;
import com.sun.xml.internal.ws.api.client.WSPortInfo;
import com.sun.xml.internal.ws.api.message.Header;
import com.sun.xml.internal.ws.api.message.Headers;
import com.sun.xml.internal.ws.api.message.Message;
import com.sun.xml.internal.ws.api.message.Messages;
import com.sun.xml.internal.ws.api.message.Packet;
import com.sun.xml.internal.ws.api.pipe.Tube;
import com.sun.xml.internal.ws.binding.BindingImpl;
import com.sun.xml.internal.ws.client.WSServiceDelegate;
import com.sun.xml.internal.ws.message.jaxb.JAXBDispatchMessage;
import com.sun.xml.internal.ws.spi.db.BindingContextFactory;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.namespace.QName;
import javax.xml.transform.Source;
import javax.xml.ws.Service;
import javax.xml.ws.WebServiceException;
public class JAXBDispatch extends DispatchImpl<Object> {
private final JAXBContext jaxbcontext;
private final boolean isContextSupported;
@Deprecated
public JAXBDispatch(QName paramQName, JAXBContext paramJAXBContext, Service.Mode paramMode, WSServiceDelegate paramWSServiceDelegate, Tube paramTube, BindingImpl paramBindingImpl, WSEndpointReference paramWSEndpointReference) {
super(paramQName, paramMode, paramWSServiceDelegate, paramTube, paramBindingImpl, paramWSEndpointReference);
this.jaxbcontext = paramJAXBContext;
this.isContextSupported = BindingContextFactory.isContextSupported(paramJAXBContext);
}
public JAXBDispatch(WSPortInfo paramWSPortInfo, JAXBContext paramJAXBContext, Service.Mode paramMode, BindingImpl paramBindingImpl, WSEndpointReference paramWSEndpointReference) {
super(paramWSPortInfo, paramMode, paramBindingImpl, paramWSEndpointReference);
this.jaxbcontext = paramJAXBContext;
this.isContextSupported = BindingContextFactory.isContextSupported(paramJAXBContext);
}
Object toReturnValue(Packet paramPacket) {
try {
Source source;
Unmarshaller unmarshaller = this.jaxbcontext.createUnmarshaller();
Message message = paramPacket.getMessage();
switch (this.mode) {
case PAYLOAD:
return message.readPayloadAsJAXB(unmarshaller);
case MESSAGE:
source = message.readEnvelopeAsSource();
return unmarshaller.unmarshal(source);
}
throw new WebServiceException("Unrecognized dispatch mode");
} catch (JAXBException jAXBException) {
throw new WebServiceException(jAXBException);
}
}
Packet createPacket(Object paramObject) {
Message message;
assert this.jaxbcontext != null;
if (this.mode == Service.Mode.MESSAGE) {
message = this.isContextSupported ? new JAXBDispatchMessage(BindingContextFactory.create(this.jaxbcontext), paramObject, this.soapVersion) : new JAXBDispatchMessage(this.jaxbcontext, paramObject, this.soapVersion);
} else if (paramObject == null) {
message = Messages.createEmpty(this.soapVersion);
} else {
message = this.isContextSupported ? Messages.create(this.jaxbcontext, paramObject, this.soapVersion) : Messages.createRaw(this.jaxbcontext, paramObject, this.soapVersion);
}
return new Packet(message);
}
public void setOutboundHeaders(Object... paramVarArgs) {
if (paramVarArgs == null)
throw new IllegalArgumentException();
Header[] arrayOfHeader = new Header[paramVarArgs.length];
for (byte b = 0; b < arrayOfHeader.length; b++) {
if (paramVarArgs[b] == null)
throw new IllegalArgumentException();
arrayOfHeader[b] = Headers.create((JAXBRIContext)this.jaxbcontext, paramVarArgs[b]);
}
setOutboundHeaders(arrayOfHeader);
}
}
/* Location: D:\software\jd-gui\jd-gui-windows-1.6.3\rt.jar!\com\sun\xml\internal\ws\client\dispatch\JAXBDispatch.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.0.7
*/
| 4,050 | 0.76 | 0.757284 | 90 | 44.011112 | 43.344227 | 229 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.855556 | false | false |
13
|
2abadc65496fa885223ffdb7c3f4b542844d182b
| 4,810,363,391,666 |
856bbaabe790a3bfd43f198ef11868863db79581
|
/JavaWireMock/app/src/main/java/io/github/picotodev/blogbitix/javawiremock/Main.java
|
04c50caaf295085e5b19c015988a1f6afa2bedcf
|
[
"Unlicense"
] |
permissive
|
picodotdev/blog-ejemplos
|
https://github.com/picodotdev/blog-ejemplos
|
a8fde6603364857e87adcf5d7e2bf6547b7a30fa
|
4e1131b8b77a9dd845dea27e8896057155aef7ff
|
refs/heads/master
| 2023-03-19T17:10:12.796000 | 2023-03-16T20:26:58 | 2023-03-16T20:26:58 | 16,209,042 | 95 | 233 |
Unlicense
| false | 2023-03-03T11:25:09 | 2014-01-24T15:55:53 | 2023-01-15T07:41:17 | 2023-03-03T11:25:09 | 66,637 | 86 | 210 | 12 |
JavaScript
| false | false |
package io.github.picotodev.blogbitix.javawiremock;
import java.io.IOException;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;
public class Main {
private Service service;
public Main() {
this.service = buildService();
}
public String getMessage(Long id) throws IOException {
return service.message(id).execute().body();
}
public Service buildService() {
OkHttpClient client = new OkHttpClient.Builder()
.build();
Retrofit retrofit = new Retrofit.Builder()
.client(client)
.addConverterFactory(ScalarsConverterFactory.create())
.baseUrl("http://localhost:8080/").build();
return retrofit.create(Service.class);
}
public static void main(String[] args) {
}
}
|
UTF-8
|
Java
| 877 |
java
|
Main.java
|
Java
|
[
{
"context": "package io.github.picotodev.blogbitix.javawiremock;\n\nimport java.io.IOExcepti",
"end": 27,
"score": 0.9987242817878723,
"start": 18,
"tag": "USERNAME",
"value": "picotodev"
}
] | null |
[] |
package io.github.picotodev.blogbitix.javawiremock;
import java.io.IOException;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;
public class Main {
private Service service;
public Main() {
this.service = buildService();
}
public String getMessage(Long id) throws IOException {
return service.message(id).execute().body();
}
public Service buildService() {
OkHttpClient client = new OkHttpClient.Builder()
.build();
Retrofit retrofit = new Retrofit.Builder()
.client(client)
.addConverterFactory(ScalarsConverterFactory.create())
.baseUrl("http://localhost:8080/").build();
return retrofit.create(Service.class);
}
public static void main(String[] args) {
}
}
| 877 | 0.652223 | 0.644242 | 35 | 24.057142 | 22.686613 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.314286 | false | false |
13
|
0e1cc2c1958545ab4031156e7487fb02c18f599a
| 8,581,344,723,935 |
52d744daee04d95bf684e0c33f902828f4a653a1
|
/src/ss/week2/hotel/Safe.java
|
5c695b325cb67244ca16c67f64111e3f7dd43ec6
|
[] |
no_license
|
emilsbee/uni-code
|
https://github.com/emilsbee/uni-code
|
47520be22d84cd8aa06301684a7c552a61741915
|
e40fd1c5ebd5726bdf45f9551e7108bf3a07efd7
|
refs/heads/main
| 2023-02-02T09:11:37.107000 | 2020-12-18T13:11:05 | 2020-12-18T13:11:05 | 302,037,599 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ss.week2.hotel;
public class Safe {
private boolean active;
private boolean open;
public Safe() {
this.active = false;
this.open = false;
}
public void activate() {
this.active = true;
}
public void deactivate() {
this.open = false;
this.active = false;
}
public void open() {
if (this.active) {
this.open = true;
}
}
public void close() {
this.open = false;
}
public boolean isActive() {
return this.active;
}
public boolean isOpen() {
return this.open;
}
}
|
UTF-8
|
Java
| 633 |
java
|
Safe.java
|
Java
|
[] | null |
[] |
package ss.week2.hotel;
public class Safe {
private boolean active;
private boolean open;
public Safe() {
this.active = false;
this.open = false;
}
public void activate() {
this.active = true;
}
public void deactivate() {
this.open = false;
this.active = false;
}
public void open() {
if (this.active) {
this.open = true;
}
}
public void close() {
this.open = false;
}
public boolean isActive() {
return this.active;
}
public boolean isOpen() {
return this.open;
}
}
| 633 | 0.515008 | 0.513428 | 39 | 15.230769 | 12.149626 | 31 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.307692 | false | false |
13
|
4dc0cc8137ce9f354a69434106aad81ec58068c0
| 30,356,828,910,988 |
78050b5c5d83b06330e3a3ac439f7e471e554001
|
/src/test/java/org/hellojavaer/poi/excel/utils/write/WriteDemo1.java
|
c2fb6648edfecc0c1c4a19039f58f2a4c39b03f0
|
[
"Apache-2.0"
] |
permissive
|
thomedw/poi-excel-utils
|
https://github.com/thomedw/poi-excel-utils
|
8547ca98f2982df6bcb438fd4202397214ba93b2
|
22b7b3e551574fa9705f6a706a01daa8f75bf190
|
refs/heads/master
| 2021-07-04T23:09:15.033000 | 2020-08-18T00:15:45 | 2020-08-18T00:15:45 | 146,068,297 | 0 | 0 |
Apache-2.0
| true | 2020-08-18T00:15:47 | 2018-08-25T05:36:13 | 2018-08-25T05:36:15 | 2020-08-18T00:15:46 | 876 | 0 | 0 | 0 |
Java
| false | false |
package org.hellojavaer.poi.excel.utils.write;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.hellojavaer.poi.excel.utils.ExcelType;
import org.hellojavaer.poi.excel.utils.ExcelUtils;
import org.hellojavaer.poi.excel.utils.TestBean;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @author <a href="mailto:hellojavaer@gmail.com">zoukaiming</a>
*/
public class WriteDemo1 {
public static void main(String[] args) throws IOException {
URL url = WriteDemo1.class.getResource("/");
final String outputFilePath = url.getPath() + "output_file1.xlsx";
File outputFile = new File(outputFilePath);
outputFile.createNewFile();
FileOutputStream output = new FileOutputStream(outputFile);
final AtomicBoolean b = new AtomicBoolean(false);
ExcelWriteSheetProcessor<TestBean> sheetProcessor = new ExcelWriteSheetProcessor<TestBean>() {
@Override
public void beforeProcess(ExcelWriteContext<TestBean> context) {
System.out.println("write excel start!");
}
@Override
public void onException(ExcelWriteContext<TestBean> context, ExcelWriteException e) {
throw e;
}
@Override
public void afterProcess(ExcelWriteContext<TestBean> context) {
Cell cell = context.setCellValue(context.getCurRowIndex() + 2, context.getCurRowIndex() + 4, 0, 8,
"Thinks for using pio-excel-utils!");
CellStyle cellStyle = cell.getSheet().getWorkbook().createCellStyle();
cellStyle.setWrapText(true);
cell.setCellStyle(cellStyle);
System.out.println("write excel end!");
System.out.println("output file path is " + outputFilePath);
}
};
ExcelWriteFieldMapping fieldMapping = new ExcelWriteFieldMapping();
fieldMapping.put("A", "byteField").setHead("byteField");
fieldMapping.put("B", "shortField").setHead("shortField");
fieldMapping.put("C", "intField").setHead("intField");
fieldMapping.put("D", "longField").setHead("longField");
fieldMapping.put("E", "floatField").setHead("floatField");
fieldMapping.put("F", "doubleField").setHead("doubleField");
fieldMapping.put("G", "boolField").setHead("boolField");
fieldMapping.put("H", "stringField").setHead("stringField");
fieldMapping.put("I", "dateField").setHead("dateField");
sheetProcessor.setSheetIndex(0);// required. It can be replaced with 'setSheetName(sheetName)';
sheetProcessor.setStartRowIndex(1);//
sheetProcessor.setFieldMapping(fieldMapping);// required
sheetProcessor.setHeadRowIndex(0);
// sheetProcessor.setTemplateRowIndex(1);
sheetProcessor.setDataList(getDateList());
ExcelUtils.write(ExcelType.XLSX, output, sheetProcessor);
}
private static List<TestBean> getDateList() {
List<TestBean> list = new ArrayList<TestBean>();
TestBean bean = new TestBean();
bean.setByteField((byte) 1);
bean.setShortField((short) 2);
bean.setIntField(3);
bean.setLongField(4L);
bean.setFloatField(5.1f);
bean.setDoubleField(6.23);
bean.setBoolField(true);
bean.setEnumField1("enumField1");
bean.setEnumField2("enumField2");
bean.setDateField(new Date());
bean.setStringField("test");
list.add(bean);
list.add(bean);
list.add(bean);
return list;
}
}
|
UTF-8
|
Java
| 3,847 |
java
|
WriteDemo1.java
|
Java
|
[
{
"context": "ic.AtomicBoolean;\n\n/**\n * @author <a href=\"mailto:hellojavaer@gmail.com\">zoukaiming</a>\n */\npublic class WriteDemo1 {\n\n ",
"end": 566,
"score": 0.9999231100082397,
"start": 545,
"tag": "EMAIL",
"value": "hellojavaer@gmail.com"
},
{
"context": " * @author <a href=\"mailto:hellojavaer@gmail.com\">zoukaiming</a>\n */\npublic class WriteDemo1 {\n\n public sta",
"end": 578,
"score": 0.99832683801651,
"start": 568,
"tag": "USERNAME",
"value": "zoukaiming"
}
] | null |
[] |
package org.hellojavaer.poi.excel.utils.write;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.hellojavaer.poi.excel.utils.ExcelType;
import org.hellojavaer.poi.excel.utils.ExcelUtils;
import org.hellojavaer.poi.excel.utils.TestBean;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @author <a href="mailto:<EMAIL>">zoukaiming</a>
*/
public class WriteDemo1 {
public static void main(String[] args) throws IOException {
URL url = WriteDemo1.class.getResource("/");
final String outputFilePath = url.getPath() + "output_file1.xlsx";
File outputFile = new File(outputFilePath);
outputFile.createNewFile();
FileOutputStream output = new FileOutputStream(outputFile);
final AtomicBoolean b = new AtomicBoolean(false);
ExcelWriteSheetProcessor<TestBean> sheetProcessor = new ExcelWriteSheetProcessor<TestBean>() {
@Override
public void beforeProcess(ExcelWriteContext<TestBean> context) {
System.out.println("write excel start!");
}
@Override
public void onException(ExcelWriteContext<TestBean> context, ExcelWriteException e) {
throw e;
}
@Override
public void afterProcess(ExcelWriteContext<TestBean> context) {
Cell cell = context.setCellValue(context.getCurRowIndex() + 2, context.getCurRowIndex() + 4, 0, 8,
"Thinks for using pio-excel-utils!");
CellStyle cellStyle = cell.getSheet().getWorkbook().createCellStyle();
cellStyle.setWrapText(true);
cell.setCellStyle(cellStyle);
System.out.println("write excel end!");
System.out.println("output file path is " + outputFilePath);
}
};
ExcelWriteFieldMapping fieldMapping = new ExcelWriteFieldMapping();
fieldMapping.put("A", "byteField").setHead("byteField");
fieldMapping.put("B", "shortField").setHead("shortField");
fieldMapping.put("C", "intField").setHead("intField");
fieldMapping.put("D", "longField").setHead("longField");
fieldMapping.put("E", "floatField").setHead("floatField");
fieldMapping.put("F", "doubleField").setHead("doubleField");
fieldMapping.put("G", "boolField").setHead("boolField");
fieldMapping.put("H", "stringField").setHead("stringField");
fieldMapping.put("I", "dateField").setHead("dateField");
sheetProcessor.setSheetIndex(0);// required. It can be replaced with 'setSheetName(sheetName)';
sheetProcessor.setStartRowIndex(1);//
sheetProcessor.setFieldMapping(fieldMapping);// required
sheetProcessor.setHeadRowIndex(0);
// sheetProcessor.setTemplateRowIndex(1);
sheetProcessor.setDataList(getDateList());
ExcelUtils.write(ExcelType.XLSX, output, sheetProcessor);
}
private static List<TestBean> getDateList() {
List<TestBean> list = new ArrayList<TestBean>();
TestBean bean = new TestBean();
bean.setByteField((byte) 1);
bean.setShortField((short) 2);
bean.setIntField(3);
bean.setLongField(4L);
bean.setFloatField(5.1f);
bean.setDoubleField(6.23);
bean.setBoolField(true);
bean.setEnumField1("enumField1");
bean.setEnumField2("enumField2");
bean.setDateField(new Date());
bean.setStringField("test");
list.add(bean);
list.add(bean);
list.add(bean);
return list;
}
}
| 3,833 | 0.646998 | 0.640759 | 97 | 38.659794 | 27.791153 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.824742 | false | false |
13
|
5e7b545268496a8e17baf97e0f4b8dff0566488c
| 33,337,536,191,171 |
65a0263d763d47a0593921bf1947ebaadd3bcd45
|
/ScrapeYahooFinanceJar/src/org/shu/main/bean/Indicator.java
|
3a1ecb6a0a48dd757819919e1a197f0ea3c1449f
|
[] |
no_license
|
sghosh79/YahooFinanceHTMLScraper
|
https://github.com/sghosh79/YahooFinanceHTMLScraper
|
16b9f937035d9d76ed2c1ce5e6195a3ba69b38b7
|
a7c9c8cbb7af405eea076f9641c02baf2ade99fc
|
refs/heads/master
| 2016-09-09T21:12:16.746000 | 2014-09-05T02:07:00 | 2014-09-05T02:07:00 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.shu.main.bean;
public interface Indicator {
}
|
UTF-8
|
Java
| 65 |
java
|
Indicator.java
|
Java
|
[] | null |
[] |
package org.shu.main.bean;
public interface Indicator {
}
| 65 | 0.692308 | 0.692308 | 5 | 11 | 13.084342 | 28 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false |
13
|
8cce8023b39600b0371233a649aa57803b394fd5
| 22,763,326,709,473 |
512dfd92faa46659981254d30aa392dd12536789
|
/TicTacToe/src/game/factories/PlayerFactory.java
|
a802cfa0e9a3b378fa42c96626a10f56386b4def
|
[] |
no_license
|
todor11/Team_Grandeeney_TicTacToe
|
https://github.com/todor11/Team_Grandeeney_TicTacToe
|
e9cbd01f3904209c9b6c805d7fcf88887808b8f0
|
df2b26640d29390bc8a66c00fbffdd851ec0a304
|
refs/heads/master
| 2016-09-12T21:49:48.251000 | 2016-04-21T06:37:52 | 2016-04-21T06:37:52 | 55,982,896 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package game.factories;
import game.Game;
import game.entities.AI;
import game.entities.Human;
import game.entities.Player;
import game.enums.Symbols;
import interfaces.UserInterface;
import interfaces.WinningDatabase;
public class PlayerFactory {
public PlayerFactory(){
}
public Player createPlayer(String type, String name, Symbols symbol, Game game){
switch (type){
case "Human":
return new Human(name, symbol, game);
case "AI":
return new AI(symbol, game);
}
return null;
}
}
|
UTF-8
|
Java
| 610 |
java
|
PlayerFactory.java
|
Java
|
[] | null |
[] |
package game.factories;
import game.Game;
import game.entities.AI;
import game.entities.Human;
import game.entities.Player;
import game.enums.Symbols;
import interfaces.UserInterface;
import interfaces.WinningDatabase;
public class PlayerFactory {
public PlayerFactory(){
}
public Player createPlayer(String type, String name, Symbols symbol, Game game){
switch (type){
case "Human":
return new Human(name, symbol, game);
case "AI":
return new AI(symbol, game);
}
return null;
}
}
| 610 | 0.614754 | 0.614754 | 27 | 20.592592 | 19.005379 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.62963 | false | false |
13
|
acd0b70557a1836722b680bb9d2e521678377f3d
| 3,607,772,587,071 |
f6de22f0a27d77d4c82b282802bc76e95ccef9f9
|
/Assignment_04/TEAM09/Attendance92Model.java
|
c44aac0b019d117e7d250b536b9bc5f0722015a4
|
[] |
no_license
|
javiergs/CSE564
|
https://github.com/javiergs/CSE564
|
e7a6bb87357ee1fcd5b23e281b5a453a17930318
|
cd667802f18238311461bc3c82feefea737d1f2f
|
refs/heads/main
| 2023-08-21T18:59:10.274000 | 2021-10-10T05:33:52 | 2021-10-10T05:33:52 | 308,484,155 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* @author rohitksingh
* @version 1.0
* @Date Modified 10/25/2020
*/
public class Attendance92Model {
public String date;
public String minutes;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getMinutes() {
return minutes;
}
public void setMinutes(String minutes) {
this.minutes = minutes;
}
}
|
UTF-8
|
Java
| 387 |
java
|
Attendance92Model.java
|
Java
|
[
{
"context": "/**\n * @author rohitksingh\n * @version 1.0\n * @Date Modified 10/25/2020\n */\n",
"end": 26,
"score": 0.998691737651825,
"start": 15,
"tag": "USERNAME",
"value": "rohitksingh"
}
] | null |
[] |
/**
* @author rohitksingh
* @version 1.0
* @Date Modified 10/25/2020
*/
public class Attendance92Model {
public String date;
public String minutes;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getMinutes() {
return minutes;
}
public void setMinutes(String minutes) {
this.minutes = minutes;
}
}
| 387 | 0.679587 | 0.648579 | 26 | 13.884615 | 12.953547 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.923077 | false | false |
13
|
881edc025ad336fa9abc46fe5569d7b0b1990f11
| 19,988,777,859,501 |
22b149569819174e4e4f6fd25e33e0a99a50d1c4
|
/learn-demo-base/src/main/java/com/yang/learn/base/datatype/PriorityQueueExample.java
|
8185fbbda9dc129c1123a65ad8b6dd8af8614988
|
[] |
no_license
|
CatYangWei/learn-tips
|
https://github.com/CatYangWei/learn-tips
|
5bb34f4a86f134d56d0b2adc6cb24eca3c8c6621
|
1daee181419f87201e43446fd0fd40802cb74d9a
|
refs/heads/master
| 2022-06-29T23:43:36.811000 | 2019-10-25T09:46:26 | 2019-10-25T09:46:26 | 172,733,725 | 0 | 0 | null | false | 2022-06-17T02:32:11 | 2019-02-26T15:03:36 | 2019-10-25T09:46:49 | 2022-06-17T02:32:10 | 70 | 0 | 0 | 4 |
Java
| false | false |
package com.yang.learn.base.datatype;
import com.yang.learn.base.lfu.Node;
import java.util.PriorityQueue;
/**
* @author coffezcat
* @title: PriorityQueen
* @description: TODO
* @date 2019-09-25 17:06
*/
public class PriorityQueueExample {
public static void main(String[] args) {
//用来存储元素
PriorityQueue<Node<String>> priorityQueue = new PriorityQueue<>();
Node<String> node1 = new Node<>("1");
Node<String> node2 = new Node<>("2");
node2.getCount();
Node<String> node3 = new Node<>("3");
priorityQueue.add(node2);
priorityQueue.add(node1);
priorityQueue.add(node3);
System.out.println(priorityQueue.peek().getVal());
System.out.println(priorityQueue.remove().getVal());
}
}
|
UTF-8
|
Java
| 797 |
java
|
PriorityQueueExample.java
|
Java
|
[
{
"context": ";\n\nimport java.util.PriorityQueue;\n\n/**\n * @author coffezcat\n * @title: PriorityQueen\n * @description: TODO\n *",
"end": 134,
"score": 0.999561071395874,
"start": 125,
"tag": "USERNAME",
"value": "coffezcat"
}
] | null |
[] |
package com.yang.learn.base.datatype;
import com.yang.learn.base.lfu.Node;
import java.util.PriorityQueue;
/**
* @author coffezcat
* @title: PriorityQueen
* @description: TODO
* @date 2019-09-25 17:06
*/
public class PriorityQueueExample {
public static void main(String[] args) {
//用来存储元素
PriorityQueue<Node<String>> priorityQueue = new PriorityQueue<>();
Node<String> node1 = new Node<>("1");
Node<String> node2 = new Node<>("2");
node2.getCount();
Node<String> node3 = new Node<>("3");
priorityQueue.add(node2);
priorityQueue.add(node1);
priorityQueue.add(node3);
System.out.println(priorityQueue.peek().getVal());
System.out.println(priorityQueue.remove().getVal());
}
}
| 797 | 0.630573 | 0.602548 | 33 | 22.787878 | 20.888968 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.393939 | false | false |
13
|
fce1b4a6f84ecc0efa918b009e91ec3bb6fdd547
| 21,328,807,606,720 |
9ecfe2b3fd488448d9ede34ebc0564658985ca36
|
/app/src/main/java/com/drizzle/zhihuuserprofile/widget/ZhihuUserProfileLayout.java
|
70169d648c856951c01b92fad504ecff4cb27229
|
[
"Apache-2.0"
] |
permissive
|
Drizzlezhang/ZhihuUserProfile
|
https://github.com/Drizzlezhang/ZhihuUserProfile
|
684701792a133fdb681838140a314d9211d424c1
|
6d6ac62eb6da79b39f4f533a8719cdb3bce18812
|
refs/heads/master
| 2021-01-18T20:31:24.145000 | 2017-04-25T06:02:36 | 2017-04-25T06:02:36 | 86,973,561 | 5 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.drizzle.zhihuuserprofile.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.NonNull;
import android.support.annotation.Px;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.Scroller;
import com.drizzle.zhihuuserprofile.BuildConfig;
import com.drizzle.zhihuuserprofile.R;
/**
* Created by drizzle on 2017/4/2.
*/
public class ZhihuUserProfileLayout extends RelativeLayout {
private static final String TAG = "ZhihuUserProfileLayout";
private static final int COLLAPSING_VIEW_POSITION = 0, NESTED_SCROLLVIEW_POSITION = 1;
private static final int FLING_UPWARD = 1, FLING_DOWNWARD = 2;
private int mFlingDirection;
private ViewGroup mCollapsingViewGroup, mNestedScrollViewGroup;
private int mMinSrollY, mMaxScrollY, mCurrentScrollY, mLastScrollY;
private int mCollapsingOffset;
private float mTouchDownX, mTouchDownY, mLastTouchY;
private ViewConfiguration mViewConfiguration;
private VelocityTracker mVelocityTracker;
private Scroller mScroller;
private OnCollapsingListener mOnCollapsingListener;
private NestedScrollViewProvider mNestedScrollViewProvider;
public ZhihuUserProfileLayout(Context context) {
this(context, null);
}
public ZhihuUserProfileLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ZhihuUserProfileLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray array = context.getTheme().obtainStyledAttributes(attrs, R.styleable.ZhihuUserProfileLayout, defStyleAttr, 0);
mCollapsingOffset = array.getDimensionPixelOffset(R.styleable.ZhihuUserProfileLayout_collapsing_offset,
(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 0, getResources().getDisplayMetrics()));
array.recycle();
init(context);
}
private void init(Context context) {
mMinSrollY = 0;
mScroller = new Scroller(context);
mViewConfiguration = ViewConfiguration.get(context);
mVelocityTracker = VelocityTracker.obtain();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (getChildCount() < 2) {
throw new IllegalArgumentException("child count can not be less than 2");
}
for (int i = 0; i < getChildCount(); i++) {
switch (i) {
case COLLAPSING_VIEW_POSITION:
mCollapsingViewGroup = (ViewGroup) getChildAt(COLLAPSING_VIEW_POSITION);
measureChildWithMargins(mCollapsingViewGroup, widthMeasureSpec, 0, MeasureSpec.UNSPECIFIED, 0);
break;
case NESTED_SCROLLVIEW_POSITION:
mNestedScrollViewGroup = (ViewGroup) getChildAt(NESTED_SCROLLVIEW_POSITION);
break;
}
}
mMaxScrollY = mCollapsingViewGroup.getMeasuredHeight() - mCollapsingOffset;
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(heightMeasureSpec) + mMaxScrollY, MeasureSpec.EXACTLY));
}
private boolean isCollapsingViewExpanded() {
return mCurrentScrollY == mMinSrollY;
}
private boolean isCollapsingViewSnapped() {
return mCurrentScrollY == mMaxScrollY;
}
private int getScrollerVelocity() {
return mScroller == null ? 0 : (int) mScroller.getCurrVelocity();
}
/**
* 判断触摸上下滑动是否为有效操作
*/
private boolean isTouchScrollVertical(float transX, float transY) {
return transY > mViewConfiguration.getScaledTouchSlop() && transY > transX;
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
float currentTouchX = event.getX();
float currentTouchY = event.getY();
float transX = Math.abs(currentTouchX - mTouchDownX);
float transY = Math.abs(currentTouchY - mTouchDownY);
float dY;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mVelocityTracker.clear();
mVelocityTracker.addMovement(event);
mTouchDownX = currentTouchX;
mTouchDownY = currentTouchY;
mLastTouchY = currentTouchY;
mScroller.forceFinished(true);
break;
case MotionEvent.ACTION_UP:
if (isTouchScrollVertical(transX, transY)) {
mVelocityTracker.computeCurrentVelocity(1000, mViewConfiguration.getScaledMaximumFlingVelocity());
float v = -mVelocityTracker.getYVelocity();
if (BuildConfig.DEBUG) Log.d(TAG, "dispatchTouchEvent: YVelocity = " + v);
mFlingDirection = v > 0 ? FLING_UPWARD : FLING_DOWNWARD;
if (((mFlingDirection == FLING_DOWNWARD && isNestedScrollViewTop() && !isCollapsingViewExpanded())
|| (mFlingDirection == FLING_DOWNWARD && isCollapsingViewSnapped())
|| (mFlingDirection == FLING_UPWARD && !isCollapsingViewSnapped()))
&& Math.abs(v) > mViewConfiguration.getScaledMinimumFlingVelocity()) {
mScroller.fling(0, getScrollY(), 0, (int) v, -Integer.MAX_VALUE, Integer.MAX_VALUE, -Integer.MAX_VALUE, Integer.MAX_VALUE);
mScroller.computeScrollOffset();
mLastScrollY = getScrollY();
postInvalidate();
}
}
break;
case MotionEvent.ACTION_MOVE:
mVelocityTracker.addMovement(event);
dY = mLastTouchY - currentTouchY;
boolean isTouchScrollUp = dY > 0;
if (isTouchScrollVertical(transX, transY)) {
if ((isTouchScrollUp && isCollapsingViewSnapped())
|| (!isTouchScrollUp && isCollapsingViewSnapped() && !isNestedScrollViewTop())) {
mNestedScrollViewGroup.requestDisallowInterceptTouchEvent(true);
} else {
this.scrollBy(0, (int) dY);
}
}
mLastTouchY = currentTouchY;
break;
default:
break;
}
super.dispatchTouchEvent(event);
return true;
}
@Override
public void computeScroll() {
if (!mScroller.computeScrollOffset()) {
return;
}
if (mFlingDirection == FLING_DOWNWARD) {
if (isNestedScrollViewTop()) {
int dY = mScroller.getCurrY() - mLastScrollY;
this.scrollTo(0, getScrollY() + dY);
}
postInvalidate();
} else {
if (isCollapsingViewSnapped()) {
mNestedScrollViewProvider.getNestedScrollView().fling(0, getScrollerVelocity());
mScroller.forceFinished(true);
return;
} else {
this.scrollTo(0, mScroller.getCurrY());
}
}
mLastScrollY = mScroller.getCurrY();
super.computeScroll();
}
@Override
public void scrollBy(@Px int x, @Px int y) {
int targetY = getScrollY() + y;
if (targetY >= mMaxScrollY) {
targetY = mMaxScrollY;
} else if (targetY <= 0) {
targetY = 0;
}
super.scrollBy(x, targetY - getScrollY());
}
@Override
public void scrollTo(@Px int x, @Px int y) {
if (y >= mMaxScrollY) {
y = mMaxScrollY;
} else if (y <= 0) {
y = 0;
}
if (mOnCollapsingListener != null) {
float progress = 1.0f - (float) y / (float) mMaxScrollY;
if (BuildConfig.DEBUG) Log.d(TAG, "collapsing progress = " + progress);
mOnCollapsingListener.onCollapsing(progress);
}
mCurrentScrollY = y;
super.scrollTo(x, y);
}
public void setNestedScrollViewProvider(NestedScrollViewProvider nestedScrollViewProvider) {
mNestedScrollViewProvider = nestedScrollViewProvider;
}
public void setOnCollapsingListener(OnCollapsingListener onCollapsingListener) {
mOnCollapsingListener = onCollapsingListener;
}
private boolean isNestedScrollViewTop() {
RecyclerView.LayoutManager layoutManager = mNestedScrollViewProvider.getNestedScrollView().getLayoutManager();
if (layoutManager instanceof LinearLayoutManager) {
int position = ((LinearLayoutManager) layoutManager).findFirstVisibleItemPosition();
View itemView = mNestedScrollViewProvider.getNestedScrollView().getChildAt(0);
if (itemView == null || (position == 0 && itemView.getTop() == 0)) {
return true;
}
}
return false;
}
public interface OnCollapsingListener {
void onCollapsing(float progress);
}
public interface NestedScrollViewProvider {
@NonNull
RecyclerView getNestedScrollView();
}
}
|
UTF-8
|
Java
| 9,579 |
java
|
ZhihuUserProfileLayout.java
|
Java
|
[
{
"context": "com.drizzle.zhihuuserprofile.R;\n\n/**\n * Created by drizzle on 2017/4/2.\n */\npublic class ZhihuUserProfileLay",
"end": 741,
"score": 0.9995822310447693,
"start": 734,
"tag": "USERNAME",
"value": "drizzle"
}
] | null |
[] |
package com.drizzle.zhihuuserprofile.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.NonNull;
import android.support.annotation.Px;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.Scroller;
import com.drizzle.zhihuuserprofile.BuildConfig;
import com.drizzle.zhihuuserprofile.R;
/**
* Created by drizzle on 2017/4/2.
*/
public class ZhihuUserProfileLayout extends RelativeLayout {
private static final String TAG = "ZhihuUserProfileLayout";
private static final int COLLAPSING_VIEW_POSITION = 0, NESTED_SCROLLVIEW_POSITION = 1;
private static final int FLING_UPWARD = 1, FLING_DOWNWARD = 2;
private int mFlingDirection;
private ViewGroup mCollapsingViewGroup, mNestedScrollViewGroup;
private int mMinSrollY, mMaxScrollY, mCurrentScrollY, mLastScrollY;
private int mCollapsingOffset;
private float mTouchDownX, mTouchDownY, mLastTouchY;
private ViewConfiguration mViewConfiguration;
private VelocityTracker mVelocityTracker;
private Scroller mScroller;
private OnCollapsingListener mOnCollapsingListener;
private NestedScrollViewProvider mNestedScrollViewProvider;
public ZhihuUserProfileLayout(Context context) {
this(context, null);
}
public ZhihuUserProfileLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ZhihuUserProfileLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray array = context.getTheme().obtainStyledAttributes(attrs, R.styleable.ZhihuUserProfileLayout, defStyleAttr, 0);
mCollapsingOffset = array.getDimensionPixelOffset(R.styleable.ZhihuUserProfileLayout_collapsing_offset,
(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 0, getResources().getDisplayMetrics()));
array.recycle();
init(context);
}
private void init(Context context) {
mMinSrollY = 0;
mScroller = new Scroller(context);
mViewConfiguration = ViewConfiguration.get(context);
mVelocityTracker = VelocityTracker.obtain();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (getChildCount() < 2) {
throw new IllegalArgumentException("child count can not be less than 2");
}
for (int i = 0; i < getChildCount(); i++) {
switch (i) {
case COLLAPSING_VIEW_POSITION:
mCollapsingViewGroup = (ViewGroup) getChildAt(COLLAPSING_VIEW_POSITION);
measureChildWithMargins(mCollapsingViewGroup, widthMeasureSpec, 0, MeasureSpec.UNSPECIFIED, 0);
break;
case NESTED_SCROLLVIEW_POSITION:
mNestedScrollViewGroup = (ViewGroup) getChildAt(NESTED_SCROLLVIEW_POSITION);
break;
}
}
mMaxScrollY = mCollapsingViewGroup.getMeasuredHeight() - mCollapsingOffset;
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(heightMeasureSpec) + mMaxScrollY, MeasureSpec.EXACTLY));
}
private boolean isCollapsingViewExpanded() {
return mCurrentScrollY == mMinSrollY;
}
private boolean isCollapsingViewSnapped() {
return mCurrentScrollY == mMaxScrollY;
}
private int getScrollerVelocity() {
return mScroller == null ? 0 : (int) mScroller.getCurrVelocity();
}
/**
* 判断触摸上下滑动是否为有效操作
*/
private boolean isTouchScrollVertical(float transX, float transY) {
return transY > mViewConfiguration.getScaledTouchSlop() && transY > transX;
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
float currentTouchX = event.getX();
float currentTouchY = event.getY();
float transX = Math.abs(currentTouchX - mTouchDownX);
float transY = Math.abs(currentTouchY - mTouchDownY);
float dY;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mVelocityTracker.clear();
mVelocityTracker.addMovement(event);
mTouchDownX = currentTouchX;
mTouchDownY = currentTouchY;
mLastTouchY = currentTouchY;
mScroller.forceFinished(true);
break;
case MotionEvent.ACTION_UP:
if (isTouchScrollVertical(transX, transY)) {
mVelocityTracker.computeCurrentVelocity(1000, mViewConfiguration.getScaledMaximumFlingVelocity());
float v = -mVelocityTracker.getYVelocity();
if (BuildConfig.DEBUG) Log.d(TAG, "dispatchTouchEvent: YVelocity = " + v);
mFlingDirection = v > 0 ? FLING_UPWARD : FLING_DOWNWARD;
if (((mFlingDirection == FLING_DOWNWARD && isNestedScrollViewTop() && !isCollapsingViewExpanded())
|| (mFlingDirection == FLING_DOWNWARD && isCollapsingViewSnapped())
|| (mFlingDirection == FLING_UPWARD && !isCollapsingViewSnapped()))
&& Math.abs(v) > mViewConfiguration.getScaledMinimumFlingVelocity()) {
mScroller.fling(0, getScrollY(), 0, (int) v, -Integer.MAX_VALUE, Integer.MAX_VALUE, -Integer.MAX_VALUE, Integer.MAX_VALUE);
mScroller.computeScrollOffset();
mLastScrollY = getScrollY();
postInvalidate();
}
}
break;
case MotionEvent.ACTION_MOVE:
mVelocityTracker.addMovement(event);
dY = mLastTouchY - currentTouchY;
boolean isTouchScrollUp = dY > 0;
if (isTouchScrollVertical(transX, transY)) {
if ((isTouchScrollUp && isCollapsingViewSnapped())
|| (!isTouchScrollUp && isCollapsingViewSnapped() && !isNestedScrollViewTop())) {
mNestedScrollViewGroup.requestDisallowInterceptTouchEvent(true);
} else {
this.scrollBy(0, (int) dY);
}
}
mLastTouchY = currentTouchY;
break;
default:
break;
}
super.dispatchTouchEvent(event);
return true;
}
@Override
public void computeScroll() {
if (!mScroller.computeScrollOffset()) {
return;
}
if (mFlingDirection == FLING_DOWNWARD) {
if (isNestedScrollViewTop()) {
int dY = mScroller.getCurrY() - mLastScrollY;
this.scrollTo(0, getScrollY() + dY);
}
postInvalidate();
} else {
if (isCollapsingViewSnapped()) {
mNestedScrollViewProvider.getNestedScrollView().fling(0, getScrollerVelocity());
mScroller.forceFinished(true);
return;
} else {
this.scrollTo(0, mScroller.getCurrY());
}
}
mLastScrollY = mScroller.getCurrY();
super.computeScroll();
}
@Override
public void scrollBy(@Px int x, @Px int y) {
int targetY = getScrollY() + y;
if (targetY >= mMaxScrollY) {
targetY = mMaxScrollY;
} else if (targetY <= 0) {
targetY = 0;
}
super.scrollBy(x, targetY - getScrollY());
}
@Override
public void scrollTo(@Px int x, @Px int y) {
if (y >= mMaxScrollY) {
y = mMaxScrollY;
} else if (y <= 0) {
y = 0;
}
if (mOnCollapsingListener != null) {
float progress = 1.0f - (float) y / (float) mMaxScrollY;
if (BuildConfig.DEBUG) Log.d(TAG, "collapsing progress = " + progress);
mOnCollapsingListener.onCollapsing(progress);
}
mCurrentScrollY = y;
super.scrollTo(x, y);
}
public void setNestedScrollViewProvider(NestedScrollViewProvider nestedScrollViewProvider) {
mNestedScrollViewProvider = nestedScrollViewProvider;
}
public void setOnCollapsingListener(OnCollapsingListener onCollapsingListener) {
mOnCollapsingListener = onCollapsingListener;
}
private boolean isNestedScrollViewTop() {
RecyclerView.LayoutManager layoutManager = mNestedScrollViewProvider.getNestedScrollView().getLayoutManager();
if (layoutManager instanceof LinearLayoutManager) {
int position = ((LinearLayoutManager) layoutManager).findFirstVisibleItemPosition();
View itemView = mNestedScrollViewProvider.getNestedScrollView().getChildAt(0);
if (itemView == null || (position == 0 && itemView.getTop() == 0)) {
return true;
}
}
return false;
}
public interface OnCollapsingListener {
void onCollapsing(float progress);
}
public interface NestedScrollViewProvider {
@NonNull
RecyclerView getNestedScrollView();
}
}
| 9,579 | 0.626348 | 0.621845 | 244 | 38.135246 | 31.213079 | 147 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.721311 | false | false |
13
|
94f68614473e63d4fbf1518a4076e37eaea0d850
| 27,307,402,132,108 |
02ee0b11c71c4463f65fbdbd9d820b58b9c99147
|
/src/Office_hours/If_Else_practice.java
|
1e2e12ae49ff6f548879f9a79f898d8c3fe2feb8
|
[] |
no_license
|
Mokhinur0317/Summer2020_B20
|
https://github.com/Mokhinur0317/Summer2020_B20
|
92454abc217cfd1b1900b1f6a0be903a9f872f95
|
2f42e214c45ea7005b87c15ff0af2e368a41b085
|
refs/heads/master
| 2022-12-04T04:38:07.465000 | 2020-08-05T02:03:23 | 2020-08-05T02:03:23 | 284,485,034 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Office_hours;
public class If_Else_practice {
public static void main(String[] args) {
int num = 305;
String result ="";
if(num % 2 == 0){
// System.out.println(num + " is even number");
result = num + " is even number";
}else{
// System.out.println(num + " is odd number");
result = num + " is even number";
}
System.out.println(result);
// ternary
String result2 = (num % 2 == 0) ? num + " is even number": num + " is even number";
System.out.println(result2); // same result
}
}
|
UTF-8
|
Java
| 626 |
java
|
If_Else_practice.java
|
Java
|
[] | null |
[] |
package Office_hours;
public class If_Else_practice {
public static void main(String[] args) {
int num = 305;
String result ="";
if(num % 2 == 0){
// System.out.println(num + " is even number");
result = num + " is even number";
}else{
// System.out.println(num + " is odd number");
result = num + " is even number";
}
System.out.println(result);
// ternary
String result2 = (num % 2 == 0) ? num + " is even number": num + " is even number";
System.out.println(result2); // same result
}
}
| 626 | 0.507987 | 0.49361 | 21 | 28.809525 | 23.825994 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.47619 | false | false |
13
|
ba91a6a48df8b07a71bf1e91198ae0a059805b61
| 15,857,019,304,116 |
cc04231a129882f0ac819474223429ce790ac6bb
|
/src/com/freetymekiyan/algorithms/Other/MinInsertionsToFormPalindrome.java
|
5ce7e14248463c794272b26a6f33a80ac8d1fc55
|
[
"MIT"
] |
permissive
|
chjwang/LeetCode-Sol-Res
|
https://github.com/chjwang/LeetCode-Sol-Res
|
f7c2e898ec5ff375a12e484a3ca93d59b695cc85
|
db90cb452139035815a56d3da8093db9a69c0216
|
refs/heads/master
| 2021-01-22T09:16:51.741000 | 2017-01-27T18:47:07 | 2017-01-27T18:47:07 | 66,747,899 | 1 | 0 | null | true | 2016-08-28T03:42:38 | 2016-08-28T03:42:38 | 2016-08-27T23:45:35 | 2016-08-27T00:07:25 | 4,347 | 0 | 0 | 0 | null | null | null |
package com.freetymekiyan.algorithms.Other;
import java.util.Arrays;
/**
* Given a string, find the minimum number of characters to be inserted to
* convert it to palindrome.
*
* Tags: Recursive, DP
*/
class MinInsertionsToFormPalindrome {
public static void main(String[] args) {
String s = "aaaabaa";
System.out.println(new MinInsertionsToFormPalindrome().minInsertionsDP(s));
System.out.println(new MinInsertionsToFormPalindrome().minInsertions(s));
System.out.println(new MinInsertionsToFormPalindrome().minInsertions2(s));
}
/**
* DP, bottom-up
* Fill a table in diagonal direction
*
* If we observe the recursion approach carefully, we can find that it exhibits overlapping subproblems.
Suppose we want to find the minimum number of insertions in string “abcde”:
abcde
/ | \
/ | \
bcde abcd bcd <- case 3 is discarded as str[l] != str[h]
/ | \ / | \
/ | \ / | \
cde bcd cd bcd abc bc
/ | \ / | \ /|\ / | \
de cd d cd bc c………………….
The substrings in bold show that the recursion to be terminated and the recursion tree cannot originate from there. Substring in the same color indicates overlapping subproblems.
How to reuse solutions of subproblems?
We can create a table to store results of subproblems so that they can be used directly if same subproblem is encountered again.
The below table represents the stored values for the string abcde.
a b c d e
----------
0 1 2 3 4
0 0 1 2 3
0 0 0 1 2
0 0 0 0 1
0 0 0 0 0
How to fill the table?
The table should be filled in diagonal fashion. For the string abcde, 0….4, the following should be order in which the table is filled:
Gap = 1:
(0, 1) (1, 2) (2, 3) (3, 4)
Gap = 2:
(0, 2) (1, 3) (2, 4)
Gap = 3:
(0, 3) (1, 4)
Gap = 4:
(0, 4)
*/
int minInsertionsDP(String s) {
int n = s.length();
// Create a table of size n*n. dp[i][j] will store minumum number of insertions needed to
// convert s[i..j] to a palindrome.
int[][] dp = new int[n][n];
for (int gap = 1; gap < n; gap++) {
for (int i = 0, j = gap; j < n; i++, j++) {
dp[i][j] = s.charAt(i) == s.charAt(j) ? dp[i+1][j-1] : Math.min(dp[i][j-1], dp[i+1][j]) + 1;
}
}
// Return minimum number of insertions for s[0..n-1]
return dp[0][n-1];
}
/**
* Recursive
*
* Before we go further, let us understand with few examples:
ab: Number of insertions required is 1. bab
aa: Number of insertions required is 0. aa
abcd: Number of insertions required is 3. dcbabcd
abcda: Number of insertions required is 2. adcbcda which is same as number of insertions in the substring bcd(Why?).
abcde: Number of insertions required is 4. edcbabcde
* Let the input string be str[l……h].
* The problem can be broken down into 3 parts:
* 1. Find the minimum # of insertions in the substring str[l+1,…….h].
* 2. Find the minimum # of insertions in the substring str[l…….h-1].
* 3. Find the minimum # of insertions in the substring str[l+1……h-1].
*
* The minimum # of insertions in the string str[l…..h] can be given as:
* If
* str[l] is equal to str[h], minInsertions(str[l+1…..h-1])
* Otherwise,
* min(minInsertions(str[l…..h-1]), minInsertions(str[l+1…..h])) + 1
*/
public int minInsertions(String s) {
return minInsertions(s, 0, s.length() - 1);
}
int minInsertions(String s, int l, int h) {
// Base Cases
if (l > h) return Integer.MAX_VALUE;
if (l == h) return 0;
if (l == h - 1) return (s.charAt(l) == s.charAt(h)) ? 0 : 1;
// Check if the first and last characters are same. On the basis of the
// comparison result, decide which subrpoblem(s) to call
return s.charAt(l) == s.charAt(h) ? minInsertions(s, l + 1, h - 1)
: Math.min(minInsertions(s, l, h-1), minInsertions(s, l+1, h)) + 1;
}
/* Returns length of LCS for X[0..m-1], Y[0..n-1]. Longest Common Subsequence.
See http://goo.gl/bHQVP for details of this function
LCS Problem Statement:
Given two sequences, find the length of longest subsequence present in both of them.
A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous.
For example, “abc”, “abg”, “bdf”, “aeg”, ‘”acefg”, .. etc are subsequences of “abcdefg”.
So a string of length n has 2^n different possible subsequences.
It is a classic computer science problem, the basis of diff (a file comparison program that outputs
the differences between two files), and has applications in bioinformatics.
Examples:
LCS for input Sequences “ABCDGH” and “AEDFHR” is “ADH” of length 3.
LCS for input Sequences “AGGTAB” and “GXTXAYB” is “GTAB” of length 4.
# A Naive recursive Python implementation of LCS problem
def lcs(X, Y, m, n):
if m == 0 or n == 0:
return 0;
elif X[m-1] == Y[n-1]:
return 1 + lcs(X, Y, m-1, n-1);
else:
return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n));
Time complexity of this method is also O(n^2) and this method also requires O(n^2) extra space.
*/
int lcs( char[] X, char[] Y, int m, int n ) {
int[][] L = new int[n+1][n+1]; // one extra
Arrays.fill(L, 0);
int i, j;
/* Following steps build L[m+1][n+1] in bottom up fashion.
Note that L[i][j] = length of LCS of X[0..i-1] and Y[0..j-1] */
for (i=0; i<=m; i++) {
for (j=0; j<=n; j++) {
if (i == 0 || j == 0) L[i][j] = 0; // no need
else if (X[i-1] == Y[j-1])
L[i][j] = L[i-1][j-1] + 1;
else
L[i][j] = Math.max(L[i-1][j], L[i][j-1]);
}
}
/* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */
return L[m][n];
}
/**
* Another Dynamic Programming Solution (Variation of Longest Common Subsequence Problem)
The problem of finding minimum insertions can also be solved using Longest Common Subsequence (LCS) Problem.
If we find out LCS of string and its reverse, we know how many maximum characters can form a palindrome.
We need insert remaining characters. Following are the steps.
1) Find the length of LCS of input string and its reverse. Let the length be ‘l’.
2) The minimum number insertions needed is length of input string minus ‘l’.
LCS based function to find minimum number of insersions
*/
public int minInsertions2(String str) {
// Creata another string to store reverse of 'str'
String reverseStr = new StringBuffer(str).reverse().toString();
int n = str.length();
// The output is length of string minus length of lcs of
// str and it reverse
return (n - lcs(str.toCharArray(), reverseStr.toCharArray(), n, n));
}
}
|
UTF-8
|
Java
| 7,325 |
java
|
MinInsertionsToFormPalindrome.java
|
Java
|
[] | null |
[] |
package com.freetymekiyan.algorithms.Other;
import java.util.Arrays;
/**
* Given a string, find the minimum number of characters to be inserted to
* convert it to palindrome.
*
* Tags: Recursive, DP
*/
class MinInsertionsToFormPalindrome {
public static void main(String[] args) {
String s = "aaaabaa";
System.out.println(new MinInsertionsToFormPalindrome().minInsertionsDP(s));
System.out.println(new MinInsertionsToFormPalindrome().minInsertions(s));
System.out.println(new MinInsertionsToFormPalindrome().minInsertions2(s));
}
/**
* DP, bottom-up
* Fill a table in diagonal direction
*
* If we observe the recursion approach carefully, we can find that it exhibits overlapping subproblems.
Suppose we want to find the minimum number of insertions in string “abcde”:
abcde
/ | \
/ | \
bcde abcd bcd <- case 3 is discarded as str[l] != str[h]
/ | \ / | \
/ | \ / | \
cde bcd cd bcd abc bc
/ | \ / | \ /|\ / | \
de cd d cd bc c………………….
The substrings in bold show that the recursion to be terminated and the recursion tree cannot originate from there. Substring in the same color indicates overlapping subproblems.
How to reuse solutions of subproblems?
We can create a table to store results of subproblems so that they can be used directly if same subproblem is encountered again.
The below table represents the stored values for the string abcde.
a b c d e
----------
0 1 2 3 4
0 0 1 2 3
0 0 0 1 2
0 0 0 0 1
0 0 0 0 0
How to fill the table?
The table should be filled in diagonal fashion. For the string abcde, 0….4, the following should be order in which the table is filled:
Gap = 1:
(0, 1) (1, 2) (2, 3) (3, 4)
Gap = 2:
(0, 2) (1, 3) (2, 4)
Gap = 3:
(0, 3) (1, 4)
Gap = 4:
(0, 4)
*/
int minInsertionsDP(String s) {
int n = s.length();
// Create a table of size n*n. dp[i][j] will store minumum number of insertions needed to
// convert s[i..j] to a palindrome.
int[][] dp = new int[n][n];
for (int gap = 1; gap < n; gap++) {
for (int i = 0, j = gap; j < n; i++, j++) {
dp[i][j] = s.charAt(i) == s.charAt(j) ? dp[i+1][j-1] : Math.min(dp[i][j-1], dp[i+1][j]) + 1;
}
}
// Return minimum number of insertions for s[0..n-1]
return dp[0][n-1];
}
/**
* Recursive
*
* Before we go further, let us understand with few examples:
ab: Number of insertions required is 1. bab
aa: Number of insertions required is 0. aa
abcd: Number of insertions required is 3. dcbabcd
abcda: Number of insertions required is 2. adcbcda which is same as number of insertions in the substring bcd(Why?).
abcde: Number of insertions required is 4. edcbabcde
* Let the input string be str[l……h].
* The problem can be broken down into 3 parts:
* 1. Find the minimum # of insertions in the substring str[l+1,…….h].
* 2. Find the minimum # of insertions in the substring str[l…….h-1].
* 3. Find the minimum # of insertions in the substring str[l+1……h-1].
*
* The minimum # of insertions in the string str[l…..h] can be given as:
* If
* str[l] is equal to str[h], minInsertions(str[l+1…..h-1])
* Otherwise,
* min(minInsertions(str[l…..h-1]), minInsertions(str[l+1…..h])) + 1
*/
public int minInsertions(String s) {
return minInsertions(s, 0, s.length() - 1);
}
int minInsertions(String s, int l, int h) {
// Base Cases
if (l > h) return Integer.MAX_VALUE;
if (l == h) return 0;
if (l == h - 1) return (s.charAt(l) == s.charAt(h)) ? 0 : 1;
// Check if the first and last characters are same. On the basis of the
// comparison result, decide which subrpoblem(s) to call
return s.charAt(l) == s.charAt(h) ? minInsertions(s, l + 1, h - 1)
: Math.min(minInsertions(s, l, h-1), minInsertions(s, l+1, h)) + 1;
}
/* Returns length of LCS for X[0..m-1], Y[0..n-1]. Longest Common Subsequence.
See http://goo.gl/bHQVP for details of this function
LCS Problem Statement:
Given two sequences, find the length of longest subsequence present in both of them.
A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous.
For example, “abc”, “abg”, “bdf”, “aeg”, ‘”acefg”, .. etc are subsequences of “abcdefg”.
So a string of length n has 2^n different possible subsequences.
It is a classic computer science problem, the basis of diff (a file comparison program that outputs
the differences between two files), and has applications in bioinformatics.
Examples:
LCS for input Sequences “ABCDGH” and “AEDFHR” is “ADH” of length 3.
LCS for input Sequences “AGGTAB” and “GXTXAYB” is “GTAB” of length 4.
# A Naive recursive Python implementation of LCS problem
def lcs(X, Y, m, n):
if m == 0 or n == 0:
return 0;
elif X[m-1] == Y[n-1]:
return 1 + lcs(X, Y, m-1, n-1);
else:
return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n));
Time complexity of this method is also O(n^2) and this method also requires O(n^2) extra space.
*/
int lcs( char[] X, char[] Y, int m, int n ) {
int[][] L = new int[n+1][n+1]; // one extra
Arrays.fill(L, 0);
int i, j;
/* Following steps build L[m+1][n+1] in bottom up fashion.
Note that L[i][j] = length of LCS of X[0..i-1] and Y[0..j-1] */
for (i=0; i<=m; i++) {
for (j=0; j<=n; j++) {
if (i == 0 || j == 0) L[i][j] = 0; // no need
else if (X[i-1] == Y[j-1])
L[i][j] = L[i-1][j-1] + 1;
else
L[i][j] = Math.max(L[i-1][j], L[i][j-1]);
}
}
/* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */
return L[m][n];
}
/**
* Another Dynamic Programming Solution (Variation of Longest Common Subsequence Problem)
The problem of finding minimum insertions can also be solved using Longest Common Subsequence (LCS) Problem.
If we find out LCS of string and its reverse, we know how many maximum characters can form a palindrome.
We need insert remaining characters. Following are the steps.
1) Find the length of LCS of input string and its reverse. Let the length be ‘l’.
2) The minimum number insertions needed is length of input string minus ‘l’.
LCS based function to find minimum number of insersions
*/
public int minInsertions2(String str) {
// Creata another string to store reverse of 'str'
String reverseStr = new StringBuffer(str).reverse().toString();
int n = str.length();
// The output is length of string minus length of lcs of
// str and it reverse
return (n - lcs(str.toCharArray(), reverseStr.toCharArray(), n, n));
}
}
| 7,325 | 0.586045 | 0.566662 | 187 | 37.631016 | 34.682789 | 183 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.631016 | false | false |
13
|
929ab47c66d4c0b50c6cc724e3e124b1f0b7d900
| 25,177,098,357,432 |
b24818a948152b06c7d85ac442e9b37cb6becbbc
|
/src/main/java/com/ash/experiments/performance/whitespace/Class858.java
|
fab2c4d28d78dc43d92ae703718dfe9500bc50f4
|
[] |
no_license
|
ajorpheus/whitespace-perf-test
|
https://github.com/ajorpheus/whitespace-perf-test
|
d0797b6aa3eea1435eaa1032612f0874537c58b8
|
d2b695aa09c6066fbba0aceb230fa4e308670b32
|
refs/heads/master
| 2020-04-17T23:38:39.420000 | 2014-06-02T09:27:17 | 2014-06-02T09:27:17 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class Class858 {}
|
UTF-8
|
Java
| 40 |
java
|
Class858.java
|
Java
|
[] | null |
[] |
public class Class858 {}
| 40 | 0.475 | 0.4 | 1 | 24 | 0 | 24 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0 | false | false |
13
|
ac2ef31c56a1f24d6b4e895059945a313b727108
| 764,504,186,523 |
2c61335e2d449c96269145b2cf5d9fb647418374
|
/examples/Parse.java
|
c06046e3fc11d0f751f3c6ccc749aecaa1758165
|
[] |
no_license
|
yugesha/codehint
|
https://github.com/yugesha/codehint
|
fbb90b1331f129081513728e8055316d9997fddd
|
ba9631a632e4bfecc8f8f3465f53a53aea7eb4b0
|
refs/heads/master
| 2020-12-07T02:23:57.060000 | 2014-08-08T18:34:58 | 2014-08-08T18:34:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Arrays;
import codehint.CodeHint;
@SuppressWarnings("unused")
public class Parse {
/*
* Builds a Map that, for each line in the string, has whatever is
* before the separator map to whatever is after it.
* For example, given the email below, it will map "Subject" to
* "[cs-grads-food] Pizza" and "Date" to "Mon, 27 Feb 2012 15:28:03 -0800".
*/
private static Map<String, String> parse(String email, String separator) {
String[] lines = email.split("\n");
Map<String, String> parts = new HashMap<String, String>(lines.length);
for (String line : lines) {
int index = 0;
//index = line.indexOf(separator);
System.out.println("Task: Find the first index where the separator string occurs in the line.");
String header = null;
//header = line.substring(0,index);
System.out.println("Task: Find everything that comes before the separator in the line.");
String body = null;
System.out.println("Task: Find everything that comes after the separator in the line.");
parts.put(header, body);
}
System.out.println(parts);
return parts;
}
/*
* Find the argument that comes offset arguments after the target string, if it is in the array.
* For example, getArgument(new String[] {"a", "b", c", "d"}, "a", 2) returns "c".
*/
private static String getArgument(String[] argsArr, String target, int offset) {
List<String> argsList = null;
//argsList = Arrays.asList(argsArr);
System.out.println("Task: Convert the array of arguments into a list.");
int index = 0;
System.out.println("Task: Get the index of the target string in the array/list.");
if (index == -1)
return null;
int newIndex = index + offset;
if (newIndex >= argsArr.length)
return null;
return argsList.get(newIndex);
}
private static final String TEST_EMAIL = "Message-ID: <4F4C1183.3030805@cs.berkeley.edu>\nDate: Mon, 27 Feb 2012 15:28:03 -0800\nFrom: Nick Hay <nickjhay@cs.berkeley.edu>\nUser-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:10.0.2) Gecko/20120216 Thunderbird/10.0.2\nMIME-Version: 1.0\nTo: cs-grads-food@eecs.berkeley.edu\nSubject: [cs-grads-food] Pizza";
public static void main(String[] args) {
parse(TEST_EMAIL, ": ");
getArgument(new String[] { "--foo", "--bar", "--baz", "42" }, "--baz", 1);
getArgument(new String[] { "--foo", "--bar", "--baz", "42" }, "--foo", 0);
getArgument(new String[] { "--foo", "--bar", "--baz", "42" }, "--bar", 0);
}
}
|
UTF-8
|
Java
| 2,666 |
java
|
Parse.java
|
Java
|
[
{
"context": "te static final String TEST_EMAIL = \"Message-ID: <4F4C1183.3030805@cs.berkeley.edu>\\nDate: Mon, 27 Feb 2012 15:28:03 -0800\\nFrom: Ni",
"end": 2082,
"score": 0.9999256730079651,
"start": 2050,
"tag": "EMAIL",
"value": "4F4C1183.3030805@cs.berkeley.edu"
},
{
"context": "edu>\\nDate: Mon, 27 Feb 2012 15:28:03 -0800\\nFrom: Nick Hay <nickjhay@cs.berkeley.edu>\\nUser-Agent: Mozilla/5",
"end": 2138,
"score": 0.9998427033424377,
"start": 2130,
"tag": "NAME",
"value": "Nick Hay"
},
{
"context": " Mon, 27 Feb 2012 15:28:03 -0800\\nFrom: Nick Hay <nickjhay@cs.berkeley.edu>\\nUser-Agent: Mozilla/5.0 (Macintosh; Intel Mac O",
"end": 2164,
"score": 0.9999337196350098,
"start": 2140,
"tag": "EMAIL",
"value": "nickjhay@cs.berkeley.edu"
},
{
"context": "/10.0.2\\nMIME-Version: 1.0\\nTo: cs-grads-food@eecs.berkeley.edu\\nSubject: [cs-grads-food] Pizza\";\n\n\tp",
"end": 2311,
"score": 0.5075317025184631,
"start": 2311,
"tag": "EMAIL",
"value": ""
}
] | null |
[] |
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Arrays;
import codehint.CodeHint;
@SuppressWarnings("unused")
public class Parse {
/*
* Builds a Map that, for each line in the string, has whatever is
* before the separator map to whatever is after it.
* For example, given the email below, it will map "Subject" to
* "[cs-grads-food] Pizza" and "Date" to "Mon, 27 Feb 2012 15:28:03 -0800".
*/
private static Map<String, String> parse(String email, String separator) {
String[] lines = email.split("\n");
Map<String, String> parts = new HashMap<String, String>(lines.length);
for (String line : lines) {
int index = 0;
//index = line.indexOf(separator);
System.out.println("Task: Find the first index where the separator string occurs in the line.");
String header = null;
//header = line.substring(0,index);
System.out.println("Task: Find everything that comes before the separator in the line.");
String body = null;
System.out.println("Task: Find everything that comes after the separator in the line.");
parts.put(header, body);
}
System.out.println(parts);
return parts;
}
/*
* Find the argument that comes offset arguments after the target string, if it is in the array.
* For example, getArgument(new String[] {"a", "b", c", "d"}, "a", 2) returns "c".
*/
private static String getArgument(String[] argsArr, String target, int offset) {
List<String> argsList = null;
//argsList = Arrays.asList(argsArr);
System.out.println("Task: Convert the array of arguments into a list.");
int index = 0;
System.out.println("Task: Get the index of the target string in the array/list.");
if (index == -1)
return null;
int newIndex = index + offset;
if (newIndex >= argsArr.length)
return null;
return argsList.get(newIndex);
}
private static final String TEST_EMAIL = "Message-ID: <<EMAIL>>\nDate: Mon, 27 Feb 2012 15:28:03 -0800\nFrom: <NAME> <<EMAIL>>\nUser-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:10.0.2) Gecko/20120216 Thunderbird/10.0.2\nMIME-Version: 1.0\nTo: cs-grads-food@eecs.berkeley.edu\nSubject: [cs-grads-food] Pizza";
public static void main(String[] args) {
parse(TEST_EMAIL, ": ");
getArgument(new String[] { "--foo", "--bar", "--baz", "42" }, "--baz", 1);
getArgument(new String[] { "--foo", "--bar", "--baz", "42" }, "--foo", 0);
getArgument(new String[] { "--foo", "--bar", "--baz", "42" }, "--bar", 0);
}
}
| 2,622 | 0.638035 | 0.607277 | 67 | 38.791046 | 50.495911 | 367 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.940299 | false | false |
13
|
1231327072fa82d28f6537bf03afa0ea466a2554
| 25,443,386,316,563 |
76684657fe1dbd8ebf465c7e8fbc97826cb8065e
|
/src/main/java/mx/nic/rdap/renderer/json/writer/EventJsonWriter.java
|
37d9ceb143ed8541e26dd2950ac32f3128c99def
|
[
"Apache-2.0"
] |
permissive
|
NICMx/rdap-json-renderer
|
https://github.com/NICMx/rdap-json-renderer
|
affd19a85f73e209ae4c98ef07d3c60e39285b13
|
25533ff11961a88df6e6a6e571e4a08ec13c8069
|
refs/heads/master
| 2022-12-28T00:32:22.085000 | 2020-10-12T21:40:17 | 2020-10-14T22:52:00 | 105,705,611 | 0 | 0 |
Apache-2.0
| false | 2020-10-14T22:52:01 | 2017-10-03T21:31:32 | 2019-08-16T00:50:52 | 2020-10-14T22:52:01 | 41 | 0 | 0 | 2 |
Java
| false | false |
package mx.nic.rdap.renderer.json.writer;
import java.util.Date;
import java.util.List;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import mx.nic.rdap.core.catalog.EventAction;
import mx.nic.rdap.core.db.Event;
import mx.nic.rdap.renderer.util.RendererUtil;
public class EventJsonWriter {
public static JsonArray getJsonArray(List<Event> events) {
JsonArrayBuilder builder = Json.createArrayBuilder();
for (Event event : events) {
builder.add(getJsonObject(event));
}
return builder.build();
}
private static JsonObject getJsonObject(Event event) {
JsonObjectBuilder builder = Json.createObjectBuilder();
String key = "eventAction";
EventAction action = event.getEventAction();
if (RendererUtil.isObjectVisible(action))
builder.add(key, action.getValue());
key = "eventActor";
String value = event.getEventActor();
if (RendererUtil.isObjectVisible(value))
builder.add(key, value);
key = "eventDate";
Date eventDate = event.getEventDate();
if (RendererUtil.isObjectVisible(eventDate))
builder.add(key, eventDate.toInstant().toString());
key = "links";
if (RendererUtil.isObjectVisible(event.getLinks()))
builder.add(key, LinkJsonWriter.getJsonArray(event.getLinks()));
return builder.build();
}
}
|
UTF-8
|
Java
| 1,373 |
java
|
EventJsonWriter.java
|
Java
|
[
{
"context": "er = Json.createObjectBuilder();\n\n\t\tString key = \"eventAction\";\n\t\tEventAction action = event.getEventAction();\n",
"end": 768,
"score": 0.6710391044616699,
"start": 757,
"tag": "KEY",
"value": "eventAction"
},
{
"context": "\t\t\tbuilder.add(key, action.getValue());\n\n\t\tkey = \"eventActor\";\n\t\tString value = event.getEventActor();\n\t\tif (R",
"end": 922,
"score": 0.6936240196228027,
"start": 912,
"tag": "KEY",
"value": "eventActor"
},
{
"context": "key, eventDate.toInstant().toString());\n\n\t\tkey = \"links\";\n\t\tif (RendererUtil.isObjectVisible(event.getLin",
"end": 1216,
"score": 0.8285516500473022,
"start": 1211,
"tag": "KEY",
"value": "links"
}
] | null |
[] |
package mx.nic.rdap.renderer.json.writer;
import java.util.Date;
import java.util.List;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import mx.nic.rdap.core.catalog.EventAction;
import mx.nic.rdap.core.db.Event;
import mx.nic.rdap.renderer.util.RendererUtil;
public class EventJsonWriter {
public static JsonArray getJsonArray(List<Event> events) {
JsonArrayBuilder builder = Json.createArrayBuilder();
for (Event event : events) {
builder.add(getJsonObject(event));
}
return builder.build();
}
private static JsonObject getJsonObject(Event event) {
JsonObjectBuilder builder = Json.createObjectBuilder();
String key = "eventAction";
EventAction action = event.getEventAction();
if (RendererUtil.isObjectVisible(action))
builder.add(key, action.getValue());
key = "eventActor";
String value = event.getEventActor();
if (RendererUtil.isObjectVisible(value))
builder.add(key, value);
key = "eventDate";
Date eventDate = event.getEventDate();
if (RendererUtil.isObjectVisible(eventDate))
builder.add(key, eventDate.toInstant().toString());
key = "links";
if (RendererUtil.isObjectVisible(event.getLinks()))
builder.add(key, LinkJsonWriter.getJsonArray(event.getLinks()));
return builder.build();
}
}
| 1,373 | 0.75091 | 0.75091 | 51 | 25.921568 | 20.186234 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.647059 | false | false |
13
|
060b94ccb98158dd9b33c46963fbe5f7f921ef8e
| 23,579,370,512,309 |
dbb5a74929fa27b88bc1741f7282a328ea4191d6
|
/src/main/java/com/app/dao/impl/CartDAOImpl.java
|
21fff9e2de9af3a3ea16f218b310cb821282f374
|
[] |
no_license
|
MohammdWakeel/ONLINE-SHOPPING-APP
|
https://github.com/MohammdWakeel/ONLINE-SHOPPING-APP
|
c18beebd52a0c0e4365841d23df4e9bb8b27219f
|
dd84b06380b730d51b1b63970c6339eefc93a0ac
|
refs/heads/master
| 2023-08-16T11:29:47.030000 | 2021-10-11T13:47:51 | 2021-10-11T13:47:51 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.app.dao.impl;
import java.util.*;
import org.apache.log4j.Logger;
import java.sql.*;
import com.app.dao.*;
import com.app.dao.impl.*;
import com.app.dao.dbutil.*;
import com.app.exception.BusinessException;
import com.app.model.*;
import com.app.model.Customer;
public class CartDAOImpl implements CartDAO {
private static Logger log=Logger.getLogger(CartDAOImpl.class);
@Override
public List<Cart> viewCart(Customer customer) throws BusinessException {
List<Cart> cartList = new ArrayList<>();
try(Connection connection = MysqlConnection.getConnection()) {
String sql = "SELECT cart_id, product_id, cust_id, product_price FROM cart";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, customer.getCust_id());
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Cart cart = new Cart();
Product product = new Product();
// Customer customer = new Customer();
cart.setCart_id(resultSet.getInt("cart_id"));
product.setProduct_id(resultSet.getInt("product_id"));
customer.setCust_id(resultSet.getInt("cust_id"));
cart.setProduct_price(resultSet.getDouble("product_price"));
cartList.add(cart);
}
} catch (ClassNotFoundException | SQLException e) {
log.warn(e);
throw new BusinessException("Internal error occurred! contact system admin");
}
return cartList;
}
@Override
public int addToCart(Cart cart) throws BusinessException {
int c;
try(Connection connection = MysqlConnection.getConnection()) {
String sql = "INSERT INTO cart(cart_id, product_id, cust_id, product_price) VALUES (?,?,?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
preparedStatement.setInt(1, cart.getCart_id());
preparedStatement.setInt(2, cart.getProduct_id());
preparedStatement.setInt(3, cart.getCust_id());
preparedStatement.setDouble(4, cart.getProduct_price());
c = preparedStatement.executeUpdate();
ResultSet resultSet = preparedStatement.getGeneratedKeys();
if (resultSet.next()) {
return resultSet.getInt(1);
}
if (c == 0) {
throw new BusinessException("Customer creation failed! Check your query and try again!!!");
}
} catch (ClassNotFoundException | SQLException e) {
log.warn(e);
throw new BusinessException("Internal error occurred! contact systemAdmin");
}
return c;
}
@Override
public int removeFromCart(int product_id) throws BusinessException {
int c;
try(Connection connection = MysqlConnection.getConnection()) {
String sql = "Delete from cart where product_id=?";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, product_id);
c = preparedStatement.executeUpdate();
log.info("The product with id "+product_id+" deleted");
} catch (ClassNotFoundException | SQLException e) {
log.warn(e);
throw new BusinessException("Internal error occurred! contact systemAdmin");
}
return c;
}
}
|
UTF-8
|
Java
| 3,508 |
java
|
CartDAOImpl.java
|
Java
|
[] | null |
[] |
package com.app.dao.impl;
import java.util.*;
import org.apache.log4j.Logger;
import java.sql.*;
import com.app.dao.*;
import com.app.dao.impl.*;
import com.app.dao.dbutil.*;
import com.app.exception.BusinessException;
import com.app.model.*;
import com.app.model.Customer;
public class CartDAOImpl implements CartDAO {
private static Logger log=Logger.getLogger(CartDAOImpl.class);
@Override
public List<Cart> viewCart(Customer customer) throws BusinessException {
List<Cart> cartList = new ArrayList<>();
try(Connection connection = MysqlConnection.getConnection()) {
String sql = "SELECT cart_id, product_id, cust_id, product_price FROM cart";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, customer.getCust_id());
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Cart cart = new Cart();
Product product = new Product();
// Customer customer = new Customer();
cart.setCart_id(resultSet.getInt("cart_id"));
product.setProduct_id(resultSet.getInt("product_id"));
customer.setCust_id(resultSet.getInt("cust_id"));
cart.setProduct_price(resultSet.getDouble("product_price"));
cartList.add(cart);
}
} catch (ClassNotFoundException | SQLException e) {
log.warn(e);
throw new BusinessException("Internal error occurred! contact system admin");
}
return cartList;
}
@Override
public int addToCart(Cart cart) throws BusinessException {
int c;
try(Connection connection = MysqlConnection.getConnection()) {
String sql = "INSERT INTO cart(cart_id, product_id, cust_id, product_price) VALUES (?,?,?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
preparedStatement.setInt(1, cart.getCart_id());
preparedStatement.setInt(2, cart.getProduct_id());
preparedStatement.setInt(3, cart.getCust_id());
preparedStatement.setDouble(4, cart.getProduct_price());
c = preparedStatement.executeUpdate();
ResultSet resultSet = preparedStatement.getGeneratedKeys();
if (resultSet.next()) {
return resultSet.getInt(1);
}
if (c == 0) {
throw new BusinessException("Customer creation failed! Check your query and try again!!!");
}
} catch (ClassNotFoundException | SQLException e) {
log.warn(e);
throw new BusinessException("Internal error occurred! contact systemAdmin");
}
return c;
}
@Override
public int removeFromCart(int product_id) throws BusinessException {
int c;
try(Connection connection = MysqlConnection.getConnection()) {
String sql = "Delete from cart where product_id=?";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, product_id);
c = preparedStatement.executeUpdate();
log.info("The product with id "+product_id+" deleted");
} catch (ClassNotFoundException | SQLException e) {
log.warn(e);
throw new BusinessException("Internal error occurred! contact systemAdmin");
}
return c;
}
}
| 3,508 | 0.63455 | 0.631984 | 87 | 39.321838 | 30.595806 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false |
13
|
2175a6e271999633b62733433586db8947419951
| 26,250,840,165,521 |
a92b6ab8deda1fda49b5aefdb85af16793b10830
|
/app/src/main/java/com/yahoo/melnichuk/a/kommunalchik/Tables/PhoneTable.java
|
adb793362c9a10d2c737ef77ad4ee4fc2c507dba
|
[] |
no_license
|
a-melnichuk/Kommunalchik_v1
|
https://github.com/a-melnichuk/Kommunalchik_v1
|
b9d48c65d473be2eed44ac531b5ed4e6cb290912
|
af27f21eed11d43d76f94611be6365ebffd994fa
|
refs/heads/master
| 2016-04-03T14:39:42.358000 | 2015-12-14T09:54:09 | 2015-12-14T09:54:09 | 31,616,194 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.yahoo.melnichuk.a.kommunalchik.Tables;
import com.yahoo.melnichuk.a.kommunalchik.DataManager;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
/**
* Created by xxxalxxx on 02.05.2015.
*/
public class PhoneTable extends Table {
private static final PhoneTable INSTANCE = new PhoneTable();
private PhoneTable(){
for(int i=0;i< DataManager.TABLE_LENS[7];++i){
mainTableData.add("0");
}
}
@Override
public String[] getTableSumColumn() {
return setSumRow(2,5,8);
}
@Override
public String getTableSumCell() {
return getMainTableData().get(8);
}
@Override
public int getSegmentSumIndex() {
return 4;
}
@Override
public ArrayList<ArrayList<String>> getEditedTable() {
return setSameColumnWidths(getMergedTable());
}
@Override
public ArrayList<ArrayList<String>> getFormedTable() {
return getMergedTable();
}
@Override
void calcMainTable() {
BigDecimal[] t = formBigDecimalArray();
BigDecimal TAX = new BigDecimal(0.2),
noTax1,withTax1,total1,
noTax2,withTax2,total2,
noTax3,withTax3,total3;
noTax1 = t[0].setScale(2, RoundingMode.HALF_UP);
withTax1 = noTax1.multiply(TAX).setScale(2, RoundingMode.HALF_UP);
if(noTax1.doubleValue()==0 || withTax1.doubleValue()==0)
total1 = t[2].setScale(2, RoundingMode.HALF_UP);
else total1 = noTax1.add(withTax1);
noTax2 = t[3].setScale(2, RoundingMode.HALF_UP);
withTax2 = noTax2.multiply(TAX).setScale(2, RoundingMode.HALF_UP);
if(noTax2.doubleValue()==0 || withTax2.doubleValue()==0)
total2 = t[5].setScale(2, RoundingMode.HALF_UP);
else total2 = noTax2.add(withTax2);
noTax3 = noTax1.add(noTax2);
withTax3 = withTax1.add(withTax2);
if(total1.doubleValue()!=0 || total2.doubleValue()!=0)
total3 = total1.add(total2);
else if(noTax3.add(withTax3).doubleValue()!=0)
total3 = noTax3.add(withTax3);
else total3 = t[8].setScale(2, RoundingMode.HALF_UP);
BigDecimal[] calculatedVals = {noTax1,withTax1,total1, noTax2,withTax2,total2, noTax3,withTax3,total3};
updateMainTable(calculatedVals);
}
public static PhoneTable getInstance() {
return INSTANCE;
}
}
|
UTF-8
|
Java
| 2,504 |
java
|
PhoneTable.java
|
Java
|
[
{
"context": "de;\nimport java.util.ArrayList;\n\n/**\n * Created by xxxalxxx on 02.05.2015.\n */\npublic class PhoneTable extend",
"end": 223,
"score": 0.9996291995048523,
"start": 215,
"tag": "USERNAME",
"value": "xxxalxxx"
}
] | null |
[] |
package com.yahoo.melnichuk.a.kommunalchik.Tables;
import com.yahoo.melnichuk.a.kommunalchik.DataManager;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
/**
* Created by xxxalxxx on 02.05.2015.
*/
public class PhoneTable extends Table {
private static final PhoneTable INSTANCE = new PhoneTable();
private PhoneTable(){
for(int i=0;i< DataManager.TABLE_LENS[7];++i){
mainTableData.add("0");
}
}
@Override
public String[] getTableSumColumn() {
return setSumRow(2,5,8);
}
@Override
public String getTableSumCell() {
return getMainTableData().get(8);
}
@Override
public int getSegmentSumIndex() {
return 4;
}
@Override
public ArrayList<ArrayList<String>> getEditedTable() {
return setSameColumnWidths(getMergedTable());
}
@Override
public ArrayList<ArrayList<String>> getFormedTable() {
return getMergedTable();
}
@Override
void calcMainTable() {
BigDecimal[] t = formBigDecimalArray();
BigDecimal TAX = new BigDecimal(0.2),
noTax1,withTax1,total1,
noTax2,withTax2,total2,
noTax3,withTax3,total3;
noTax1 = t[0].setScale(2, RoundingMode.HALF_UP);
withTax1 = noTax1.multiply(TAX).setScale(2, RoundingMode.HALF_UP);
if(noTax1.doubleValue()==0 || withTax1.doubleValue()==0)
total1 = t[2].setScale(2, RoundingMode.HALF_UP);
else total1 = noTax1.add(withTax1);
noTax2 = t[3].setScale(2, RoundingMode.HALF_UP);
withTax2 = noTax2.multiply(TAX).setScale(2, RoundingMode.HALF_UP);
if(noTax2.doubleValue()==0 || withTax2.doubleValue()==0)
total2 = t[5].setScale(2, RoundingMode.HALF_UP);
else total2 = noTax2.add(withTax2);
noTax3 = noTax1.add(noTax2);
withTax3 = withTax1.add(withTax2);
if(total1.doubleValue()!=0 || total2.doubleValue()!=0)
total3 = total1.add(total2);
else if(noTax3.add(withTax3).doubleValue()!=0)
total3 = noTax3.add(withTax3);
else total3 = t[8].setScale(2, RoundingMode.HALF_UP);
BigDecimal[] calculatedVals = {noTax1,withTax1,total1, noTax2,withTax2,total2, noTax3,withTax3,total3};
updateMainTable(calculatedVals);
}
public static PhoneTable getInstance() {
return INSTANCE;
}
}
| 2,504 | 0.616214 | 0.580272 | 88 | 27.454546 | 25.265818 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.727273 | false | false |
13
|
b1ca0665cc8bb15670774242c363842479c87413
| 29,557,964,985,409 |
d59dd61cdf1eb723b1d5da9866bda45007496a33
|
/io/src/main/java/net/zhanghc/toolkit/io/QuickFileReader.java
|
bcf7709d4412553e87a1978858898ef32bbac2f2
|
[] |
no_license
|
rukyzhc/toolkit
|
https://github.com/rukyzhc/toolkit
|
53f876975aa30b42fa454424c60acc6aab1858ff
|
28e686911a4fa963c1af8343d6b8a97456591845
|
refs/heads/master
| 2016-09-05T17:31:40.620000 | 2014-12-22T08:59:50 | 2014-12-22T08:59:50 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package net.zhanghc.toolkit.io;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
/**
*
* @deprecated
* See {@link EasyFileReader}
*
* @author zhanghc
*
*/
public class QuickFileReader extends BufferedReader {
public QuickFileReader(Reader r) {
super(r);
}
public QuickFileReader(String file) throws FileNotFoundException {
super(new InputStreamReader(new FileInputStream(file)));
}
public QuickFileReader(String file, String charset) throws UnsupportedEncodingException, FileNotFoundException {
super(new InputStreamReader(new FileInputStream(file), charset));
}
public String readLineSkip(char c) throws IOException {
String line = null;
while((line = readLine()) != null && line.charAt(0) != c) ;
return line;
}
}
|
UTF-8
|
Java
| 936 |
java
|
QuickFileReader.java
|
Java
|
[
{
"context": "cated\n * See {@link EasyFileReader}\n * \n * @author zhanghc\n *\n */\npublic class QuickFileReader extends Buffe",
"end": 340,
"score": 0.9995424151420593,
"start": 333,
"tag": "USERNAME",
"value": "zhanghc"
}
] | null |
[] |
package net.zhanghc.toolkit.io;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
/**
*
* @deprecated
* See {@link EasyFileReader}
*
* @author zhanghc
*
*/
public class QuickFileReader extends BufferedReader {
public QuickFileReader(Reader r) {
super(r);
}
public QuickFileReader(String file) throws FileNotFoundException {
super(new InputStreamReader(new FileInputStream(file)));
}
public QuickFileReader(String file, String charset) throws UnsupportedEncodingException, FileNotFoundException {
super(new InputStreamReader(new FileInputStream(file), charset));
}
public String readLineSkip(char c) throws IOException {
String line = null;
while((line = readLine()) != null && line.charAt(0) != c) ;
return line;
}
}
| 936 | 0.75641 | 0.755342 | 39 | 23 | 25.808964 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false |
13
|
fc031ba1477b30745c75d2a31cf4735523f34f0e
| 12,833,362,331,134 |
3703e3ff6215d743901ccbb9ff584ac8b5419e2d
|
/src/app/src/main/java/clowdtech/mpositive/areas/till/IDualPaneContainer.java
|
5f547db3a1b2522089b3abfb8020dca4528db7a0
|
[] |
no_license
|
Clowdtech/Mpositive-App
|
https://github.com/Clowdtech/Mpositive-App
|
39f27cdb30bf274b749baba139376b2be1d09d90
|
56709a5bdecc10c6c30f16062c723f6328063cfe
|
refs/heads/master
| 2021-01-10T18:16:07.271000 | 2016-10-07T18:36:23 | 2016-10-07T18:36:23 | 54,271,501 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package clowdtech.mpositive.areas.till;
import com.clowdtech.data.entities.ITransactionLineManual;
import com.clowdtech.data.entities.ITransactionLineProduct;
public interface IDualPaneContainer {
void displayCheckout();
void addReceiptEntry(ITransactionLineProduct line);
void addReceiptEntry(ITransactionLineManual line);
void refreshRunningTotal();
void displayPaymentChoice();
void displayPaymentComplete(long receiptId);
boolean isBackHandled();
void clearReceipt();
}
|
UTF-8
|
Java
| 515 |
java
|
IDualPaneContainer.java
|
Java
|
[] | null |
[] |
package clowdtech.mpositive.areas.till;
import com.clowdtech.data.entities.ITransactionLineManual;
import com.clowdtech.data.entities.ITransactionLineProduct;
public interface IDualPaneContainer {
void displayCheckout();
void addReceiptEntry(ITransactionLineProduct line);
void addReceiptEntry(ITransactionLineManual line);
void refreshRunningTotal();
void displayPaymentChoice();
void displayPaymentComplete(long receiptId);
boolean isBackHandled();
void clearReceipt();
}
| 515 | 0.784466 | 0.784466 | 22 | 22.40909 | 22.368116 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
13
|
9f6f5218eea8328b5eff3f1b9b6c2d5380b85bbf
| 1,915,555,484,571 |
ba37915d1ac412df2ca1ce8fb63658f875681a3d
|
/Module/cas-server-4.0.1_customized/App/src/java/com/technology/jep/jepcommon/security/PkgOperator.java
|
4660870dc1a3ca383d41eb4e01a8a7b2be5b5212
|
[] |
no_license
|
almirus/javaenterpriseplatform
|
https://github.com/almirus/javaenterpriseplatform
|
61d195fded708a15c7d91a267aa9607041759018
|
4d1ffb55a24ff602a90747f75f62929fd25fe37b
|
refs/heads/master
| 2016-08-12T06:05:49.219000 | 2016-01-27T12:39:20 | 2016-01-27T12:39:20 | 50,493,872 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.technology.jep.jepcommon.security;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import oracle.jdbc.driver.OracleTypes;
import com.technology.jep.jepria.server.db.Db;
/**
* Обеспечивает доступ к некоторым методам пакета pkg_Operator в базе данных.
*/
public class PkgOperator {
/**
* Регистрация оператора в базе данных.<br/>
* Функция осуществляет последовательный вызов функций базы данных:<br/>
* <code>
* pkg_Operator.Login(login, password);<br/>
* pkg_Operator.GetCurrentUserID();<br/>
* </code>
*
* @param db соединение с базой данных
* @param login логин пользователя
* @param password пароль пользователя
* @return идентификатор текущего пользователя при успешной аутентификации
* @throws SQLException при неудачной аутентификации
*/
public static final Integer logon(Db db, String login, String password) throws SQLException {
trace("logon(Db db, " + login + ", " + password + ")");
Integer result = null;
String sqlQuery =
" begin"
+ " ? := pkg_Operator.Login(?, ?);"
+ " ? := pkg_Operator.GetCurrentUserID();"
+ " end;";
try {
CallableStatement callableStatement = db.prepare(sqlQuery);
// Установим Логин.
if(login != null) callableStatement.setString(2, login);
else callableStatement.setNull(2, Types.VARCHAR);
// Установим Пароль.
if(password != null) callableStatement.setString(3, password);
else callableStatement.setNull(3, Types.VARCHAR);
callableStatement.registerOutParameter(1, Types.VARCHAR);
callableStatement.registerOutParameter(4, Types.INTEGER);
callableStatement.execute();
result = new Integer(callableStatement.getInt(4));
if(callableStatement.wasNull())result = null;
} finally {
db.closeStatement(sqlQuery);
}
return result;
}
/**
* Регистрация оператора в базе данных.<br/>
* Функция осуществляет последовательный вызов функций базы данных:<br/>
* <code>
* pkg_Operator.Login(login);<br/>
* pkg_Operator.GetCurrentUserID();<br/>
* </code>
*
* @param db соединение с базой данных
* @param login логин пользователя
* @return идентификатор текущего пользователя
* @throws SQLException при отсутствии пользователя с указанным логином
*/
public static final Integer logon(Db db, String login) throws SQLException {
trace("logon(Db db, " + login + ")");
Integer result = null;
String sqlQuery =
" begin"
+ " ? := pkg_Operator.Login(?);"
+ " ? := pkg_Operator.GetCurrentUserID();"
+ " end;";
try {
CallableStatement callableStatement = db.prepare(sqlQuery);
// Установим Логин.
if(login != null) callableStatement.setString(2, login);
else callableStatement.setNull(2, Types.VARCHAR);
callableStatement.registerOutParameter(1, Types.VARCHAR);
callableStatement.registerOutParameter(3, Types.INTEGER);
callableStatement.execute();
result = new Integer(callableStatement.getInt(3));
if(callableStatement.wasNull())result = null;
} finally {
db.closeStatement(sqlQuery);
}
return result;
}
/**
* Функция определяет необходимость смены пользователем пароля.
*
* @param operatorId идентификатор пользователя
* @return true - если пользователю необходимо сменить пароль, false - в противном случае.
* @throws SQLException
*/
public static final boolean isChangePassword(Db db, Integer operatorId) throws SQLException {
trace("isChangePassword(Db db, " + operatorId + ")");
Integer result = null;
String sqlQuery =
" begin"
+ " ? := pkg_Operator.IsChangePassword(?);"
+ " end;";
try {
CallableStatement callableStatement = db.prepare(sqlQuery);
if(operatorId != null) callableStatement.setInt(2, operatorId);
else callableStatement.setNull(2, Types.INTEGER);
callableStatement.registerOutParameter(1, Types.INTEGER);
callableStatement.execute();
result = new Integer(callableStatement.getInt(1));
if(callableStatement.wasNull())result = null;
} finally {
db.closeStatement(sqlQuery);
}
return result != null && result.intValue() == 1;
}
/**
* Изменение пароля пользователя.
*
* @param db соединение с базой данных
* @param operatorId идентификатор пользователя, пароль которого необходимо изменить
* @param password пароль пользователя
* @param newPassword новый пароль пользователя
* @param newPasswordConfirm подтверждение нового пароля пользователя
* @throws SQLException при неудавшейся смене пароля
*/
public static final void changePassword(
Db db
, Integer operatorId
, String password
, String newPassword
, String newPasswordConfirm)
throws SQLException {
trace("changePassword()");
String sqlQuery =
" begin"
+ " pkg_Operator.ChangePassword(?, ?, ?, ?);"
+ " end;";
try {
CallableStatement callableStatement = db.prepare(sqlQuery);
if(operatorId != null) callableStatement.setInt(1, operatorId.intValue());
else callableStatement.setNull(1, Types.INTEGER);
if(password != null) callableStatement.setString(2, password);
else callableStatement.setNull(2, Types.VARCHAR);
if(newPassword != null) callableStatement.setString(3, newPassword);
else callableStatement.setNull(3, Types.VARCHAR);
if(newPasswordConfirm != null) callableStatement.setString(4, newPasswordConfirm);
else callableStatement.setNull(4, Types.VARCHAR);
callableStatement.execute();
} finally {
db.closeStatement(sqlQuery);
}
}
/**
* Получение списка ролей пользователя.
*
* @param db соединение с базой данных
* @param login логин пользователя
* @return список ролей пользователя в виде List<String>
* @throws SQLException
*/
public static final List<String> getRoles(Db db, String login) throws SQLException {
trace("getRoles(Db db, " + login + ")");
List<String> result = new ArrayList<String>();
String sqlQuery =
" begin"
+ " ? := pkg_Operator.getRolesShortName("
+ " ?"
+ " );"
+ " end;";
try {
CallableStatement callableStatement = db.prepare(sqlQuery);
callableStatement.registerOutParameter(1, OracleTypes.CURSOR);
// Установим Логин.
if(login != null) callableStatement.setString(2, login);
else callableStatement.setNull(2, Types.VARCHAR);
// Выполнение запроса.
callableStatement.execute();
//Получим набор.
ResultSet resultSet = (ResultSet) callableStatement.getObject(1);
while (resultSet.next()) {
result.add(resultSet.getString("short_name"));
}
} finally {
db.closeStatement(sqlQuery);
}
return result;
}
/**
* Получение списка ролей пользователя.
*
* @param db соединение с базой данных
* @param operatorId идентификатор пользователя
* @return список ролей пользователя в виде List<String>
* @throws SQLException
*/
public static final List<String> getRoles(Db db, Integer operatorId) throws SQLException {
trace("getRoles(Db db, " + operatorId + ")");
List<String> result = new ArrayList<String>();
String sqlQuery =
" begin"
+ " ? := pkg_Operator.getRolesShortName("
+ " ?"
+ " );"
+ " end;";
try {
CallableStatement callableStatement = db.prepare(sqlQuery);
callableStatement.registerOutParameter(1, OracleTypes.CURSOR);
// Установим Логин.
if(operatorId != null) callableStatement.setInt(2, operatorId);
else callableStatement.setNull(2, Types.VARCHAR);
// Выполнение запроса.
callableStatement.execute();
//Получим набор.
ResultSet resultSet = (ResultSet) callableStatement.getObject(1);
while (resultSet.next()) {
result.add(resultSet.getString("short_name"));
}
} finally {
db.closeStatement(sqlQuery);
}
return result;
}
private static void trace(String message) {
System.out.println("pkg_Operator: " + message);
}
}
|
UTF-8
|
Java
| 9,107 |
java
|
PkgOperator.java
|
Java
|
[
{
"context": "b\t\t\t\tсоединение с базой данных\n\t * @param login\t\t\tлогин пользователя\n\t * @param password\tпароль пользователя\n\t * @retu",
"end": 737,
"score": 0.8901060223579407,
"start": 719,
"tag": "NAME",
"value": "логин пользователя"
},
{
"context": "am login\t\t\tлогин пользователя\n\t * @param password\tпароль пользователя\n\t * @return идентификатор текущего пользователя п",
"end": 777,
"score": 0.8599497079849243,
"start": 758,
"tag": "PASSWORD",
"value": "пароль пользователя"
},
{
"context": "b\t\t\t\tсоединение с базой данных\n\t * @param login\t\t\tлогин пользователя\n\t * @return идентификатор текущего пользователя\n\t",
"end": 2231,
"score": 0.9508676528930664,
"start": 2213,
"tag": "NAME",
"value": "логин пользователя"
},
{
"context": "рого необходимо изменить\n\t * @param password\t\t\t\t\t\tпароль пользователя\n\t * @param newPassword\t\t\t\t\tновый пароль пользоват",
"end": 4434,
"score": 0.8908990025520325,
"start": 4415,
"tag": "PASSWORD",
"value": "пароль пользователя"
},
{
"context": "\t\t\tпароль пользователя\n\t * @param newPassword\t\t\t\t\tновый пароль пользователя\n\t * @param newPasswordConfirm\tподтверждение новог",
"end": 4487,
"score": 0.8478265404701233,
"start": 4462,
"tag": "PASSWORD",
"value": "новый пароль пользователя"
},
{
"context": "ram db соединение с базой данных\n\t * @param login\tлогин пользователя\n\t * @return список ролей пользовател",
"end": 5714,
"score": 0.8460893630981445,
"start": 5709,
"tag": "NAME",
"value": "логин"
},
{
"context": "b соединение с базой данных\n\t * @param login\tлогин пользователя\n\t * @return список ролей пользователя в виде List",
"end": 5727,
"score": 0.669977605342865,
"start": 5715,
"tag": "NAME",
"value": "пользователя"
},
{
"context": "нных\n\t * @param operatorId\tидентификатор пользователя\n\t * @return список ролей пользователя в виде List",
"end": 6851,
"score": 0.5841515064239502,
"start": 6848,
"tag": "NAME",
"value": "еля"
}
] | null |
[] |
package com.technology.jep.jepcommon.security;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import oracle.jdbc.driver.OracleTypes;
import com.technology.jep.jepria.server.db.Db;
/**
* Обеспечивает доступ к некоторым методам пакета pkg_Operator в базе данных.
*/
public class PkgOperator {
/**
* Регистрация оператора в базе данных.<br/>
* Функция осуществляет последовательный вызов функций базы данных:<br/>
* <code>
* pkg_Operator.Login(login, password);<br/>
* pkg_Operator.GetCurrentUserID();<br/>
* </code>
*
* @param db соединение с базой данных
* @param login <NAME>
* @param password <PASSWORD>
* @return идентификатор текущего пользователя при успешной аутентификации
* @throws SQLException при неудачной аутентификации
*/
public static final Integer logon(Db db, String login, String password) throws SQLException {
trace("logon(Db db, " + login + ", " + password + ")");
Integer result = null;
String sqlQuery =
" begin"
+ " ? := pkg_Operator.Login(?, ?);"
+ " ? := pkg_Operator.GetCurrentUserID();"
+ " end;";
try {
CallableStatement callableStatement = db.prepare(sqlQuery);
// Установим Логин.
if(login != null) callableStatement.setString(2, login);
else callableStatement.setNull(2, Types.VARCHAR);
// Установим Пароль.
if(password != null) callableStatement.setString(3, password);
else callableStatement.setNull(3, Types.VARCHAR);
callableStatement.registerOutParameter(1, Types.VARCHAR);
callableStatement.registerOutParameter(4, Types.INTEGER);
callableStatement.execute();
result = new Integer(callableStatement.getInt(4));
if(callableStatement.wasNull())result = null;
} finally {
db.closeStatement(sqlQuery);
}
return result;
}
/**
* Регистрация оператора в базе данных.<br/>
* Функция осуществляет последовательный вызов функций базы данных:<br/>
* <code>
* pkg_Operator.Login(login);<br/>
* pkg_Operator.GetCurrentUserID();<br/>
* </code>
*
* @param db соединение с базой данных
* @param login <NAME>
* @return идентификатор текущего пользователя
* @throws SQLException при отсутствии пользователя с указанным логином
*/
public static final Integer logon(Db db, String login) throws SQLException {
trace("logon(Db db, " + login + ")");
Integer result = null;
String sqlQuery =
" begin"
+ " ? := pkg_Operator.Login(?);"
+ " ? := pkg_Operator.GetCurrentUserID();"
+ " end;";
try {
CallableStatement callableStatement = db.prepare(sqlQuery);
// Установим Логин.
if(login != null) callableStatement.setString(2, login);
else callableStatement.setNull(2, Types.VARCHAR);
callableStatement.registerOutParameter(1, Types.VARCHAR);
callableStatement.registerOutParameter(3, Types.INTEGER);
callableStatement.execute();
result = new Integer(callableStatement.getInt(3));
if(callableStatement.wasNull())result = null;
} finally {
db.closeStatement(sqlQuery);
}
return result;
}
/**
* Функция определяет необходимость смены пользователем пароля.
*
* @param operatorId идентификатор пользователя
* @return true - если пользователю необходимо сменить пароль, false - в противном случае.
* @throws SQLException
*/
public static final boolean isChangePassword(Db db, Integer operatorId) throws SQLException {
trace("isChangePassword(Db db, " + operatorId + ")");
Integer result = null;
String sqlQuery =
" begin"
+ " ? := pkg_Operator.IsChangePassword(?);"
+ " end;";
try {
CallableStatement callableStatement = db.prepare(sqlQuery);
if(operatorId != null) callableStatement.setInt(2, operatorId);
else callableStatement.setNull(2, Types.INTEGER);
callableStatement.registerOutParameter(1, Types.INTEGER);
callableStatement.execute();
result = new Integer(callableStatement.getInt(1));
if(callableStatement.wasNull())result = null;
} finally {
db.closeStatement(sqlQuery);
}
return result != null && result.intValue() == 1;
}
/**
* Изменение пароля пользователя.
*
* @param db соединение с базой данных
* @param operatorId идентификатор пользователя, пароль которого необходимо изменить
* @param password <PASSWORD>
* @param newPassword <PASSWORD>
* @param newPasswordConfirm подтверждение нового пароля пользователя
* @throws SQLException при неудавшейся смене пароля
*/
public static final void changePassword(
Db db
, Integer operatorId
, String password
, String newPassword
, String newPasswordConfirm)
throws SQLException {
trace("changePassword()");
String sqlQuery =
" begin"
+ " pkg_Operator.ChangePassword(?, ?, ?, ?);"
+ " end;";
try {
CallableStatement callableStatement = db.prepare(sqlQuery);
if(operatorId != null) callableStatement.setInt(1, operatorId.intValue());
else callableStatement.setNull(1, Types.INTEGER);
if(password != null) callableStatement.setString(2, password);
else callableStatement.setNull(2, Types.VARCHAR);
if(newPassword != null) callableStatement.setString(3, newPassword);
else callableStatement.setNull(3, Types.VARCHAR);
if(newPasswordConfirm != null) callableStatement.setString(4, newPasswordConfirm);
else callableStatement.setNull(4, Types.VARCHAR);
callableStatement.execute();
} finally {
db.closeStatement(sqlQuery);
}
}
/**
* Получение списка ролей пользователя.
*
* @param db соединение с базой данных
* @param login логин пользователя
* @return список ролей пользователя в виде List<String>
* @throws SQLException
*/
public static final List<String> getRoles(Db db, String login) throws SQLException {
trace("getRoles(Db db, " + login + ")");
List<String> result = new ArrayList<String>();
String sqlQuery =
" begin"
+ " ? := pkg_Operator.getRolesShortName("
+ " ?"
+ " );"
+ " end;";
try {
CallableStatement callableStatement = db.prepare(sqlQuery);
callableStatement.registerOutParameter(1, OracleTypes.CURSOR);
// Установим Логин.
if(login != null) callableStatement.setString(2, login);
else callableStatement.setNull(2, Types.VARCHAR);
// Выполнение запроса.
callableStatement.execute();
//Получим набор.
ResultSet resultSet = (ResultSet) callableStatement.getObject(1);
while (resultSet.next()) {
result.add(resultSet.getString("short_name"));
}
} finally {
db.closeStatement(sqlQuery);
}
return result;
}
/**
* Получение списка ролей пользователя.
*
* @param db соединение с базой данных
* @param operatorId идентификатор пользователя
* @return список ролей пользователя в виде List<String>
* @throws SQLException
*/
public static final List<String> getRoles(Db db, Integer operatorId) throws SQLException {
trace("getRoles(Db db, " + operatorId + ")");
List<String> result = new ArrayList<String>();
String sqlQuery =
" begin"
+ " ? := pkg_Operator.getRolesShortName("
+ " ?"
+ " );"
+ " end;";
try {
CallableStatement callableStatement = db.prepare(sqlQuery);
callableStatement.registerOutParameter(1, OracleTypes.CURSOR);
// Установим Логин.
if(operatorId != null) callableStatement.setInt(2, operatorId);
else callableStatement.setNull(2, Types.VARCHAR);
// Выполнение запроса.
callableStatement.execute();
//Получим набор.
ResultSet resultSet = (ResultSet) callableStatement.getObject(1);
while (resultSet.next()) {
result.add(resultSet.getString("short_name"));
}
} finally {
db.closeStatement(sqlQuery);
}
return result;
}
private static void trace(String message) {
System.out.println("pkg_Operator: " + message);
}
}
| 8,957 | 0.696451 | 0.692298 | 281 | 27.274021 | 25.010595 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.427046 | false | false |
13
|
af56971c3ea4040c057dfa6542591a37550ea873
| 22,368,189,734,278 |
6ffd3adb4908c386f5da2c3e408d5705a96c9c64
|
/JDBC-01-JDBCTemplate-CURD-DirectMethod/src/main/java/com/nt/service/IEmployeeMangService.java
|
311d1a255ffe492455f42ce5918d00116a8e0afa
|
[] |
no_license
|
Gaikwadavinash/Spring-jdbc
|
https://github.com/Gaikwadavinash/Spring-jdbc
|
d6db5db15ba83a5e437b6c4ca34d234c3e6df982
|
722420bdb9828417af1262e6bd118c8d6047a354
|
refs/heads/master
| 2023-04-22T22:41:07.395000 | 2021-05-15T09:45:04 | 2021-05-15T09:45:04 | 366,131,900 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.nt.service;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.support.rowset.SqlRowSet;
public interface IEmployeeMangService {
//public int fetchemployeeCount();
//public Float fetchSalarybyEmpNo(int eno);
//public Map<String,Object> fetchEmpDetailsByEno(int eno);
//public List<Map<String,Object>> fetchEmpDetailsByDesg(String desg1,String desg2,String desg3);
//public SqlRowSet fetchEmpSalaryByRange(float startSal,float endSal);
//public String insertRecordActor(String actorName,String actorAddress,Long phoneNo);
//public String updateActorRecord(String actorAddress,Long actorId);
public String deleteActorRecordByRange(Float start,float end);
}
|
UTF-8
|
Java
| 713 |
java
|
IEmployeeMangService.java
|
Java
|
[] | null |
[] |
package com.nt.service;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.support.rowset.SqlRowSet;
public interface IEmployeeMangService {
//public int fetchemployeeCount();
//public Float fetchSalarybyEmpNo(int eno);
//public Map<String,Object> fetchEmpDetailsByEno(int eno);
//public List<Map<String,Object>> fetchEmpDetailsByDesg(String desg1,String desg2,String desg3);
//public SqlRowSet fetchEmpSalaryByRange(float startSal,float endSal);
//public String insertRecordActor(String actorName,String actorAddress,Long phoneNo);
//public String updateActorRecord(String actorAddress,Long actorId);
public String deleteActorRecordByRange(Float start,float end);
}
| 713 | 0.802244 | 0.798036 | 17 | 39.941177 | 29.983271 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.235294 | false | false |
13
|
925b4292917f9a70dfbb474564876ec8245fee26
| 3,161,095,980,386 |
39036c21603d8e4be046aa311e201502465d7ca2
|
/src/im_system_demo/server/handler/CreateGroupHandler.java
|
39dcdda422da14545af23eec2e9b86d229ab4d05
|
[] |
no_license
|
xiong1783296281/Netty
|
https://github.com/xiong1783296281/Netty
|
8a9aac8cfe2588d602a72a4417294eb1c6186e6d
|
fc4ae8e06f5120ab82b5e6ce331780e019040629
|
refs/heads/master
| 2020-05-27T10:44:45.154000 | 2019-07-26T09:28:27 | 2019-07-26T09:28:27 | 188,587,039 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package im_system_demo.server.handler;
import im_system_demo.proto.request_packet.CreateGroupRequestPacket;
import im_system_demo.proto.response_packet.CreateGroupResponsePacket;
import im_system_demo.server.util.IDUtil;
import im_system_demo.server.util.SessionUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import java.util.ArrayList;
import java.util.List;
/**
* @author xiong
* @date 2019-06-06 21:24
*/
@ChannelHandler.Sharable
public class CreateGroupHandler extends SimpleChannelInboundHandler<CreateGroupRequestPacket> {
public static final CreateGroupHandler INSTANCE = new CreateGroupHandler();
private CreateGroupHandler(){}
@Override
protected void channelRead0(ChannelHandlerContext ctx, CreateGroupRequestPacket msg) throws Exception {
List<String> usernameList = msg.getUsernameList();
String nickname = msg.getNickname();
List<String> users = new ArrayList<>();
ChannelGroup group = new DefaultChannelGroup(ctx.executor());
for(String name : usernameList){
Channel channel = SessionUtil.getChannel(name);
if(channel != null){
group.add(channel);
users.add(name);
}
}
CreateGroupResponsePacket groupPacket = new CreateGroupResponsePacket();
groupPacket.setSuccess(true);
groupPacket.setUUID(IDUtil.getID());
groupPacket.setNickname(nickname);
groupPacket.setUsers(users);
group.writeAndFlush(groupPacket);
System.out.println("创群成功: " + groupPacket.getNickname());
System.out.println("群成员: " + groupPacket.getUsers());
SessionUtil.bindChannelGroup(nickname, group);
}
}
|
UTF-8
|
Java
| 1,949 |
java
|
CreateGroupHandler.java
|
Java
|
[
{
"context": ".ArrayList;\nimport java.util.List;\n\n/**\n * @author xiong\n * @date 2019-06-06 21:24\n */\n@ChannelHandler.Sh",
"end": 610,
"score": 0.9995710253715515,
"start": 605,
"tag": "USERNAME",
"value": "xiong"
}
] | null |
[] |
package im_system_demo.server.handler;
import im_system_demo.proto.request_packet.CreateGroupRequestPacket;
import im_system_demo.proto.response_packet.CreateGroupResponsePacket;
import im_system_demo.server.util.IDUtil;
import im_system_demo.server.util.SessionUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import java.util.ArrayList;
import java.util.List;
/**
* @author xiong
* @date 2019-06-06 21:24
*/
@ChannelHandler.Sharable
public class CreateGroupHandler extends SimpleChannelInboundHandler<CreateGroupRequestPacket> {
public static final CreateGroupHandler INSTANCE = new CreateGroupHandler();
private CreateGroupHandler(){}
@Override
protected void channelRead0(ChannelHandlerContext ctx, CreateGroupRequestPacket msg) throws Exception {
List<String> usernameList = msg.getUsernameList();
String nickname = msg.getNickname();
List<String> users = new ArrayList<>();
ChannelGroup group = new DefaultChannelGroup(ctx.executor());
for(String name : usernameList){
Channel channel = SessionUtil.getChannel(name);
if(channel != null){
group.add(channel);
users.add(name);
}
}
CreateGroupResponsePacket groupPacket = new CreateGroupResponsePacket();
groupPacket.setSuccess(true);
groupPacket.setUUID(IDUtil.getID());
groupPacket.setNickname(nickname);
groupPacket.setUsers(users);
group.writeAndFlush(groupPacket);
System.out.println("创群成功: " + groupPacket.getNickname());
System.out.println("群成员: " + groupPacket.getUsers());
SessionUtil.bindChannelGroup(nickname, group);
}
}
| 1,949 | 0.71938 | 0.712662 | 57 | 32.947369 | 27.012291 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.561404 | false | false |
13
|
26d6e5b3ef8119e48dc0044d2c7e563ef95b2e26
| 13,743,895,358,796 |
41a27d48a3fd2cf1e4377137ef095a58d02541a4
|
/src/main/java/be/vdab/services/BrouwerServiceImpl.java
|
5b7c2cbd135f736993771a3c72a1aec780c62bc5
|
[] |
no_license
|
YThibos/Brouwers
|
https://github.com/YThibos/Brouwers
|
1ccdcdea66c3de42ca660358ccadf07e008611ed
|
365b250bfc7c5f63d81de9e343f8cea59de52a3f
|
refs/heads/master
| 2021-01-01T05:17:39.941000 | 2016-06-06T08:57:44 | 2016-06-06T08:57:44 | 59,281,678 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package be.vdab.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import be.vdab.entities.Brouwer;
import be.vdab.repositories.BrouwerRepository;
@EnableTransactionManagement
@ReadOnlyTransactionalService
class BrouwerServiceImpl implements BrouwerService {
private final BrouwerRepository brouwerRepository;
@Autowired
BrouwerServiceImpl(BrouwerRepository brouwerRepository) {
this.brouwerRepository = brouwerRepository;
}
@Override
@ModifyingTransactionalServiceMethod
public void create(Brouwer brouwer) {
brouwerRepository.save(brouwer);
}
@Override
public List<Brouwer> findAll() {
return brouwerRepository.findAll(new Sort("naam"));
}
@Override
public List<Brouwer> findByEersteLetter(String eersteLetter) {
return brouwerRepository.findByNaamStartsWithOrderByNaamAsc(eersteLetter);
}
}
|
UTF-8
|
Java
| 1,036 |
java
|
BrouwerServiceImpl.java
|
Java
|
[] | null |
[] |
package be.vdab.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import be.vdab.entities.Brouwer;
import be.vdab.repositories.BrouwerRepository;
@EnableTransactionManagement
@ReadOnlyTransactionalService
class BrouwerServiceImpl implements BrouwerService {
private final BrouwerRepository brouwerRepository;
@Autowired
BrouwerServiceImpl(BrouwerRepository brouwerRepository) {
this.brouwerRepository = brouwerRepository;
}
@Override
@ModifyingTransactionalServiceMethod
public void create(Brouwer brouwer) {
brouwerRepository.save(brouwer);
}
@Override
public List<Brouwer> findAll() {
return brouwerRepository.findAll(new Sort("naam"));
}
@Override
public List<Brouwer> findByEersteLetter(String eersteLetter) {
return brouwerRepository.findByNaamStartsWithOrderByNaamAsc(eersteLetter);
}
}
| 1,036 | 0.794402 | 0.794402 | 39 | 24.564102 | 24.259066 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.923077 | false | false |
13
|
f4844eb198e8fb400d3647e653adc65bc59f94ca
| 14,474,039,844,701 |
99deb1ad42e5091c8a2f79157ffe89bc1eac9c8a
|
/JavaRDFJena/src/javardfjena/JavaRDFJena.java
|
8dbdcf0f39afa374966a6375fcd9784f6edd4270
|
[] |
no_license
|
jenishanghan/Web-Services-RDF-Jena
|
https://github.com/jenishanghan/Web-Services-RDF-Jena
|
cf2e352f978e179fb4c8955bbf17f453a53d7320
|
f8401db174426f7faa29cdb3ed388b961aecef26
|
refs/heads/master
| 2021-01-20T06:50:48.220000 | 2017-05-01T15:09:21 | 2017-05-01T15:09:21 | 89,933,845 | 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 javardfjena;
import org.apache.jena.datatypes.xsd.*;
import org.apache.jena.rdf.model.*;
import java.io.*;
/**
*
* @author Jenish Anghan
*/
public class JavaRDFJena {
/**
* @param args the command line arguments
*/
static private String nameSpace = "http://example.org/test/#";
public static void main(String[] args) {
Model model = ModelFactory.createDefaultModel();
Resource subject = model.createResource(nameSpace + "MyInfo");
Property propertyName = model.createProperty(nameSpace + "MyName");
Property propertyStudentOf = model.createProperty(nameSpace + "StudentOf");
Property propertyRegNo = model.createProperty(nameSpace + "RegNo");
Property propertyCity = model.createProperty(nameSpace + "City");
Property propertyState = model.createProperty(nameSpace + "State");
subject.addProperty(propertyState, " Gujarat ",XSDDatatype.XSDstring);
subject.addProperty(propertyCity, " Surat ",XSDDatatype.XSDstring);
subject.addProperty(propertyStudentOf, " VIT ",XSDDatatype.XSDstring);
subject.addProperty(propertyRegNo, " 16MCS0050 ",XSDDatatype.XSDstring);
subject.addProperty(propertyName, " Is Jainishkumar Anghan",XSDDatatype.XSDstring);
model.write(System.out);
}
}
|
UTF-8
|
Java
| 1,577 |
java
|
JavaRDFJena.java
|
Java
|
[
{
"context": "f.model.*;\r\nimport java.io.*;\r\n/**\r\n *\r\n * @author Jenish Anghan\r\n */\r\npublic class JavaRDFJena {\r\n\r\n /**\r\n ",
"end": 344,
"score": 0.9997924566268921,
"start": 331,
"tag": "NAME",
"value": "Jenish Anghan"
},
{
"context": ");\r\n subject.addProperty(propertyName, \" Is Jainishkumar Anghan\",XSDDatatype.XSDstring);\r\n \r\n model.",
"end": 1490,
"score": 0.9945087432861328,
"start": 1471,
"tag": "NAME",
"value": "Jainishkumar Anghan"
}
] | 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 javardfjena;
import org.apache.jena.datatypes.xsd.*;
import org.apache.jena.rdf.model.*;
import java.io.*;
/**
*
* @author <NAME>
*/
public class JavaRDFJena {
/**
* @param args the command line arguments
*/
static private String nameSpace = "http://example.org/test/#";
public static void main(String[] args) {
Model model = ModelFactory.createDefaultModel();
Resource subject = model.createResource(nameSpace + "MyInfo");
Property propertyName = model.createProperty(nameSpace + "MyName");
Property propertyStudentOf = model.createProperty(nameSpace + "StudentOf");
Property propertyRegNo = model.createProperty(nameSpace + "RegNo");
Property propertyCity = model.createProperty(nameSpace + "City");
Property propertyState = model.createProperty(nameSpace + "State");
subject.addProperty(propertyState, " Gujarat ",XSDDatatype.XSDstring);
subject.addProperty(propertyCity, " Surat ",XSDDatatype.XSDstring);
subject.addProperty(propertyStudentOf, " VIT ",XSDDatatype.XSDstring);
subject.addProperty(propertyRegNo, " 16MCS0050 ",XSDDatatype.XSDstring);
subject.addProperty(propertyName, " Is <NAME>",XSDDatatype.XSDstring);
model.write(System.out);
}
}
| 1,557 | 0.670894 | 0.667089 | 42 | 35.547619 | 31.58526 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.738095 | false | false |
13
|
438d872959eda1d042d851619d81c27e5fd5cfc9
| 25,383,256,753,349 |
86cf61187d22b867d1e5d3c8a23d97e806636020
|
/src/main/java/base/operators/operator/timeseries/operator/forecast/holt_winters/HoltWintersTrainerOperator.java
|
b3f29d46ca0367a2aa9e8a3dede66f6117db6d87
|
[] |
no_license
|
hitaitengteng/abc-pipeline-engine
|
https://github.com/hitaitengteng/abc-pipeline-engine
|
f94bb3b1888ad809541c83d6923a64c39fef9b19
|
165a620b94fb91ae97647135cc15a66d212a39e8
|
refs/heads/master
| 2022-02-22T18:49:28.915000 | 2019-10-27T13:40:58 | 2019-10-27T13:40:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package base.operators.operator.timeseries.operator.forecast.holt_winters;
import base.operators.operator.timeseries.operator.ExampleSetTimeSeriesOperator;
import base.operators.operator.timeseries.operator.forecast.arima.ArimaModel;
import base.operators.operator.timeseries.operator.helper.ExampleSetTimeSeriesHelper;
import base.operators.operator.timeseries.operator.helper.TimeSeriesHelperBuilder;
import base.operators.operator.timeseries.operator.helper.WrongConfiguredHelperException;
import base.operators.operator.OperatorDescription;
import base.operators.operator.OperatorException;
import base.operators.operator.UserError;
import base.operators.operator.ProcessSetupError.Severity;
import base.operators.operator.ports.IncompatibleMDClassException;
import base.operators.operator.ports.InputPort;
import base.operators.operator.ports.OutputPort;
import base.operators.operator.ports.metadata.AttributeMetaData;
import base.operators.operator.ports.metadata.ExampleSetMetaData;
import base.operators.operator.ports.metadata.ExampleSetPrecondition;
import base.operators.operator.ports.metadata.GenerateNewMDRule;
import base.operators.operator.ports.metadata.MDInteger;
import base.operators.operator.ports.metadata.MetaData;
import base.operators.operator.ports.metadata.MDNumber.Relation;
import base.operators.parameter.ParameterTypeCategory;
import base.operators.parameter.ParameterTypeDouble;
import base.operators.parameter.ParameterTypeInt;
import base.operators.parameter.UndefinedParameterError;
import base.operators.operator.timeseries.timeseriesanalysis.datamodel.Series;
import base.operators.operator.timeseries.timeseriesanalysis.datamodel.TimeSeries;
import base.operators.operator.timeseries.timeseriesanalysis.datamodel.ValueSeries;
import base.operators.operator.timeseries.timeseriesanalysis.forecast.holtwinters.HoltWinters;
import base.operators.operator.timeseries.timeseriesanalysis.forecast.holtwinters.HoltWintersTrainer;
import java.util.Arrays;
import java.util.List;
public class HoltWintersTrainerOperator extends ExampleSetTimeSeriesOperator {
private OutputPort holtWintersPort = (OutputPort)this.getOutputPorts().createPort("forecast model");
private OutputPort exampleSetOutputPort = (OutputPort)this.getOutputPorts().createPort("original");
private static final String PARAMETER_ALPHA = "alpha:_coefficient_for_level_smoothing";
private static final String PARAMETER_BETA = "beta:_coefficient_for_trend_smoothing";
private static final String PARAMETER_GAMMA = "gamma:_coefficient_for_seasonality_smoothing";
private static final String PARAMETER_PERIOD = "period:_length_of_one_period";
private static final String PARAMETER_SEASONAL_MODEL = "seasonality_model";
public HoltWintersTrainerOperator(OperatorDescription description) throws WrongConfiguredHelperException {
super(description);
final InputPort exampleSetInputPort = this.exampleSetTimeSeriesHelper.getExampleSetInputPort();
this.getTransformer().addGenerationRule(this.holtWintersPort, ArimaModel.class);
this.getTransformer().addRule(new GenerateNewMDRule(this.holtWintersPort, new MetaData(ArimaModel.class)) {
public MetaData modifyMetaData(MetaData unmodifiedMetaData) {
try {
if (exampleSetInputPort.isConnected()) {
unmodifiedMetaData.putMetaData("Series name", HoltWintersTrainerOperator.this.getParameterAsString("time_series_attribute"));
if (HoltWintersTrainerOperator.this.getParameterAsBoolean("has_indices")) {
unmodifiedMetaData.putMetaData("Indices name", HoltWintersTrainerOperator.this.getParameterAsString("indices_attribute"));
}
ExampleSetMetaData exampleSetMetaData = (ExampleSetMetaData)exampleSetInputPort.getMetaData(ExampleSetMetaData.class);
if (exampleSetMetaData != null) {
unmodifiedMetaData.putMetaData("Length of series", exampleSetMetaData.getNumberOfExamples());
if (HoltWintersTrainerOperator.this.getParameterAsBoolean("has_indices")) {
AttributeMetaData indicesAttributeMetaData = exampleSetMetaData.getAttributeByName(HoltWintersTrainerOperator.this.getParameterAsString("indices_attribute"));
if (indicesAttributeMetaData != null) {
if (indicesAttributeMetaData.isNumerical()) {
unmodifiedMetaData.putMetaData("Indices type", 2);
} else if (indicesAttributeMetaData.isDateTime()) {
unmodifiedMetaData.putMetaData("Indices type", 9);
}
}
}
}
}
} catch (IncompatibleMDClassException | UndefinedParameterError var4) {
var4.printStackTrace();
}
return unmodifiedMetaData;
}
});
this.getTransformer().addPassThroughRule(exampleSetInputPort, this.exampleSetOutputPort);
exampleSetInputPort.addPrecondition(new ExampleSetPrecondition(exampleSetInputPort) {
public void makeAdditionalChecks(ExampleSetMetaData emd) throws UndefinedParameterError {
int period = HoltWintersTrainerOperator.this.getParameterAsInt("period:_length_of_one_period");
MDInteger numberOfExamples = emd.getNumberOfExamples();
if (numberOfExamples.getRelation() == Relation.EQUAL || numberOfExamples.getRelation() == Relation.AT_MOST) {
int lengthOfTimeSeries = (Integer)emd.getNumberOfExamples().getNumber();
if (lengthOfTimeSeries < 2 * period) {
this.createError(Severity.ERROR, "time_series_extension.parameters.parameter_too_large", new Object[]{"period: length of one period", period, " larger than half the time series length", lengthOfTimeSeries});
}
}
}
});
}
protected ExampleSetTimeSeriesHelper initExampleSetTimeSeriesOperator() throws WrongConfiguredHelperException {
TimeSeriesHelperBuilder builder = new TimeSeriesHelperBuilder(this);
return builder.asInputPortOperator("example set").setIndiceHandling(ExampleSetTimeSeriesHelper.IndiceHandling.OPTIONAL_INDICES).build();
}
public void doWork() throws OperatorException {
this.exampleSetTimeSeriesHelper.resetHelper();
this.exampleSetTimeSeriesHelper.readInputData(this.exampleSetTimeSeriesHelper.getExampleSetInputPort());
this.exampleSetOutputPort.deliver(this.exampleSetTimeSeriesHelper.getInputExampleSet());
int progressCallsInGetMethods = this.exampleSetTimeSeriesHelper.progressCallsInGetAddConvertMethods() + 1;
this.getProgress().setCheckForStop(true);
this.getProgress().setTotal(2 * progressCallsInGetMethods + 1);
this.exampleSetTimeSeriesHelper.enableCallProgressStep();
boolean timeSeriesInput = this.exampleSetTimeSeriesHelper.checkForTimeIndices();
Object inputSeries;
if (timeSeriesInput) {
inputSeries = this.exampleSetTimeSeriesHelper.getInputTimeSeries();
} else {
inputSeries = this.exampleSetTimeSeriesHelper.getInputValueSeries();
}
this.getProgress().step();
String indicesAttributeName = this.getParameterAsString("indices_attribute");
double alpha = this.getParameterAsDouble("alpha:_coefficient_for_level_smoothing");
double beta = this.getParameterAsDouble("beta:_coefficient_for_trend_smoothing");
double gamma = this.getParameterAsDouble("gamma:_coefficient_for_seasonality_smoothing");
int period = this.getParameterAsInt("period:_length_of_one_period");
if (((Series)inputSeries).getLength() < 2 * period) {
throw new UserError(this, "time_series_extension.parameter.timeseries_length_larger_than_parameter", new Object[]{"period: length of one period", "smaller than half of", period, ((Series)inputSeries).getLength()});
} else {
String seasonalModelName = this.getParameterAsString("seasonality_model");
HoltWinters.SeasonalModel seasonalModel = HoltWinters.SeasonalModel.valueOf(seasonalModelName.toUpperCase());
HoltWintersTrainer holtWintersTrainer = HoltWintersTrainer.create(alpha, beta, gamma, period, seasonalModel);
HoltWinters holtWinters;
try {
if (timeSeriesInput) {
holtWinters = (HoltWinters)holtWintersTrainer.trainForecast((TimeSeries)inputSeries);
indicesAttributeName = this.getParameterAsString("indices_attribute");
} else {
ValueSeries valueSeries = (ValueSeries)inputSeries;
holtWinters = (HoltWinters)holtWintersTrainer.trainForecast(valueSeries);
if (!valueSeries.hasDefaultIndices()) {
indicesAttributeName = this.getParameterAsString("indices_attribute");
}
}
} catch (Exception var17) {
throw this.exampleSetTimeSeriesHelper.handleException(var17, this.getParameterAsString("time_series_attribute"));
}
HoltWintersModel holtWintersModel = new HoltWintersModel(holtWinters, (Series)inputSeries, indicesAttributeName);
this.holtWintersPort.deliver(holtWintersModel);
}
}
public List getParameterTypes() {
List types = this.exampleSetTimeSeriesHelper.getParameterTypes(super.getParameterTypes());
types.add(new ParameterTypeDouble("alpha:_coefficient_for_level_smoothing", "The parameter alpha specifies the smoothing coefficient for the level component of the Holt-Winters model.", 1.0E-9D, 1.0D, 0.5D, false));
types.add(new ParameterTypeDouble("beta:_coefficient_for_trend_smoothing", "The parameter beta specifies the smoothing coefficient for the trend component of the Holt-Winters model. ", 0.0D, 1.0D, 0.1D, false));
types.add(new ParameterTypeDouble("gamma:_coefficient_for_seasonality_smoothing", "The parameter gamma specifies the smoothing coefficient for the seasonal component of the Holt-Winters model", 0.0D, 1.0D, 0.5D, false));
types.add(new ParameterTypeInt("period:_length_of_one_period", "This parameter specifies the length of the period of the input time series", 0, Integer.MAX_VALUE, 4, false));
types.add(new ParameterTypeCategory("seasonality_model", "The parameter specifies the type of seasonal model used..", (String[])Arrays.stream(HoltWinters.SeasonalModel.class.getEnumConstants()).map(Enum::name).map(String::toLowerCase).toArray((x$0) -> {
return new String[x$0];
}), 1, false));
return types;
}
}
|
UTF-8
|
Java
| 10,680 |
java
|
HoltWintersTrainerOperator.java
|
Java
|
[] | null |
[] |
package base.operators.operator.timeseries.operator.forecast.holt_winters;
import base.operators.operator.timeseries.operator.ExampleSetTimeSeriesOperator;
import base.operators.operator.timeseries.operator.forecast.arima.ArimaModel;
import base.operators.operator.timeseries.operator.helper.ExampleSetTimeSeriesHelper;
import base.operators.operator.timeseries.operator.helper.TimeSeriesHelperBuilder;
import base.operators.operator.timeseries.operator.helper.WrongConfiguredHelperException;
import base.operators.operator.OperatorDescription;
import base.operators.operator.OperatorException;
import base.operators.operator.UserError;
import base.operators.operator.ProcessSetupError.Severity;
import base.operators.operator.ports.IncompatibleMDClassException;
import base.operators.operator.ports.InputPort;
import base.operators.operator.ports.OutputPort;
import base.operators.operator.ports.metadata.AttributeMetaData;
import base.operators.operator.ports.metadata.ExampleSetMetaData;
import base.operators.operator.ports.metadata.ExampleSetPrecondition;
import base.operators.operator.ports.metadata.GenerateNewMDRule;
import base.operators.operator.ports.metadata.MDInteger;
import base.operators.operator.ports.metadata.MetaData;
import base.operators.operator.ports.metadata.MDNumber.Relation;
import base.operators.parameter.ParameterTypeCategory;
import base.operators.parameter.ParameterTypeDouble;
import base.operators.parameter.ParameterTypeInt;
import base.operators.parameter.UndefinedParameterError;
import base.operators.operator.timeseries.timeseriesanalysis.datamodel.Series;
import base.operators.operator.timeseries.timeseriesanalysis.datamodel.TimeSeries;
import base.operators.operator.timeseries.timeseriesanalysis.datamodel.ValueSeries;
import base.operators.operator.timeseries.timeseriesanalysis.forecast.holtwinters.HoltWinters;
import base.operators.operator.timeseries.timeseriesanalysis.forecast.holtwinters.HoltWintersTrainer;
import java.util.Arrays;
import java.util.List;
public class HoltWintersTrainerOperator extends ExampleSetTimeSeriesOperator {
private OutputPort holtWintersPort = (OutputPort)this.getOutputPorts().createPort("forecast model");
private OutputPort exampleSetOutputPort = (OutputPort)this.getOutputPorts().createPort("original");
private static final String PARAMETER_ALPHA = "alpha:_coefficient_for_level_smoothing";
private static final String PARAMETER_BETA = "beta:_coefficient_for_trend_smoothing";
private static final String PARAMETER_GAMMA = "gamma:_coefficient_for_seasonality_smoothing";
private static final String PARAMETER_PERIOD = "period:_length_of_one_period";
private static final String PARAMETER_SEASONAL_MODEL = "seasonality_model";
public HoltWintersTrainerOperator(OperatorDescription description) throws WrongConfiguredHelperException {
super(description);
final InputPort exampleSetInputPort = this.exampleSetTimeSeriesHelper.getExampleSetInputPort();
this.getTransformer().addGenerationRule(this.holtWintersPort, ArimaModel.class);
this.getTransformer().addRule(new GenerateNewMDRule(this.holtWintersPort, new MetaData(ArimaModel.class)) {
public MetaData modifyMetaData(MetaData unmodifiedMetaData) {
try {
if (exampleSetInputPort.isConnected()) {
unmodifiedMetaData.putMetaData("Series name", HoltWintersTrainerOperator.this.getParameterAsString("time_series_attribute"));
if (HoltWintersTrainerOperator.this.getParameterAsBoolean("has_indices")) {
unmodifiedMetaData.putMetaData("Indices name", HoltWintersTrainerOperator.this.getParameterAsString("indices_attribute"));
}
ExampleSetMetaData exampleSetMetaData = (ExampleSetMetaData)exampleSetInputPort.getMetaData(ExampleSetMetaData.class);
if (exampleSetMetaData != null) {
unmodifiedMetaData.putMetaData("Length of series", exampleSetMetaData.getNumberOfExamples());
if (HoltWintersTrainerOperator.this.getParameterAsBoolean("has_indices")) {
AttributeMetaData indicesAttributeMetaData = exampleSetMetaData.getAttributeByName(HoltWintersTrainerOperator.this.getParameterAsString("indices_attribute"));
if (indicesAttributeMetaData != null) {
if (indicesAttributeMetaData.isNumerical()) {
unmodifiedMetaData.putMetaData("Indices type", 2);
} else if (indicesAttributeMetaData.isDateTime()) {
unmodifiedMetaData.putMetaData("Indices type", 9);
}
}
}
}
}
} catch (IncompatibleMDClassException | UndefinedParameterError var4) {
var4.printStackTrace();
}
return unmodifiedMetaData;
}
});
this.getTransformer().addPassThroughRule(exampleSetInputPort, this.exampleSetOutputPort);
exampleSetInputPort.addPrecondition(new ExampleSetPrecondition(exampleSetInputPort) {
public void makeAdditionalChecks(ExampleSetMetaData emd) throws UndefinedParameterError {
int period = HoltWintersTrainerOperator.this.getParameterAsInt("period:_length_of_one_period");
MDInteger numberOfExamples = emd.getNumberOfExamples();
if (numberOfExamples.getRelation() == Relation.EQUAL || numberOfExamples.getRelation() == Relation.AT_MOST) {
int lengthOfTimeSeries = (Integer)emd.getNumberOfExamples().getNumber();
if (lengthOfTimeSeries < 2 * period) {
this.createError(Severity.ERROR, "time_series_extension.parameters.parameter_too_large", new Object[]{"period: length of one period", period, " larger than half the time series length", lengthOfTimeSeries});
}
}
}
});
}
protected ExampleSetTimeSeriesHelper initExampleSetTimeSeriesOperator() throws WrongConfiguredHelperException {
TimeSeriesHelperBuilder builder = new TimeSeriesHelperBuilder(this);
return builder.asInputPortOperator("example set").setIndiceHandling(ExampleSetTimeSeriesHelper.IndiceHandling.OPTIONAL_INDICES).build();
}
public void doWork() throws OperatorException {
this.exampleSetTimeSeriesHelper.resetHelper();
this.exampleSetTimeSeriesHelper.readInputData(this.exampleSetTimeSeriesHelper.getExampleSetInputPort());
this.exampleSetOutputPort.deliver(this.exampleSetTimeSeriesHelper.getInputExampleSet());
int progressCallsInGetMethods = this.exampleSetTimeSeriesHelper.progressCallsInGetAddConvertMethods() + 1;
this.getProgress().setCheckForStop(true);
this.getProgress().setTotal(2 * progressCallsInGetMethods + 1);
this.exampleSetTimeSeriesHelper.enableCallProgressStep();
boolean timeSeriesInput = this.exampleSetTimeSeriesHelper.checkForTimeIndices();
Object inputSeries;
if (timeSeriesInput) {
inputSeries = this.exampleSetTimeSeriesHelper.getInputTimeSeries();
} else {
inputSeries = this.exampleSetTimeSeriesHelper.getInputValueSeries();
}
this.getProgress().step();
String indicesAttributeName = this.getParameterAsString("indices_attribute");
double alpha = this.getParameterAsDouble("alpha:_coefficient_for_level_smoothing");
double beta = this.getParameterAsDouble("beta:_coefficient_for_trend_smoothing");
double gamma = this.getParameterAsDouble("gamma:_coefficient_for_seasonality_smoothing");
int period = this.getParameterAsInt("period:_length_of_one_period");
if (((Series)inputSeries).getLength() < 2 * period) {
throw new UserError(this, "time_series_extension.parameter.timeseries_length_larger_than_parameter", new Object[]{"period: length of one period", "smaller than half of", period, ((Series)inputSeries).getLength()});
} else {
String seasonalModelName = this.getParameterAsString("seasonality_model");
HoltWinters.SeasonalModel seasonalModel = HoltWinters.SeasonalModel.valueOf(seasonalModelName.toUpperCase());
HoltWintersTrainer holtWintersTrainer = HoltWintersTrainer.create(alpha, beta, gamma, period, seasonalModel);
HoltWinters holtWinters;
try {
if (timeSeriesInput) {
holtWinters = (HoltWinters)holtWintersTrainer.trainForecast((TimeSeries)inputSeries);
indicesAttributeName = this.getParameterAsString("indices_attribute");
} else {
ValueSeries valueSeries = (ValueSeries)inputSeries;
holtWinters = (HoltWinters)holtWintersTrainer.trainForecast(valueSeries);
if (!valueSeries.hasDefaultIndices()) {
indicesAttributeName = this.getParameterAsString("indices_attribute");
}
}
} catch (Exception var17) {
throw this.exampleSetTimeSeriesHelper.handleException(var17, this.getParameterAsString("time_series_attribute"));
}
HoltWintersModel holtWintersModel = new HoltWintersModel(holtWinters, (Series)inputSeries, indicesAttributeName);
this.holtWintersPort.deliver(holtWintersModel);
}
}
public List getParameterTypes() {
List types = this.exampleSetTimeSeriesHelper.getParameterTypes(super.getParameterTypes());
types.add(new ParameterTypeDouble("alpha:_coefficient_for_level_smoothing", "The parameter alpha specifies the smoothing coefficient for the level component of the Holt-Winters model.", 1.0E-9D, 1.0D, 0.5D, false));
types.add(new ParameterTypeDouble("beta:_coefficient_for_trend_smoothing", "The parameter beta specifies the smoothing coefficient for the trend component of the Holt-Winters model. ", 0.0D, 1.0D, 0.1D, false));
types.add(new ParameterTypeDouble("gamma:_coefficient_for_seasonality_smoothing", "The parameter gamma specifies the smoothing coefficient for the seasonal component of the Holt-Winters model", 0.0D, 1.0D, 0.5D, false));
types.add(new ParameterTypeInt("period:_length_of_one_period", "This parameter specifies the length of the period of the input time series", 0, Integer.MAX_VALUE, 4, false));
types.add(new ParameterTypeCategory("seasonality_model", "The parameter specifies the type of seasonal model used..", (String[])Arrays.stream(HoltWinters.SeasonalModel.class.getEnumConstants()).map(Enum::name).map(String::toLowerCase).toArray((x$0) -> {
return new String[x$0];
}), 1, false));
return types;
}
}
| 10,680 | 0.738858 | 0.735393 | 160 | 65.75 | 51.209129 | 259 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.93125 | false | false |
13
|
5f3fbc068a929b1c51835de7537df28e8fea9d3b
| 4,896,262,748,255 |
7343673dd9123e7f8fdaa08200cf8eb0e81dd802
|
/ESApp/app/src/main/java/com/example/lucas/esapp/Interface/RecycleViewOnClickListenerHack.java
|
80ebd10bbaf3471f3bb50a44b43370f6cbc92bcf
|
[] |
no_license
|
lucasncabral/ProjetoES1
|
https://github.com/lucasncabral/ProjetoES1
|
cc78a931e7f180408b8f05c6754cb441aac98225
|
2da92531dadc7110f32bae9830271de587362631
|
refs/heads/master
| 2017-04-23T03:38:19.322000 | 2016-09-18T14:08:28 | 2016-09-18T14:08:28 | 64,249,741 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.lucas.esapp.Interface;
import android.view.View;
/**
* Created by Lucas on 07/08/2016.
*/
public interface RecycleViewOnClickListenerHack {
void onClickListener(View v, int position);
void OnLongClickListener(View v, int position);
}
|
UTF-8
|
Java
| 277 |
java
|
RecycleViewOnClickListenerHack.java
|
Java
|
[
{
"context": "ace;\n\nimport android.view.View;\n\n/**\n * Created by Lucas on 07/08/2016.\n */\npublic interface RecycleViewOn",
"end": 94,
"score": 0.9996846914291382,
"start": 89,
"tag": "NAME",
"value": "Lucas"
}
] | null |
[] |
package com.example.lucas.esapp.Interface;
import android.view.View;
/**
* Created by Lucas on 07/08/2016.
*/
public interface RecycleViewOnClickListenerHack {
void onClickListener(View v, int position);
void OnLongClickListener(View v, int position);
}
| 277 | 0.722022 | 0.693141 | 14 | 18.785715 | 21.79508 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false |
13
|
bdcb1ab5277298024faaf3e9775e9649ab9d13e3
| 26,491,358,318,656 |
8be80fc11fd80c56923a8d06e8fc2e6bb10ee160
|
/hunt4j-server/src/test/java/TestTrim.java
|
1b2b367c5234357970cea7084301c38767489a78
|
[
"Apache-2.0"
] |
permissive
|
zhishan332/hunt4j
|
https://github.com/zhishan332/hunt4j
|
dcfc62ef72ac3c084177d1f66d7f76979f2e6d72
|
a499ac2319fbd4d67cbf634bb2d53920b453d35f
|
refs/heads/master
| 2021-01-22T09:33:21.274000 | 2014-09-03T03:20:57 | 2014-09-03T03:20:57 | 22,499,504 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* To change this template use File | Settings | File Templates.
*
* @author wangqing
* @since 14-5-21 上午10:21
*/
public class TestTrim {
public static void main(String[] args) {
String str=" &334";
str=TestTrim.removeAllBlank(str);
System.out.println(str);
}
private static final String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式
private static final String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式
private static final String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
public static String delHTMLTag(String htmlStr) {
Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
Matcher m_script = p_script.matcher(htmlStr);
htmlStr = m_script.replaceAll(""); // 过滤script标签
Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
Matcher m_style = p_style.matcher(htmlStr);
htmlStr = m_style.replaceAll(""); // 过滤style标签
Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
Matcher m_html = p_html.matcher(htmlStr);
htmlStr = m_html.replaceAll(""); // 过滤html标签
return htmlStr.trim(); // 返回文本字符串
}
/**
* 去除字符串中所包含的空格(包括:空格(全角,半角)、制表符、换页符等)
* @param s
* @return
*/
public static String removeAllBlank(String s){
String result = "";
if(null!=s && !"".equals(s)){
result = s.replaceAll("[ *| *| *|//s*]*", "");
result=result.replaceAll("[\\s\\p{Zs}]+", "");
}
return result;
}
/**
* 去除字符串中头部和尾部所包含的空格(包括:空格(全角,半角)、制表符、换页符等)
* @param s
* @return
*/
public static String trim(String s){
String result = "";
if(null!=s && !"".equals(s)){
result = s.replaceAll("^[ *| *| *|//s*]*", "").replaceAll("[ *| *| *|//s*]*$", "");
}
return result;
}
}
|
UTF-8
|
Java
| 2,295 |
java
|
TestTrim.java
|
Java
|
[
{
"context": "se File | Settings | File Templates.\n *\n * @author wangqing\n * @since 14-5-21 上午10:21\n */\npublic class TestTr",
"end": 156,
"score": 0.9598621129989624,
"start": 148,
"tag": "USERNAME",
"value": "wangqing"
}
] | null |
[] |
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* To change this template use File | Settings | File Templates.
*
* @author wangqing
* @since 14-5-21 上午10:21
*/
public class TestTrim {
public static void main(String[] args) {
String str=" &334";
str=TestTrim.removeAllBlank(str);
System.out.println(str);
}
private static final String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式
private static final String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式
private static final String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
public static String delHTMLTag(String htmlStr) {
Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
Matcher m_script = p_script.matcher(htmlStr);
htmlStr = m_script.replaceAll(""); // 过滤script标签
Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
Matcher m_style = p_style.matcher(htmlStr);
htmlStr = m_style.replaceAll(""); // 过滤style标签
Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
Matcher m_html = p_html.matcher(htmlStr);
htmlStr = m_html.replaceAll(""); // 过滤html标签
return htmlStr.trim(); // 返回文本字符串
}
/**
* 去除字符串中所包含的空格(包括:空格(全角,半角)、制表符、换页符等)
* @param s
* @return
*/
public static String removeAllBlank(String s){
String result = "";
if(null!=s && !"".equals(s)){
result = s.replaceAll("[ *| *| *|//s*]*", "");
result=result.replaceAll("[\\s\\p{Zs}]+", "");
}
return result;
}
/**
* 去除字符串中头部和尾部所包含的空格(包括:空格(全角,半角)、制表符、换页符等)
* @param s
* @return
*/
public static String trim(String s){
String result = "";
if(null!=s && !"".equals(s)){
result = s.replaceAll("^[ *| *| *|//s*]*", "").replaceAll("[ *| *| *|//s*]*$", "");
}
return result;
}
}
| 2,295 | 0.564178 | 0.558321 | 61 | 32.590164 | 28.188696 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.754098 | false | false |
13
|
83cb20e38c57729cde3a2dd03f06161c015f1282
| 5,634,997,097,207 |
d730e4d76b76783be5e4e44924d2c39c44a30862
|
/src/leetcode/Q20_ValidParentheses.java
|
8713f2685d6b0b4334864e62b3517c5b6b127a89
|
[] |
no_license
|
kaikanwu/Algorithm-Learning
|
https://github.com/kaikanwu/Algorithm-Learning
|
6e4b665cc537bb7abe82c6b634d8f32525fc885b
|
839e5dbadfb64ff3ba07917f07700412d54956de
|
refs/heads/master
| 2023-03-05T09:25:59.027000 | 2023-02-23T07:50:08 | 2023-02-23T07:50:08 | 153,860,834 | 2 | 1 | null | false | 2020-12-27T14:50:42 | 2018-10-20T02:05:58 | 2020-12-27T14:50:20 | 2020-12-27T14:50:40 | 237 | 0 | 0 | 1 |
Java
| false | false |
package leetcode;
import java.util.*;
/**
* 给定一个只包括 '(',')','{','}','[',']'的字符串 s ,判断字符串是否有效。
*
* 有效字符串需满足:
* 左括号必须用相同类型的右括号闭合。
* 左括号必须以正确的顺序闭合。
*
* 输入:s = "(]"
* 输出:false
*
* 输入:s = "([)]"
* 输出:false
*
* 输入:s = "{[]}"
* 输出:true
*/
public class Q20_ValidParentheses {
/**
* Stack
*
* Stack's basic operation:
* 1. push: push an element onto the top of the stack
* 2. pop: remove and return the top element
* 3. peek: return the top element of the stack without removing.
*
* Time: O(n)
* Space: O(n)
*/
public static boolean isValid(String s) {
int n = s.length();
if (n % 2 == 1) {// 判断奇数可以用 n&1 ==1 来判断,因为奇数的二进制最后一位都是 1
return false;
}
// right bracket as key
Map<Character, Character> map = new HashMap<>();
map.put(')', '(');
map.put(']', '[');
map.put('}', '{');
Deque<Character> stack = new ArrayDeque<>();
// right bracket: check and pop
// left bracket : pop or push
for (int i = 0; i < n; i++) {
char ch = s.charAt(i);
if (map.containsKey(ch)) {
if (stack.isEmpty() || stack.peek() != map.get(ch)) {
return false;
}
stack.pop();
} else {
// stack only saves left brackets
stack.push(ch);
}
}
// 注意返回值
return stack.isEmpty();
}
}
|
UTF-8
|
Java
| 1,731 |
java
|
Q20_ValidParentheses.java
|
Java
|
[] | null |
[] |
package leetcode;
import java.util.*;
/**
* 给定一个只包括 '(',')','{','}','[',']'的字符串 s ,判断字符串是否有效。
*
* 有效字符串需满足:
* 左括号必须用相同类型的右括号闭合。
* 左括号必须以正确的顺序闭合。
*
* 输入:s = "(]"
* 输出:false
*
* 输入:s = "([)]"
* 输出:false
*
* 输入:s = "{[]}"
* 输出:true
*/
public class Q20_ValidParentheses {
/**
* Stack
*
* Stack's basic operation:
* 1. push: push an element onto the top of the stack
* 2. pop: remove and return the top element
* 3. peek: return the top element of the stack without removing.
*
* Time: O(n)
* Space: O(n)
*/
public static boolean isValid(String s) {
int n = s.length();
if (n % 2 == 1) {// 判断奇数可以用 n&1 ==1 来判断,因为奇数的二进制最后一位都是 1
return false;
}
// right bracket as key
Map<Character, Character> map = new HashMap<>();
map.put(')', '(');
map.put(']', '[');
map.put('}', '{');
Deque<Character> stack = new ArrayDeque<>();
// right bracket: check and pop
// left bracket : pop or push
for (int i = 0; i < n; i++) {
char ch = s.charAt(i);
if (map.containsKey(ch)) {
if (stack.isEmpty() || stack.peek() != map.get(ch)) {
return false;
}
stack.pop();
} else {
// stack only saves left brackets
stack.push(ch);
}
}
// 注意返回值
return stack.isEmpty();
}
}
| 1,731 | 0.461026 | 0.453698 | 65 | 22.092308 | 18.561932 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.338462 | false | false |
13
|
8b69a66793682d44ea99d0fafa1eeeea819fcf26
| 1,812,476,267,470 |
c50f942977153b3f0c524509050b0d047f21576d
|
/x7-repo/x7-redis-integration/src/main/java/io/xream/x7/repository/redis/id/DefaultIdGeneratorPolicy.java
|
29dff7dbd9201be1f1c3bf07ddb5b54c9625286b
|
[
"Apache-2.0"
] |
permissive
|
kongGe55/x7
|
https://github.com/kongGe55/x7
|
b5b812d2eb60f871894e7cde7b4f45461d261c04
|
4167916bbc0de6d6e64f965acb2a48eba5546393
|
refs/heads/master
| 2022-04-23T13:38:46.740000 | 2020-04-17T10:33:06 | 2020-04-17T10:33:06 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.xream.x7.repository.redis.id;
import io.xream.x7.repository.id.IdGenerator;
import io.xream.x7.repository.id.IdGeneratorPolicy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class DefaultIdGeneratorPolicy implements IdGeneratorPolicy {
@Autowired
private StringRedisTemplate stringRedisTemplate;
public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
this.stringRedisTemplate = stringRedisTemplate;
}
@Override
public long createId(String clzName) {
return this.stringRedisTemplate.opsForHash().increment(ID_MAP_KEY,clzName,1);
}
@Override
public void onStart(List<IdGenerator> idGeneratorList) {
System.out.println("\n" + "----------------------------------------");
for (IdGenerator generator : idGeneratorList) {
String name = generator.getClzName();
long maxId = generator.getMaxId();
String idInRedis = null;
Object obj = this.stringRedisTemplate.opsForHash().get(IdGeneratorPolicy.ID_MAP_KEY, name);
if (obj != null) {
idInRedis = obj.toString().trim();
}
System.out.println(name + ",test, idInDB = " + maxId + ", idInRedis = " + idInRedis);
if (idInRedis == null) {
this.stringRedisTemplate.opsForHash().put(IdGeneratorPolicy.ID_MAP_KEY, name, String.valueOf(maxId));
} else if (idInRedis != null && maxId > Long.valueOf(idInRedis)) {
this.stringRedisTemplate.opsForHash().put(IdGeneratorPolicy.ID_MAP_KEY, name, String.valueOf(maxId));
}
System.out.println(name + ",final, idInRedis = " + this.stringRedisTemplate.opsForHash().get(IdGeneratorPolicy.ID_MAP_KEY, name));
}
System.out.println("----------------------------------------" + "\n");
}
}
|
UTF-8
|
Java
| 2,920 |
java
|
DefaultIdGeneratorPolicy.java
|
Java
|
[] | null |
[] |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.xream.x7.repository.redis.id;
import io.xream.x7.repository.id.IdGenerator;
import io.xream.x7.repository.id.IdGeneratorPolicy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class DefaultIdGeneratorPolicy implements IdGeneratorPolicy {
@Autowired
private StringRedisTemplate stringRedisTemplate;
public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
this.stringRedisTemplate = stringRedisTemplate;
}
@Override
public long createId(String clzName) {
return this.stringRedisTemplate.opsForHash().increment(ID_MAP_KEY,clzName,1);
}
@Override
public void onStart(List<IdGenerator> idGeneratorList) {
System.out.println("\n" + "----------------------------------------");
for (IdGenerator generator : idGeneratorList) {
String name = generator.getClzName();
long maxId = generator.getMaxId();
String idInRedis = null;
Object obj = this.stringRedisTemplate.opsForHash().get(IdGeneratorPolicy.ID_MAP_KEY, name);
if (obj != null) {
idInRedis = obj.toString().trim();
}
System.out.println(name + ",test, idInDB = " + maxId + ", idInRedis = " + idInRedis);
if (idInRedis == null) {
this.stringRedisTemplate.opsForHash().put(IdGeneratorPolicy.ID_MAP_KEY, name, String.valueOf(maxId));
} else if (idInRedis != null && maxId > Long.valueOf(idInRedis)) {
this.stringRedisTemplate.opsForHash().put(IdGeneratorPolicy.ID_MAP_KEY, name, String.valueOf(maxId));
}
System.out.println(name + ",final, idInRedis = " + this.stringRedisTemplate.opsForHash().get(IdGeneratorPolicy.ID_MAP_KEY, name));
}
System.out.println("----------------------------------------" + "\n");
}
}
| 2,920 | 0.657192 | 0.654452 | 74 | 38.459461 | 36.572842 | 146 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.527027 | false | false |
13
|
b3935730853089891d985f9054c63958a36179d3
| 17,205,638,994,061 |
0122a86ea69653569013f4d55409a8c0b2a0ae60
|
/app/src/main/java/com/appsforusers/ops/constants/Constants.java
|
21c71ba0207e7f23a6714937bf1360440449b628
|
[] |
no_license
|
learningdevelop/Eucs
|
https://github.com/learningdevelop/Eucs
|
0b4475ed48cda7eec2ab42194d2735e7596f24ac
|
251e4bdbb714ae72ed0ca0720f9e72f0996a2be2
|
refs/heads/master
| 2018-02-07T19:35:12.968000 | 2017-07-10T17:38:22 | 2017-07-10T17:38:22 | 96,079,076 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.appsforusers.ops.constants;
/**
* Created by robert.rivero on 03/07/2017.
*/
public final class Constants {
public static final String SLASH_CS = "/";
public static final String NULL_CS = " ";
}
|
UTF-8
|
Java
| 221 |
java
|
Constants.java
|
Java
|
[
{
"context": "com.appsforusers.ops.constants;\n\n/**\n * Created by robert.rivero on 03/07/2017.\n */\n\npublic final class Constants ",
"end": 72,
"score": 0.9171353578567505,
"start": 59,
"tag": "NAME",
"value": "robert.rivero"
}
] | null |
[] |
package com.appsforusers.ops.constants;
/**
* Created by robert.rivero on 03/07/2017.
*/
public final class Constants {
public static final String SLASH_CS = "/";
public static final String NULL_CS = " ";
}
| 221 | 0.674208 | 0.638009 | 12 | 17.416666 | 19.800919 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false |
13
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.