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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
186eb34ad9d4f9fa434ddbe0b3ea42965d20fad5
| 20,873,541,119,794 |
ba6a174a1f4d086434b0e9f86f57df6ebb963c87
|
/dekes03-lab4/dekes03_lab4/RaknaTecken.java
|
1b9e13c099e80f080556ccbb927f3f16a777edd4
|
[] |
no_license
|
Ekerot/1DV506
|
https://github.com/Ekerot/1DV506
|
8c2bf415abfaafa607632bcdbacc86e29b8dae7d
|
ab96cb837f295b31bad3b4dcc99fda98e12b37a6
|
refs/heads/master
| 2021-01-16T21:36:59.937000 | 2016-06-11T12:18:01 | 2016-06-11T12:18:01 | 60,905,735 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package dekes03_lab4;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class RaknaTecken {
public static void main(String[] args) throws IOException {
StringBuilder text = new StringBuilder();
text = add();
rakna(text);
}
public static StringBuilder add() throws IOException {
StringBuilder text = new StringBuilder();
try { // läser in text från fil
File file = new File("/Users/ekerot/Desktop/ChampagnenBlirDyrare.txt");
Scanner scan = new Scanner(file);
while (scan.hasNext()) { // läser in filen i stringbuilder
String line = scan.nextLine();
text.append(line);
}
scan.close();
} catch (IOException e) { // exception om ingen fil hittas
System.out.println(e.getMessage());
System.exit(0);
}
return text;
}
public static void rakna(StringBuilder in) { // räknar antalet stora, små,
// whitespace och överiga
// bokstäver i SB:n
int antalStora = 0, antalSma = 0, antalWhite = 0, antalOvriga = 0;
for (int i = 0; i < in.length(); i++) {
if (Character.isUpperCase(in.charAt(i))) {
antalStora++;
}
else if (Character.isLowerCase(in.charAt(i))) {
antalSma++;
}
else if (Character.isWhitespace(in.charAt(i))) { // programerar på
// MAC och
// resultatet på
// whitespaces
// blir då 420st
// pga annan
// formatering
// av texten.
antalWhite++;
}
else {
antalOvriga++;
}
}
System.out.println("Antal stora bokstäver: " + antalStora);
System.out.println("Antal små bokstäver: " + antalSma);
System.out.println("Antal \"whitespaces\": " + antalWhite);
System.out.println("Antal övriga: " + antalOvriga);
}
}
|
UTF-8
|
Java
| 1,817 |
java
|
RaknaTecken.java
|
Java
|
[
{
"context": "in text från fil\n\n\t\t\tFile file = new File(\"/Users/ekerot/Desktop/ChampagnenBlirDyrare.txt\");\n\t\t\tScanner sc",
"end": 444,
"score": 0.9980485439300537,
"start": 438,
"tag": "USERNAME",
"value": "ekerot"
}
] | null |
[] |
package dekes03_lab4;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class RaknaTecken {
public static void main(String[] args) throws IOException {
StringBuilder text = new StringBuilder();
text = add();
rakna(text);
}
public static StringBuilder add() throws IOException {
StringBuilder text = new StringBuilder();
try { // läser in text från fil
File file = new File("/Users/ekerot/Desktop/ChampagnenBlirDyrare.txt");
Scanner scan = new Scanner(file);
while (scan.hasNext()) { // läser in filen i stringbuilder
String line = scan.nextLine();
text.append(line);
}
scan.close();
} catch (IOException e) { // exception om ingen fil hittas
System.out.println(e.getMessage());
System.exit(0);
}
return text;
}
public static void rakna(StringBuilder in) { // räknar antalet stora, små,
// whitespace och överiga
// bokstäver i SB:n
int antalStora = 0, antalSma = 0, antalWhite = 0, antalOvriga = 0;
for (int i = 0; i < in.length(); i++) {
if (Character.isUpperCase(in.charAt(i))) {
antalStora++;
}
else if (Character.isLowerCase(in.charAt(i))) {
antalSma++;
}
else if (Character.isWhitespace(in.charAt(i))) { // programerar på
// MAC och
// resultatet på
// whitespaces
// blir då 420st
// pga annan
// formatering
// av texten.
antalWhite++;
}
else {
antalOvriga++;
}
}
System.out.println("Antal stora bokstäver: " + antalStora);
System.out.println("Antal små bokstäver: " + antalSma);
System.out.println("Antal \"whitespaces\": " + antalWhite);
System.out.println("Antal övriga: " + antalOvriga);
}
}
| 1,817 | 0.608985 | 0.602329 | 82 | 20.987804 | 22.412155 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.353658 | false | false |
12
|
c5715137ec741b520c1d3a907b2806917e8f5072
| 15,831,249,520,176 |
0e073fb456bce03aa17aeb0c317ce5937efc626f
|
/app/src/main/java/kh/edu/rupp/fe/ruppmad/SettingsFragment.java
|
c39336773e18280ba721e0ddfc3cab50ab078d69
|
[] |
no_license
|
NCSOPHAL/HW_RUPP_MAD
|
https://github.com/NCSOPHAL/HW_RUPP_MAD
|
215e4464bf312b424e8bd06a2c436be7ba08c6eb
|
1e759a49ef39c9f8aecd38fee8cfe410c75cbcfa
|
refs/heads/master
| 2021-01-20T14:22:35.644000 | 2017-05-09T15:10:58 | 2017-05-09T15:10:58 | 90,595,409 | 0 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package kh.edu.rupp.fe.ruppmad;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* RUPPMAD
* Created by leapkh on 21/3/17.
*/
public class SettingsFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View fragmentView = inflater.inflate(R.layout.fragment_settings, container, false);
return fragmentView;
}
}
|
UTF-8
|
Java
| 545 |
java
|
SettingsFragment.java
|
Java
|
[
{
"context": "roid.view.ViewGroup;\n\n/**\n * RUPPMAD\n * Created by leapkh on 21/3/17.\n */\n\npublic class SettingsFragment ex",
"end": 228,
"score": 0.9996652603149414,
"start": 222,
"tag": "USERNAME",
"value": "leapkh"
}
] | null |
[] |
package kh.edu.rupp.fe.ruppmad;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* RUPPMAD
* Created by leapkh on 21/3/17.
*/
public class SettingsFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View fragmentView = inflater.inflate(R.layout.fragment_settings, container, false);
return fragmentView;
}
}
| 545 | 0.748624 | 0.737615 | 23 | 22.695652 | 27.445496 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.521739 | false | false |
12
|
f6320232dd2830118ac6fe0cce2dd340b681d481
| 14,499,809,605,283 |
f9c7bd176f7912b1ec9551fbcc241861bd91f1b3
|
/ManupulateData/app/src/main/java/com/example/user/manupulatedata/ProductContract.java
|
d6e981ce36f20b71ed255fa20cf7465884f71e4a
|
[] |
no_license
|
nadeemsadi/AndroidApp2
|
https://github.com/nadeemsadi/AndroidApp2
|
22c75e707da3a27933c0553ca83be36e1f0234f7
|
d81ef569d626726d50e926c0c4efcc3b0a16aaca
|
refs/heads/master
| 2021-01-19T06:35:53.697000 | 2016-07-08T14:08:38 | 2016-07-08T14:08:38 | 62,893,333 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.user.manupulatedata;
/**
* Created by user on 7/8/2016.
*/
public final class ProductContract {
ProductContract(){}
public static abstract class ProductEntry{
public static final String ID = "id";
public static final String NAME = "name";
public static final String PRICE = "price";
public static final String QTY = "qty";
public static final String TABLE_NAME = "product_table";
}
}
|
UTF-8
|
Java
| 467 |
java
|
ProductContract.java
|
Java
|
[
{
"context": "om.example.user.manupulatedata;\n\n/**\n * Created by user on 7/8/2016.\n */\npublic final class ProductContra",
"end": 64,
"score": 0.9156301617622375,
"start": 60,
"tag": "USERNAME",
"value": "user"
}
] | null |
[] |
package com.example.user.manupulatedata;
/**
* Created by user on 7/8/2016.
*/
public final class ProductContract {
ProductContract(){}
public static abstract class ProductEntry{
public static final String ID = "id";
public static final String NAME = "name";
public static final String PRICE = "price";
public static final String QTY = "qty";
public static final String TABLE_NAME = "product_table";
}
}
| 467 | 0.648822 | 0.635974 | 23 | 19.304348 | 22.172123 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.26087 | false | false |
12
|
7d021f7273225d87c914cdd2180d4bd12c9cfa5a
| 23,493,471,125,437 |
92d17b2188b58f5169903ff73b758f690c7bfff6
|
/src/main/java/com/genusIIc/vt/Main.java
|
ad0412a7911be8b2ce2eb29643856f42915b99be
|
[] |
no_license
|
Vent-Tardar/com.genusIIc.vt.level2
|
https://github.com/Vent-Tardar/com.genusIIc.vt.level2
|
07a1f1f59b882a96fd96f6e128a00aac6dee780c
|
3f827bbda283abce30ae887e662610a2f565b068
|
refs/heads/master
| 2023-05-08T16:11:12.295000 | 2021-04-30T08:17:02 | 2021-04-30T08:17:02 | 362,084,283 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.genusIIc.vt;
import org.apache.logging.log4j.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Main {
private static final Logger logger = LogManager.getLogger(Main.class);
public static void main(String[] args) throws IOException {
if (args.length != 2){
logger.error("Parameters entered incorrectly");
} else {
ComparisonDoc cd = new ComparisonDoc();
List<String> lst = cd.compare(args[0], args[1]);
for (String s : lst) {
System.out.println(s);
}
}
}
}
|
UTF-8
|
Java
| 628 |
java
|
Main.java
|
Java
|
[] | null |
[] |
package com.genusIIc.vt;
import org.apache.logging.log4j.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Main {
private static final Logger logger = LogManager.getLogger(Main.class);
public static void main(String[] args) throws IOException {
if (args.length != 2){
logger.error("Parameters entered incorrectly");
} else {
ComparisonDoc cd = new ComparisonDoc();
List<String> lst = cd.compare(args[0], args[1]);
for (String s : lst) {
System.out.println(s);
}
}
}
}
| 628 | 0.605096 | 0.598726 | 22 | 27.545454 | 21.848085 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
12
|
35b753ec7944818f239e4dbeaa8ffea0b430b6a1
| 21,440,476,756,837 |
a0f41e85cccd50790ee71433bf5e6054c48ba5cd
|
/src/main/java/com/moodybluez/enterprise/dao/EntrySQLDAO.java
|
48c7fce4911ab76689a7fd77cdb36815e34679fd
|
[] |
no_license
|
mikeal200/MoodyBluez
|
https://github.com/mikeal200/MoodyBluez
|
dd17ef1f39b83a321f4d1e8419f39d8fd725c9aa
|
d2a05f877135f44a002abc821c7ab935356bb2ea
|
refs/heads/main
| 2023-04-08T06:37:12.717000 | 2021-04-22T05:24:33 | 2021-04-22T05:24:33 | 334,245,116 | 2 | 4 | null | false | 2021-04-22T00:42:56 | 2021-01-29T19:37:11 | 2021-04-20T21:34:36 | 2021-04-20T21:46:54 | 648 | 2 | 3 | 0 |
Java
| false | false |
package com.moodybluez.enterprise.dao;
import com.moodybluez.enterprise.dto.Entry;
import com.moodybluez.enterprise.service.CustomUserDetails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Repository;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
@Repository
@Profile({"dev", "default"})
public class EntrySQLDAO implements IEntryDAO{
@Autowired
private EntryRepository entryRepository;
Logger LOG = LoggerFactory.getLogger(this.getClass());
@Override
public Entry save(Entry entry) {
return entryRepository.save(entry);
}
@Override
public List<Entry> fetchByMonth(int year, int month) {
return entryRepository.findByMonth(year,month);
}
@Override
public Entry fetchByDate(String date) {
Date d = new Date();
Entry entry = new Entry();
int userId = 0;
try {
d = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse(date);
} catch (ParseException e) {
LOG.error("Failed to Parse Date, please check if the date is in correct format. Date : " + date, e);
}
List<Entry> entries = entryRepository.findByDate(d);
if(entries.size() == 0) {
entry = null;
}
else if(entries.size() == 1) {
entry = entries.get(0);
}
else {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
Object principal = authentication.getPrincipal();
userId = ((CustomUserDetails) principal).getUserId();
}
for (Entry e : entries) {
if(e.getUserId() == userId) {
entry = e;
}
}
}
return entry;
}
@Override
public List<Entry> fetchByMood(int moodId) {
int userId = 0;
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
Object principal = authentication.getPrincipal();
userId = ((CustomUserDetails) principal).getUserId();
}
return entryRepository.findByMood(moodId, userId);
}
@Override
public Map<Integer, Entry> fetchAll() {
Map<Integer, Entry> entities = new HashMap<>();
entryRepository.findAll().forEach(entry -> {
entities.put(entry.getEntryId(),entry);
});
return entities;
}
@Override
public void delete(int entryID) {
entryRepository.deleteById(entryID);
}
@Override
public Entry fetchById(int id){
return entryRepository.findById(id).get();
}
}
|
UTF-8
|
Java
| 3,200 |
java
|
EntrySQLDAO.java
|
Java
|
[] | null |
[] |
package com.moodybluez.enterprise.dao;
import com.moodybluez.enterprise.dto.Entry;
import com.moodybluez.enterprise.service.CustomUserDetails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Repository;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
@Repository
@Profile({"dev", "default"})
public class EntrySQLDAO implements IEntryDAO{
@Autowired
private EntryRepository entryRepository;
Logger LOG = LoggerFactory.getLogger(this.getClass());
@Override
public Entry save(Entry entry) {
return entryRepository.save(entry);
}
@Override
public List<Entry> fetchByMonth(int year, int month) {
return entryRepository.findByMonth(year,month);
}
@Override
public Entry fetchByDate(String date) {
Date d = new Date();
Entry entry = new Entry();
int userId = 0;
try {
d = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse(date);
} catch (ParseException e) {
LOG.error("Failed to Parse Date, please check if the date is in correct format. Date : " + date, e);
}
List<Entry> entries = entryRepository.findByDate(d);
if(entries.size() == 0) {
entry = null;
}
else if(entries.size() == 1) {
entry = entries.get(0);
}
else {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
Object principal = authentication.getPrincipal();
userId = ((CustomUserDetails) principal).getUserId();
}
for (Entry e : entries) {
if(e.getUserId() == userId) {
entry = e;
}
}
}
return entry;
}
@Override
public List<Entry> fetchByMood(int moodId) {
int userId = 0;
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
Object principal = authentication.getPrincipal();
userId = ((CustomUserDetails) principal).getUserId();
}
return entryRepository.findByMood(moodId, userId);
}
@Override
public Map<Integer, Entry> fetchAll() {
Map<Integer, Entry> entities = new HashMap<>();
entryRepository.findAll().forEach(entry -> {
entities.put(entry.getEntryId(),entry);
});
return entities;
}
@Override
public void delete(int entryID) {
entryRepository.deleteById(entryID);
}
@Override
public Entry fetchById(int id){
return entryRepository.findById(id).get();
}
}
| 3,200 | 0.64625 | 0.644063 | 101 | 30.683168 | 25.994642 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.514852 | false | false |
12
|
c44f2c26b3741e6b11d1c9d438d5929cba9793ce
| 1,803,886,286,870 |
08c0da46a3ce2ed66c1a90d43fa77eceb4c62879
|
/src/main/java/frc/robot/commands/wheelcommands/SpinWheelColor.java
|
3379a61a075203d69439d675888f58562958e0b2
|
[] |
no_license
|
Geneva-Robovikes/Robot-2020
|
https://github.com/Geneva-Robovikes/Robot-2020
|
9d355d7428b3b9b36761e6b16aa5834b9dbc6984
|
fcb83a16f3503f66adb0fe21c63b67e3ca3dbca1
|
refs/heads/master
| 2022-05-03T23:13:00.536000 | 2020-03-05T22:04:57 | 2020-03-05T22:04:57 | 236,255,809 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package frc.robot.commands.wheelcommands;
import edu.wpi.first.wpilibj.DriverStation;
import edu.wpi.first.wpilibj2.command.CommandBase;
import frc.robot.subsystems.WheelSpinner;
import static frc.robot.Constants.*;
public class SpinWheelColor extends CommandBase {
private WheelSpinner wheel;
private String ourColor;
private String currentColor;
private String previousColor;
private int rotateCounter;
private int colorCounter;
private boolean rotated;
public SpinWheelColor(WheelSpinner wheel){
this.wheel = wheel;
addRequirements(wheel);
}
@Override
public void initialize(){
rotateCounter = 0;
colorCounter = 0;
rotated = false;
String wantedColor = DriverStation.getInstance().getGameSpecificMessage();
char check = wantedColor.charAt(0);
if (check == 'B') {
ourColor = "Red";
} else if (check == 'R') {
ourColor = "Blue";
} else if (check == 'G') {
ourColor = "Yellow";
} else if (check == 'Y') {
ourColor = "Green";
} else{
end(true);
}
wheel.spinWheel(wheelSpinnerSpeed);
previousColor = wheel.getColorMatch();
}
@Override
public void execute(){
if(!rotated) {
currentColor = wheel.getColorMatch();
if (previousColor.equals("Red") && currentColor.equals("Yellow")) {
rotateCounter++;
}
previousColor = currentColor;
} else {
if (ourColor.equals(wheel.getColorMatch())) {
colorCounter++;
}
}
}
@Override
public boolean isFinished(){
if(rotateCounter >= 2){
rotated = true;
}
if(colorCounter == 2){
wheel.spinWheel(-wheelSpinnerSpeed);
}
return colorCounter >= 13;
}
@Override
public void end(boolean interrupted){
super.end(interrupted);
wheel.spinWheel(0);
wheel.closeServo();
}
}
|
UTF-8
|
Java
| 2,080 |
java
|
SpinWheelColor.java
|
Java
|
[] | null |
[] |
package frc.robot.commands.wheelcommands;
import edu.wpi.first.wpilibj.DriverStation;
import edu.wpi.first.wpilibj2.command.CommandBase;
import frc.robot.subsystems.WheelSpinner;
import static frc.robot.Constants.*;
public class SpinWheelColor extends CommandBase {
private WheelSpinner wheel;
private String ourColor;
private String currentColor;
private String previousColor;
private int rotateCounter;
private int colorCounter;
private boolean rotated;
public SpinWheelColor(WheelSpinner wheel){
this.wheel = wheel;
addRequirements(wheel);
}
@Override
public void initialize(){
rotateCounter = 0;
colorCounter = 0;
rotated = false;
String wantedColor = DriverStation.getInstance().getGameSpecificMessage();
char check = wantedColor.charAt(0);
if (check == 'B') {
ourColor = "Red";
} else if (check == 'R') {
ourColor = "Blue";
} else if (check == 'G') {
ourColor = "Yellow";
} else if (check == 'Y') {
ourColor = "Green";
} else{
end(true);
}
wheel.spinWheel(wheelSpinnerSpeed);
previousColor = wheel.getColorMatch();
}
@Override
public void execute(){
if(!rotated) {
currentColor = wheel.getColorMatch();
if (previousColor.equals("Red") && currentColor.equals("Yellow")) {
rotateCounter++;
}
previousColor = currentColor;
} else {
if (ourColor.equals(wheel.getColorMatch())) {
colorCounter++;
}
}
}
@Override
public boolean isFinished(){
if(rotateCounter >= 2){
rotated = true;
}
if(colorCounter == 2){
wheel.spinWheel(-wheelSpinnerSpeed);
}
return colorCounter >= 13;
}
@Override
public void end(boolean interrupted){
super.end(interrupted);
wheel.spinWheel(0);
wheel.closeServo();
}
}
| 2,080 | 0.573558 | 0.569231 | 77 | 26.012987 | 17.29912 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.467532 | false | false |
12
|
56b7e7033fd412ee83bd39d69f154672b8550dcb
| 17,446,157,200,424 |
6616059dbdfa40b5601fd5fa3d608770586ca378
|
/src/main/java/org/sdo/rendezvous/model/types/serialization/SigInfoDeserializer.java
|
e803cffedd8ae1443d032fae0c6ec296e950db01
|
[
"Apache-2.0"
] |
permissive
|
Darshini-Parikh93/rendezvous-service
|
https://github.com/Darshini-Parikh93/rendezvous-service
|
3af8b373de0db7ebe44c28892544ef163ff6cdf2
|
0b670375df67e9130519c05bffba886da5d3f1ce
|
refs/heads/master
| 2023-05-28T04:54:06.001000 | 2020-06-01T04:36:01 | 2020-06-01T04:36:01 | 264,828,316 | 1 | 0 |
Apache-2.0
| true | 2020-06-01T04:36:03 | 2020-05-18T04:42:46 | 2020-05-18T04:42:48 | 2020-06-01T04:36:02 | 267 | 0 | 0 | 0 | null | false | false |
// Copyright 2019 Intel Corporation
// SPDX-License-Identifier: Apache 2.0
package org.sdo.rendezvous.model.types.serialization;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.collect.ImmutableSet;
import java.io.IOException;
import java.util.Set;
import lombok.extern.slf4j.Slf4j;
import org.sdo.rendezvous.model.types.PublicKeyType;
import org.sdo.rendezvous.model.types.SigInfo;
@Slf4j
public class SigInfoDeserializer extends JsonDeserializer<SigInfo> {
private static final int PK_TYPE_INDEX = 0;
private static final int LENGTH_INDEX = 1;
private static final int SIGINFO_INDEX = 2;
private static final Set<PublicKeyType> ALLOWED_TYPES =
ImmutableSet.of(
PublicKeyType.EPID_1_0,
PublicKeyType.EPID_1_1,
PublicKeyType.EPID_2_0,
PublicKeyType.ECDSA_P_256,
PublicKeyType.ECDSA_P_384);
@Override
public SigInfo deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
throws IOException {
ObjectCodec objectCodec = jsonParser.getCodec();
JsonNode jsonNode = objectCodec.readTree(jsonParser);
PublicKeyType pkType = PublicKeyType.valueOf(jsonNode.get(PK_TYPE_INDEX).asInt());
if (!ALLOWED_TYPES.contains(pkType)) {
log.error("Invalid EPID public key type. Public key type: {}.", pkType.name());
throw new JsonParseException(jsonParser, "SigInfo is invalid.");
}
jsonNode.get(LENGTH_INDEX).asInt();
byte[] sigInfo = jsonNode.get(SIGINFO_INDEX).binaryValue();
return new SigInfo(pkType, sigInfo);
}
}
|
UTF-8
|
Java
| 1,843 |
java
|
SigInfoDeserializer.java
|
Java
|
[] | null |
[] |
// Copyright 2019 Intel Corporation
// SPDX-License-Identifier: Apache 2.0
package org.sdo.rendezvous.model.types.serialization;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.collect.ImmutableSet;
import java.io.IOException;
import java.util.Set;
import lombok.extern.slf4j.Slf4j;
import org.sdo.rendezvous.model.types.PublicKeyType;
import org.sdo.rendezvous.model.types.SigInfo;
@Slf4j
public class SigInfoDeserializer extends JsonDeserializer<SigInfo> {
private static final int PK_TYPE_INDEX = 0;
private static final int LENGTH_INDEX = 1;
private static final int SIGINFO_INDEX = 2;
private static final Set<PublicKeyType> ALLOWED_TYPES =
ImmutableSet.of(
PublicKeyType.EPID_1_0,
PublicKeyType.EPID_1_1,
PublicKeyType.EPID_2_0,
PublicKeyType.ECDSA_P_256,
PublicKeyType.ECDSA_P_384);
@Override
public SigInfo deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
throws IOException {
ObjectCodec objectCodec = jsonParser.getCodec();
JsonNode jsonNode = objectCodec.readTree(jsonParser);
PublicKeyType pkType = PublicKeyType.valueOf(jsonNode.get(PK_TYPE_INDEX).asInt());
if (!ALLOWED_TYPES.contains(pkType)) {
log.error("Invalid EPID public key type. Public key type: {}.", pkType.name());
throw new JsonParseException(jsonParser, "SigInfo is invalid.");
}
jsonNode.get(LENGTH_INDEX).asInt();
byte[] sigInfo = jsonNode.get(SIGINFO_INDEX).binaryValue();
return new SigInfo(pkType, sigInfo);
}
}
| 1,843 | 0.755833 | 0.742811 | 48 | 37.395832 | 24.378731 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6875 | false | false |
12
|
5902f822467295a2afaa155c7b9b568b377699b9
| 6,502,580,489,628 |
9c7aaea82d3eeba49c24b75ade47c9f6c02c1cf8
|
/假期刷题/day05.java
|
8259c12ee051f746d5a0b52d1478240fa0dc1b9a
|
[] |
no_license
|
jw1028/JavaDemo
|
https://github.com/jw1028/JavaDemo
|
c25b4aa7aa91b873a6dd2b4ae6bbb74f25d4a8c2
|
2e242ff42aedb67a8b16b18a2a91ec7c460c5389
|
refs/heads/main
| 2023-08-26T17:45:40.059000 | 2021-10-09T14:54:00 | 2021-10-09T14:54:00 | 311,989,681 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
//全排列
class Solution {
public List<List<Integer>> ret = new ArrayList<>();
public List<Integer> path = new ArrayList<>();
public List<List<Integer>> permute(int[] nums) {
if(nums == null || nums.length == 0) {
return ret;
}
int n = nums.length;
boolean[] used = new boolean[n];
dfs(nums, n, 0, used, ret, path);
return ret;
}
public void dfs(int[] nums, int len, int depth, boolean[] used, List<List<Integer>> ret,
List<Integer> path) {
if(depth == len) {
ret.add(new ArrayList<>(path));
}
for(int i = 0; i < nums.length; i++) {
if(!used[i]) {
path.add(nums[i]);
used[i] = true;
dfs(nums, len, depth + 1, used, ret, path);
used[i] = false;
path.remove(path.size() - 1);
}
}
}
}
//全排列II
class Solution {
public List<List<Integer>> ret = new ArrayList<>();
public List<Integer> path = new ArrayList<>();
public List<List<Integer>> permuteUnique(int[] nums) {
if(nums == null ||nums.length == 0) {
return ret;
}
int n = nums.length;
Arrays.sort(nums);
boolean[] used = new boolean[n];
dfs(nums, n, 0, used, ret, path);
return ret;
}
public void dfs(int[] nums, int len, int depth, boolean[] used, List<List<Integer>> ret, List<Integer> path ) {
if (depth == len) {
ret.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < len; ++i) {
if (used[i]) {
continue;
}
if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) {
continue;
}
path.add(nums[i]);
used[i] = true;
dfs(nums, len, depth + 1, used, ret, path);
used[i] = false;
path.remove(path.size() - 1);
}
}
}
//字符串排列
class Solution {
public String[] permutation(String s) {
int len = s.length();
if (len == 0) {
return new String[0];
}
// 转换成字符数组是常见的做法
char[] str = s.toCharArray();
// 排序是为了去重方便
Arrays.sort(str);
// 由于操作的都是字符,使用 StringBuilder
StringBuilder path = new StringBuilder();
boolean[] used = new boolean[len];
// 为了方便收集结果,使用动态数组
List<String> res = new ArrayList<>();
dfs(str, len, 0, used, path, res);
// 记得转成字符串数组
return res.toArray(new String[0]);
}
private void dfs(char[] str, int len, int depth,boolean[] used,StringBuilder path,
List<String> res) {
if (depth == len) {
// path.toString() 恰好生成了新的字符对象
res.add(path.toString());
return;
}
for (int i = 0; i < len; i++) {
if (used[i]) {
continue;
}
if (i > 0 && str[i] == str[i - 1] && !used[i - 1]) {
continue;
}
path.append(str[i]);
used[i] = true;
dfs(str, len, depth + 1, used, path, res);
used[i] = false;
path.deleteCharAt(path.length() - 1);
}
}
}
|
UTF-8
|
Java
| 3,490 |
java
|
day05.java
|
Java
|
[] | null |
[] |
//全排列
class Solution {
public List<List<Integer>> ret = new ArrayList<>();
public List<Integer> path = new ArrayList<>();
public List<List<Integer>> permute(int[] nums) {
if(nums == null || nums.length == 0) {
return ret;
}
int n = nums.length;
boolean[] used = new boolean[n];
dfs(nums, n, 0, used, ret, path);
return ret;
}
public void dfs(int[] nums, int len, int depth, boolean[] used, List<List<Integer>> ret,
List<Integer> path) {
if(depth == len) {
ret.add(new ArrayList<>(path));
}
for(int i = 0; i < nums.length; i++) {
if(!used[i]) {
path.add(nums[i]);
used[i] = true;
dfs(nums, len, depth + 1, used, ret, path);
used[i] = false;
path.remove(path.size() - 1);
}
}
}
}
//全排列II
class Solution {
public List<List<Integer>> ret = new ArrayList<>();
public List<Integer> path = new ArrayList<>();
public List<List<Integer>> permuteUnique(int[] nums) {
if(nums == null ||nums.length == 0) {
return ret;
}
int n = nums.length;
Arrays.sort(nums);
boolean[] used = new boolean[n];
dfs(nums, n, 0, used, ret, path);
return ret;
}
public void dfs(int[] nums, int len, int depth, boolean[] used, List<List<Integer>> ret, List<Integer> path ) {
if (depth == len) {
ret.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < len; ++i) {
if (used[i]) {
continue;
}
if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) {
continue;
}
path.add(nums[i]);
used[i] = true;
dfs(nums, len, depth + 1, used, ret, path);
used[i] = false;
path.remove(path.size() - 1);
}
}
}
//字符串排列
class Solution {
public String[] permutation(String s) {
int len = s.length();
if (len == 0) {
return new String[0];
}
// 转换成字符数组是常见的做法
char[] str = s.toCharArray();
// 排序是为了去重方便
Arrays.sort(str);
// 由于操作的都是字符,使用 StringBuilder
StringBuilder path = new StringBuilder();
boolean[] used = new boolean[len];
// 为了方便收集结果,使用动态数组
List<String> res = new ArrayList<>();
dfs(str, len, 0, used, path, res);
// 记得转成字符串数组
return res.toArray(new String[0]);
}
private void dfs(char[] str, int len, int depth,boolean[] used,StringBuilder path,
List<String> res) {
if (depth == len) {
// path.toString() 恰好生成了新的字符对象
res.add(path.toString());
return;
}
for (int i = 0; i < len; i++) {
if (used[i]) {
continue;
}
if (i > 0 && str[i] == str[i - 1] && !used[i - 1]) {
continue;
}
path.append(str[i]);
used[i] = true;
dfs(str, len, depth + 1, used, path, res);
used[i] = false;
path.deleteCharAt(path.length() - 1);
}
}
}
| 3,490 | 0.451351 | 0.444444 | 114 | 28.201754 | 20.436543 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.903509 | false | false |
12
|
818253718215a184646e798cd0ff4007e4227a0c
| 32,865,089,793,450 |
eb79c36d77e2e9f24247da422642ae9d8f233b74
|
/FindbugsTools/src/cbg/app/Logger.java
|
b2806596df5746b8649f1999ec1bbba6a5cb967c
|
[] |
no_license
|
mycsoft/nbfindbugs
|
https://github.com/mycsoft/nbfindbugs
|
8c826b44ce97cbffeead9eb303145c42c22f1efd
|
af4d6d663ad334c97389d6fbff5f180558a59e63
|
refs/heads/master
| 2021-01-10T19:28:01.594000 | 2010-03-16T01:49:47 | 2010-03-16T01:49:47 | 41,296,134 | 1 | 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 cbg.app;
/**
*
* @author Ma Yichao
*/
public class Logger {
public static boolean isLogging(){
return true;
}
public static void log(String s,String s2){
}
public static void log(String s){
}
}
|
UTF-8
|
Java
| 368 |
java
|
Logger.java
|
Java
|
[
{
"context": "e editor.\n */\n\npackage cbg.app;\n\n/**\n *\n * @author Ma Yichao\n */\npublic class Logger {\n\n public static bool",
"end": 146,
"score": 0.9998711943626404,
"start": 137,
"tag": "NAME",
"value": "Ma Yichao"
}
] | null |
[] |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package cbg.app;
/**
*
* @author <NAME>
*/
public class Logger {
public static boolean isLogging(){
return true;
}
public static void log(String s,String s2){
}
public static void log(String s){
}
}
| 365 | 0.57337 | 0.570652 | 25 | 13.72 | 15.885893 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false |
12
|
eaf4bdbebb23f67df122a47457da904f954c7ea4
| 32,495,722,575,174 |
fb566fb0caa9305c90ce400d1d7c639bb3d02eeb
|
/PetShop5/src/Model/Pet.java
|
9fadb77ccf8bd65d924c9445608ee046acd4c4e1
|
[] |
no_license
|
darkquake93/PIIInew
|
https://github.com/darkquake93/PIIInew
|
a4c28f5a4514380b5706ed26889151cafd124a02
|
08489fdc13e350350d26bb20369e63df21991b70
|
refs/heads/master
| 2021-01-21T11:34:22.289000 | 2017-08-31T15:20:02 | 2017-08-31T15:20:10 | 102,014,816 | 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 Model;
/**
*
* @author Sonya
*/
public class Pet{
//Shop,Type,price,dateAcquired,notes
private String shop;
private String breed;
private double price;
private String dateAquired;
private String notes;
public Pet() {
}
public Pet(String shop, String type, double price, String dateAquired, String notes) {
this.shop = shop;
this.breed = type;
this.price = price;
this.dateAquired = dateAquired;
this.notes = notes;
}
public String getShop() {
return shop;
}
public void setShop(String shop) {
this.shop = shop;
}
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getDateAquired() {
return dateAquired;
}
public void setDateAquired(String dateAquired) {
this.dateAquired = dateAquired;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
@Override
public String toString()
{
return this.shop+"\n"+this.breed+"\n"+this.price+"\n"+this.dateAquired+"\n"+this.notes+"\n";
}
public String reportDetails()
{
return this.breed+"\n Shop: "+this.shop+"\n Price: £"+this.price+"\n Date Acquired: "+this.dateAquired+"\n Notes: "+this.notes+"\n";
}
public String searchDetails()
{
return this.breed+" "+this.price+" "+this.dateAquired+" "+this.notes;
}
}
|
UTF-8
|
Java
| 1,895 |
java
|
Pet.java
|
Java
|
[
{
"context": " the editor.\n */\npackage Model;\n\n/**\n *\n * @author Sonya\n */\npublic class Pet{\n //Shop,Type,price,dateA",
"end": 224,
"score": 0.9958778023719788,
"start": 219,
"tag": "NAME",
"value": "Sonya"
}
] | 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 Model;
/**
*
* @author Sonya
*/
public class Pet{
//Shop,Type,price,dateAcquired,notes
private String shop;
private String breed;
private double price;
private String dateAquired;
private String notes;
public Pet() {
}
public Pet(String shop, String type, double price, String dateAquired, String notes) {
this.shop = shop;
this.breed = type;
this.price = price;
this.dateAquired = dateAquired;
this.notes = notes;
}
public String getShop() {
return shop;
}
public void setShop(String shop) {
this.shop = shop;
}
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getDateAquired() {
return dateAquired;
}
public void setDateAquired(String dateAquired) {
this.dateAquired = dateAquired;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
@Override
public String toString()
{
return this.shop+"\n"+this.breed+"\n"+this.price+"\n"+this.dateAquired+"\n"+this.notes+"\n";
}
public String reportDetails()
{
return this.breed+"\n Shop: "+this.shop+"\n Price: £"+this.price+"\n Date Acquired: "+this.dateAquired+"\n Notes: "+this.notes+"\n";
}
public String searchDetails()
{
return this.breed+" "+this.price+" "+this.dateAquired+" "+this.notes;
}
}
| 1,895 | 0.596093 | 0.596093 | 86 | 21.023256 | 24.408813 | 140 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.406977 | false | false |
12
|
abebf034dddc513f9285ccf7e38cf2a03c72adc7
| 17,575,006,176,786 |
7c46aa10e5821a727387bf489457ef157fd20241
|
/src/automation3.java
|
3dbf982ee9d6e34159e081c4e1987f1bda77aef8
|
[] |
no_license
|
svitkinalexander/automation
|
https://github.com/svitkinalexander/automation
|
e5f3017b03440a0dc4e257dea95843a91f378668
|
63b329e59b77139e9bb84afc25c9546e772597fa
|
refs/heads/master
| 2023-04-01T09:09:51.551000 | 2021-03-29T16:08:18 | 2021-03-29T16:08:18 | 336,548,955 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
//Задача 3 (на циклы for и for(each))
// Элементы массива, которые меньше среднего арифметического, умножить на два.
// Для этого нужно:
// а. объвить массив arr размером 10 элементов;
// б. запросить у пользователя ввод целочисленных значений элементов массива arr в цикле;
// в. вывести исходный массив arr в консоль;
// г. объявить переменную sum;
// д. найти сумму элементов массива arr, используя цикл for(each);
// е. объявить переменную avg и вычислить среднее арифметическое элементов массива;
// ж. в цикле for (обычном) умножить на 2 все элементы массива arr, которые меньше среднего арифметического;
// з. вывести итоговый массив arr в консоль.
import java.util.Arrays;
import java.util.Scanner;
public class automation3 {
public static void main(String args[]) {
int[] arr = new int[10];
int n = arr.length;
Scanner in = new Scanner(System.in);
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
System.out.println(Arrays.toString(arr));
int sum = 0;
for(int l : arr){
sum += l;
}
System.out.println("Sum:" + sum);
int avg = 0;
avg = sum / n;
System.out.println("Average:" + avg);
for (int i = 0; i < n; i++) {
if (arr[i] < avg){
arr[i] *= 2;
}
}
System.out.println(Arrays.toString(arr));
}
}
|
UTF-8
|
Java
| 1,978 |
java
|
automation3.java
|
Java
|
[] | null |
[] |
//Задача 3 (на циклы for и for(each))
// Элементы массива, которые меньше среднего арифметического, умножить на два.
// Для этого нужно:
// а. объвить массив arr размером 10 элементов;
// б. запросить у пользователя ввод целочисленных значений элементов массива arr в цикле;
// в. вывести исходный массив arr в консоль;
// г. объявить переменную sum;
// д. найти сумму элементов массива arr, используя цикл for(each);
// е. объявить переменную avg и вычислить среднее арифметическое элементов массива;
// ж. в цикле for (обычном) умножить на 2 все элементы массива arr, которые меньше среднего арифметического;
// з. вывести итоговый массив arr в консоль.
import java.util.Arrays;
import java.util.Scanner;
public class automation3 {
public static void main(String args[]) {
int[] arr = new int[10];
int n = arr.length;
Scanner in = new Scanner(System.in);
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
System.out.println(Arrays.toString(arr));
int sum = 0;
for(int l : arr){
sum += l;
}
System.out.println("Sum:" + sum);
int avg = 0;
avg = sum / n;
System.out.println("Average:" + avg);
for (int i = 0; i < n; i++) {
if (arr[i] < avg){
arr[i] *= 2;
}
}
System.out.println(Arrays.toString(arr));
}
}
| 1,978 | 0.556796 | 0.548917 | 41 | 35.146343 | 26.298994 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.731707 | false | false |
12
|
c500e4f98b867ab40aa7d69416a53563a1bb6ac4
| 13,211,319,467,690 |
5ae0cb0abeba9c2732167b17db1880f6937efd52
|
/chec_en/src/cn/com/chec/en/dao/DBInfoDao.java
|
66d5146e809760bf5149153aa268ce29f34f4333
|
[] |
no_license
|
glameyzhou/cn-com-chec-en
|
https://github.com/glameyzhou/cn-com-chec-en
|
ef2add30f41d35b69806f478f0a15f0579535da1
|
fd58c62db381a704b76a3364e0ff298e8dc76ab7
|
refs/heads/master
| 2021-01-01T19:07:42.971000 | 2014-05-26T08:03:24 | 2014-05-26T08:03:24 | 32,307,419 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package cn.com.chec.en.dao;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;
import cn.com.chec.en.model.domain.TableDesc;
import cn.com.chec.en.util.FileUtils;
import cn.com.chec.en.util.PropertiesUtil;
import cn.com.chec.en.util.StringTools;
@Repository
public class DBInfoDao {
protected static final Logger logger = Logger.getLogger(DBInfoDao.class);
public List<String> getAllTables() {
List<String> list = new ArrayList<String>();
try {
Connection conn = DBFactory.getInstance().getConnection();
String sql = "show tables";
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
list.add(rs.getString(
"Tables_in_" + PropertiesUtil.getValue("mysqlDBName"))
.toLowerCase());
}
rs.close();
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
public synchronized boolean dataDump(String dbBasePath, String dbName,
String tblNames, String destSQLDir) {
boolean result = false;
dbBasePath = StringTools.decoder(dbBasePath).replaceAll("/", "\\\\");
destSQLDir = StringTools.decoder(destSQLDir);
FileUtils.mkdirs(destSQLDir);
logger.info("[data dump] " + dbName + " [" + tblNames + "] to " + destSQLDir);
try {
String sqlName = dbName + "_"
+ DateFormatUtils.format(new Date(), "yyyyMMddHHmmss")
+ ".sql";
String dumpCommond = "cmd /c \"" + dbBasePath
+ "mysqldump.exe\" -h127.0.0.1 -u"
+ PropertiesUtil.getValue("mysqlDBUsername") + " -p"
+ PropertiesUtil.getValue("mysqlDBPassword") + " " + dbName
+ " " + tblNames + " > " + destSQLDir + sqlName;
logger.info("[data dump] " + dumpCommond);
Runtime.getRuntime().exec(dumpCommond);
result = true;
} catch (IOException e) {
logger.error("[data dump] eroor ! " + dbName + " [" + tblNames
+ "] to " + destSQLDir, e);
}
return result;
}
public synchronized boolean dataImport(String dbBasePath, String dbName,
String sqlFile) {
boolean result = false;
dbBasePath = StringTools.decoder(dbBasePath).replaceAll("/", "\\\\");
sqlFile = StringTools.decoder(sqlFile).replaceAll("/", "\\\\");
logger.info("[data import] " + dbName + " use " + sqlFile);
try {
String importCommond = "cmd /c \"" + dbBasePath
+ "mysql\" -h127.0.0.1 -u"
+ PropertiesUtil.getValue("mysqlDBUsername") + " -p"
+ PropertiesUtil.getValue("mysqlDBPassword") + " " + dbName
+ " < " + sqlFile;
logger.info("[data import] " + importCommond);
Runtime.getRuntime().exec(importCommond);
result = true;
} catch (IOException e) {
logger.info("[data import] error ! " + dbName + " use " + sqlFile);
}
return result;
}
public List<File> getSubDumpList(String dumpDir, int start, int num) {
File[] files = new File(dumpDir).listFiles();
List<File> list = Arrays.asList(files);
Collections.sort(list, new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
return o1.lastModified() < o2.lastModified() ? 1 : 0 ;
}
});
int len = (list != null) && (list.size() > 0) ? list.size() : 0;
if (len <= num) {
return list;
}
if (len > start + num) {
return list.subList(start, start + num);
}
return list.subList(start, len);
}
public int getCountDumpList(String dumpDir) {
File[] files = new File(dumpDir).listFiles();
return files.length;
}
public List<TableDesc> getTableDesc(String tblName) {
List<TableDesc> list = new ArrayList<TableDesc>();
Connection conn = DBFactory.getInstance().getConnection();
String descshowTable = "desc " + tblName;
try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(descshowTable);
TableDesc desc = null;
while (rs.next()) {
desc = new TableDesc();
desc.setField(rs.getString("Field"));
desc.setType(rs.getString("Type"));
desc.setIsNull(rs.getString("Null"));
desc.setKey(rs.getString("Key"));
desc.setIsDefault(rs.getString("Default"));
desc.setExtra(rs.getString("Extra"));
list.add(desc);
}
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
public static void main(String[] args) {
DBInfoDao dao = new DBInfoDao();
dao.dataImport(PropertiesUtil.getValue("mysqlBasePath") + "bin/",
PropertiesUtil.getValue("mysqlDBName"), "c:/user.sql");
}
}
|
UTF-8
|
Java
| 5,015 |
java
|
DBInfoDao.java
|
Java
|
[
{
"context": "md /c \\\"\" + dbBasePath\r\n\t\t\t\t\t+ \"mysqldump.exe\\\" -h127.0.0.1 -u\"\r\n\t\t\t\t\t+ PropertiesUtil.getValue(\"mysqlDBUsern",
"end": 1983,
"score": 0.9988159537315369,
"start": 1974,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "ond = \"cmd /c \\\"\" + dbBasePath\r\n\t\t\t\t\t+ \"mysql\\\" -h127.0.0.1 -u\"\r\n\t\t\t\t\t+ PropertiesUtil.getValue(\"mysqlDBUsern",
"end": 2859,
"score": 0.9982270002365112,
"start": 2850,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
}
] | null |
[] |
package cn.com.chec.en.dao;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;
import cn.com.chec.en.model.domain.TableDesc;
import cn.com.chec.en.util.FileUtils;
import cn.com.chec.en.util.PropertiesUtil;
import cn.com.chec.en.util.StringTools;
@Repository
public class DBInfoDao {
protected static final Logger logger = Logger.getLogger(DBInfoDao.class);
public List<String> getAllTables() {
List<String> list = new ArrayList<String>();
try {
Connection conn = DBFactory.getInstance().getConnection();
String sql = "show tables";
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
list.add(rs.getString(
"Tables_in_" + PropertiesUtil.getValue("mysqlDBName"))
.toLowerCase());
}
rs.close();
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
public synchronized boolean dataDump(String dbBasePath, String dbName,
String tblNames, String destSQLDir) {
boolean result = false;
dbBasePath = StringTools.decoder(dbBasePath).replaceAll("/", "\\\\");
destSQLDir = StringTools.decoder(destSQLDir);
FileUtils.mkdirs(destSQLDir);
logger.info("[data dump] " + dbName + " [" + tblNames + "] to " + destSQLDir);
try {
String sqlName = dbName + "_"
+ DateFormatUtils.format(new Date(), "yyyyMMddHHmmss")
+ ".sql";
String dumpCommond = "cmd /c \"" + dbBasePath
+ "mysqldump.exe\" -h127.0.0.1 -u"
+ PropertiesUtil.getValue("mysqlDBUsername") + " -p"
+ PropertiesUtil.getValue("mysqlDBPassword") + " " + dbName
+ " " + tblNames + " > " + destSQLDir + sqlName;
logger.info("[data dump] " + dumpCommond);
Runtime.getRuntime().exec(dumpCommond);
result = true;
} catch (IOException e) {
logger.error("[data dump] eroor ! " + dbName + " [" + tblNames
+ "] to " + destSQLDir, e);
}
return result;
}
public synchronized boolean dataImport(String dbBasePath, String dbName,
String sqlFile) {
boolean result = false;
dbBasePath = StringTools.decoder(dbBasePath).replaceAll("/", "\\\\");
sqlFile = StringTools.decoder(sqlFile).replaceAll("/", "\\\\");
logger.info("[data import] " + dbName + " use " + sqlFile);
try {
String importCommond = "cmd /c \"" + dbBasePath
+ "mysql\" -h127.0.0.1 -u"
+ PropertiesUtil.getValue("mysqlDBUsername") + " -p"
+ PropertiesUtil.getValue("mysqlDBPassword") + " " + dbName
+ " < " + sqlFile;
logger.info("[data import] " + importCommond);
Runtime.getRuntime().exec(importCommond);
result = true;
} catch (IOException e) {
logger.info("[data import] error ! " + dbName + " use " + sqlFile);
}
return result;
}
public List<File> getSubDumpList(String dumpDir, int start, int num) {
File[] files = new File(dumpDir).listFiles();
List<File> list = Arrays.asList(files);
Collections.sort(list, new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
return o1.lastModified() < o2.lastModified() ? 1 : 0 ;
}
});
int len = (list != null) && (list.size() > 0) ? list.size() : 0;
if (len <= num) {
return list;
}
if (len > start + num) {
return list.subList(start, start + num);
}
return list.subList(start, len);
}
public int getCountDumpList(String dumpDir) {
File[] files = new File(dumpDir).listFiles();
return files.length;
}
public List<TableDesc> getTableDesc(String tblName) {
List<TableDesc> list = new ArrayList<TableDesc>();
Connection conn = DBFactory.getInstance().getConnection();
String descshowTable = "desc " + tblName;
try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(descshowTable);
TableDesc desc = null;
while (rs.next()) {
desc = new TableDesc();
desc.setField(rs.getString("Field"));
desc.setType(rs.getString("Type"));
desc.setIsNull(rs.getString("Null"));
desc.setKey(rs.getString("Key"));
desc.setIsDefault(rs.getString("Default"));
desc.setExtra(rs.getString("Extra"));
list.add(desc);
}
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
public static void main(String[] args) {
DBInfoDao dao = new DBInfoDao();
dao.dataImport(PropertiesUtil.getValue("mysqlBasePath") + "bin/",
PropertiesUtil.getValue("mysqlDBName"), "c:/user.sql");
}
}
| 5,015 | 0.647458 | 0.64327 | 163 | 28.77914 | 21.789856 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.619632 | false | false |
12
|
acb6748b3deeec9e92510da344684b466d7eb92d
| 5,351,529,305,607 |
19e0f5afd149cea8c31cc4e745fe835153a4d331
|
/aula/arvoreDeArvore/ArvoreDeArvore.java
|
c77dca394f86b47715622f51507a9e9f446ade62
|
[] |
no_license
|
Diogo-Miranda/aeds
|
https://github.com/Diogo-Miranda/aeds
|
91ee71974fb62b7b96997232d9f1241d40d27c9b
|
05bd89419be73564afb441ccc289054088a4664e
|
refs/heads/master
| 2023-01-31T19:38:30.964000 | 2020-12-13T20:12:02 | 2020-12-13T20:12:02 | 305,811,300 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
class NoChar {
char elemento;
NoChar dir;
NoChar esq;
NoString noString;
NoChar(char elemento) {
this.elemento = elemento;
noString = null;
this.dir = null;
this.esq = null;
}
}
class NoString {
String elemento;
NoString dir;
NoString esq;
NoString(String elemento) {
this.elemento = elemento;
this.dir = null;
this.esq = null;
}
}
public NoString inserirPalavra(String p, NoString i)
{
if(i == null) {
i = inserir(p);
} else if(i.elemento.compareTo(p) < 0) {
i = inserirPalavra(p, i.dir);
} else {
i = inserirPalavra(p, i.esq);
}
return i;
}
public NoChar inserir(String p, NoChar i)
{
char c = p.charAt(0);
if(i == null) {
i = inserir(c);
// Verificar se é igual
} else if(i.elemento == c) {
i = inserirPalavra(p, i.noString);
} else if(i.elemento > c) {
i = inserirPalavra(p, i.esq);
} else {
i = inserirPalavra(p, i.dir);
}
return i;
}
public boolean temString10(NoString i)
{
boolean resp = false;
if(i != null) {
resp = (i.elemento.length() == 10) || noString10(i.esq) || noString10(i.dir);
}
return resp;
}
public boolean temString10(NoChar i)
{
boolean resp = false;
if(i != null) {
resp = temString10(i.noString) || temString10(i.esq) || temString10(i.dir);
}
return resp;
}
public class ArvoreDeArvore {
public static void main (String[] args) {
}
}
|
UTF-8
|
Java
| 1,348 |
java
|
ArvoreDeArvore.java
|
Java
|
[] | null |
[] |
class NoChar {
char elemento;
NoChar dir;
NoChar esq;
NoString noString;
NoChar(char elemento) {
this.elemento = elemento;
noString = null;
this.dir = null;
this.esq = null;
}
}
class NoString {
String elemento;
NoString dir;
NoString esq;
NoString(String elemento) {
this.elemento = elemento;
this.dir = null;
this.esq = null;
}
}
public NoString inserirPalavra(String p, NoString i)
{
if(i == null) {
i = inserir(p);
} else if(i.elemento.compareTo(p) < 0) {
i = inserirPalavra(p, i.dir);
} else {
i = inserirPalavra(p, i.esq);
}
return i;
}
public NoChar inserir(String p, NoChar i)
{
char c = p.charAt(0);
if(i == null) {
i = inserir(c);
// Verificar se é igual
} else if(i.elemento == c) {
i = inserirPalavra(p, i.noString);
} else if(i.elemento > c) {
i = inserirPalavra(p, i.esq);
} else {
i = inserirPalavra(p, i.dir);
}
return i;
}
public boolean temString10(NoString i)
{
boolean resp = false;
if(i != null) {
resp = (i.elemento.length() == 10) || noString10(i.esq) || noString10(i.dir);
}
return resp;
}
public boolean temString10(NoChar i)
{
boolean resp = false;
if(i != null) {
resp = temString10(i.noString) || temString10(i.esq) || temString10(i.dir);
}
return resp;
}
public class ArvoreDeArvore {
public static void main (String[] args) {
}
}
| 1,348 | 0.634001 | 0.620638 | 79 | 16.037975 | 16.378006 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.455696 | false | false |
12
|
27e099aa82a96127c5aed9d19afc8a7cf282d919
| 8,435,315,829,213 |
962a369cb83e3f0cca152ce37db4ba28c28242bd
|
/app/src/main/java/com/crackncrunch/amplain/di/components/PicassoComponent.java
|
d15420e814679e119915be3682d87b7cbc6da8d6
|
[] |
no_license
|
burdianov/AmEcommerce
|
https://github.com/burdianov/AmEcommerce
|
740e880fa1ff8177974e2a592091b0ec19168b8d
|
56892a45499569731c114e7ac8ecca61b01a3e6a
|
refs/heads/master
| 2021-01-21T11:54:45.252000 | 2017-04-05T09:19:59 | 2017-04-05T09:19:59 | 83,580,102 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.crackncrunch.amplain.di.components;
import com.crackncrunch.amplain.di.modules.PicassoCacheModule;
import com.crackncrunch.amplain.di.scopes.RootScope;
import com.squareup.picasso.Picasso;
import dagger.Component;
/**
* Created by Lilian on 21-Feb-17.
*/
@Component(dependencies = AppComponent.class,
modules = PicassoCacheModule.class)
@RootScope
public interface PicassoComponent {
Picasso getPicasso();
}
|
UTF-8
|
Java
| 438 |
java
|
PicassoComponent.java
|
Java
|
[
{
"context": "asso;\n\nimport dagger.Component;\n\n/**\n * Created by Lilian on 21-Feb-17.\n */\n\n@Component(dependencies = AppC",
"end": 253,
"score": 0.9710857272148132,
"start": 247,
"tag": "NAME",
"value": "Lilian"
}
] | null |
[] |
package com.crackncrunch.amplain.di.components;
import com.crackncrunch.amplain.di.modules.PicassoCacheModule;
import com.crackncrunch.amplain.di.scopes.RootScope;
import com.squareup.picasso.Picasso;
import dagger.Component;
/**
* Created by Lilian on 21-Feb-17.
*/
@Component(dependencies = AppComponent.class,
modules = PicassoCacheModule.class)
@RootScope
public interface PicassoComponent {
Picasso getPicasso();
}
| 438 | 0.780822 | 0.771689 | 18 | 23.333334 | 20.853991 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.388889 | false | false |
12
|
88c0696cc0dca65a2f768a2e1a98a203fd8d1ea0
| 7,103,875,961,880 |
71ad6c529016800004e5641d16539446b6e01234
|
/src/main/java/com/classes/app/presentation/serializer/SubjectSerializer.java
|
d7cf164abfba71bea9fd41fb207b38c29bb3c8da
|
[] |
no_license
|
nicogarcia/classes-web-server
|
https://github.com/nicogarcia/classes-web-server
|
c7023c7f4e086a86e60481f473033d0b255d8091
|
4b15c0648aa99bc735a0763bafb4a40b55361df1
|
refs/heads/master
| 2015-07-11T17:03:30 | 2015-07-06T13:10:15 | 2015-07-06T13:10:15 | 35,990,744 | 0 | 0 | null | false | 2015-09-08T20:28:36 | 2015-05-21T04:21:05 | 2015-05-21T04:24:03 | 2015-09-08T20:28:36 | 980 | 0 | 0 | 2 |
Java
| null | null |
package com.classes.app.presentation.serializer;
import com.classes.app.domain.entity.Subject;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.stereotype.Component;
import java.io.IOException;
@Component
public class SubjectSerializer extends JsonSerializer<Subject> {
@Override
public void serialize(Subject subject, JsonGenerator generator, SerializerProvider provider) throws IOException {
generator.writeStartObject();
generator.writeStringField("id", subject.getId().toString());
generator.writeStringField("name", subject.getName());
generator.writeNumberField("level", subject.getLevel());
generator.writeEndObject();
}
}
|
UTF-8
|
Java
| 826 |
java
|
SubjectSerializer.java
|
Java
|
[] | null |
[] |
package com.classes.app.presentation.serializer;
import com.classes.app.domain.entity.Subject;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.stereotype.Component;
import java.io.IOException;
@Component
public class SubjectSerializer extends JsonSerializer<Subject> {
@Override
public void serialize(Subject subject, JsonGenerator generator, SerializerProvider provider) throws IOException {
generator.writeStartObject();
generator.writeStringField("id", subject.getId().toString());
generator.writeStringField("name", subject.getName());
generator.writeNumberField("level", subject.getLevel());
generator.writeEndObject();
}
}
| 826 | 0.774818 | 0.774818 | 23 | 34.913044 | 30.262493 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.73913 | false | false |
12
|
4a6538dd89aa51b470a1094d4fc6bea9487c9059
| 28,698,971,515,813 |
4a804562cec0ae45130c7e08423bf67b71858f69
|
/kie-wb-common-dmn/kie-wb-common-dmn-client/src/main/java/org/kie/workbench/common/dmn/client/editors/types/listview/constraint/DataTypeConstraintView.java
|
bd83b97e5134e07e23ddbdfce616959631f65816
|
[
"Apache-2.0"
] |
permissive
|
albfan/kie-wb-common
|
https://github.com/albfan/kie-wb-common
|
8cac1afce6b6dba47dc23d3d74ca10708947efb6
|
bc6fbbddd0944ae1d9394bf6cf9af512ab43956f
|
refs/heads/master
| 2020-08-29T18:28:26.137000 | 2019-10-25T20:55:14 | 2019-10-25T20:55:14 | 218,126,735 | 1 | 0 |
Apache-2.0
| true | 2019-10-28T19:17:07 | 2019-10-28T19:17:06 | 2019-10-25T20:55:19 | 2019-10-28T10:38:13 | 71,901 | 0 | 0 | 0 | null | false | false |
/*
* Copyright 2019 Red Hat, Inc. and/or its affiliates.
*
* 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.kie.workbench.common.dmn.client.editors.types.listview.constraint;
import javax.annotation.PostConstruct;
import javax.enterprise.context.Dependent;
import javax.inject.Inject;
import javax.inject.Named;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import elemental2.dom.HTMLAnchorElement;
import elemental2.dom.HTMLDivElement;
import elemental2.dom.HTMLElement;
import org.jboss.errai.ui.client.local.spi.TranslationService;
import org.jboss.errai.ui.shared.api.annotations.DataField;
import org.jboss.errai.ui.shared.api.annotations.EventHandler;
import org.jboss.errai.ui.shared.api.annotations.Templated;
import static org.kie.workbench.common.dmn.client.editors.types.common.HiddenHelper.hide;
import static org.kie.workbench.common.dmn.client.editors.types.common.HiddenHelper.show;
import static org.kie.workbench.common.dmn.client.editors.types.listview.common.JQueryTooltip.$;
import static org.kie.workbench.common.dmn.client.resources.i18n.DMNEditorConstants.DataTypeConstraintView_ConstraintsTooltip;
import static org.kie.workbench.common.stunner.core.util.StringUtils.isEmpty;
@Templated
@Dependent
public class DataTypeConstraintView implements DataTypeConstraint.View {
@DataField("constraints-anchor")
private final HTMLAnchorElement constraintsAnchor;
@DataField("constraints-tooltip")
private final HTMLElement constraintsTooltip;
@DataField("constraints-label")
private final HTMLElement constraintsLabel;
@DataField("constraints-text")
private final HTMLDivElement constraintsText;
private final TranslationService translationService;
private DataTypeConstraint presenter;
@Inject
public DataTypeConstraintView(final HTMLAnchorElement constraintsAnchor,
final @Named("span") HTMLElement constraintsTooltip,
final @Named("span") HTMLElement constraintsLabel,
final HTMLDivElement constraintsText,
final TranslationService translationService) {
this.constraintsAnchor = constraintsAnchor;
this.constraintsTooltip = constraintsTooltip;
this.constraintsLabel = constraintsLabel;
this.constraintsText = constraintsText;
this.translationService = translationService;
}
@Override
public void init(final DataTypeConstraint presenter) {
this.presenter = presenter;
}
@PostConstruct
public void setup() {
constraintsTooltip.setAttribute("title", translationService.format(DataTypeConstraintView_ConstraintsTooltip));
setupTooltip(properties().getJavaScriptObject());
}
@EventHandler("constraints-anchor")
public void onConstraintsClick(final ClickEvent e) {
presenter.openModal();
}
@Override
public void showAnchor() {
show(constraintsAnchor);
show(constraintsTooltip);
}
@Override
public void showTextLabel() {
show(constraintsLabel);
}
@Override
public void hideAnchor() {
hide(constraintsAnchor);
hide(constraintsTooltip);
}
@Override
public void hideTextLabel() {
hide(constraintsLabel);
}
@Override
public void showText() {
show(constraintsText);
}
@Override
public void hideText() {
hide(constraintsText);
}
@Override
public void setText(final String text) {
final boolean isValueBlank = isEmpty(text);
final String noneCSSClass = "none";
if (isValueBlank) {
constraintsText.textContent = "NONE";
constraintsText.classList.add(noneCSSClass);
} else {
constraintsText.classList.remove(noneCSSClass);
constraintsText.textContent = text;
}
}
@Override
public void enable() {
show(getElement());
}
@Override
public void disable() {
hide(getElement());
}
void setupTooltip(final JavaScriptObject javaScriptObject) {
$(constraintsTooltip).tooltip(javaScriptObject);
}
JSONObject properties() {
final JSONObject jsonObject = makeJsonObject();
jsonObject.put("container", new JSONString("body"));
return jsonObject;
}
JSONObject makeJsonObject() {
return new JSONObject();
}
}
|
UTF-8
|
Java
| 5,134 |
java
|
DataTypeConstraintView.java
|
Java
|
[] | null |
[] |
/*
* Copyright 2019 Red Hat, Inc. and/or its affiliates.
*
* 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.kie.workbench.common.dmn.client.editors.types.listview.constraint;
import javax.annotation.PostConstruct;
import javax.enterprise.context.Dependent;
import javax.inject.Inject;
import javax.inject.Named;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import elemental2.dom.HTMLAnchorElement;
import elemental2.dom.HTMLDivElement;
import elemental2.dom.HTMLElement;
import org.jboss.errai.ui.client.local.spi.TranslationService;
import org.jboss.errai.ui.shared.api.annotations.DataField;
import org.jboss.errai.ui.shared.api.annotations.EventHandler;
import org.jboss.errai.ui.shared.api.annotations.Templated;
import static org.kie.workbench.common.dmn.client.editors.types.common.HiddenHelper.hide;
import static org.kie.workbench.common.dmn.client.editors.types.common.HiddenHelper.show;
import static org.kie.workbench.common.dmn.client.editors.types.listview.common.JQueryTooltip.$;
import static org.kie.workbench.common.dmn.client.resources.i18n.DMNEditorConstants.DataTypeConstraintView_ConstraintsTooltip;
import static org.kie.workbench.common.stunner.core.util.StringUtils.isEmpty;
@Templated
@Dependent
public class DataTypeConstraintView implements DataTypeConstraint.View {
@DataField("constraints-anchor")
private final HTMLAnchorElement constraintsAnchor;
@DataField("constraints-tooltip")
private final HTMLElement constraintsTooltip;
@DataField("constraints-label")
private final HTMLElement constraintsLabel;
@DataField("constraints-text")
private final HTMLDivElement constraintsText;
private final TranslationService translationService;
private DataTypeConstraint presenter;
@Inject
public DataTypeConstraintView(final HTMLAnchorElement constraintsAnchor,
final @Named("span") HTMLElement constraintsTooltip,
final @Named("span") HTMLElement constraintsLabel,
final HTMLDivElement constraintsText,
final TranslationService translationService) {
this.constraintsAnchor = constraintsAnchor;
this.constraintsTooltip = constraintsTooltip;
this.constraintsLabel = constraintsLabel;
this.constraintsText = constraintsText;
this.translationService = translationService;
}
@Override
public void init(final DataTypeConstraint presenter) {
this.presenter = presenter;
}
@PostConstruct
public void setup() {
constraintsTooltip.setAttribute("title", translationService.format(DataTypeConstraintView_ConstraintsTooltip));
setupTooltip(properties().getJavaScriptObject());
}
@EventHandler("constraints-anchor")
public void onConstraintsClick(final ClickEvent e) {
presenter.openModal();
}
@Override
public void showAnchor() {
show(constraintsAnchor);
show(constraintsTooltip);
}
@Override
public void showTextLabel() {
show(constraintsLabel);
}
@Override
public void hideAnchor() {
hide(constraintsAnchor);
hide(constraintsTooltip);
}
@Override
public void hideTextLabel() {
hide(constraintsLabel);
}
@Override
public void showText() {
show(constraintsText);
}
@Override
public void hideText() {
hide(constraintsText);
}
@Override
public void setText(final String text) {
final boolean isValueBlank = isEmpty(text);
final String noneCSSClass = "none";
if (isValueBlank) {
constraintsText.textContent = "NONE";
constraintsText.classList.add(noneCSSClass);
} else {
constraintsText.classList.remove(noneCSSClass);
constraintsText.textContent = text;
}
}
@Override
public void enable() {
show(getElement());
}
@Override
public void disable() {
hide(getElement());
}
void setupTooltip(final JavaScriptObject javaScriptObject) {
$(constraintsTooltip).tooltip(javaScriptObject);
}
JSONObject properties() {
final JSONObject jsonObject = makeJsonObject();
jsonObject.put("container", new JSONString("body"));
return jsonObject;
}
JSONObject makeJsonObject() {
return new JSONObject();
}
}
| 5,134 | 0.707051 | 0.704519 | 161 | 30.888199 | 27.513969 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false |
12
|
1ff3c72697b5714a0abf30e96146f706a074dbc0
| 4,672,924,465,680 |
88031a4227d5a4d7428f19fb5a64d9567e22ddd1
|
/src/main/java/com/atguigu/day06/Flink01_State_Keyed_Value.java
|
92c5df95bb21ec607140eb152dfdf6b83a8731c8
|
[] |
no_license
|
Aron1015/0225-flink
|
https://github.com/Aron1015/0225-flink
|
c1a7e3049cd0e73e38ba73b84cc81dd4822a57e4
|
2100f8269a65b0b21554ef293339d9f76e786112
|
refs/heads/master
| 2023-06-27T09:07:08.746000 | 2021-07-24T05:47:29 | 2021-07-24T05:47:29 | 385,181,456 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.atguigu.day06;
import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
public class Flink01_State_Keyed_Value {
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(1);
DataStreamSource<String> streamSource = env.socketTextStream("hadoop102", 9999);
SingleOutputStreamOperator<WaterSensor> waterSensorDS = streamSource.map(new MapFunction<String, WaterSensor>() {
@Override
public WaterSensor map(String value) throws Exception {
String[] words = value.split(" ");
return new WaterSensor(words[0], Long.parseLong(words[1]), Integer.parseInt(words[2]));
}
});
//检测传感器的水位线值,如果连续的两个水位线差值超过10,就输出报警
waterSensorDS.keyBy("id")
.process(new KeyedProcessFunction<Tuple, WaterSensor, String>() {
private ValueState<Integer> valueState;
@Override
public void open(Configuration parameters) throws Exception {
//初始化
valueState = getRuntimeContext().getState(new ValueStateDescriptor<Integer>("valueState", Integer.class));
}
@Override
public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {
Integer lastVc = valueState.value() == null ? 0 : valueState.value();
if (Math.abs(value.getVc() - lastVc) >= 10) {
out.collect("报警");
}
valueState.update(value.getVc());
}
}).print();
env.execute();
}
}
|
UTF-8
|
Java
| 2,503 |
java
|
Flink01_State_Keyed_Value.java
|
Java
|
[] | null |
[] |
package com.atguigu.day06;
import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
public class Flink01_State_Keyed_Value {
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(1);
DataStreamSource<String> streamSource = env.socketTextStream("hadoop102", 9999);
SingleOutputStreamOperator<WaterSensor> waterSensorDS = streamSource.map(new MapFunction<String, WaterSensor>() {
@Override
public WaterSensor map(String value) throws Exception {
String[] words = value.split(" ");
return new WaterSensor(words[0], Long.parseLong(words[1]), Integer.parseInt(words[2]));
}
});
//检测传感器的水位线值,如果连续的两个水位线差值超过10,就输出报警
waterSensorDS.keyBy("id")
.process(new KeyedProcessFunction<Tuple, WaterSensor, String>() {
private ValueState<Integer> valueState;
@Override
public void open(Configuration parameters) throws Exception {
//初始化
valueState = getRuntimeContext().getState(new ValueStateDescriptor<Integer>("valueState", Integer.class));
}
@Override
public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {
Integer lastVc = valueState.value() == null ? 0 : valueState.value();
if (Math.abs(value.getVc() - lastVc) >= 10) {
out.collect("报警");
}
valueState.update(value.getVc());
}
}).print();
env.execute();
}
}
| 2,503 | 0.639654 | 0.631427 | 54 | 44.01852 | 34.658382 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.62963 | false | false |
12
|
024c964e81c47e5f89c818f0db68f36bd5c90c07
| 4,672,924,465,128 |
028ae8710b4062859dacf65f0cda28204e728ceb
|
/xar/src/main/java/com/sprylab/xar/signing/checksum/ChecksumProvider.java
|
87f50fe3af1906b15d0f03c66d662ce0c860a33c
|
[
"Apache-2.0"
] |
permissive
|
bosrj/xar
|
https://github.com/bosrj/xar
|
52955c926929f914c146c31a165a09b4b3c3ef75
|
e6d112e62e9ba9fae1befe795a688e55d3654bdd
|
refs/heads/master
| 2020-07-11T01:12:51.224000 | 2020-02-25T12:33:17 | 2020-02-25T12:33:17 | 204,416,503 | 0 | 0 |
Apache-2.0
| true | 2020-02-25T14:43:50 | 2019-08-26T07:04:49 | 2020-02-25T12:33:23 | 2020-02-25T14:43:29 | 34,782 | 0 | 0 | 1 |
Java
| false | false |
package com.sprylab.xar.signing.checksum;
import okio.ByteString;
import okio.HashingSource;
import okio.Source;
public abstract class ChecksumProvider {
private HashingSource hashingSource;
/**
* @param source the source over which to calculate the checksum
* @return the wrapped source, over which the checksum will be calculated
*/
public Source wrap(final Source source) {
this.hashingSource = this.buildHashingSource(source);
return this.hashingSource;
}
/**
* @return the calculated checksum
* @throws IllegalStateException when there's no source over which to calculate the checksum
*/
public ByteString getChecksum() throws IllegalStateException {
if (hashingSource == null) {
throw new IllegalStateException("A source should be wrapped with a provider before retrieving the checksum");
}
return hashingSource.hash();
}
protected abstract HashingSource buildHashingSource(Source source);
}
|
UTF-8
|
Java
| 1,018 |
java
|
ChecksumProvider.java
|
Java
|
[] | null |
[] |
package com.sprylab.xar.signing.checksum;
import okio.ByteString;
import okio.HashingSource;
import okio.Source;
public abstract class ChecksumProvider {
private HashingSource hashingSource;
/**
* @param source the source over which to calculate the checksum
* @return the wrapped source, over which the checksum will be calculated
*/
public Source wrap(final Source source) {
this.hashingSource = this.buildHashingSource(source);
return this.hashingSource;
}
/**
* @return the calculated checksum
* @throws IllegalStateException when there's no source over which to calculate the checksum
*/
public ByteString getChecksum() throws IllegalStateException {
if (hashingSource == null) {
throw new IllegalStateException("A source should be wrapped with a provider before retrieving the checksum");
}
return hashingSource.hash();
}
protected abstract HashingSource buildHashingSource(Source source);
}
| 1,018 | 0.709234 | 0.709234 | 32 | 30.8125 | 31.194387 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.34375 | false | false |
12
|
886209d26902049377c09f206ba60e1599fbf464
| 12,446,815,273,353 |
3f9b08f626caa37f139bf93c75c23afe856fa570
|
/TCP_Entity/src/model/Friend.java
|
30fd2834303f919184612bce4eb8782bb9368724
|
[] |
no_license
|
xuanhiep2k/TCP-IP_Java_GameDuaXe
|
https://github.com/xuanhiep2k/TCP-IP_Java_GameDuaXe
|
e2eb047be15f6f06d989686a8b3861cf3de69eba
|
07a2b69cd6fe64cee3385efe1d8e22c8a72d30e0
|
refs/heads/main
| 2023-08-28T08:46:47.176000 | 2021-11-10T04:38:41 | 2021-11-10T04:38:41 | null | 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 model;
import java.io.Serializable;
/**
*
* @author NONAME
*/
public class Friend implements Serializable {
private int id, idPlayer1, idPlayer2;
private String namePlayer1, namePlayer2, stt1, stt2;
public Friend() {
super();
}
public void setStt1(String stt1) {
this.stt1 = stt1;
}
public void setStt2(String stt2) {
this.stt2 = stt2;
}
public String getStt1() {
return stt1;
}
public String getStt2() {
return stt2;
}
public void setId(int id) {
this.id = id;
}
public void setIdPlayer1(int idPlayer1) {
this.idPlayer1 = idPlayer1;
}
public void setIdPlayer2(int idPlayer2) {
this.idPlayer2 = idPlayer2;
}
public void setNamePlayer1(String namePlayer1) {
this.namePlayer1 = namePlayer1;
}
public void setNamePlayer2(String namePlayer2) {
this.namePlayer2 = namePlayer2;
}
public int getId() {
return id;
}
public int getIdPlayer1() {
return idPlayer1;
}
public int getIdPlayer2() {
return idPlayer2;
}
public String getNamePlayer1() {
return namePlayer1;
}
public String getNamePlayer2() {
return namePlayer2;
}
}
|
UTF-8
|
Java
| 1,479 |
java
|
Friend.java
|
Java
|
[
{
"context": ";\n\nimport java.io.Serializable;\n\n/**\n *\n * @author NONAME\n */\npublic class Friend implements Serializable {",
"end": 255,
"score": 0.999616265296936,
"start": 249,
"tag": "USERNAME",
"value": "NONAME"
}
] | 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 model;
import java.io.Serializable;
/**
*
* @author NONAME
*/
public class Friend implements Serializable {
private int id, idPlayer1, idPlayer2;
private String namePlayer1, namePlayer2, stt1, stt2;
public Friend() {
super();
}
public void setStt1(String stt1) {
this.stt1 = stt1;
}
public void setStt2(String stt2) {
this.stt2 = stt2;
}
public String getStt1() {
return stt1;
}
public String getStt2() {
return stt2;
}
public void setId(int id) {
this.id = id;
}
public void setIdPlayer1(int idPlayer1) {
this.idPlayer1 = idPlayer1;
}
public void setIdPlayer2(int idPlayer2) {
this.idPlayer2 = idPlayer2;
}
public void setNamePlayer1(String namePlayer1) {
this.namePlayer1 = namePlayer1;
}
public void setNamePlayer2(String namePlayer2) {
this.namePlayer2 = namePlayer2;
}
public int getId() {
return id;
}
public int getIdPlayer1() {
return idPlayer1;
}
public int getIdPlayer2() {
return idPlayer2;
}
public String getNamePlayer1() {
return namePlayer1;
}
public String getNamePlayer2() {
return namePlayer2;
}
}
| 1,479 | 0.611224 | 0.582826 | 79 | 17.721519 | 18.319899 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.341772 | false | false |
12
|
d82881199c62ea52c58befad52f2bc5a306dd7f6
| 23,270,132,870,509 |
96ce172712505acf0485d9cc23d67b00c60ba064
|
/src/main/java/com/ychs/service/IPaperService.java
|
065857e03df722ef171c7d6073652f095f1dfa5d
|
[] |
no_license
|
lss15364965404/exam
|
https://github.com/lss15364965404/exam
|
a602ef924d9efc28d78f66850e2c244f768575ff
|
153d90fd92c37b196eac20316a0153a3b4b6d26c
|
refs/heads/master
| 2020-05-09T21:54:36.208000 | 2019-04-15T09:33:39 | 2019-04-15T09:33:39 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.ychs.service;
import java.util.List;
import java.util.Map;
import com.ychs.bean.Paper;
/**
* 试卷的service接口
* @author FENG
*
*/
public interface IPaperService {
/**
* 添加试卷
* @param fillBlank
* @return
*/
public boolean addPaper(Map<String, String> map);
/**
* 查询所有判断题
* @param check
* @return
*/
public List<Paper> selectPaperService(String paperName,String page,String limit);
/**
* 查询总条数
* @return
*/
public int selectCountS();
}
|
UTF-8
|
Java
| 556 |
java
|
IPaperService.java
|
Java
|
[
{
"context": "hs.bean.Paper;\r\n\r\n/**\r\n * 试卷的service接口\r\n * @author FENG\r\n *\r\n */\r\npublic interface IPaperService {\r\n\t/**\r",
"end": 146,
"score": 0.9778828620910645,
"start": 142,
"tag": "USERNAME",
"value": "FENG"
}
] | null |
[] |
package com.ychs.service;
import java.util.List;
import java.util.Map;
import com.ychs.bean.Paper;
/**
* 试卷的service接口
* @author FENG
*
*/
public interface IPaperService {
/**
* 添加试卷
* @param fillBlank
* @return
*/
public boolean addPaper(Map<String, String> map);
/**
* 查询所有判断题
* @param check
* @return
*/
public List<Paper> selectPaperService(String paperName,String page,String limit);
/**
* 查询总条数
* @return
*/
public int selectCountS();
}
| 556 | 0.61284 | 0.61284 | 33 | 13.575758 | 16.542013 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.878788 | false | false |
12
|
d5e94d5ab769f37d0a895850cb75391903d5ee4c
| 10,617,159,225,713 |
18f39f7dba118e1d68ced827b23833778794e896
|
/community-persistence/src/main/java/com/rfchina/community/persistence/mapper/MasterChildInfoMapper.java
|
29813fccb5eb26cfe5d2b69672015e1dbedf6526
|
[] |
no_license
|
amxsa/application-community-openweb
|
https://github.com/amxsa/application-community-openweb
|
27457697314b787273663b035e63e9202f89c210
|
0c111375311b39c1a7369ee6d2a16e1c8408bd1b
|
refs/heads/master
| 2020-07-31T08:43:26.180000 | 2019-04-11T09:00:20 | 2019-04-11T09:00:20 | 210,547,591 | 0 | 3 | null | false | 2020-12-16T14:27:15 | 2019-09-24T08:10:10 | 2020-05-06T17:05:57 | 2019-04-11T09:01:37 | 3,535 | 0 | 1 | 1 | null | false | false |
package com.rfchina.community.persistence.mapper;
import com.rfchina.community.persistence.model.MasterChildInfo;
import com.rfchina.community.persistence.model.MasterChildInfoExample;
import java.io.Serializable;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.DeleteProvider;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectKey;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.UpdateProvider;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.type.JdbcType;
public interface MasterChildInfoMapper extends Serializable {
@SelectProvider(type=MasterChildInfoSqlProvider.class, method="countByExample")
long countByExample(MasterChildInfoExample example);
@DeleteProvider(type=MasterChildInfoSqlProvider.class, method="deleteByExample")
int deleteByExample(MasterChildInfoExample example);
@Delete({
"delete from master_child_info",
"where id = #{id,jdbcType=BIGINT}"
})
int deleteByPrimaryKey(Long id);
@Insert({
"insert into master_child_info (master_id, info_type, ",
"info_title, info_mark, ",
"select_type, operation_time)",
"values (#{masterId,jdbcType=BIGINT}, #{infoType,jdbcType=BIGINT}, ",
"#{infoTitle,jdbcType=VARCHAR}, #{infoMark,jdbcType=VARCHAR}, ",
"#{selectType,jdbcType=BIGINT}, #{operationTime,jdbcType=TIMESTAMP})"
})
@SelectKey(statement="SELECT LAST_INSERT_ID()", keyProperty="id", before=false, resultType=Long.class)
int insert(MasterChildInfo record);
@InsertProvider(type=MasterChildInfoSqlProvider.class, method="insertSelective")
@SelectKey(statement="SELECT LAST_INSERT_ID()", keyProperty="id", before=false, resultType=Long.class)
int insertSelective(MasterChildInfo record);
@SelectProvider(type=MasterChildInfoSqlProvider.class, method="selectByExample")
@Results({
@Result(column="id", property="id", jdbcType=JdbcType.BIGINT, id=true),
@Result(column="master_id", property="masterId", jdbcType=JdbcType.BIGINT),
@Result(column="info_type", property="infoType", jdbcType=JdbcType.BIGINT),
@Result(column="info_title", property="infoTitle", jdbcType=JdbcType.VARCHAR),
@Result(column="info_mark", property="infoMark", jdbcType=JdbcType.VARCHAR),
@Result(column="select_type", property="selectType", jdbcType=JdbcType.BIGINT),
@Result(column="operation_time", property="operationTime", jdbcType=JdbcType.TIMESTAMP)
})
List<MasterChildInfo> selectByExampleWithRowbounds(MasterChildInfoExample example, RowBounds rowBounds);
@SelectProvider(type=MasterChildInfoSqlProvider.class, method="selectByExample")
@Results({
@Result(column="id", property="id", jdbcType=JdbcType.BIGINT, id=true),
@Result(column="master_id", property="masterId", jdbcType=JdbcType.BIGINT),
@Result(column="info_type", property="infoType", jdbcType=JdbcType.BIGINT),
@Result(column="info_title", property="infoTitle", jdbcType=JdbcType.VARCHAR),
@Result(column="info_mark", property="infoMark", jdbcType=JdbcType.VARCHAR),
@Result(column="select_type", property="selectType", jdbcType=JdbcType.BIGINT),
@Result(column="operation_time", property="operationTime", jdbcType=JdbcType.TIMESTAMP)
})
List<MasterChildInfo> selectByExample(MasterChildInfoExample example);
@Select({
"select",
"id, master_id, info_type, info_title, info_mark, select_type, operation_time",
"from master_child_info",
"where id = #{id,jdbcType=BIGINT}"
})
@Results({
@Result(column="id", property="id", jdbcType=JdbcType.BIGINT, id=true),
@Result(column="master_id", property="masterId", jdbcType=JdbcType.BIGINT),
@Result(column="info_type", property="infoType", jdbcType=JdbcType.BIGINT),
@Result(column="info_title", property="infoTitle", jdbcType=JdbcType.VARCHAR),
@Result(column="info_mark", property="infoMark", jdbcType=JdbcType.VARCHAR),
@Result(column="select_type", property="selectType", jdbcType=JdbcType.BIGINT),
@Result(column="operation_time", property="operationTime", jdbcType=JdbcType.TIMESTAMP)
})
MasterChildInfo selectByPrimaryKey(Long id);
@UpdateProvider(type=MasterChildInfoSqlProvider.class, method="updateByExampleSelective")
int updateByExampleSelective(@Param("record") MasterChildInfo record, @Param("example") MasterChildInfoExample example);
@UpdateProvider(type=MasterChildInfoSqlProvider.class, method="updateByExample")
int updateByExample(@Param("record") MasterChildInfo record, @Param("example") MasterChildInfoExample example);
@UpdateProvider(type=MasterChildInfoSqlProvider.class, method="updateByPrimaryKeySelective")
int updateByPrimaryKeySelective(MasterChildInfo record);
@Update({
"update master_child_info",
"set master_id = #{masterId,jdbcType=BIGINT},",
"info_type = #{infoType,jdbcType=BIGINT},",
"info_title = #{infoTitle,jdbcType=VARCHAR},",
"info_mark = #{infoMark,jdbcType=VARCHAR},",
"select_type = #{selectType,jdbcType=BIGINT},",
"operation_time = #{operationTime,jdbcType=TIMESTAMP}",
"where id = #{id,jdbcType=BIGINT}"
})
int updateByPrimaryKey(MasterChildInfo record);
}
|
UTF-8
|
Java
| 5,736 |
java
|
MasterChildInfoMapper.java
|
Java
|
[] | null |
[] |
package com.rfchina.community.persistence.mapper;
import com.rfchina.community.persistence.model.MasterChildInfo;
import com.rfchina.community.persistence.model.MasterChildInfoExample;
import java.io.Serializable;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.DeleteProvider;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectKey;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.UpdateProvider;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.type.JdbcType;
public interface MasterChildInfoMapper extends Serializable {
@SelectProvider(type=MasterChildInfoSqlProvider.class, method="countByExample")
long countByExample(MasterChildInfoExample example);
@DeleteProvider(type=MasterChildInfoSqlProvider.class, method="deleteByExample")
int deleteByExample(MasterChildInfoExample example);
@Delete({
"delete from master_child_info",
"where id = #{id,jdbcType=BIGINT}"
})
int deleteByPrimaryKey(Long id);
@Insert({
"insert into master_child_info (master_id, info_type, ",
"info_title, info_mark, ",
"select_type, operation_time)",
"values (#{masterId,jdbcType=BIGINT}, #{infoType,jdbcType=BIGINT}, ",
"#{infoTitle,jdbcType=VARCHAR}, #{infoMark,jdbcType=VARCHAR}, ",
"#{selectType,jdbcType=BIGINT}, #{operationTime,jdbcType=TIMESTAMP})"
})
@SelectKey(statement="SELECT LAST_INSERT_ID()", keyProperty="id", before=false, resultType=Long.class)
int insert(MasterChildInfo record);
@InsertProvider(type=MasterChildInfoSqlProvider.class, method="insertSelective")
@SelectKey(statement="SELECT LAST_INSERT_ID()", keyProperty="id", before=false, resultType=Long.class)
int insertSelective(MasterChildInfo record);
@SelectProvider(type=MasterChildInfoSqlProvider.class, method="selectByExample")
@Results({
@Result(column="id", property="id", jdbcType=JdbcType.BIGINT, id=true),
@Result(column="master_id", property="masterId", jdbcType=JdbcType.BIGINT),
@Result(column="info_type", property="infoType", jdbcType=JdbcType.BIGINT),
@Result(column="info_title", property="infoTitle", jdbcType=JdbcType.VARCHAR),
@Result(column="info_mark", property="infoMark", jdbcType=JdbcType.VARCHAR),
@Result(column="select_type", property="selectType", jdbcType=JdbcType.BIGINT),
@Result(column="operation_time", property="operationTime", jdbcType=JdbcType.TIMESTAMP)
})
List<MasterChildInfo> selectByExampleWithRowbounds(MasterChildInfoExample example, RowBounds rowBounds);
@SelectProvider(type=MasterChildInfoSqlProvider.class, method="selectByExample")
@Results({
@Result(column="id", property="id", jdbcType=JdbcType.BIGINT, id=true),
@Result(column="master_id", property="masterId", jdbcType=JdbcType.BIGINT),
@Result(column="info_type", property="infoType", jdbcType=JdbcType.BIGINT),
@Result(column="info_title", property="infoTitle", jdbcType=JdbcType.VARCHAR),
@Result(column="info_mark", property="infoMark", jdbcType=JdbcType.VARCHAR),
@Result(column="select_type", property="selectType", jdbcType=JdbcType.BIGINT),
@Result(column="operation_time", property="operationTime", jdbcType=JdbcType.TIMESTAMP)
})
List<MasterChildInfo> selectByExample(MasterChildInfoExample example);
@Select({
"select",
"id, master_id, info_type, info_title, info_mark, select_type, operation_time",
"from master_child_info",
"where id = #{id,jdbcType=BIGINT}"
})
@Results({
@Result(column="id", property="id", jdbcType=JdbcType.BIGINT, id=true),
@Result(column="master_id", property="masterId", jdbcType=JdbcType.BIGINT),
@Result(column="info_type", property="infoType", jdbcType=JdbcType.BIGINT),
@Result(column="info_title", property="infoTitle", jdbcType=JdbcType.VARCHAR),
@Result(column="info_mark", property="infoMark", jdbcType=JdbcType.VARCHAR),
@Result(column="select_type", property="selectType", jdbcType=JdbcType.BIGINT),
@Result(column="operation_time", property="operationTime", jdbcType=JdbcType.TIMESTAMP)
})
MasterChildInfo selectByPrimaryKey(Long id);
@UpdateProvider(type=MasterChildInfoSqlProvider.class, method="updateByExampleSelective")
int updateByExampleSelective(@Param("record") MasterChildInfo record, @Param("example") MasterChildInfoExample example);
@UpdateProvider(type=MasterChildInfoSqlProvider.class, method="updateByExample")
int updateByExample(@Param("record") MasterChildInfo record, @Param("example") MasterChildInfoExample example);
@UpdateProvider(type=MasterChildInfoSqlProvider.class, method="updateByPrimaryKeySelective")
int updateByPrimaryKeySelective(MasterChildInfo record);
@Update({
"update master_child_info",
"set master_id = #{masterId,jdbcType=BIGINT},",
"info_type = #{infoType,jdbcType=BIGINT},",
"info_title = #{infoTitle,jdbcType=VARCHAR},",
"info_mark = #{infoMark,jdbcType=VARCHAR},",
"select_type = #{selectType,jdbcType=BIGINT},",
"operation_time = #{operationTime,jdbcType=TIMESTAMP}",
"where id = #{id,jdbcType=BIGINT}"
})
int updateByPrimaryKey(MasterChildInfo record);
}
| 5,736 | 0.726987 | 0.726987 | 111 | 50.684685 | 33.443775 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.468468 | false | false |
12
|
e8deeab3d88e539aac4cb4b7d14cec6faed3ce2c
| 20,186,346,357,104 |
1815de02e35355065e627a2d73508faf3d482000
|
/Client/src/client/Http2ClientHandler.java
|
bad8d1d7de33cad3350314fd63a25e8ae62b17b3
|
[] |
no_license
|
Trenson/HTTP2_EndlessStream
|
https://github.com/Trenson/HTTP2_EndlessStream
|
7b2f9a3f14d50563449d409d6296b4b1874902e7
|
aeab375a39ebd6b4f80ddd5f9e26a7035c537520
|
refs/heads/master
| 2020-04-05T17:26:16.686000 | 2018-11-11T08:53:38 | 2018-11-11T08:53:38 | 157,060,808 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package client;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.http2.*;
public class Http2ClientHandler extends DelegatingDecompressorFrameListener {
private Http2Request mHttp2Request;
int cnt = 0;
public Http2ClientHandler(Http2Connection connection, Http2FrameListener listener) {
super(connection, listener);
mHttp2Request = new HelloWorldHttp2HandlerBuilder().build();
}
@Override
public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream) throws Http2Exception {
System.out.println("onData: " + data + ",cnt = " + cnt);
cnt++;
if (cnt == 50 && mHttp2Request != null) {
mHttp2Request.rstStream(ctx, streamId);
}
return super.onDataRead(ctx, streamId, data, padding, endOfStream);
}
@Override
public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding, boolean endStream) throws Http2Exception {
super.onHeadersRead(ctx, streamId, headers, padding, endStream);
}
@Override
public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency, short weight, boolean exclusive, int padding, boolean endStream) throws Http2Exception {
super.onHeadersRead(ctx, streamId, headers, streamDependency, weight, exclusive, padding, endStream);
}
@Override
protected EmbeddedChannel newContentDecompressor(ChannelHandlerContext ctx, CharSequence contentEncoding) throws Http2Exception {
return super.newContentDecompressor(ctx, contentEncoding);
}
@Override
protected CharSequence getTargetContentEncoding(CharSequence contentEncoding) throws Http2Exception {
return super.getTargetContentEncoding(contentEncoding);
}
}
|
UTF-8
|
Java
| 1,944 |
java
|
Http2ClientHandler.java
|
Java
|
[] | null |
[] |
package client;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.http2.*;
public class Http2ClientHandler extends DelegatingDecompressorFrameListener {
private Http2Request mHttp2Request;
int cnt = 0;
public Http2ClientHandler(Http2Connection connection, Http2FrameListener listener) {
super(connection, listener);
mHttp2Request = new HelloWorldHttp2HandlerBuilder().build();
}
@Override
public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream) throws Http2Exception {
System.out.println("onData: " + data + ",cnt = " + cnt);
cnt++;
if (cnt == 50 && mHttp2Request != null) {
mHttp2Request.rstStream(ctx, streamId);
}
return super.onDataRead(ctx, streamId, data, padding, endOfStream);
}
@Override
public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding, boolean endStream) throws Http2Exception {
super.onHeadersRead(ctx, streamId, headers, padding, endStream);
}
@Override
public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency, short weight, boolean exclusive, int padding, boolean endStream) throws Http2Exception {
super.onHeadersRead(ctx, streamId, headers, streamDependency, weight, exclusive, padding, endStream);
}
@Override
protected EmbeddedChannel newContentDecompressor(ChannelHandlerContext ctx, CharSequence contentEncoding) throws Http2Exception {
return super.newContentDecompressor(ctx, contentEncoding);
}
@Override
protected CharSequence getTargetContentEncoding(CharSequence contentEncoding) throws Http2Exception {
return super.getTargetContentEncoding(contentEncoding);
}
}
| 1,944 | 0.744342 | 0.733539 | 46 | 41.260868 | 47.195446 | 203 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.152174 | false | false |
12
|
900567c0cfb341a01f67d4150706c2d8021c55c0
| 19,318,762,900,394 |
6e9821a5cf3f8246558b7754b0037425e8c134d5
|
/cloud/src/main/java/io/cess/cloud/ResourceRestTemplate.java
|
6b84966a7b8e6caa993c9d6181025a112f99f16f
|
[] |
no_license
|
wangjianglin/lin
|
https://github.com/wangjianglin/lin
|
6053be7abee1dcbc620c986aeee523814b67af40
|
553714dc880e6dc48767300951fc86da098b20f4
|
refs/heads/master
| 2020-04-17T08:53:04.950000 | 2018-03-10T17:20:11 | 2018-03-10T17:20:11 | 25,158,190 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package io.cess.cloud;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URI;
/**
* @author lin
* @date 28/06/2017.
*/
public class ResourceRestTemplate extends RestTemplate {
@Value("${io.cess.gzip:false}")
private boolean gzip = false;
@Override
protected ClientHttpRequest createRequest(URI url, HttpMethod method) throws IOException {
final ClientHttpRequest request = super.createRequest(url, method);
HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
request.getHeaders().add("authorization", httpServletRequest.getHeader("authorization"));
if(gzip){
request.getHeaders().add("Accept-Encoding","gzip,deflate");
}
return request;
}
public boolean isGzip() {
return gzip;
}
public void setGzip(boolean gzip) {
this.gzip = gzip;
}
}
|
UTF-8
|
Java
| 1,332 |
java
|
ResourceRestTemplate.java
|
Java
|
[
{
"context": ".IOException;\nimport java.net.URI;\n\n/**\n * @author lin\n * @date 28/06/2017.\n */\npublic class ResourceRes",
"end": 494,
"score": 0.9815096855163574,
"start": 491,
"tag": "USERNAME",
"value": "lin"
}
] | null |
[] |
package io.cess.cloud;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URI;
/**
* @author lin
* @date 28/06/2017.
*/
public class ResourceRestTemplate extends RestTemplate {
@Value("${io.cess.gzip:false}")
private boolean gzip = false;
@Override
protected ClientHttpRequest createRequest(URI url, HttpMethod method) throws IOException {
final ClientHttpRequest request = super.createRequest(url, method);
HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
request.getHeaders().add("authorization", httpServletRequest.getHeader("authorization"));
if(gzip){
request.getHeaders().add("Accept-Encoding","gzip,deflate");
}
return request;
}
public boolean isGzip() {
return gzip;
}
public void setGzip(boolean gzip) {
this.gzip = gzip;
}
}
| 1,332 | 0.735736 | 0.72973 | 43 | 29.976744 | 31.744246 | 134 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.534884 | false | false |
12
|
8975693b6e60b7d5a7a8e2bac6c578e705af2617
| 19,318,762,900,295 |
6ebee68c4561dadec3e96d7158c99ccee775b64c
|
/FinancialReportingTool/src/com/frt/service/ProjectService.java
|
cc7e58d5b261be4544f0e65acfaaf91fb7cbc0f3
|
[] |
no_license
|
juhisoni4/CD-Assignment
|
https://github.com/juhisoni4/CD-Assignment
|
2203761f1c7d5d477b30af568db35deb3d6f36ef
|
b38ed5ecd80aed92f4694349f7b3dfb5fc3def1e
|
refs/heads/master
| 2020-07-26T03:30:20.887000 | 2019-01-16T15:31:03 | 2019-01-16T15:31:03 | 73,737,328 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.frt.service;
import java.util.List;
import com.frt.model.Project;
public interface ProjectService {
public void saveProject(Project project);
public Project getProjectById(Long id);
public List<Project> getAllProject();
public List<Project> search(Project Project);
}
|
UTF-8
|
Java
| 292 |
java
|
ProjectService.java
|
Java
|
[] | null |
[] |
package com.frt.service;
import java.util.List;
import com.frt.model.Project;
public interface ProjectService {
public void saveProject(Project project);
public Project getProjectById(Long id);
public List<Project> getAllProject();
public List<Project> search(Project Project);
}
| 292 | 0.773973 | 0.773973 | 16 | 17.25 | 17.949583 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false |
12
|
110e262b078e1f0863e982de43f6a64938c7b784
| 20,040,317,450,830 |
896a1976d66cbcc6ebffb00dd251e130bda85795
|
/test/org/sglaser/invest/funder/data/DataTest.java
|
e283f35e9ae86b8ce737d25595f931e36fe6df80
|
[] |
no_license
|
rsg00usa/funder
|
https://github.com/rsg00usa/funder
|
4ba3bf5b1c3fd99d325f3a4d93171b225a48855a
|
e247c582e3990449a08cbd83f6d85a994548d7b2
|
refs/heads/master
| 2021-01-10T04:26:03.532000 | 2015-12-19T21:35:02 | 2015-12-19T21:35:02 | 45,587,594 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.sglaser.invest.funder.data;
import java.util.Collection;
import java.util.Iterator;
import com.vaadin.data.Item;
import com.vaadin.data.util.sqlcontainer.SQLContainer;
import com.vaadin.external.org.slf4j.Logger;
import com.vaadin.external.org.slf4j.LoggerFactory;
public class DataTest {
private static final Logger LOG = LoggerFactory.getLogger(DataTest.class);
public static void main(String[] args) {
LOG.info("Create simple test to verify it works");
DBConnector dbcon = new DBConnector();
SQLContainer sqlcon = dbcon.getSQLContainer("history");
System.out.println("Number of items(rows): " + sqlcon.size() + " row ids: " + sqlcon.getItemIds());
System.out.println("Last item: " + sqlcon.getItem(sqlcon.lastItemId()));
System.out.println("Last item id: " + sqlcon.lastItemId());
Item item = sqlcon.getItem(sqlcon.lastItemId());
Collection<?> list = item.getItemPropertyIds();
for (Iterator<?> it = list.iterator(); it.hasNext();) {
System.out.println("Property: " + (String) it.next());
}
System.out.println("Number of properties per item: " + list.size());
}
}
|
UTF-8
|
Java
| 1,114 |
java
|
DataTest.java
|
Java
|
[] | null |
[] |
package org.sglaser.invest.funder.data;
import java.util.Collection;
import java.util.Iterator;
import com.vaadin.data.Item;
import com.vaadin.data.util.sqlcontainer.SQLContainer;
import com.vaadin.external.org.slf4j.Logger;
import com.vaadin.external.org.slf4j.LoggerFactory;
public class DataTest {
private static final Logger LOG = LoggerFactory.getLogger(DataTest.class);
public static void main(String[] args) {
LOG.info("Create simple test to verify it works");
DBConnector dbcon = new DBConnector();
SQLContainer sqlcon = dbcon.getSQLContainer("history");
System.out.println("Number of items(rows): " + sqlcon.size() + " row ids: " + sqlcon.getItemIds());
System.out.println("Last item: " + sqlcon.getItem(sqlcon.lastItemId()));
System.out.println("Last item id: " + sqlcon.lastItemId());
Item item = sqlcon.getItem(sqlcon.lastItemId());
Collection<?> list = item.getItemPropertyIds();
for (Iterator<?> it = list.iterator(); it.hasNext();) {
System.out.println("Property: " + (String) it.next());
}
System.out.println("Number of properties per item: " + list.size());
}
}
| 1,114 | 0.723519 | 0.721723 | 30 | 36.133335 | 27.778568 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.633333 | false | false |
12
|
3e1e496b8a1e86558765ce0079644f99e17807f4
| 29,463,475,698,705 |
136bb5d9030fa1519855eb02c9a90271bce40e89
|
/xueyinyin/src/com/blb/bean/User.java
|
e8ada59232ffbe94cc19109df7c1a33485a4e6e9
|
[] |
no_license
|
2274650112/test
|
https://github.com/2274650112/test
|
f5386c5b05a454ea6ee76b5d71a6dd0bb4efa36a
|
1fac1d5a78082612dc9e9db5abd343d9dc79f349
|
refs/heads/master
| 2020-11-28T04:18:17.587000 | 2020-05-07T02:24:27 | 2020-05-07T02:24:27 | 229,701,039 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.blb.bean;
/**
* @Author: cxk
* @Description:用户表
* @Date: Created in 11:16 2019/12/20
*/
public class User {
private Integer userid;// bigint(30) NOT NULL AUTO_INCREMENT COMMENT '用户id',
private String username;// varchar(50) DEFAULT NULL COMMENT '用户真实姓名',
private String nickname;// varchar(100) DEFAULT NULL COMMENT '用户昵称',
private String password;// varchar(50) DEFAULT NULL COMMENT '密码',
private String email;// varchar(50) DEFAULT NULL COMMENT '邮箱',
private String phone;// varchar(20) DEFAULT NULL COMMENT '手机号码',
private Integer deptid;// bigint(30) DEFAULT NULL COMMENT '部门ID',
private Integer roleid;// bigint(30) DEFAULT NULL COMMENT '角色ID',
private Integer sex;// int(1) DEFAULT '0' COMMENT '性别 0男 1女',
private String note;// varchar(200) DEFAULT NULL COMMENT '备注',
private Integer ischange ;//int(1) DEFAULT '0' COMMENT '是否修改密码 0无1修改',
private String remember;
public User() {
}
public User(Integer userid, String username, String nickname, String password, String email, String phone, Integer deptid, Integer roleid, Integer sex, String note, Integer ischange, String remember) {
this.userid = userid;
this.username = username;
this.nickname = nickname;
this.password = password;
this.email = email;
this.phone = phone;
this.deptid = deptid;
this.roleid = roleid;
this.sex = sex;
this.note = note;
this.ischange = ischange;
this.remember = remember;
}
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Integer getDeptid() {
return deptid;
}
public void setDeptid(Integer deptid) {
this.deptid = deptid;
}
public Integer getRoleid() {
return roleid;
}
public void setRoleid(Integer roleid) {
this.roleid = roleid;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public Integer getIschange() {
return ischange;
}
public void setIschange(Integer ischange) {
this.ischange = ischange;
}
public String getRemember() {
return remember;
}
public void setRemember(String remember) {
this.remember = remember;
}
}
|
UTF-8
|
Java
| 3,363 |
java
|
User.java
|
Java
|
[
{
"context": "package com.blb.bean;\n\n/**\n * @Author: cxk\n * @Description:用户表\n * @Date: Created in 11:16 20",
"end": 42,
"score": 0.999711275100708,
"start": 39,
"tag": "USERNAME",
"value": "cxk"
},
{
"context": " this.userid = userid;\n this.username = username;\n this.nickname = nickname;\n this.p",
"end": 1235,
"score": 0.9808772206306458,
"start": 1227,
"tag": "USERNAME",
"value": "username"
},
{
"context": " this.nickname = nickname;\n this.password = password;\n this.email = email;\n this.phone =",
"end": 1303,
"score": 0.9991772174835205,
"start": 1295,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "sername(String username) {\n this.username = username;\n }\n\n public String getNickname() {\n ",
"end": 1835,
"score": 0.7755782604217529,
"start": 1827,
"tag": "USERNAME",
"value": "username"
}
] | null |
[] |
package com.blb.bean;
/**
* @Author: cxk
* @Description:用户表
* @Date: Created in 11:16 2019/12/20
*/
public class User {
private Integer userid;// bigint(30) NOT NULL AUTO_INCREMENT COMMENT '用户id',
private String username;// varchar(50) DEFAULT NULL COMMENT '用户真实姓名',
private String nickname;// varchar(100) DEFAULT NULL COMMENT '用户昵称',
private String password;// varchar(50) DEFAULT NULL COMMENT '密码',
private String email;// varchar(50) DEFAULT NULL COMMENT '邮箱',
private String phone;// varchar(20) DEFAULT NULL COMMENT '手机号码',
private Integer deptid;// bigint(30) DEFAULT NULL COMMENT '部门ID',
private Integer roleid;// bigint(30) DEFAULT NULL COMMENT '角色ID',
private Integer sex;// int(1) DEFAULT '0' COMMENT '性别 0男 1女',
private String note;// varchar(200) DEFAULT NULL COMMENT '备注',
private Integer ischange ;//int(1) DEFAULT '0' COMMENT '是否修改密码 0无1修改',
private String remember;
public User() {
}
public User(Integer userid, String username, String nickname, String password, String email, String phone, Integer deptid, Integer roleid, Integer sex, String note, Integer ischange, String remember) {
this.userid = userid;
this.username = username;
this.nickname = nickname;
this.password = <PASSWORD>;
this.email = email;
this.phone = phone;
this.deptid = deptid;
this.roleid = roleid;
this.sex = sex;
this.note = note;
this.ischange = ischange;
this.remember = remember;
}
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Integer getDeptid() {
return deptid;
}
public void setDeptid(Integer deptid) {
this.deptid = deptid;
}
public Integer getRoleid() {
return roleid;
}
public void setRoleid(Integer roleid) {
this.roleid = roleid;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public Integer getIschange() {
return ischange;
}
public void setIschange(Integer ischange) {
this.ischange = ischange;
}
public String getRemember() {
return remember;
}
public void setRemember(String remember) {
this.remember = remember;
}
}
| 3,365 | 0.613602 | 0.601403 | 135 | 23.288889 | 25.740259 | 205 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.525926 | false | false |
12
|
798b62150ee109ba3889ddfcae9c0c2d8c080dd3
| 24,824,911,020,310 |
b21b63f4a6928317e9163f25d4f6d1ca7ba289e8
|
/app/src/main/java/com/example/hotelhealthy2/Tips16.java
|
b625c47b166fb1769849ba58cf998a015f09ad8c
|
[] |
no_license
|
neirautomatae/ProjectHotelHealthy
|
https://github.com/neirautomatae/ProjectHotelHealthy
|
869bc4fb983eef0f2e6f5d314f532c05d066ee3a
|
2da6f486c638ff22f5f7ce0b331764510b433133
|
refs/heads/master
| 2020-07-07T12:31:55.286000 | 2019-08-20T09:56:02 | 2019-08-20T09:56:02 | 203,348,584 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.hotelhealthy2;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Tips16 extends AppCompatActivity {
private Button backtips16;
private Button hometips16;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tips16);
backtips16 = findViewById(R.id.btnbktips16);
hometips16 = findViewById(R.id.btnhometips16);
backtips16.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
hometips16.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent hometips16 = new Intent(Tips16.this , MainActivity.class);
finish();
startActivity(hometips16);
}
});
}
}
|
UTF-8
|
Java
| 1,093 |
java
|
Tips16.java
|
Java
|
[] | null |
[] |
package com.example.hotelhealthy2;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Tips16 extends AppCompatActivity {
private Button backtips16;
private Button hometips16;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tips16);
backtips16 = findViewById(R.id.btnbktips16);
hometips16 = findViewById(R.id.btnhometips16);
backtips16.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
hometips16.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent hometips16 = new Intent(Tips16.this , MainActivity.class);
finish();
startActivity(hometips16);
}
});
}
}
| 1,093 | 0.639524 | 0.614822 | 39 | 27.02564 | 21.953899 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.487179 | false | false |
12
|
4aad4353ef869039a547307557576b6340d0a68b
| 8,203,387,589,294 |
757fb3d8698f0b01fb8b41df114d9241c2889a5c
|
/src/ch/renklus/java/i/unterricht/TestClass2.java
|
873d0412995b99d26e91dc4579d800c951caea99
|
[] |
no_license
|
renklus/OO-Tests
|
https://github.com/renklus/OO-Tests
|
4c22f303759c83e8e142e821cd6e45904a9adf03
|
e3032ee77c43c35f20fb1b4e65ebd683e01154ba
|
refs/heads/master
| 2021-08-14T11:32:04.051000 | 2017-11-15T12:39:12 | 2017-11-15T12:39:12 | 110,809,393 | 0 | 0 | null | false | 2017-11-15T12:37:32 | 2017-11-15T09:00:37 | 2017-11-15T12:17:35 | 2017-11-15T12:37:32 | 0 | 0 | 0 | 0 |
Java
| false | null |
package ch.renklus.java.i.unterricht;
public class TestClass2 extends TestClass {
@Override
public String MyMethod()
{
super.MyMethod();
return "TestClass2";
}
}
|
UTF-8
|
Java
| 196 |
java
|
TestClass2.java
|
Java
|
[] | null |
[] |
package ch.renklus.java.i.unterricht;
public class TestClass2 extends TestClass {
@Override
public String MyMethod()
{
super.MyMethod();
return "TestClass2";
}
}
| 196 | 0.637755 | 0.627551 | 11 | 16.818182 | 15.134657 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.272727 | false | false |
12
|
13044ea57490b7774e4342c77dcba3bc9bd3d8ac
| 14,345,190,768,948 |
8cf0f342a3f19186b8fbba3f7ca5fa093dd3d322
|
/src/main/java/listener/FailureScreenShotListener.java
|
c0a8c61bd00f608a9393bc36a587d866b3b6db60
|
[] |
no_license
|
shchurkobohdan/mobymax
|
https://github.com/shchurkobohdan/mobymax
|
8e8a38608300fcf68bdbe4409890a729477927fb
|
dbbf368b35b94e5c626cda9814d04706f589a68d
|
refs/heads/master
| 2023-04-03T06:33:11.473000 | 2021-04-05T19:44:24 | 2021-04-05T19:44:24 | 340,159,829 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package listener;
import driver.WebDriverFactory;
import io.qameta.allure.Attachment;
import io.qameta.allure.Step;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
@Slf4j
public class FailureScreenShotListener extends TestListenerAdapter {
@Override
public void onTestFailure(ITestResult result) {
makeScreenshotOnFinish(WebDriverFactory.getDriver());
}
@Step("Screenshot attachment")
public void makeScreenshotOnFinish(WebDriver driver) {
getScreenshot(driver);
}
@Attachment(value = "Screenshot after test", type = "image/png")
public byte[] getScreenshot(WebDriver driver) {
log.info("Taking the screenshot on test failure");
File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
byte[] screen = null;
try {
screen = IOUtils.toByteArray(new FileInputStream(screenshot));
} catch (IOException e) {
e.printStackTrace();
}
return screen;
}
}
|
UTF-8
|
Java
| 1,203 |
java
|
FailureScreenShotListener.java
|
Java
|
[] | null |
[] |
package listener;
import driver.WebDriverFactory;
import io.qameta.allure.Attachment;
import io.qameta.allure.Step;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
@Slf4j
public class FailureScreenShotListener extends TestListenerAdapter {
@Override
public void onTestFailure(ITestResult result) {
makeScreenshotOnFinish(WebDriverFactory.getDriver());
}
@Step("Screenshot attachment")
public void makeScreenshotOnFinish(WebDriver driver) {
getScreenshot(driver);
}
@Attachment(value = "Screenshot after test", type = "image/png")
public byte[] getScreenshot(WebDriver driver) {
log.info("Taking the screenshot on test failure");
File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
byte[] screen = null;
try {
screen = IOUtils.toByteArray(new FileInputStream(screenshot));
} catch (IOException e) {
e.printStackTrace();
}
return screen;
}
}
| 1,203 | 0.779717 | 0.777224 | 44 | 26.34091 | 21.82778 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.272727 | false | false |
12
|
9996d193ae9217327ed04dcfff4fe0efda58c1e5
| 14,345,190,771,397 |
c856326a42e5a46494f6f8e1199de214053ae8f8
|
/src/UpTo400/Problem374.java
|
8bc39b11c37e350ad33507e39567c2c2945ee4b7
|
[] |
no_license
|
siyile/leetcode
|
https://github.com/siyile/leetcode
|
548f3a3ad3cf2590bd271c0f2b5977287793f87c
|
8d2ec581f9966b0ca19eec20e86b77c39eb1e840
|
refs/heads/master
| 2021-06-16T21:30:46.303000 | 2021-02-19T03:50:35 | 2021-02-19T03:50:35 | 165,610,794 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package UpTo400;
public class Problem374 {
int guess(int num) {
return 0;
}
public int guessNumber(int n) {
int left = 1, right = n;
while (left <= right) {
int mid = (right - left) / 2 + left;
int res = guess(mid);
if (res == 0) return mid;
else if (res == 1) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
}
|
UTF-8
|
Java
| 486 |
java
|
Problem374.java
|
Java
|
[] | null |
[] |
package UpTo400;
public class Problem374 {
int guess(int num) {
return 0;
}
public int guessNumber(int n) {
int left = 1, right = n;
while (left <= right) {
int mid = (right - left) / 2 + left;
int res = guess(mid);
if (res == 0) return mid;
else if (res == 1) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
}
| 486 | 0.401235 | 0.372428 | 22 | 21.09091 | 13.42626 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false |
12
|
e5976ee7c8da4f6256213cc1b305dcbe582b1b67
| 17,085,379,932,837 |
2f6d39c2daf70ebaae90e72ca503f8b275d3572a
|
/test/debug_info/InlineTestCode.java
|
b7481ec0a8e1c1bf09d34f491943b90e6f016881
|
[
"MIT"
] |
permissive
|
facebook/redex
|
https://github.com/facebook/redex
|
5a39c5b733e729ecb52101dd3f941a63f9fa32f0
|
36c6607be749ba2009210aae404d68cd57e747eb
|
refs/heads/main
| 2023-09-01T18:21:21.839000 | 2023-09-01T02:01:59 | 2023-09-01T02:01:59 | 54,664,770 | 6,459 | 775 |
MIT
| false | 2023-08-25T00:06:04 | 2016-03-24T18:26:35 | 2023-08-23T16:34:48 | 2023-08-25T00:06:00 | 36,242 | 5,896 | 674 | 74 |
C++
| false | false |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.redexlinemap;
import static org.assertj.core.api.Assertions.assertThat;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
public class InlineTestCode {
LineMapperV2 lm;
public InlineTestCode(LineMapperV2 lm) {
this.lm = lm;
}
/** Check that the stack trace of a non-inlined function makes sense. */
@NoInline
@SuppressWarnings("CatchGeneralException")
public void testBasic() throws Exception {
try {
InlineSeparateFileV2.wrapsThrow();
} catch (Exception e) {
assertRawStackSize(e, 2, "testBasic");
ArrayList<StackTraceElement> trace = lm.mapStackTrace(e.getStackTrace());
assertThat(TraceUtil.traceToString(trace, 2))
.isEqualTo(
Arrays.asList(
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrow(InlineSeparateFileV2.java:12)",
"com.facebook.redexlinemap.InlineTestCode.testBasic(InlineTestCode.java:30)"));
}
}
/** Check the stack trace of a once-inlined function. */
@NoInline
@SuppressWarnings("CatchGeneralException")
public void testInlineOnce() throws Exception {
try {
InlineSeparateFileV2.inlineOnce();
} catch (Exception e) {
assertRawStackSize(e, 2, "testInlineOnce");
ArrayList<StackTraceElement> trace = lm.mapStackTrace(e.getStackTrace());
assertThat(TraceUtil.traceToString(trace, 3))
.isEqualTo(
Arrays.asList(
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrow(InlineSeparateFileV2.java:12)",
"com.facebook.redexlinemap.InlineSeparateFileV2.inlineOnce(InlineSeparateFileV2.java:16)",
"com.facebook.redexlinemap.InlineTestCode.testInlineOnce(InlineTestCode.java:47)"));
}
}
/** Check the stack trace of a multiply-inlined function. */
@NoInline
@SuppressWarnings("CatchGeneralException")
public void testInlineTwice() throws Exception {
try {
InlineSeparateFileV2.inlineTwice();
} catch (Exception e) {
assertRawStackSize(e, 2, "testInlineTwice");
ArrayList<StackTraceElement> trace = lm.mapStackTrace(e.getStackTrace());
assertThat(TraceUtil.traceToString(trace, 4))
.isEqualTo(
Arrays.asList(
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrow(InlineSeparateFileV2.java:12)",
"com.facebook.redexlinemap.InlineSeparateFileV2.inlineOnce1(InlineSeparateFileV2.java:20)",
"com.facebook.redexlinemap.InlineSeparateFileV2.inlineTwice(InlineSeparateFileV2.java:24)",
"com.facebook.redexlinemap.InlineTestCode.testInlineTwice(InlineTestCode.java:65)"));
}
}
private static int inlineMe() {
return 1;
}
@NoInline
private void ignoreAndThrow(Object x) throws Exception {
throw new RuntimeException("foo");
}
/**
* Check that the line number is reset to the original for the code that follows an inlined
* method. We expect the resulting stack trace *not* to point to inlineMe().
*/
@NoInline
@SuppressWarnings("CatchGeneralException")
public void testPositionReset() throws Exception {
try {
ignoreAndThrow(inlineMe());
} catch (Exception e) {
assertRawStackSize(e, 2, "testPositionReset");
ArrayList<StackTraceElement> trace = lm.mapStackTrace(e.getStackTrace());
assertThat(TraceUtil.traceToString(trace, 2))
.isEqualTo(
Arrays.asList(
"com.facebook.redexlinemap.InlineTestCode.ignoreAndThrow(InlineTestCode.java:85)",
"com.facebook.redexlinemap.InlineTestCode.testPositionReset(InlineTestCode.java:96)"));
}
}
private void elseThrows() throws Exception {
if (lm == null) {
System.out.println("");
} else {
InlineSeparateFileV2.wrapsThrow();
}
}
@NoInline
@SuppressWarnings("CatchGeneralException")
public void testElseThrows() throws Exception {
try {
elseThrows();
} catch (Exception e) {
assertRawStackSize(e, 2, "testElseThrows");
ArrayList<StackTraceElement> trace = lm.mapStackTrace(e.getStackTrace());
assertThat(TraceUtil.traceToString(trace, 3))
.isEqualTo(
Arrays.asList(
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrow(InlineSeparateFileV2.java:12)",
"com.facebook.redexlinemap.InlineTestCode.elseThrows(InlineTestCode.java:112)",
"com.facebook.redexlinemap.InlineTestCode.testElseThrows(InlineTestCode.java:120)"));
}
}
@NoInline
private void elseThrows(int i) throws Exception {
if (lm == null) {
System.out.println(i);
} else {
InlineSeparateFileV2.wrapsThrow();
}
}
@NoInline
private void elseThrows(char c) throws Exception {
if (lm != null) { // Intentionally changed order.
InlineSeparateFileV2.wrapsThrow();
} else {
System.out.println(c);
}
}
@NoInline
private void elseThrows(float f) throws Exception {
if (lm == null) {
System.out.println(f);
} else {
InlineSeparateFileV2.wrapsThrow();
}
}
@NoInline
private void elseThrows(Object o) throws Exception {
if (lm != null) { // Intentionally changed order.
InlineSeparateFileV2.wrapsThrow();
} else {
System.out.println(o);
}
}
@NoInline
@SuppressWarnings("CatchGeneralException")
public void testElseThrowsOverload(OverloadCheck oc) throws Exception {
HashSet<StackTraceElement> frames = new HashSet<>();
try {
elseThrows((int)0);
} catch (Exception e) {
assertRawStackSize(e, 3, "testElseThrowsOverload");
frames.add(e.getStackTrace()[1]);
ArrayList<StackTraceElement> trace = lm.mapStackTrace(e.getStackTrace());
assertThat(TraceUtil.traceToString(trace, 3))
.isEqualTo(
Arrays.asList(
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrow(InlineSeparateFileV2.java:12)",
"com.facebook.redexlinemap.InlineTestCode.elseThrows(InlineTestCode.java:138)",
"com.facebook.redexlinemap.InlineTestCode.testElseThrowsOverload(InlineTestCode.java:174)"));
}
try {
elseThrows('a');
} catch (Exception e) {
assertRawStackSize(e, 3, "testElseThrowsOverload");
frames.add(e.getStackTrace()[1]);
ArrayList<StackTraceElement> trace = lm.mapStackTrace(e.getStackTrace());
assertThat(TraceUtil.traceToString(trace, 3))
.isEqualTo(
Arrays.asList(
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrow(InlineSeparateFileV2.java:12)",
"com.facebook.redexlinemap.InlineTestCode.elseThrows(InlineTestCode.java:145)",
"com.facebook.redexlinemap.InlineTestCode.testElseThrowsOverload(InlineTestCode.java:188)"));
}
try {
elseThrows(0.1f);
} catch (Exception e) {
assertRawStackSize(e, 3, "testElseThrowsOverload");
frames.add(e.getStackTrace()[1]);
ArrayList<StackTraceElement> trace = lm.mapStackTrace(e.getStackTrace());
assertThat(TraceUtil.traceToString(trace, 3))
.isEqualTo(
Arrays.asList(
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrow(InlineSeparateFileV2.java:12)",
"com.facebook.redexlinemap.InlineTestCode.elseThrows(InlineTestCode.java:156)",
"com.facebook.redexlinemap.InlineTestCode.testElseThrowsOverload(InlineTestCode.java:202)"));
}
try {
elseThrows(null);
} catch (Exception e) {
assertRawStackSize(e, 3, "testElseThrowsOverload");
frames.add(e.getStackTrace()[1]);
ArrayList<StackTraceElement> trace = lm.mapStackTrace(e.getStackTrace());
assertThat(TraceUtil.traceToString(trace, 3))
.isEqualTo(
Arrays.asList(
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrow(InlineSeparateFileV2.java:12)",
"com.facebook.redexlinemap.InlineTestCode.elseThrows(InlineTestCode.java:163)",
"com.facebook.redexlinemap.InlineTestCode.testElseThrowsOverload(InlineTestCode.java:216)"));
}
// Check that all `elseThrows` functions exist (not inlined).
HashSet<Method> methods = new HashSet<>();
for (Method m : getClass().getDeclaredMethods()) {
if (m.getName().equals("elseThrows")) {
methods.add(m);
}
}
assertThat(methods).hasSize(4);
// Extra checks?
if (oc != null) {
oc.check(frames);
}
}
public interface OverloadCheck {
public void check(HashSet<StackTraceElement> frames);
}
public static void checkTests(Class<?> cls) throws Exception {
HashSet<String> expected = getTestNamedMethods(InlineTestCode.class);
HashSet<String> actual = getTestNamedMethods(cls);
assertThat(actual).isEqualTo(expected);
}
private static HashSet<String> getTestNamedMethods(Class<?> cls) throws Exception {
HashSet<String> res = new HashSet<>();
for (Method m : cls.getDeclaredMethods()) {
String name = m.getName();
if (name.startsWith("test")) {
res.add(name);
}
}
return res;
}
private static void assertRawStackSize(Throwable t, int size, String expectedMethod) {
assertRawStackSize(t, size, expectedMethod, InlineTestCode.class.getName());
}
private static void assertRawStackSize(Throwable t, int size, String expectedMethod, String expectedClass) {
StackTraceElement[] trace = t.getStackTrace();
assertThat(trace.length).isGreaterThanOrEqualTo(size);
assertThat(trace[size - 1].getMethodName()).isEqualTo(expectedMethod);
if (expectedClass != null) {
assertThat(trace[size - 1].getClassName()).endsWith(expectedClass);
}
}
@NoInline
@SuppressWarnings("CatchGeneralException")
public void testOutlined() throws Exception {
try {
InlineSeparateFileV2.counter = 1;
InlineSeparateFileV2.outlinedThrower();
} catch (Exception e) {
ArrayList<StackTraceElement> trace = lm.mapStackTrace(e.getStackTrace());
assertThat(TraceUtil.traceToString(trace, 4))
.isEqualTo(
Arrays.asList(
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrow2(InlineSeparateFileV2.java:32)",
"com.facebook.redexlinemap.InlineSeparateFileV2.outlinedThrower(InlineSeparateFileV2.java:38)",
"com.redex.Outlined$0$0$0.$outlined$0$88687b1b5dba69a0(RedexGenerated)", // ideally, we wouldn't see this
"com.facebook.redexlinemap.InlineTestCode.testOutlined(InlineTestCode.java:282)"));
}
try {
InlineSeparateFileV2.counter = 2;
InlineSeparateFileV2.outlinedThrower();
} catch (Exception e) {
ArrayList<StackTraceElement> trace = lm.mapStackTrace(e.getStackTrace());
assertThat(TraceUtil.traceToString(trace, 4))
.isEqualTo(
Arrays.asList(
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrow2(InlineSeparateFileV2.java:32)",
"com.facebook.redexlinemap.InlineSeparateFileV2.outlinedThrower(InlineSeparateFileV2.java:39)",
"com.redex.Outlined$0$0$0.$outlined$0$88687b1b5dba69a0(RedexGenerated)",
"com.facebook.redexlinemap.InlineTestCode.testOutlined(InlineTestCode.java:296)"));
}
try {
InlineSeparateFileV2.counter = 3;
InlineSeparateFileV2.outlinedThrower();
} catch (Exception e) {
ArrayList<StackTraceElement> trace = lm.mapStackTrace(e.getStackTrace());
assertThat(TraceUtil.traceToString(trace, 4))
.isEqualTo(
Arrays.asList(
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrow2(InlineSeparateFileV2.java:32)",
"com.facebook.redexlinemap.InlineSeparateFileV2.outlinedThrower(InlineSeparateFileV2.java:40)",
"com.redex.Outlined$0$0$0.$outlined$0$88687b1b5dba69a0(RedexGenerated)",
"com.facebook.redexlinemap.InlineTestCode.testOutlined(InlineTestCode.java:310)"));
}
try {
InlineSeparateFileV2.counter = 42;
InlineSeparateFileV2.outlinedThrower();
} catch (Exception e) {
ArrayList<StackTraceElement> trace = lm.mapStackTrace(e.getStackTrace());
assertThat(TraceUtil.traceToString(trace, 4))
.isEqualTo(
Arrays.asList(
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrow2(InlineSeparateFileV2.java:32)",
"com.facebook.redexlinemap.InlineSeparateFileV2.outlinedThrower(InlineSeparateFileV2.java:39)", // <-- wrong, should be :79
"com.redex.Outlined$0$0$0.$outlined$0$88687b1b5dba69a0(RedexGenerated)",
"com.facebook.redexlinemap.InlineTestCode.testOutlined(InlineTestCode.java:324)"));
}
}
@NoInline
@SuppressWarnings("CatchGeneralException")
public void testOutlinedInlined() throws Exception {
try {
InlineSeparateFileV2.counter = 1;
InlineSeparateFileV2.outlinedThrowerInlined();
} catch (Exception e) {
ArrayList<StackTraceElement> trace = lm.mapStackTrace(e.getStackTrace());
assertThat(TraceUtil.traceToString(trace, 5))
.isEqualTo(
Arrays.asList(
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrow3(InlineSeparateFileV2.java:91)",
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrowInline(InlineSeparateFileV2.java:97)",
"com.facebook.redexlinemap.InlineSeparateFileV2.outlinedThrowerInlined(InlineSeparateFileV2.java:102)",
"com.redex.Outlined$0$0$0.$outlined$0$886bb44310f1a408(RedexGenerated)",
"com.facebook.redexlinemap.InlineTestCode.testOutlinedInlined(InlineTestCode.java:342)"));
}
try {
InlineSeparateFileV2.counter = 2;
InlineSeparateFileV2.outlinedThrowerInlined();
} catch (Exception e) {
ArrayList<StackTraceElement> trace = lm.mapStackTrace(e.getStackTrace());
assertThat(TraceUtil.traceToString(trace, 5))
.isEqualTo(
Arrays.asList(
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrow3(InlineSeparateFileV2.java:91)",
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrowInline(InlineSeparateFileV2.java:97)",
"com.facebook.redexlinemap.InlineSeparateFileV2.outlinedThrowerInlined(InlineSeparateFileV2.java:103)",
"com.redex.Outlined$0$0$0.$outlined$0$886bb44310f1a408(RedexGenerated)",
"com.facebook.redexlinemap.InlineTestCode.testOutlinedInlined(InlineTestCode.java:357)"));
}
try {
InlineSeparateFileV2.counter = 3;
InlineSeparateFileV2.outlinedThrowerInlined();
} catch (Exception e) {
ArrayList<StackTraceElement> trace = lm.mapStackTrace(e.getStackTrace());
assertThat(TraceUtil.traceToString(trace, 5))
.isEqualTo(
Arrays.asList(
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrow3(InlineSeparateFileV2.java:91)",
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrowInline(InlineSeparateFileV2.java:97)",
"com.facebook.redexlinemap.InlineSeparateFileV2.outlinedThrowerInlined(InlineSeparateFileV2.java:104)",
"com.redex.Outlined$0$0$0.$outlined$0$886bb44310f1a408(RedexGenerated)",
"com.facebook.redexlinemap.InlineTestCode.testOutlinedInlined(InlineTestCode.java:372)"));
}
try {
InlineSeparateFileV2.counter = 42;
InlineSeparateFileV2.outlinedThrowerInlined();
} catch (Exception e) {
ArrayList<StackTraceElement> trace = lm.mapStackTrace(e.getStackTrace());
assertThat(TraceUtil.traceToString(trace, 5))
.isEqualTo(
Arrays.asList(
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrow3(InlineSeparateFileV2.java:91)",
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrowInline(InlineSeparateFileV2.java:97)",
"com.facebook.redexlinemap.InlineSeparateFileV2.outlinedThrowerInlined(InlineSeparateFileV2.java:103)", // <-- wrong, should be :143
"com.redex.Outlined$0$0$0.$outlined$0$886bb44310f1a408(RedexGenerated)",
"com.facebook.redexlinemap.InlineTestCode.testOutlinedInlined(InlineTestCode.java:387)"));
}
}
}
|
UTF-8
|
Java
| 16,802 |
java
|
InlineTestCode.java
|
Java
|
[] | null |
[] |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.redexlinemap;
import static org.assertj.core.api.Assertions.assertThat;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
public class InlineTestCode {
LineMapperV2 lm;
public InlineTestCode(LineMapperV2 lm) {
this.lm = lm;
}
/** Check that the stack trace of a non-inlined function makes sense. */
@NoInline
@SuppressWarnings("CatchGeneralException")
public void testBasic() throws Exception {
try {
InlineSeparateFileV2.wrapsThrow();
} catch (Exception e) {
assertRawStackSize(e, 2, "testBasic");
ArrayList<StackTraceElement> trace = lm.mapStackTrace(e.getStackTrace());
assertThat(TraceUtil.traceToString(trace, 2))
.isEqualTo(
Arrays.asList(
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrow(InlineSeparateFileV2.java:12)",
"com.facebook.redexlinemap.InlineTestCode.testBasic(InlineTestCode.java:30)"));
}
}
/** Check the stack trace of a once-inlined function. */
@NoInline
@SuppressWarnings("CatchGeneralException")
public void testInlineOnce() throws Exception {
try {
InlineSeparateFileV2.inlineOnce();
} catch (Exception e) {
assertRawStackSize(e, 2, "testInlineOnce");
ArrayList<StackTraceElement> trace = lm.mapStackTrace(e.getStackTrace());
assertThat(TraceUtil.traceToString(trace, 3))
.isEqualTo(
Arrays.asList(
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrow(InlineSeparateFileV2.java:12)",
"com.facebook.redexlinemap.InlineSeparateFileV2.inlineOnce(InlineSeparateFileV2.java:16)",
"com.facebook.redexlinemap.InlineTestCode.testInlineOnce(InlineTestCode.java:47)"));
}
}
/** Check the stack trace of a multiply-inlined function. */
@NoInline
@SuppressWarnings("CatchGeneralException")
public void testInlineTwice() throws Exception {
try {
InlineSeparateFileV2.inlineTwice();
} catch (Exception e) {
assertRawStackSize(e, 2, "testInlineTwice");
ArrayList<StackTraceElement> trace = lm.mapStackTrace(e.getStackTrace());
assertThat(TraceUtil.traceToString(trace, 4))
.isEqualTo(
Arrays.asList(
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrow(InlineSeparateFileV2.java:12)",
"com.facebook.redexlinemap.InlineSeparateFileV2.inlineOnce1(InlineSeparateFileV2.java:20)",
"com.facebook.redexlinemap.InlineSeparateFileV2.inlineTwice(InlineSeparateFileV2.java:24)",
"com.facebook.redexlinemap.InlineTestCode.testInlineTwice(InlineTestCode.java:65)"));
}
}
private static int inlineMe() {
return 1;
}
@NoInline
private void ignoreAndThrow(Object x) throws Exception {
throw new RuntimeException("foo");
}
/**
* Check that the line number is reset to the original for the code that follows an inlined
* method. We expect the resulting stack trace *not* to point to inlineMe().
*/
@NoInline
@SuppressWarnings("CatchGeneralException")
public void testPositionReset() throws Exception {
try {
ignoreAndThrow(inlineMe());
} catch (Exception e) {
assertRawStackSize(e, 2, "testPositionReset");
ArrayList<StackTraceElement> trace = lm.mapStackTrace(e.getStackTrace());
assertThat(TraceUtil.traceToString(trace, 2))
.isEqualTo(
Arrays.asList(
"com.facebook.redexlinemap.InlineTestCode.ignoreAndThrow(InlineTestCode.java:85)",
"com.facebook.redexlinemap.InlineTestCode.testPositionReset(InlineTestCode.java:96)"));
}
}
private void elseThrows() throws Exception {
if (lm == null) {
System.out.println("");
} else {
InlineSeparateFileV2.wrapsThrow();
}
}
@NoInline
@SuppressWarnings("CatchGeneralException")
public void testElseThrows() throws Exception {
try {
elseThrows();
} catch (Exception e) {
assertRawStackSize(e, 2, "testElseThrows");
ArrayList<StackTraceElement> trace = lm.mapStackTrace(e.getStackTrace());
assertThat(TraceUtil.traceToString(trace, 3))
.isEqualTo(
Arrays.asList(
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrow(InlineSeparateFileV2.java:12)",
"com.facebook.redexlinemap.InlineTestCode.elseThrows(InlineTestCode.java:112)",
"com.facebook.redexlinemap.InlineTestCode.testElseThrows(InlineTestCode.java:120)"));
}
}
@NoInline
private void elseThrows(int i) throws Exception {
if (lm == null) {
System.out.println(i);
} else {
InlineSeparateFileV2.wrapsThrow();
}
}
@NoInline
private void elseThrows(char c) throws Exception {
if (lm != null) { // Intentionally changed order.
InlineSeparateFileV2.wrapsThrow();
} else {
System.out.println(c);
}
}
@NoInline
private void elseThrows(float f) throws Exception {
if (lm == null) {
System.out.println(f);
} else {
InlineSeparateFileV2.wrapsThrow();
}
}
@NoInline
private void elseThrows(Object o) throws Exception {
if (lm != null) { // Intentionally changed order.
InlineSeparateFileV2.wrapsThrow();
} else {
System.out.println(o);
}
}
@NoInline
@SuppressWarnings("CatchGeneralException")
public void testElseThrowsOverload(OverloadCheck oc) throws Exception {
HashSet<StackTraceElement> frames = new HashSet<>();
try {
elseThrows((int)0);
} catch (Exception e) {
assertRawStackSize(e, 3, "testElseThrowsOverload");
frames.add(e.getStackTrace()[1]);
ArrayList<StackTraceElement> trace = lm.mapStackTrace(e.getStackTrace());
assertThat(TraceUtil.traceToString(trace, 3))
.isEqualTo(
Arrays.asList(
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrow(InlineSeparateFileV2.java:12)",
"com.facebook.redexlinemap.InlineTestCode.elseThrows(InlineTestCode.java:138)",
"com.facebook.redexlinemap.InlineTestCode.testElseThrowsOverload(InlineTestCode.java:174)"));
}
try {
elseThrows('a');
} catch (Exception e) {
assertRawStackSize(e, 3, "testElseThrowsOverload");
frames.add(e.getStackTrace()[1]);
ArrayList<StackTraceElement> trace = lm.mapStackTrace(e.getStackTrace());
assertThat(TraceUtil.traceToString(trace, 3))
.isEqualTo(
Arrays.asList(
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrow(InlineSeparateFileV2.java:12)",
"com.facebook.redexlinemap.InlineTestCode.elseThrows(InlineTestCode.java:145)",
"com.facebook.redexlinemap.InlineTestCode.testElseThrowsOverload(InlineTestCode.java:188)"));
}
try {
elseThrows(0.1f);
} catch (Exception e) {
assertRawStackSize(e, 3, "testElseThrowsOverload");
frames.add(e.getStackTrace()[1]);
ArrayList<StackTraceElement> trace = lm.mapStackTrace(e.getStackTrace());
assertThat(TraceUtil.traceToString(trace, 3))
.isEqualTo(
Arrays.asList(
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrow(InlineSeparateFileV2.java:12)",
"com.facebook.redexlinemap.InlineTestCode.elseThrows(InlineTestCode.java:156)",
"com.facebook.redexlinemap.InlineTestCode.testElseThrowsOverload(InlineTestCode.java:202)"));
}
try {
elseThrows(null);
} catch (Exception e) {
assertRawStackSize(e, 3, "testElseThrowsOverload");
frames.add(e.getStackTrace()[1]);
ArrayList<StackTraceElement> trace = lm.mapStackTrace(e.getStackTrace());
assertThat(TraceUtil.traceToString(trace, 3))
.isEqualTo(
Arrays.asList(
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrow(InlineSeparateFileV2.java:12)",
"com.facebook.redexlinemap.InlineTestCode.elseThrows(InlineTestCode.java:163)",
"com.facebook.redexlinemap.InlineTestCode.testElseThrowsOverload(InlineTestCode.java:216)"));
}
// Check that all `elseThrows` functions exist (not inlined).
HashSet<Method> methods = new HashSet<>();
for (Method m : getClass().getDeclaredMethods()) {
if (m.getName().equals("elseThrows")) {
methods.add(m);
}
}
assertThat(methods).hasSize(4);
// Extra checks?
if (oc != null) {
oc.check(frames);
}
}
public interface OverloadCheck {
public void check(HashSet<StackTraceElement> frames);
}
public static void checkTests(Class<?> cls) throws Exception {
HashSet<String> expected = getTestNamedMethods(InlineTestCode.class);
HashSet<String> actual = getTestNamedMethods(cls);
assertThat(actual).isEqualTo(expected);
}
private static HashSet<String> getTestNamedMethods(Class<?> cls) throws Exception {
HashSet<String> res = new HashSet<>();
for (Method m : cls.getDeclaredMethods()) {
String name = m.getName();
if (name.startsWith("test")) {
res.add(name);
}
}
return res;
}
private static void assertRawStackSize(Throwable t, int size, String expectedMethod) {
assertRawStackSize(t, size, expectedMethod, InlineTestCode.class.getName());
}
private static void assertRawStackSize(Throwable t, int size, String expectedMethod, String expectedClass) {
StackTraceElement[] trace = t.getStackTrace();
assertThat(trace.length).isGreaterThanOrEqualTo(size);
assertThat(trace[size - 1].getMethodName()).isEqualTo(expectedMethod);
if (expectedClass != null) {
assertThat(trace[size - 1].getClassName()).endsWith(expectedClass);
}
}
@NoInline
@SuppressWarnings("CatchGeneralException")
public void testOutlined() throws Exception {
try {
InlineSeparateFileV2.counter = 1;
InlineSeparateFileV2.outlinedThrower();
} catch (Exception e) {
ArrayList<StackTraceElement> trace = lm.mapStackTrace(e.getStackTrace());
assertThat(TraceUtil.traceToString(trace, 4))
.isEqualTo(
Arrays.asList(
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrow2(InlineSeparateFileV2.java:32)",
"com.facebook.redexlinemap.InlineSeparateFileV2.outlinedThrower(InlineSeparateFileV2.java:38)",
"com.redex.Outlined$0$0$0.$outlined$0$88687b1b5dba69a0(RedexGenerated)", // ideally, we wouldn't see this
"com.facebook.redexlinemap.InlineTestCode.testOutlined(InlineTestCode.java:282)"));
}
try {
InlineSeparateFileV2.counter = 2;
InlineSeparateFileV2.outlinedThrower();
} catch (Exception e) {
ArrayList<StackTraceElement> trace = lm.mapStackTrace(e.getStackTrace());
assertThat(TraceUtil.traceToString(trace, 4))
.isEqualTo(
Arrays.asList(
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrow2(InlineSeparateFileV2.java:32)",
"com.facebook.redexlinemap.InlineSeparateFileV2.outlinedThrower(InlineSeparateFileV2.java:39)",
"com.redex.Outlined$0$0$0.$outlined$0$88687b1b5dba69a0(RedexGenerated)",
"com.facebook.redexlinemap.InlineTestCode.testOutlined(InlineTestCode.java:296)"));
}
try {
InlineSeparateFileV2.counter = 3;
InlineSeparateFileV2.outlinedThrower();
} catch (Exception e) {
ArrayList<StackTraceElement> trace = lm.mapStackTrace(e.getStackTrace());
assertThat(TraceUtil.traceToString(trace, 4))
.isEqualTo(
Arrays.asList(
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrow2(InlineSeparateFileV2.java:32)",
"com.facebook.redexlinemap.InlineSeparateFileV2.outlinedThrower(InlineSeparateFileV2.java:40)",
"com.redex.Outlined$0$0$0.$outlined$0$88687b1b5dba69a0(RedexGenerated)",
"com.facebook.redexlinemap.InlineTestCode.testOutlined(InlineTestCode.java:310)"));
}
try {
InlineSeparateFileV2.counter = 42;
InlineSeparateFileV2.outlinedThrower();
} catch (Exception e) {
ArrayList<StackTraceElement> trace = lm.mapStackTrace(e.getStackTrace());
assertThat(TraceUtil.traceToString(trace, 4))
.isEqualTo(
Arrays.asList(
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrow2(InlineSeparateFileV2.java:32)",
"com.facebook.redexlinemap.InlineSeparateFileV2.outlinedThrower(InlineSeparateFileV2.java:39)", // <-- wrong, should be :79
"com.redex.Outlined$0$0$0.$outlined$0$88687b1b5dba69a0(RedexGenerated)",
"com.facebook.redexlinemap.InlineTestCode.testOutlined(InlineTestCode.java:324)"));
}
}
@NoInline
@SuppressWarnings("CatchGeneralException")
public void testOutlinedInlined() throws Exception {
try {
InlineSeparateFileV2.counter = 1;
InlineSeparateFileV2.outlinedThrowerInlined();
} catch (Exception e) {
ArrayList<StackTraceElement> trace = lm.mapStackTrace(e.getStackTrace());
assertThat(TraceUtil.traceToString(trace, 5))
.isEqualTo(
Arrays.asList(
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrow3(InlineSeparateFileV2.java:91)",
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrowInline(InlineSeparateFileV2.java:97)",
"com.facebook.redexlinemap.InlineSeparateFileV2.outlinedThrowerInlined(InlineSeparateFileV2.java:102)",
"com.redex.Outlined$0$0$0.$outlined$0$886bb44310f1a408(RedexGenerated)",
"com.facebook.redexlinemap.InlineTestCode.testOutlinedInlined(InlineTestCode.java:342)"));
}
try {
InlineSeparateFileV2.counter = 2;
InlineSeparateFileV2.outlinedThrowerInlined();
} catch (Exception e) {
ArrayList<StackTraceElement> trace = lm.mapStackTrace(e.getStackTrace());
assertThat(TraceUtil.traceToString(trace, 5))
.isEqualTo(
Arrays.asList(
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrow3(InlineSeparateFileV2.java:91)",
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrowInline(InlineSeparateFileV2.java:97)",
"com.facebook.redexlinemap.InlineSeparateFileV2.outlinedThrowerInlined(InlineSeparateFileV2.java:103)",
"com.redex.Outlined$0$0$0.$outlined$0$886bb44310f1a408(RedexGenerated)",
"com.facebook.redexlinemap.InlineTestCode.testOutlinedInlined(InlineTestCode.java:357)"));
}
try {
InlineSeparateFileV2.counter = 3;
InlineSeparateFileV2.outlinedThrowerInlined();
} catch (Exception e) {
ArrayList<StackTraceElement> trace = lm.mapStackTrace(e.getStackTrace());
assertThat(TraceUtil.traceToString(trace, 5))
.isEqualTo(
Arrays.asList(
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrow3(InlineSeparateFileV2.java:91)",
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrowInline(InlineSeparateFileV2.java:97)",
"com.facebook.redexlinemap.InlineSeparateFileV2.outlinedThrowerInlined(InlineSeparateFileV2.java:104)",
"com.redex.Outlined$0$0$0.$outlined$0$886bb44310f1a408(RedexGenerated)",
"com.facebook.redexlinemap.InlineTestCode.testOutlinedInlined(InlineTestCode.java:372)"));
}
try {
InlineSeparateFileV2.counter = 42;
InlineSeparateFileV2.outlinedThrowerInlined();
} catch (Exception e) {
ArrayList<StackTraceElement> trace = lm.mapStackTrace(e.getStackTrace());
assertThat(TraceUtil.traceToString(trace, 5))
.isEqualTo(
Arrays.asList(
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrow3(InlineSeparateFileV2.java:91)",
"com.facebook.redexlinemap.InlineSeparateFileV2.wrapsThrowInline(InlineSeparateFileV2.java:97)",
"com.facebook.redexlinemap.InlineSeparateFileV2.outlinedThrowerInlined(InlineSeparateFileV2.java:103)", // <-- wrong, should be :143
"com.redex.Outlined$0$0$0.$outlined$0$886bb44310f1a408(RedexGenerated)",
"com.facebook.redexlinemap.InlineTestCode.testOutlinedInlined(InlineTestCode.java:387)"));
}
}
}
| 16,802 | 0.677181 | 0.653434 | 400 | 41.005001 | 36.177063 | 150 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.505 | false | false |
12
|
15f27fe5ee0cef114888bee06ff26c7da3488295
| 6,751,688,604,267 |
d1a881cfbdaee5c6bae119ae7188c451be79abec
|
/info_price_platform/src/main/java/com/gcj/entity/from/FilesForm.java
|
b835955dbaf9487b6d97a2f425312aa48a3a0290
|
[] |
no_license
|
kinbod/datamanager
|
https://github.com/kinbod/datamanager
|
6698e8dafccd97856e4b1d224f3a86e8bdf879f0
|
3a827bec0694f8825892c9465ade545f741cf7ce
|
refs/heads/master
| 2023-09-02T17:16:23.842000 | 2014-12-23T07:19:12 | 2014-12-23T07:19:12 | 28,382,944 | 0 | 0 | null | false | 2023-08-08T00:52:37 | 2014-12-23T06:54:15 | 2014-12-23T07:35:34 | 2023-08-08T00:52:37 | 16,204 | 0 | 0 | 1 |
JavaScript
| false | false |
/***********************************************************
*(该类的功能及其特点描述)
*
*@see(与该类相关联的类)
*
*广联达
*
*版权:本文件版权归属北京广联达软件股份有限公司
*
*
*@author:郭冲
*
*@since:jdk1.5
*
*
*@version:1.0
*
*@date:2014-5-8
*
*最后更改日期:
*
*
*修改人:
*
*
********************************************************/
package com.gcj.entity.from;
public class FilesForm {
private String fileName;
private String filePhysicalPath;
private String fileMappingPath;
private String fileType;
private String fileSize;
private String companyId;
private String ownGroupId;
private String paId;
private int userId;
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getFilePhysicalPath() {
return filePhysicalPath;
}
public void setFilePhysicalPath(String filePhysicalPath) {
this.filePhysicalPath = filePhysicalPath;
}
public String getFileMappingPath() {
return fileMappingPath;
}
public void setFileMappingPath(String fileMappingPath) {
this.fileMappingPath = fileMappingPath;
}
public String getFileType() {
return fileType;
}
public void setFileType(String fileType) {
this.fileType = fileType;
}
public String getFileSize() {
return fileSize;
}
public void setFileSize(String fileSize) {
this.fileSize = fileSize;
}
public String getCompanyId() {
return companyId;
}
public void setCompanyId(String companyId) {
this.companyId = companyId;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getOwnGroupId() {
return ownGroupId;
}
public void setOwnGroupId(String ownGroupId) {
this.ownGroupId = ownGroupId;
}
public String getPaId() {
return paId;
}
public void setPaId(String paId) {
this.paId = paId;
}
}
|
UTF-8
|
Java
| 2,028 |
java
|
FilesForm.java
|
Java
|
[
{
"context": "广联达\r\n*\r\n*版权:本文件版权归属北京广联达软件股份有限公司\r\n*\r\n*\r\n\t*@author:郭冲\r\n\t*\r\n\t*@since:jdk1.5\r\n\t*\r\n*\r\n\t*@version:1.0\r\n\t*\r\n",
"end": 158,
"score": 0.999743640422821,
"start": 156,
"tag": "NAME",
"value": "郭冲"
}
] | null |
[] |
/***********************************************************
*(该类的功能及其特点描述)
*
*@see(与该类相关联的类)
*
*广联达
*
*版权:本文件版权归属北京广联达软件股份有限公司
*
*
*@author:郭冲
*
*@since:jdk1.5
*
*
*@version:1.0
*
*@date:2014-5-8
*
*最后更改日期:
*
*
*修改人:
*
*
********************************************************/
package com.gcj.entity.from;
public class FilesForm {
private String fileName;
private String filePhysicalPath;
private String fileMappingPath;
private String fileType;
private String fileSize;
private String companyId;
private String ownGroupId;
private String paId;
private int userId;
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getFilePhysicalPath() {
return filePhysicalPath;
}
public void setFilePhysicalPath(String filePhysicalPath) {
this.filePhysicalPath = filePhysicalPath;
}
public String getFileMappingPath() {
return fileMappingPath;
}
public void setFileMappingPath(String fileMappingPath) {
this.fileMappingPath = fileMappingPath;
}
public String getFileType() {
return fileType;
}
public void setFileType(String fileType) {
this.fileType = fileType;
}
public String getFileSize() {
return fileSize;
}
public void setFileSize(String fileSize) {
this.fileSize = fileSize;
}
public String getCompanyId() {
return companyId;
}
public void setCompanyId(String companyId) {
this.companyId = companyId;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getOwnGroupId() {
return ownGroupId;
}
public void setOwnGroupId(String ownGroupId) {
this.ownGroupId = ownGroupId;
}
public String getPaId() {
return paId;
}
public void setPaId(String paId) {
this.paId = paId;
}
}
| 2,028 | 0.642259 | 0.637029 | 96 | 17.916666 | 16.346296 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.260417 | false | false |
12
|
e06c4c8b63ac78c13e498bdabe908ffd06831391
| 12,232,066,880,888 |
22ecc7ec503cc2eecf3b607e6481b5190f2a86b5
|
/src/main/java/com/abbajoa/codecombine/Console.java
|
b3df82fee088dac42a890bb355bbbc03a60377fc
|
[] |
no_license
|
abbajoa/codecombine
|
https://github.com/abbajoa/codecombine
|
327c8e89b88322cc094289ee1a4ade37f9acb60e
|
dbd3e1297a89d5d87a30492b12d27765d0989d2e
|
refs/heads/master
| 2018-01-07T08:14:27.640000 | 2014-07-13T15:57:04 | 2014-07-13T15:57:04 | 9,360,187 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.abbajoa.codecombine;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import com.abbajoa.codecombine.util.FileUtil;
import com.abbajoa.codecombine.util.StringUtil;
import com.abbajoa.codecombine.validator.CompilationValidatorResult;
public class Console {
// TODO 유닛테스트를 하자...
// TODO validate 옵션넣기
public static void main(String[] args) throws Exception {
File sourceFileOrNull = null;
String outputEncoding = "UTF-8";
ArrayList<String> searchDir = new ArrayList<String>();
File outputFileOrNull = null;
boolean validate = false;
for (int i = 0; i < args.length;) { // TODO 커맨드라인 파싱하는 기능을 유틸로 뺴자.
String token = args[i];
if (token.equals("-v")) {
validate = true;
i++;
} else if (token.equals("-f") && i + 1 < args.length) {
outputFileOrNull = new File(args[i + 1]);
i += 2;
} else if (token.equals("-e") && i + 1 < args.length) {
outputEncoding = args[i + 1]; // TODO 인코딩이 valid한지 검사해야함.
i += 2;
} else if (sourceFileOrNull == null) {
sourceFileOrNull = new File(token);
i++;
} else {
searchDir.add(token);
i++;
}
}
if (sourceFileOrNull == null) {
echoUsage();
return;
}
File srcFile = sourceFileOrNull;
searchDir.add(srcFile.getParentFile().toString());
Language language = LanguageSelector.select(srcFile, null);
if (language == null) {
System.err.println("Not Supported Language");
return;
}
LanguageTool tool = LanguageToolSelector.createLanguageTool(language); // TODO 지원하는 language인지 validation 단계에서 검사하기.
String code = FileUtil.loadUTF8(srcFile);
String merged = tool.createCombiner().combine(code, searchDir);
merged += "\n" + tool.getLineCommentPrefix() + " Combined by CodeCombine CLI (https://github.com/abbajoa/codecombine)";
if (validate) {
CompilationValidatorResult r = tool.createCompilationValidator().validate(StringUtil.toLineList(merged));
if (!r.isSuccess()) {
System.err.println(r.getErrorMessage());
return;
}
}
output(merged, outputFileOrNull, outputEncoding);
}
private static void output(String code, File outputFileOrNull, String outputEncoding) throws FileNotFoundException, IOException, UnsupportedEncodingException {
if (outputFileOrNull == null)
System.out.println(code);
else
FileUtil.writeToFile(outputFileOrNull, code, outputEncoding);
}
private static void echoUsage() {
System.out.println("Usage:");
System.out.println("\tcodecombine [-options] [source file path] [search dir...]");
System.out.println("Options:");
System.out.println("\t-f <file name>");
System.out.println("\t\twrite combined result to a file. default is standard output.");
System.out.println("\t-e <character set>");
System.out.println("\t\twrite the output file as specified encoding. default is UTF-8.");
System.out.println("\t-v");
System.out.println("\t\tvalidate combined source code using default compiler.");
System.out.println("Example:");
System.out.println("\tcodecombine -f Out.java -e UTF-8 Main.java lib1/src lib2/src");
}
static Collection<String> toSearchDirs(String[] args, int start) {
Collection<String> r = new ArrayList<String>();
for (int i = start; i < args.length; i++)
r.add(args[i]);
return r;
}
}
|
UTF-8
|
Java
| 3,586 |
java
|
Console.java
|
Java
|
[
{
"context": "\" Combined by CodeCombine CLI (https://github.com/abbajoa/codecombine)\";\r\n\t\tif (validate) {\r\n\t\t\tCompilation",
"end": 1956,
"score": 0.9976585507392883,
"start": 1949,
"tag": "USERNAME",
"value": "abbajoa"
}
] | null |
[] |
package com.abbajoa.codecombine;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import com.abbajoa.codecombine.util.FileUtil;
import com.abbajoa.codecombine.util.StringUtil;
import com.abbajoa.codecombine.validator.CompilationValidatorResult;
public class Console {
// TODO 유닛테스트를 하자...
// TODO validate 옵션넣기
public static void main(String[] args) throws Exception {
File sourceFileOrNull = null;
String outputEncoding = "UTF-8";
ArrayList<String> searchDir = new ArrayList<String>();
File outputFileOrNull = null;
boolean validate = false;
for (int i = 0; i < args.length;) { // TODO 커맨드라인 파싱하는 기능을 유틸로 뺴자.
String token = args[i];
if (token.equals("-v")) {
validate = true;
i++;
} else if (token.equals("-f") && i + 1 < args.length) {
outputFileOrNull = new File(args[i + 1]);
i += 2;
} else if (token.equals("-e") && i + 1 < args.length) {
outputEncoding = args[i + 1]; // TODO 인코딩이 valid한지 검사해야함.
i += 2;
} else if (sourceFileOrNull == null) {
sourceFileOrNull = new File(token);
i++;
} else {
searchDir.add(token);
i++;
}
}
if (sourceFileOrNull == null) {
echoUsage();
return;
}
File srcFile = sourceFileOrNull;
searchDir.add(srcFile.getParentFile().toString());
Language language = LanguageSelector.select(srcFile, null);
if (language == null) {
System.err.println("Not Supported Language");
return;
}
LanguageTool tool = LanguageToolSelector.createLanguageTool(language); // TODO 지원하는 language인지 validation 단계에서 검사하기.
String code = FileUtil.loadUTF8(srcFile);
String merged = tool.createCombiner().combine(code, searchDir);
merged += "\n" + tool.getLineCommentPrefix() + " Combined by CodeCombine CLI (https://github.com/abbajoa/codecombine)";
if (validate) {
CompilationValidatorResult r = tool.createCompilationValidator().validate(StringUtil.toLineList(merged));
if (!r.isSuccess()) {
System.err.println(r.getErrorMessage());
return;
}
}
output(merged, outputFileOrNull, outputEncoding);
}
private static void output(String code, File outputFileOrNull, String outputEncoding) throws FileNotFoundException, IOException, UnsupportedEncodingException {
if (outputFileOrNull == null)
System.out.println(code);
else
FileUtil.writeToFile(outputFileOrNull, code, outputEncoding);
}
private static void echoUsage() {
System.out.println("Usage:");
System.out.println("\tcodecombine [-options] [source file path] [search dir...]");
System.out.println("Options:");
System.out.println("\t-f <file name>");
System.out.println("\t\twrite combined result to a file. default is standard output.");
System.out.println("\t-e <character set>");
System.out.println("\t\twrite the output file as specified encoding. default is UTF-8.");
System.out.println("\t-v");
System.out.println("\t\tvalidate combined source code using default compiler.");
System.out.println("Example:");
System.out.println("\tcodecombine -f Out.java -e UTF-8 Main.java lib1/src lib2/src");
}
static Collection<String> toSearchDirs(String[] args, int start) {
Collection<String> r = new ArrayList<String>();
for (int i = start; i < args.length; i++)
r.add(args[i]);
return r;
}
}
| 3,586 | 0.681139 | 0.677401 | 100 | 32.779999 | 30.728025 | 160 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.55 | false | false |
12
|
53c583c6b687e67536e7e5ab7c9c14fcec91c886
| 19,490,561,615,709 |
1b18ac4a0fc9a489a3313d09b1530d56423a44d2
|
/src/main/java/simpleModel/SimpleUser.java
|
ec50982b76889984b68d4cc4a25dc7aaf09ccbb2
|
[] |
no_license
|
cartellll/sber_project
|
https://github.com/cartellll/sber_project
|
c8e95ff7f6a5b4c7c0340e05e8ea314d6eb0febe
|
dc20ec506144627b31ea11a1104025ab1f071b74
|
refs/heads/master
| 2023-05-13T21:37:31.047000 | 2020-07-19T16:20:22 | 2020-07-19T16:20:22 | 280,905,785 | 0 | 0 | null | false | 2021-06-04T22:12:44 | 2020-07-19T16:30:25 | 2020-07-19T16:31:04 | 2021-06-04T22:12:44 | 70 | 0 | 0 | 3 |
Java
| false | false |
package simpleModel;
import java.io.Serializable;
import java.lang.IndexOutOfBoundsException;
import java.util.List;
public class SimpleUser implements Serializable {
private int ID;
private String name;
private String login;
private String password;
private List<SimplePoint> simplePoints;
public SimpleUser() {
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public String getName() {
return name;
}
public String getLogin() {
return login;
}
public String getPassword() {
return password;
}
public void setName(String name) {
this.name = name;
}
public void setLogin(String login) {
this.login = login;
}
public void setPassword(String password) {
this.password = password;
}
public SimplePoint getPoint(int i) {
try {
return simplePoints.get(i);
} catch (IndexOutOfBoundsException exp) {
System.out.print("Выход за пределы массива пользователей");
}
return null;
}
public void addPoint(int i, SimplePoint cars) {
simplePoints.add(i, cars);
}
public void removePoint(int i) {
simplePoints.remove(i);
}
public int getPointSize() {
return simplePoints.size();
}
public void setSimplePoints(List<SimplePoint> points) {
this.simplePoints = points;
}
public List<SimplePoint> getSimplePoints() {
return simplePoints;
}
}
|
UTF-8
|
Java
| 1,607 |
java
|
SimpleUser.java
|
Java
|
[
{
"context": "assword(String password) {\n this.password = password;\n }\n\n public SimplePoint getPoint(int i) {\n",
"end": 875,
"score": 0.7373695969581604,
"start": 867,
"tag": "PASSWORD",
"value": "password"
}
] | null |
[] |
package simpleModel;
import java.io.Serializable;
import java.lang.IndexOutOfBoundsException;
import java.util.List;
public class SimpleUser implements Serializable {
private int ID;
private String name;
private String login;
private String password;
private List<SimplePoint> simplePoints;
public SimpleUser() {
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public String getName() {
return name;
}
public String getLogin() {
return login;
}
public String getPassword() {
return password;
}
public void setName(String name) {
this.name = name;
}
public void setLogin(String login) {
this.login = login;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public SimplePoint getPoint(int i) {
try {
return simplePoints.get(i);
} catch (IndexOutOfBoundsException exp) {
System.out.print("Выход за пределы массива пользователей");
}
return null;
}
public void addPoint(int i, SimplePoint cars) {
simplePoints.add(i, cars);
}
public void removePoint(int i) {
simplePoints.remove(i);
}
public int getPointSize() {
return simplePoints.size();
}
public void setSimplePoints(List<SimplePoint> points) {
this.simplePoints = points;
}
public List<SimplePoint> getSimplePoints() {
return simplePoints;
}
}
| 1,609 | 0.60712 | 0.60712 | 82 | 18.182926 | 17.586807 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.329268 | false | false |
12
|
a83e398bb67868331572303491ef0907b799a085
| 12,764,642,825,920 |
ff533b192dcd03cc4407fc6d663ec6435511955d
|
/app/src/main/java/com/ystl/yysj/network/RequestContent.java
|
4f3e70029e35d054e0fa5efefc7087b5e2b207a5
|
[] |
no_license
|
zhangdibill/yysj
|
https://github.com/zhangdibill/yysj
|
fef339125a05b2380a43810b86004b1b4c9ecd8a
|
484b2b2511ca9bd3810aa1481643c78c1ee5eac7
|
refs/heads/master
| 2021-01-20T01:37:57.604000 | 2017-04-25T02:52:39 | 2017-04-25T02:52:39 | 89,308,606 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.ystl.yysj.network;
/**
* 网络数据返回信息
* Created by jinpeng on 15/10/23.
*/
public class RequestContent {
private int code;
private int busimessCode;
private String message;
private String data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public int getBusimessCode() {
return busimessCode;
}
public void setBusimessCode(int busimessCode) {
this.busimessCode = busimessCode;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
|
UTF-8
|
Java
| 814 |
java
|
RequestContent.java
|
Java
|
[
{
"context": ".ystl.yysj.network;\n\n/**\n * 网络数据返回信息\n * Created by jinpeng on 15/10/23.\n */\npublic class RequestContent {\n ",
"end": 69,
"score": 0.9992961287498474,
"start": 62,
"tag": "USERNAME",
"value": "jinpeng"
}
] | null |
[] |
package com.ystl.yysj.network;
/**
* 网络数据返回信息
* Created by jinpeng on 15/10/23.
*/
public class RequestContent {
private int code;
private int busimessCode;
private String message;
private String data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public int getBusimessCode() {
return busimessCode;
}
public void setBusimessCode(int busimessCode) {
this.busimessCode = busimessCode;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
| 814 | 0.602757 | 0.595238 | 44 | 17.136364 | 14.932562 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.295455 | false | false |
12
|
b12c8ffffa1f5cfbbf7d7e1709a9863736ab4d2c
| 28,922,309,804,439 |
2eab1a9140386c5b7f7fc34ee20ab64ea24ae85b
|
/src/test/java/com/imranoftherings/fix/stronglytyped/message/types/OrdTypeTest.java
|
3db248323f94b4fe3494948cd1fabe03fbea7d21
|
[] |
no_license
|
imranoftherings/repeating-fix
|
https://github.com/imranoftherings/repeating-fix
|
a87232c4045e722a0a539b9c1e50fd1a03652ff1
|
499a3f213442e2bfc20d0ccb3904f0997982fc4b
|
refs/heads/master
| 2020-03-31T06:35:57.177000 | 2018-10-14T23:54:21 | 2018-10-14T23:55:23 | 151,988,082 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.imranoftherings.fix.stronglytyped.message.types;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.stream.Stream;
public class OrdTypeTest {
@ParameterizedTest
@MethodSource("validValuesProvider")
public void testValidOrderTypes(char fixValue, OrdType expectedOrdType) {
Assertions.assertEquals(expectedOrdType, OrdType.parseOrdType(fixValue));
}
static Stream<Arguments> validValuesProvider() {
return Stream.of(
Arguments.of('1', OrdType.Market),
Arguments.of('2', OrdType.Limit),
Arguments.of('P', OrdType.Pegged)
);
}
@ParameterizedTest
@ValueSource(chars = {'a', 'b', 'c'})
public void testInvalidOrderTypes(char fixValue) {
Assertions.assertEquals(null, OrdType.parseOrdType(fixValue));
}
}
|
UTF-8
|
Java
| 1,055 |
java
|
OrdTypeTest.java
|
Java
|
[] | null |
[] |
package com.imranoftherings.fix.stronglytyped.message.types;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.stream.Stream;
public class OrdTypeTest {
@ParameterizedTest
@MethodSource("validValuesProvider")
public void testValidOrderTypes(char fixValue, OrdType expectedOrdType) {
Assertions.assertEquals(expectedOrdType, OrdType.parseOrdType(fixValue));
}
static Stream<Arguments> validValuesProvider() {
return Stream.of(
Arguments.of('1', OrdType.Market),
Arguments.of('2', OrdType.Limit),
Arguments.of('P', OrdType.Pegged)
);
}
@ParameterizedTest
@ValueSource(chars = {'a', 'b', 'c'})
public void testInvalidOrderTypes(char fixValue) {
Assertions.assertEquals(null, OrdType.parseOrdType(fixValue));
}
}
| 1,055 | 0.711848 | 0.709953 | 32 | 31.96875 | 25.199806 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.625 | false | false |
12
|
b620624ae18bb58c4abed65f5b74cf79174ae17f
| 4,432,406,267,943 |
9f7ccf9020ab2a61faecf703b457ea8ad2fe4913
|
/app/src/main/java/com/rasalhague/commandsender/commands/CommandNext.java
|
d3b14f07c4658b92ba96586234aebbabbc838f67
|
[] |
no_license
|
RasAlhague/CommandSender
|
https://github.com/RasAlhague/CommandSender
|
e55367b6730abd204b75aba3fe20040654e2bdf1
|
436be3c6279511aea21ecab0707a430880b6148b
|
refs/heads/master
| 2016-08-04T19:03:58.695000 | 2015-05-06T14:58:38 | 2015-05-06T14:58:38 | 34,992,787 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.rasalhague.commandsender.commands;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class CommandNext implements Command
{
private final String COMMAND = "Next\n";
@Override
public void perform(Socket socket)
{
try
{
new DataOutputStream(socket.getOutputStream()).writeBytes(COMMAND);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
|
UTF-8
|
Java
| 488 |
java
|
CommandNext.java
|
Java
|
[] | null |
[] |
package com.rasalhague.commandsender.commands;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class CommandNext implements Command
{
private final String COMMAND = "Next\n";
@Override
public void perform(Socket socket)
{
try
{
new DataOutputStream(socket.getOutputStream()).writeBytes(COMMAND);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
| 488 | 0.635246 | 0.635246 | 23 | 20.217392 | 19.779121 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.304348 | false | false |
12
|
64623b146e9d06d643060ee4daacd9b2b6f8cec0
| 4,432,406,266,440 |
ea8cb544310e878bc324684d12ad1648dc51299c
|
/app/src/main/java/com/mattcao/androidlearningproject/CrimeListFragment.java
|
69b5c86d95c3241650c14dc84a0009d9bae02413
|
[] |
no_license
|
piggy925/Android-Learning-Project
|
https://github.com/piggy925/Android-Learning-Project
|
939bad2400b7153cf78abe663c90bed7a6b3e53f
|
909fd6acca27ca8c6f091bbb3ca16d4100822de6
|
refs/heads/master
| 2020-06-07T02:32:43.445000 | 2019-07-11T16:27:10 | 2019-07-11T16:27:10 | 192,901,524 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.mattcao.androidlearningproject;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.view.menu.MenuView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.mattcao.androidlearningproject.databinding.FragmentCrimeListBinding;
import com.mattcao.androidlearningproject.entity.Crime;
import com.mattcao.androidlearningproject.entity.CrimeLab;
import com.mattcao.androidlearningproject.util.DateUtil;
import java.util.List;
public class CrimeListFragment extends Fragment {
private static final String SUBTITLE_VISIBLE = "SUBTITLE_VISIBLE";
private RecyclerView mRecyclerView;
private FragmentCrimeListBinding mBinding;
private CrimeAdapter mCrimeAdapter;
private boolean mSubtitleVisible = false;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_crime_list, container, false);
mRecyclerView = mBinding.recyclerCrimeView;
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
if (savedInstanceState != null) {
mSubtitleVisible = savedInstanceState.getBoolean(SUBTITLE_VISIBLE);
}
updateUI();
return mBinding.getRoot();
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(SUBTITLE_VISIBLE, mSubtitleVisible);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_crime_list, menu);
MenuItem item = menu.findItem(R.id.show_subtitle);
item.setTitle(mSubtitleVisible ? "HIDE SUBTITLE" : "SHOW SUBTITLE");
}
private void updateTitle() {
CrimeLab crimeLab = CrimeLab.getCrimeLab(getActivity());
int count = crimeLab.getCrimes().size();
//与设备语言设置有关,需要把设备设置成英语或其他才能正常显示
String subtitle = getResources().getQuantityString(R.plurals.subtitle_plural, count, count);
if (!mSubtitleVisible) {
subtitle = null;
}
AppCompatActivity activity = (AppCompatActivity) getActivity();
if (activity != null) {
activity.getSupportActionBar().setSubtitle(subtitle);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.new_crime:
Crime crime = new Crime();
CrimeLab.getCrimeLab(getActivity()).addCrime(crime);
Intent intent = CrimePagerActivity.newIntent(getActivity(), crime.getId());
startActivity(intent);
return true;
case R.id.show_subtitle:
mSubtitleVisible = !mSubtitleVisible;
getActivity().invalidateOptionsMenu();
updateTitle();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onResume() {
super.onResume();
updateUI();
}
private void updateUI() {
CrimeLab crimeLab = CrimeLab.getCrimeLab(getActivity());
List<Crime> crimes = crimeLab.getCrimes();
if (crimes.size() == 0) {
mBinding.noRecordsTextView.setVisibility(View.VISIBLE);
mBinding.recyclerCrimeView.setVisibility(View.GONE);
} else {
mBinding.noRecordsTextView.setVisibility(View.GONE);
mBinding.recyclerCrimeView.setVisibility(View.VISIBLE);
if (mCrimeAdapter == null) {
mCrimeAdapter = new CrimeAdapter(crimes);
mRecyclerView.setAdapter(mCrimeAdapter);
} else {
mCrimeAdapter.setCrimes(crimes);
mCrimeAdapter.notifyDataSetChanged();
}
}
updateTitle();
}
private class CrimeHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private Crime mCrime;
private ImageView mCrimeSolvedImageView;
private TextView mTitleTextView;
private TextView mDateTextView;
public CrimeHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.list_item_crime, parent, false));
//mListItemCrimeBinding = DataBindingUtil.inflate(inflater, R.layout.list_item_crime, parent, false);
mTitleTextView = itemView.findViewById(R.id.crime_title);
mDateTextView = itemView.findViewById(R.id.crime_date);
mCrimeSolvedImageView = itemView.findViewById(R.id.crime_solved_image_view);
itemView.setOnClickListener(this);
itemView.findViewById(R.id.delete_crime_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CrimeLab.getCrimeLab(getActivity()).deleteCrime(mCrime);
updateUI();
}
});
}
@Override
public void onClick(View v) {
Intent intent = CrimePagerActivity.newIntent(getActivity(), mCrime.getId());
startActivity(intent);
}
public void bind(Crime crime) {
mCrime = crime;
//mListItemCrimeBinding.crimeDate.setText(mCrime.getDate().toString());
//mListItemCrimeBinding.crimeTitle.setText(mCrime.getTitle());
mTitleTextView.setText(mCrime.getTitle());
mDateTextView.setText(DateUtil.formatDate(mCrime.getDate()));
mCrimeSolvedImageView.setVisibility(mCrime.isSolved() ? View.VISIBLE : View.GONE);
}
}
private class CrimeAdapter extends RecyclerView.Adapter<CrimeHolder> {
private List<Crime> mCrimes;
public CrimeAdapter(List<Crime> crimes) {
mCrimes = crimes;
}
@NonNull
@Override
public CrimeHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
return new CrimeHolder(layoutInflater, viewGroup);
}
@Override
public void onBindViewHolder(@NonNull CrimeHolder crimeHolder, int i) {
Crime crime = mCrimes.get(i);
crimeHolder.bind(crime);
}
@Override
public int getItemCount() {
return mCrimes.size();
}
public void setCrimes(List<Crime> crimes) {
mCrimes = crimes;
}
}
}
|
UTF-8
|
Java
| 7,453 |
java
|
CrimeListFragment.java
|
Java
|
[] | null |
[] |
package com.mattcao.androidlearningproject;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.view.menu.MenuView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.mattcao.androidlearningproject.databinding.FragmentCrimeListBinding;
import com.mattcao.androidlearningproject.entity.Crime;
import com.mattcao.androidlearningproject.entity.CrimeLab;
import com.mattcao.androidlearningproject.util.DateUtil;
import java.util.List;
public class CrimeListFragment extends Fragment {
private static final String SUBTITLE_VISIBLE = "SUBTITLE_VISIBLE";
private RecyclerView mRecyclerView;
private FragmentCrimeListBinding mBinding;
private CrimeAdapter mCrimeAdapter;
private boolean mSubtitleVisible = false;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_crime_list, container, false);
mRecyclerView = mBinding.recyclerCrimeView;
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
if (savedInstanceState != null) {
mSubtitleVisible = savedInstanceState.getBoolean(SUBTITLE_VISIBLE);
}
updateUI();
return mBinding.getRoot();
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(SUBTITLE_VISIBLE, mSubtitleVisible);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_crime_list, menu);
MenuItem item = menu.findItem(R.id.show_subtitle);
item.setTitle(mSubtitleVisible ? "HIDE SUBTITLE" : "SHOW SUBTITLE");
}
private void updateTitle() {
CrimeLab crimeLab = CrimeLab.getCrimeLab(getActivity());
int count = crimeLab.getCrimes().size();
//与设备语言设置有关,需要把设备设置成英语或其他才能正常显示
String subtitle = getResources().getQuantityString(R.plurals.subtitle_plural, count, count);
if (!mSubtitleVisible) {
subtitle = null;
}
AppCompatActivity activity = (AppCompatActivity) getActivity();
if (activity != null) {
activity.getSupportActionBar().setSubtitle(subtitle);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.new_crime:
Crime crime = new Crime();
CrimeLab.getCrimeLab(getActivity()).addCrime(crime);
Intent intent = CrimePagerActivity.newIntent(getActivity(), crime.getId());
startActivity(intent);
return true;
case R.id.show_subtitle:
mSubtitleVisible = !mSubtitleVisible;
getActivity().invalidateOptionsMenu();
updateTitle();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onResume() {
super.onResume();
updateUI();
}
private void updateUI() {
CrimeLab crimeLab = CrimeLab.getCrimeLab(getActivity());
List<Crime> crimes = crimeLab.getCrimes();
if (crimes.size() == 0) {
mBinding.noRecordsTextView.setVisibility(View.VISIBLE);
mBinding.recyclerCrimeView.setVisibility(View.GONE);
} else {
mBinding.noRecordsTextView.setVisibility(View.GONE);
mBinding.recyclerCrimeView.setVisibility(View.VISIBLE);
if (mCrimeAdapter == null) {
mCrimeAdapter = new CrimeAdapter(crimes);
mRecyclerView.setAdapter(mCrimeAdapter);
} else {
mCrimeAdapter.setCrimes(crimes);
mCrimeAdapter.notifyDataSetChanged();
}
}
updateTitle();
}
private class CrimeHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private Crime mCrime;
private ImageView mCrimeSolvedImageView;
private TextView mTitleTextView;
private TextView mDateTextView;
public CrimeHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.list_item_crime, parent, false));
//mListItemCrimeBinding = DataBindingUtil.inflate(inflater, R.layout.list_item_crime, parent, false);
mTitleTextView = itemView.findViewById(R.id.crime_title);
mDateTextView = itemView.findViewById(R.id.crime_date);
mCrimeSolvedImageView = itemView.findViewById(R.id.crime_solved_image_view);
itemView.setOnClickListener(this);
itemView.findViewById(R.id.delete_crime_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CrimeLab.getCrimeLab(getActivity()).deleteCrime(mCrime);
updateUI();
}
});
}
@Override
public void onClick(View v) {
Intent intent = CrimePagerActivity.newIntent(getActivity(), mCrime.getId());
startActivity(intent);
}
public void bind(Crime crime) {
mCrime = crime;
//mListItemCrimeBinding.crimeDate.setText(mCrime.getDate().toString());
//mListItemCrimeBinding.crimeTitle.setText(mCrime.getTitle());
mTitleTextView.setText(mCrime.getTitle());
mDateTextView.setText(DateUtil.formatDate(mCrime.getDate()));
mCrimeSolvedImageView.setVisibility(mCrime.isSolved() ? View.VISIBLE : View.GONE);
}
}
private class CrimeAdapter extends RecyclerView.Adapter<CrimeHolder> {
private List<Crime> mCrimes;
public CrimeAdapter(List<Crime> crimes) {
mCrimes = crimes;
}
@NonNull
@Override
public CrimeHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
return new CrimeHolder(layoutInflater, viewGroup);
}
@Override
public void onBindViewHolder(@NonNull CrimeHolder crimeHolder, int i) {
Crime crime = mCrimes.get(i);
crimeHolder.bind(crime);
}
@Override
public int getItemCount() {
return mCrimes.size();
}
public void setCrimes(List<Crime> crimes) {
mCrimes = crimes;
}
}
}
| 7,453 | 0.658959 | 0.658147 | 205 | 35.07317 | 28.243013 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false |
12
|
40c0b868357ad8448da1080f6c3786aec3b8f58e
| 2,104,534,037,283 |
ddc932d83cd774566a40503202dea323e1dc40db
|
/src/main/java/de/up/ling/irtg/algebra/SetAlgebra.java
|
4635a946e23582a71c35bc20ec95020768eae747
|
[] |
no_license
|
jgontrum/irtg.indexing
|
https://github.com/jgontrum/irtg.indexing
|
fbe0c8df0efb74492ea98b7ca6d45fd5af015ec2
|
b41f03edbacaff5e2735e82b6a8ea492fde133bd
|
refs/heads/master
| 2016-08-03T02:22:12.916000 | 2013-05-31T12:37:28 | 2013-05-31T12:37:28 | 35,878,098 | 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 de.up.ling.irtg.algebra;
import de.up.ling.irtg.automata.TreeAutomaton;
import de.up.ling.irtg.automata.Rule;
import de.up.ling.irtg.signature.Signature;
import de.up.ling.tree.Tree;
import de.up.ling.tree.TreeVisitor;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
*
* @author koller
*/
public class SetAlgebra implements Algebra<Set<List<String>>> {
private static final String PROJECT = "project_";
private static final String INTERSECT = "intersect_";
private static final String UNIQ = "uniq_";
private static final String TOP = "T";
private static final String[] SPECIAL_STRINGS = {PROJECT, INTERSECT, UNIQ};
private static final int MAX_TUPLE_LENGTH = 3;
private final Map<String, Set<List<String>>> atomicInterpretations;
private final Set<String> allIndividuals;
private final Set<String> allLabels;
private final Set<List<String>> allIndividualsAsTuples;
public SetAlgebra() {
this(new HashMap<String, Set<List<String>>>());
}
public SetAlgebra(Map<String, Set<List<String>>> atomicInterpretations) {
this.atomicInterpretations = atomicInterpretations;
allIndividuals = new HashSet<String>();
allIndividualsAsTuples = new HashSet<List<String>>();
for (Set<List<String>> sls : atomicInterpretations.values()) {
for (List<String> ls : sls) {
allIndividuals.addAll(ls);
for (String x : ls) {
List<String> tuple = new ArrayList<String>();
tuple.add(x);
allIndividualsAsTuples.add(tuple);
}
}
}
allLabels = new HashSet<String>();
allLabels.addAll(atomicInterpretations.keySet());
for (int i = 1; i <= MAX_TUPLE_LENGTH; i++) {
allLabels.add(PROJECT + i);
allLabels.add(INTERSECT + i);
}
for (String individual : allIndividuals) {
allLabels.add(UNIQ + individual);
}
}
@Override
public Set<List<String>> evaluate(final Tree<String> t) {
return (Set<List<String>>) t.dfs(new TreeVisitor<String, Void, Set<List<String>>>() {
@Override
public Set<List<String>> combine(Tree<String> node, List<Set<List<String>>> childrenValues) {
return evaluate(node.getLabel(), childrenValues);
}
});
}
private Set<List<String>> evaluate(String label, List<Set<List<String>>> childrenValues) {
if (label.startsWith(PROJECT)) {
return project(childrenValues.get(0), Integer.parseInt(arg(label)) - 1);
} else if (label.startsWith(INTERSECT)) {
return intersect(childrenValues.get(0), childrenValues.get(1), Integer.parseInt(arg(label)) - 1);
} else if (label.startsWith(UNIQ)) {
return uniq(childrenValues.get(0), arg(label));
} else if (label.equals(TOP)) {
return allIndividualsAsTuples;
} else {
return atomicInterpretations.get(label);
}
}
private Set<List<String>> project(Set<List<String>> tupleSet, int pos) {
Set<List<String>> ret = new HashSet<List<String>>();
for (List<String> tuple : tupleSet) {
List<String> l = new ArrayList<String>();
l.add(tuple.get(pos));
ret.add(l);
}
return ret;
}
private Set<List<String>> intersect(Set<List<String>> tupleSet, Set<List<String>> filterSet, int pos) {
Set<String> filter = new HashSet<String>();
Set<List<String>> ret = new HashSet<List<String>>();
for (List<String> f : filterSet) {
filter.add(f.get(0));
}
for (List<String> tuple : tupleSet) {
if (filter.contains(tuple.get(pos))) {
ret.add(tuple);
}
}
return ret;
}
private Set<List<String>> uniq(Set<List<String>> tupleSet, String value) {
List<String> uniqArg = new ArrayList<String>();
uniqArg.add(value);
if (tupleSet.size() == 1 && tupleSet.iterator().next().equals(uniqArg)) {
return tupleSet;
} else {
return new HashSet<List<String>>();
}
}
private static String arg(String stringWithArg) {
for (String s : SPECIAL_STRINGS) {
if (stringWithArg.startsWith(s)) {
return stringWithArg.substring(s.length());
}
}
return null;
}
// private String getLabel(Tree t, String node) {
// return t.getLabel(node).toString();
// }
@Override
public TreeAutomaton decompose(Set<List<String>> value) {
return new SetDecompositionAutomaton(value);
}
@Override
public Signature getSignature() {
throw new UnsupportedOperationException("Not supported yet.");
}
private class SetDecompositionAutomaton extends TreeAutomaton<Set<List<String>>> {
public SetDecompositionAutomaton(Set<List<String>> finalElement) {
super(SetAlgebra.this.getSignature());
finalStates = new HashSet<Set<List<String>>>();
finalStates.add(finalElement);
// this is theoretically correct, but WAY too slow,
// and anyway the Guava powerset function only allows
// up to 30 elements in the base set
// for( int arity = 1; arity <= MAX_TUPLE_LENGTH; arity++ ) {
// List<Set<String>> tupleLists = new ArrayList<Set<String>>();
// for( int i = 0; i < arity; i++ ) {
// tupleLists.add(allIndividuals);
// }
//
// CartesianIterator<String> it = new CartesianIterator<String>(tupleLists);
// Set<List<String>> tuples = new HashSet<List<String>>();
// while( it.hasNext() ) {
// tuples.add(it.next());
// }
//
// Set<Set<List<String>>> powerset = Sets.powerSet(tuples);
// allStates.addAll(powerset);
// }
}
@Override
public Set<Rule<Set<List<String>>>> getRulesBottomUp(String label, List<Set<List<String>>> childStates) {
if (useCachedRuleBottomUp(label, childStates)) {
return getRulesBottomUpFromExplicit(label, childStates);
} else {
Set<Rule<Set<List<String>>>> ret = new HashSet<Rule<Set<List<String>>>>();
Set<List<String>> parents = evaluate(label, childStates);
// require that set in parent state must be non-empty; otherwise there is simply no rule
if (parents != null && !parents.isEmpty()) {
Rule<Set<List<String>>> rule = new Rule<Set<List<String>>>(parents, label, childStates);
ret.add(rule);
storeRule(rule);
}
return ret;
}
}
@Override
public Set<Rule<Set<List<String>>>> getRulesTopDown(String label, Set<List<String>> parentState) {
throw new UnsupportedOperationException("Not supported yet.");
}
// @Override
// public int getArity(String label) {
// if (label.startsWith(UNIQ)) {
// return 1;
// } else if (label.startsWith(INTERSECT)) {
// return 2;
// } else if (label.startsWith(PROJECT)) {
// return 1;
// } else {
// return 0;
// }
// }
@Override
public Set<Set<List<String>>> getFinalStates() {
return finalStates;
}
@Override
// ultimately, only needed for EM training -- and can we get rid of it there?
// (and for correct computation of
public Set<Set<List<String>>> getAllStates() {
return new HashSet<Set<List<String>>>();
}
@Override
public boolean isBottomUpDeterministic() {
return true;
}
}
@Override
public Set<List<String>> parseString(String representation) throws ParserException {
try {
return SetParser.parse(new StringReader(representation));
} catch (ParseException ex) {
throw new ParserException(ex);
}
}
private static List<String> l(String x) {
List<String> ret = new ArrayList<String>();
ret.add(x);
return ret;
}
}
|
UTF-8
|
Java
| 8,791 |
java
|
SetAlgebra.java
|
Java
|
[
{
"context": "util.Map;\nimport java.util.Set;\n\n/**\n *\n * @author koller\n */\npublic class SetAlgebra implements Algebra<Se",
"end": 529,
"score": 0.9975854158401489,
"start": 523,
"tag": "USERNAME",
"value": "koller"
}
] | null |
[] |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package de.up.ling.irtg.algebra;
import de.up.ling.irtg.automata.TreeAutomaton;
import de.up.ling.irtg.automata.Rule;
import de.up.ling.irtg.signature.Signature;
import de.up.ling.tree.Tree;
import de.up.ling.tree.TreeVisitor;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
*
* @author koller
*/
public class SetAlgebra implements Algebra<Set<List<String>>> {
private static final String PROJECT = "project_";
private static final String INTERSECT = "intersect_";
private static final String UNIQ = "uniq_";
private static final String TOP = "T";
private static final String[] SPECIAL_STRINGS = {PROJECT, INTERSECT, UNIQ};
private static final int MAX_TUPLE_LENGTH = 3;
private final Map<String, Set<List<String>>> atomicInterpretations;
private final Set<String> allIndividuals;
private final Set<String> allLabels;
private final Set<List<String>> allIndividualsAsTuples;
public SetAlgebra() {
this(new HashMap<String, Set<List<String>>>());
}
public SetAlgebra(Map<String, Set<List<String>>> atomicInterpretations) {
this.atomicInterpretations = atomicInterpretations;
allIndividuals = new HashSet<String>();
allIndividualsAsTuples = new HashSet<List<String>>();
for (Set<List<String>> sls : atomicInterpretations.values()) {
for (List<String> ls : sls) {
allIndividuals.addAll(ls);
for (String x : ls) {
List<String> tuple = new ArrayList<String>();
tuple.add(x);
allIndividualsAsTuples.add(tuple);
}
}
}
allLabels = new HashSet<String>();
allLabels.addAll(atomicInterpretations.keySet());
for (int i = 1; i <= MAX_TUPLE_LENGTH; i++) {
allLabels.add(PROJECT + i);
allLabels.add(INTERSECT + i);
}
for (String individual : allIndividuals) {
allLabels.add(UNIQ + individual);
}
}
@Override
public Set<List<String>> evaluate(final Tree<String> t) {
return (Set<List<String>>) t.dfs(new TreeVisitor<String, Void, Set<List<String>>>() {
@Override
public Set<List<String>> combine(Tree<String> node, List<Set<List<String>>> childrenValues) {
return evaluate(node.getLabel(), childrenValues);
}
});
}
private Set<List<String>> evaluate(String label, List<Set<List<String>>> childrenValues) {
if (label.startsWith(PROJECT)) {
return project(childrenValues.get(0), Integer.parseInt(arg(label)) - 1);
} else if (label.startsWith(INTERSECT)) {
return intersect(childrenValues.get(0), childrenValues.get(1), Integer.parseInt(arg(label)) - 1);
} else if (label.startsWith(UNIQ)) {
return uniq(childrenValues.get(0), arg(label));
} else if (label.equals(TOP)) {
return allIndividualsAsTuples;
} else {
return atomicInterpretations.get(label);
}
}
private Set<List<String>> project(Set<List<String>> tupleSet, int pos) {
Set<List<String>> ret = new HashSet<List<String>>();
for (List<String> tuple : tupleSet) {
List<String> l = new ArrayList<String>();
l.add(tuple.get(pos));
ret.add(l);
}
return ret;
}
private Set<List<String>> intersect(Set<List<String>> tupleSet, Set<List<String>> filterSet, int pos) {
Set<String> filter = new HashSet<String>();
Set<List<String>> ret = new HashSet<List<String>>();
for (List<String> f : filterSet) {
filter.add(f.get(0));
}
for (List<String> tuple : tupleSet) {
if (filter.contains(tuple.get(pos))) {
ret.add(tuple);
}
}
return ret;
}
private Set<List<String>> uniq(Set<List<String>> tupleSet, String value) {
List<String> uniqArg = new ArrayList<String>();
uniqArg.add(value);
if (tupleSet.size() == 1 && tupleSet.iterator().next().equals(uniqArg)) {
return tupleSet;
} else {
return new HashSet<List<String>>();
}
}
private static String arg(String stringWithArg) {
for (String s : SPECIAL_STRINGS) {
if (stringWithArg.startsWith(s)) {
return stringWithArg.substring(s.length());
}
}
return null;
}
// private String getLabel(Tree t, String node) {
// return t.getLabel(node).toString();
// }
@Override
public TreeAutomaton decompose(Set<List<String>> value) {
return new SetDecompositionAutomaton(value);
}
@Override
public Signature getSignature() {
throw new UnsupportedOperationException("Not supported yet.");
}
private class SetDecompositionAutomaton extends TreeAutomaton<Set<List<String>>> {
public SetDecompositionAutomaton(Set<List<String>> finalElement) {
super(SetAlgebra.this.getSignature());
finalStates = new HashSet<Set<List<String>>>();
finalStates.add(finalElement);
// this is theoretically correct, but WAY too slow,
// and anyway the Guava powerset function only allows
// up to 30 elements in the base set
// for( int arity = 1; arity <= MAX_TUPLE_LENGTH; arity++ ) {
// List<Set<String>> tupleLists = new ArrayList<Set<String>>();
// for( int i = 0; i < arity; i++ ) {
// tupleLists.add(allIndividuals);
// }
//
// CartesianIterator<String> it = new CartesianIterator<String>(tupleLists);
// Set<List<String>> tuples = new HashSet<List<String>>();
// while( it.hasNext() ) {
// tuples.add(it.next());
// }
//
// Set<Set<List<String>>> powerset = Sets.powerSet(tuples);
// allStates.addAll(powerset);
// }
}
@Override
public Set<Rule<Set<List<String>>>> getRulesBottomUp(String label, List<Set<List<String>>> childStates) {
if (useCachedRuleBottomUp(label, childStates)) {
return getRulesBottomUpFromExplicit(label, childStates);
} else {
Set<Rule<Set<List<String>>>> ret = new HashSet<Rule<Set<List<String>>>>();
Set<List<String>> parents = evaluate(label, childStates);
// require that set in parent state must be non-empty; otherwise there is simply no rule
if (parents != null && !parents.isEmpty()) {
Rule<Set<List<String>>> rule = new Rule<Set<List<String>>>(parents, label, childStates);
ret.add(rule);
storeRule(rule);
}
return ret;
}
}
@Override
public Set<Rule<Set<List<String>>>> getRulesTopDown(String label, Set<List<String>> parentState) {
throw new UnsupportedOperationException("Not supported yet.");
}
// @Override
// public int getArity(String label) {
// if (label.startsWith(UNIQ)) {
// return 1;
// } else if (label.startsWith(INTERSECT)) {
// return 2;
// } else if (label.startsWith(PROJECT)) {
// return 1;
// } else {
// return 0;
// }
// }
@Override
public Set<Set<List<String>>> getFinalStates() {
return finalStates;
}
@Override
// ultimately, only needed for EM training -- and can we get rid of it there?
// (and for correct computation of
public Set<Set<List<String>>> getAllStates() {
return new HashSet<Set<List<String>>>();
}
@Override
public boolean isBottomUpDeterministic() {
return true;
}
}
@Override
public Set<List<String>> parseString(String representation) throws ParserException {
try {
return SetParser.parse(new StringReader(representation));
} catch (ParseException ex) {
throw new ParserException(ex);
}
}
private static List<String> l(String x) {
List<String> ret = new ArrayList<String>();
ret.add(x);
return ret;
}
}
| 8,791 | 0.56865 | 0.566602 | 254 | 33.610237 | 27.890705 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.511811 | false | false |
12
|
4c77d56c20b88db34372ebf75a4273222c4f89de
| 4,234,837,765,188 |
3a9acd28ac5abdca076f57b29b1d4e3a1c9bc3b4
|
/app/src/main/java/com/example/userprofile/di/UserProfileComponent.java
|
ae6bf1483e53310b2d0c888512b49a490238fd8d
|
[
"Apache-2.0"
] |
permissive
|
hyd2016/profile-mvvm
|
https://github.com/hyd2016/profile-mvvm
|
a1a19cc99523d2ed5ff0efcccb2007b661ad70a7
|
09a7de03f4341b80d2193a275c5cb9ec43e0e91a
|
refs/heads/master
| 2020-08-03T16:10:43.298000 | 2019-10-11T11:38:59 | 2019-10-11T11:38:59 | 211,809,611 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.userprofile.di;
import com.example.userprofile.repository.UserProfileRepository;
import com.example.userprofile.repository.published.PublishDataSource;
import com.example.userprofile.repository.recommend.RecommenDataSource;
import com.example.userprofile.view.MusicHistoryFragment;
import com.example.userprofile.view.SearchFragment;
import com.example.userprofile.view.UserProfileActivity;
import com.example.userprofile.viewmodel.PublishViewModel;
import javax.inject.Singleton;
import dagger.Component;
/**
* @descriptioon:
* @author: dinghaoyu
* @date: 2019-10-06 11:29
*/
@Singleton
@Component(modules = {UserProfileModule.class})
public interface UserProfileComponent{
void inject(UserProfileRepository userProfileRepository);
void inject(PublishDataSource publishDataSource);
void inject(RecommenDataSource recommenDataSource);
void inject(UserProfileActivity userProfileActivity);
void inject(PublishViewModel publishViewModel);
void inject(MusicHistoryFragment musicHistoryFragment);
void inject(SearchFragment searchFragment);
}
|
UTF-8
|
Java
| 1,096 |
java
|
UserProfileComponent.java
|
Java
|
[
{
"context": "gger.Component;\n\n/**\n * @descriptioon:\n * @author: dinghaoyu\n * @date: 2019-10-06 11:29\n */\n\n@Singleton\n@Compo",
"end": 573,
"score": 0.9981250762939453,
"start": 564,
"tag": "USERNAME",
"value": "dinghaoyu"
}
] | null |
[] |
package com.example.userprofile.di;
import com.example.userprofile.repository.UserProfileRepository;
import com.example.userprofile.repository.published.PublishDataSource;
import com.example.userprofile.repository.recommend.RecommenDataSource;
import com.example.userprofile.view.MusicHistoryFragment;
import com.example.userprofile.view.SearchFragment;
import com.example.userprofile.view.UserProfileActivity;
import com.example.userprofile.viewmodel.PublishViewModel;
import javax.inject.Singleton;
import dagger.Component;
/**
* @descriptioon:
* @author: dinghaoyu
* @date: 2019-10-06 11:29
*/
@Singleton
@Component(modules = {UserProfileModule.class})
public interface UserProfileComponent{
void inject(UserProfileRepository userProfileRepository);
void inject(PublishDataSource publishDataSource);
void inject(RecommenDataSource recommenDataSource);
void inject(UserProfileActivity userProfileActivity);
void inject(PublishViewModel publishViewModel);
void inject(MusicHistoryFragment musicHistoryFragment);
void inject(SearchFragment searchFragment);
}
| 1,096 | 0.82573 | 0.814781 | 31 | 34.354839 | 24.608612 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.548387 | false | false |
12
|
ae834d496af5d98e3d6b1cfa37b18f9e35d302a1
| 10,806,137,727,897 |
cdb86546d5053670ee31edeadedd1922fd4424db
|
/app/src/main/java/com/hackathon/codechefapp/constants/PreferenceConstants.java
|
53c5941085f70ebe40effde4e8bb6d88f796f2f9
|
[] |
no_license
|
Sandip-Jana/codechef-mentor
|
https://github.com/Sandip-Jana/codechef-mentor
|
32b5617255fb7a59ae5265bb0797129820660f35
|
f3655ab053413303d2b303412b6519dae48f02a7
|
refs/heads/master
| 2021-08-08T15:50:00.153000 | 2019-01-02T16:03:26 | 2019-01-02T16:03:26 | 150,985,157 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.hackathon.codechefapp.constants;
/**
* Created by SANDIP JANA on 10-09-2018.
*/
public final class PreferenceConstants {
//added for access tokens
public static final String AUTH_CODE = "Auth-Code";
public static final String ACCESS_TOKEN_UPDATED = "accessToken_updated";
public static final String ACCESS_TOKEN = "access_token";
public static final String REFRESH_TOKEN = "refresh_token";
//added for fecthing username
public static final String USER_PROFILE = "user_profile";
public static final String LOGGED_IN_USER_NAME = "user_name_logged_in";
//added for maintaining cookies & privacy in rooms chat
public static final String COOKIES = "cookies";
//added for problems nav
public static final String CONTESTCODE = "contest_code";
public static final String PROBLEM_CODE = "problem_code";
}
|
UTF-8
|
Java
| 867 |
java
|
PreferenceConstants.java
|
Java
|
[
{
"context": "ackathon.codechefapp.constants;\n\n/**\n * Created by SANDIP JANA on 10-09-2018.\n */\npublic final class PreferenceC",
"end": 75,
"score": 0.9996377229690552,
"start": 64,
"tag": "NAME",
"value": "SANDIP JANA"
}
] | null |
[] |
package com.hackathon.codechefapp.constants;
/**
* Created by <NAME> on 10-09-2018.
*/
public final class PreferenceConstants {
//added for access tokens
public static final String AUTH_CODE = "Auth-Code";
public static final String ACCESS_TOKEN_UPDATED = "accessToken_updated";
public static final String ACCESS_TOKEN = "access_token";
public static final String REFRESH_TOKEN = "refresh_token";
//added for fecthing username
public static final String USER_PROFILE = "user_profile";
public static final String LOGGED_IN_USER_NAME = "user_name_logged_in";
//added for maintaining cookies & privacy in rooms chat
public static final String COOKIES = "cookies";
//added for problems nav
public static final String CONTESTCODE = "contest_code";
public static final String PROBLEM_CODE = "problem_code";
}
| 862 | 0.723183 | 0.713956 | 24 | 35.125 | 27.002026 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.416667 | false | false |
12
|
50902b11772d865d3e672ae471f423cc87bab1c1
| 28,441,273,466,616 |
8d8b97d9af3dd6120b62eeec6d4dc6ac9324a320
|
/src/main/java/com/lesson/service/impl/BookServiceImpl.java
|
1a5564c3a0544434f10c5b0bf413d9bb36ed553d
|
[] |
no_license
|
PanruifengWawa/lesson
|
https://github.com/PanruifengWawa/lesson
|
97c62e57b0d30dec6c5b88381cd0775300ba7abb
|
194ae43fff749325e68ab4cefe4dc26a40145025
|
refs/heads/master
| 2020-04-05T12:38:30.815000 | 2017-12-11T14:15:04 | 2017-12-11T14:15:04 | 95,204,301 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.lesson.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import com.lesson.enums.BookOrigin;
import com.lesson.exceptions.AuthException;
import com.lesson.exceptions.DBException;
import com.lesson.exceptions.ParameterException;
import com.lesson.models.Book;
import com.lesson.repository.BookRepository;
import com.lesson.service.BookService;
import com.lesson.utils.DataWrapper;
@Service
public class BookServiceImpl implements BookService {
@Autowired
BookRepository bookRepository;
@Override
public DataWrapper<List<Book>> getUserBookListByUserId(Long userId, Integer numberPerPage, Integer currentPage) {
// TODO Auto-generated method stub
if (numberPerPage == null || numberPerPage <= 0 || numberPerPage > 50) {
numberPerPage = 10;
}
if (currentPage == null || currentPage <= 0) {
currentPage = 1;
}
Pageable pageable = new PageRequest(currentPage-1, numberPerPage);
Page<Book> page = bookRepository.findBookListByUserId(userId, pageable);
DataWrapper<List<Book>> dataWrapper = new DataWrapper<List<Book>>();
dataWrapper.setData(page.getContent());
dataWrapper.setTotalNumber((int)page.getTotalElements());
dataWrapper.setCurrentPage(currentPage);
dataWrapper.setTotalPage(page.getTotalPages());
dataWrapper.setNumberPerPage(numberPerPage);
return dataWrapper;
}
@Override
public DataWrapper<Book> addBook(Book book) {
// TODO Auto-generated method stub
if (book.getBookName() == null || book.getBookName().equals("")) {
throw new ParameterException("绘本名称为空");
}
if (book.getBookImgSrc() == null || book.getBookImgSrc().equals("")) {
throw new ParameterException("绘本封面为空");
}
if (book.getUserId() == null) {
throw new ParameterException("用户未登录");
}
if (book.getReadDate() == null) {
throw new ParameterException("阅读时间错误");
}
book.setBookId(null);
book.setIsCourseBook(BookOrigin.PersonalBook.getCode());
book.setCourseContentId(null);
try {
bookRepository.save(book);
} catch (Exception e) {
// TODO: handle exception
throw new DBException("数据库错误",e);
}
DataWrapper<Book> dataWrapper = new DataWrapper<Book>();
dataWrapper.setData(book);
return dataWrapper;
}
@Override
public DataWrapper<Void> deleteBook(Long userId, Long bookId) {
// TODO Auto-generated method stub
Book book = bookRepository.findByBookId(bookId);
if (book == null) {
throw new AuthException("绘本不存在");
}
if (!book.getUserId().equals(userId)) {
throw new AuthException("无权删不属于自己的书籍");
}
if (book.getIsCourseBook().equals(BookOrigin.CourseBook.getCode())) {
throw new AuthException("无权删除课程书籍");
}
try {
bookRepository.delete(book);
} catch (Exception e) {
// TODO: handle exception
throw new DBException("数据库错误",e);
}
DataWrapper<Void> dataWrapper = new DataWrapper<Void>();
return dataWrapper;
}
}
|
UTF-8
|
Java
| 3,236 |
java
|
BookServiceImpl.java
|
Java
|
[] | null |
[] |
package com.lesson.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import com.lesson.enums.BookOrigin;
import com.lesson.exceptions.AuthException;
import com.lesson.exceptions.DBException;
import com.lesson.exceptions.ParameterException;
import com.lesson.models.Book;
import com.lesson.repository.BookRepository;
import com.lesson.service.BookService;
import com.lesson.utils.DataWrapper;
@Service
public class BookServiceImpl implements BookService {
@Autowired
BookRepository bookRepository;
@Override
public DataWrapper<List<Book>> getUserBookListByUserId(Long userId, Integer numberPerPage, Integer currentPage) {
// TODO Auto-generated method stub
if (numberPerPage == null || numberPerPage <= 0 || numberPerPage > 50) {
numberPerPage = 10;
}
if (currentPage == null || currentPage <= 0) {
currentPage = 1;
}
Pageable pageable = new PageRequest(currentPage-1, numberPerPage);
Page<Book> page = bookRepository.findBookListByUserId(userId, pageable);
DataWrapper<List<Book>> dataWrapper = new DataWrapper<List<Book>>();
dataWrapper.setData(page.getContent());
dataWrapper.setTotalNumber((int)page.getTotalElements());
dataWrapper.setCurrentPage(currentPage);
dataWrapper.setTotalPage(page.getTotalPages());
dataWrapper.setNumberPerPage(numberPerPage);
return dataWrapper;
}
@Override
public DataWrapper<Book> addBook(Book book) {
// TODO Auto-generated method stub
if (book.getBookName() == null || book.getBookName().equals("")) {
throw new ParameterException("绘本名称为空");
}
if (book.getBookImgSrc() == null || book.getBookImgSrc().equals("")) {
throw new ParameterException("绘本封面为空");
}
if (book.getUserId() == null) {
throw new ParameterException("用户未登录");
}
if (book.getReadDate() == null) {
throw new ParameterException("阅读时间错误");
}
book.setBookId(null);
book.setIsCourseBook(BookOrigin.PersonalBook.getCode());
book.setCourseContentId(null);
try {
bookRepository.save(book);
} catch (Exception e) {
// TODO: handle exception
throw new DBException("数据库错误",e);
}
DataWrapper<Book> dataWrapper = new DataWrapper<Book>();
dataWrapper.setData(book);
return dataWrapper;
}
@Override
public DataWrapper<Void> deleteBook(Long userId, Long bookId) {
// TODO Auto-generated method stub
Book book = bookRepository.findByBookId(bookId);
if (book == null) {
throw new AuthException("绘本不存在");
}
if (!book.getUserId().equals(userId)) {
throw new AuthException("无权删不属于自己的书籍");
}
if (book.getIsCourseBook().equals(BookOrigin.CourseBook.getCode())) {
throw new AuthException("无权删除课程书籍");
}
try {
bookRepository.delete(book);
} catch (Exception e) {
// TODO: handle exception
throw new DBException("数据库错误",e);
}
DataWrapper<Void> dataWrapper = new DataWrapper<Void>();
return dataWrapper;
}
}
| 3,236 | 0.730942 | 0.728379 | 103 | 29.31068 | 23.710238 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.067961 | false | false |
12
|
fa232fbb67e5bc3504ef42d001cc060fdb204e75
| 9,981,504,004,237 |
2a654fd308c3ec47a54b9652dcd24b75dd335975
|
/src/main/java/ru/bjcreslin/service/criteria/TaskCriteria.java
|
f9d1a40e139f913a8360668e9e7e4920bcdf4922
|
[] |
no_license
|
BJCreslin/Home-for-your-projects
|
https://github.com/BJCreslin/Home-for-your-projects
|
74b54205477f2b661e7f0e17eecf5a3b71fb1f20
|
1d46355541b4cec5478be603523456890e3d62fe
|
refs/heads/main
| 2023-03-30T21:50:19.134000 | 2021-04-05T12:55:14 | 2021-04-05T12:55:14 | 352,530,707 | 0 | 0 | null | false | 2021-03-29T06:23:14 | 2021-03-29T05:51:30 | 2021-03-29T05:51:50 | 2021-03-29T06:23:13 | 0 | 0 | 0 | 0 |
Java
| false | false |
package ru.bjcreslin.service.criteria;
import java.io.Serializable;
import java.util.Objects;
import ru.bjcreslin.domain.enumeration.TaskAndProjectStatus;
import tech.jhipster.service.Criteria;
import tech.jhipster.service.filter.BooleanFilter;
import tech.jhipster.service.filter.DoubleFilter;
import tech.jhipster.service.filter.Filter;
import tech.jhipster.service.filter.FloatFilter;
import tech.jhipster.service.filter.IntegerFilter;
import tech.jhipster.service.filter.LongFilter;
import tech.jhipster.service.filter.StringFilter;
import tech.jhipster.service.filter.ZonedDateTimeFilter;
/**
* Criteria class for the {@link ru.bjcreslin.domain.Task} entity. This class is used
* in {@link ru.bjcreslin.web.rest.TaskResource} to receive all the possible filtering options from
* the Http GET request parameters.
* For example the following could be a valid request:
* {@code /tasks?id.greaterThan=5&attr1.contains=something&attr2.specified=false}
* As Spring is unable to properly convert the types, unless specific {@link Filter} class are used, we need to use
* fix type specific filters.
*/
public class TaskCriteria implements Serializable, Criteria {
/**
* Class for filtering TaskAndProjectStatus
*/
public static class TaskAndProjectStatusFilter extends Filter<TaskAndProjectStatus> {
public TaskAndProjectStatusFilter() {}
public TaskAndProjectStatusFilter(TaskAndProjectStatusFilter filter) {
super(filter);
}
@Override
public TaskAndProjectStatusFilter copy() {
return new TaskAndProjectStatusFilter(this);
}
}
private static final long serialVersionUID = 1L;
private LongFilter id;
private StringFilter author;
private StringFilter implementer;
private StringFilter name;
private StringFilter text;
private StringFilter comment;
private TaskAndProjectStatusFilter status;
private ZonedDateTimeFilter created;
private ZonedDateTimeFilter edited;
private LongFilter commentId;
private LongFilter projectId;
public TaskCriteria() {}
public TaskCriteria(TaskCriteria other) {
this.id = other.id == null ? null : other.id.copy();
this.author = other.author == null ? null : other.author.copy();
this.implementer = other.implementer == null ? null : other.implementer.copy();
this.name = other.name == null ? null : other.name.copy();
this.text = other.text == null ? null : other.text.copy();
this.comment = other.comment == null ? null : other.comment.copy();
this.status = other.status == null ? null : other.status.copy();
this.created = other.created == null ? null : other.created.copy();
this.edited = other.edited == null ? null : other.edited.copy();
this.commentId = other.commentId == null ? null : other.commentId.copy();
this.projectId = other.projectId == null ? null : other.projectId.copy();
}
@Override
public TaskCriteria copy() {
return new TaskCriteria(this);
}
public LongFilter getId() {
return id;
}
public LongFilter id() {
if (id == null) {
id = new LongFilter();
}
return id;
}
public void setId(LongFilter id) {
this.id = id;
}
public StringFilter getAuthor() {
return author;
}
public StringFilter author() {
if (author == null) {
author = new StringFilter();
}
return author;
}
public void setAuthor(StringFilter author) {
this.author = author;
}
public StringFilter getImplementer() {
return implementer;
}
public StringFilter implementer() {
if (implementer == null) {
implementer = new StringFilter();
}
return implementer;
}
public void setImplementer(StringFilter implementer) {
this.implementer = implementer;
}
public StringFilter getName() {
return name;
}
public StringFilter name() {
if (name == null) {
name = new StringFilter();
}
return name;
}
public void setName(StringFilter name) {
this.name = name;
}
public StringFilter getText() {
return text;
}
public StringFilter text() {
if (text == null) {
text = new StringFilter();
}
return text;
}
public void setText(StringFilter text) {
this.text = text;
}
public StringFilter getComment() {
return comment;
}
public StringFilter comment() {
if (comment == null) {
comment = new StringFilter();
}
return comment;
}
public void setComment(StringFilter comment) {
this.comment = comment;
}
public TaskAndProjectStatusFilter getStatus() {
return status;
}
public TaskAndProjectStatusFilter status() {
if (status == null) {
status = new TaskAndProjectStatusFilter();
}
return status;
}
public void setStatus(TaskAndProjectStatusFilter status) {
this.status = status;
}
public ZonedDateTimeFilter getCreated() {
return created;
}
public ZonedDateTimeFilter created() {
if (created == null) {
created = new ZonedDateTimeFilter();
}
return created;
}
public void setCreated(ZonedDateTimeFilter created) {
this.created = created;
}
public ZonedDateTimeFilter getEdited() {
return edited;
}
public ZonedDateTimeFilter edited() {
if (edited == null) {
edited = new ZonedDateTimeFilter();
}
return edited;
}
public void setEdited(ZonedDateTimeFilter edited) {
this.edited = edited;
}
public LongFilter getCommentId() {
return commentId;
}
public LongFilter commentId() {
if (commentId == null) {
commentId = new LongFilter();
}
return commentId;
}
public void setCommentId(LongFilter commentId) {
this.commentId = commentId;
}
public LongFilter getProjectId() {
return projectId;
}
public LongFilter projectId() {
if (projectId == null) {
projectId = new LongFilter();
}
return projectId;
}
public void setProjectId(LongFilter projectId) {
this.projectId = projectId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final TaskCriteria that = (TaskCriteria) o;
return (
Objects.equals(id, that.id) &&
Objects.equals(author, that.author) &&
Objects.equals(implementer, that.implementer) &&
Objects.equals(name, that.name) &&
Objects.equals(text, that.text) &&
Objects.equals(comment, that.comment) &&
Objects.equals(status, that.status) &&
Objects.equals(created, that.created) &&
Objects.equals(edited, that.edited) &&
Objects.equals(commentId, that.commentId) &&
Objects.equals(projectId, that.projectId)
);
}
@Override
public int hashCode() {
return Objects.hash(id, author, implementer, name, text, comment, status, created, edited, commentId, projectId);
}
// prettier-ignore
@Override
public String toString() {
return "TaskCriteria{" +
(id != null ? "id=" + id + ", " : "") +
(author != null ? "author=" + author + ", " : "") +
(implementer != null ? "implementer=" + implementer + ", " : "") +
(name != null ? "name=" + name + ", " : "") +
(text != null ? "text=" + text + ", " : "") +
(comment != null ? "comment=" + comment + ", " : "") +
(status != null ? "status=" + status + ", " : "") +
(created != null ? "created=" + created + ", " : "") +
(edited != null ? "edited=" + edited + ", " : "") +
(commentId != null ? "commentId=" + commentId + ", " : "") +
(projectId != null ? "projectId=" + projectId + ", " : "") +
"}";
}
}
|
UTF-8
|
Java
| 8,396 |
java
|
TaskCriteria.java
|
Java
|
[] | null |
[] |
package ru.bjcreslin.service.criteria;
import java.io.Serializable;
import java.util.Objects;
import ru.bjcreslin.domain.enumeration.TaskAndProjectStatus;
import tech.jhipster.service.Criteria;
import tech.jhipster.service.filter.BooleanFilter;
import tech.jhipster.service.filter.DoubleFilter;
import tech.jhipster.service.filter.Filter;
import tech.jhipster.service.filter.FloatFilter;
import tech.jhipster.service.filter.IntegerFilter;
import tech.jhipster.service.filter.LongFilter;
import tech.jhipster.service.filter.StringFilter;
import tech.jhipster.service.filter.ZonedDateTimeFilter;
/**
* Criteria class for the {@link ru.bjcreslin.domain.Task} entity. This class is used
* in {@link ru.bjcreslin.web.rest.TaskResource} to receive all the possible filtering options from
* the Http GET request parameters.
* For example the following could be a valid request:
* {@code /tasks?id.greaterThan=5&attr1.contains=something&attr2.specified=false}
* As Spring is unable to properly convert the types, unless specific {@link Filter} class are used, we need to use
* fix type specific filters.
*/
public class TaskCriteria implements Serializable, Criteria {
/**
* Class for filtering TaskAndProjectStatus
*/
public static class TaskAndProjectStatusFilter extends Filter<TaskAndProjectStatus> {
public TaskAndProjectStatusFilter() {}
public TaskAndProjectStatusFilter(TaskAndProjectStatusFilter filter) {
super(filter);
}
@Override
public TaskAndProjectStatusFilter copy() {
return new TaskAndProjectStatusFilter(this);
}
}
private static final long serialVersionUID = 1L;
private LongFilter id;
private StringFilter author;
private StringFilter implementer;
private StringFilter name;
private StringFilter text;
private StringFilter comment;
private TaskAndProjectStatusFilter status;
private ZonedDateTimeFilter created;
private ZonedDateTimeFilter edited;
private LongFilter commentId;
private LongFilter projectId;
public TaskCriteria() {}
public TaskCriteria(TaskCriteria other) {
this.id = other.id == null ? null : other.id.copy();
this.author = other.author == null ? null : other.author.copy();
this.implementer = other.implementer == null ? null : other.implementer.copy();
this.name = other.name == null ? null : other.name.copy();
this.text = other.text == null ? null : other.text.copy();
this.comment = other.comment == null ? null : other.comment.copy();
this.status = other.status == null ? null : other.status.copy();
this.created = other.created == null ? null : other.created.copy();
this.edited = other.edited == null ? null : other.edited.copy();
this.commentId = other.commentId == null ? null : other.commentId.copy();
this.projectId = other.projectId == null ? null : other.projectId.copy();
}
@Override
public TaskCriteria copy() {
return new TaskCriteria(this);
}
public LongFilter getId() {
return id;
}
public LongFilter id() {
if (id == null) {
id = new LongFilter();
}
return id;
}
public void setId(LongFilter id) {
this.id = id;
}
public StringFilter getAuthor() {
return author;
}
public StringFilter author() {
if (author == null) {
author = new StringFilter();
}
return author;
}
public void setAuthor(StringFilter author) {
this.author = author;
}
public StringFilter getImplementer() {
return implementer;
}
public StringFilter implementer() {
if (implementer == null) {
implementer = new StringFilter();
}
return implementer;
}
public void setImplementer(StringFilter implementer) {
this.implementer = implementer;
}
public StringFilter getName() {
return name;
}
public StringFilter name() {
if (name == null) {
name = new StringFilter();
}
return name;
}
public void setName(StringFilter name) {
this.name = name;
}
public StringFilter getText() {
return text;
}
public StringFilter text() {
if (text == null) {
text = new StringFilter();
}
return text;
}
public void setText(StringFilter text) {
this.text = text;
}
public StringFilter getComment() {
return comment;
}
public StringFilter comment() {
if (comment == null) {
comment = new StringFilter();
}
return comment;
}
public void setComment(StringFilter comment) {
this.comment = comment;
}
public TaskAndProjectStatusFilter getStatus() {
return status;
}
public TaskAndProjectStatusFilter status() {
if (status == null) {
status = new TaskAndProjectStatusFilter();
}
return status;
}
public void setStatus(TaskAndProjectStatusFilter status) {
this.status = status;
}
public ZonedDateTimeFilter getCreated() {
return created;
}
public ZonedDateTimeFilter created() {
if (created == null) {
created = new ZonedDateTimeFilter();
}
return created;
}
public void setCreated(ZonedDateTimeFilter created) {
this.created = created;
}
public ZonedDateTimeFilter getEdited() {
return edited;
}
public ZonedDateTimeFilter edited() {
if (edited == null) {
edited = new ZonedDateTimeFilter();
}
return edited;
}
public void setEdited(ZonedDateTimeFilter edited) {
this.edited = edited;
}
public LongFilter getCommentId() {
return commentId;
}
public LongFilter commentId() {
if (commentId == null) {
commentId = new LongFilter();
}
return commentId;
}
public void setCommentId(LongFilter commentId) {
this.commentId = commentId;
}
public LongFilter getProjectId() {
return projectId;
}
public LongFilter projectId() {
if (projectId == null) {
projectId = new LongFilter();
}
return projectId;
}
public void setProjectId(LongFilter projectId) {
this.projectId = projectId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final TaskCriteria that = (TaskCriteria) o;
return (
Objects.equals(id, that.id) &&
Objects.equals(author, that.author) &&
Objects.equals(implementer, that.implementer) &&
Objects.equals(name, that.name) &&
Objects.equals(text, that.text) &&
Objects.equals(comment, that.comment) &&
Objects.equals(status, that.status) &&
Objects.equals(created, that.created) &&
Objects.equals(edited, that.edited) &&
Objects.equals(commentId, that.commentId) &&
Objects.equals(projectId, that.projectId)
);
}
@Override
public int hashCode() {
return Objects.hash(id, author, implementer, name, text, comment, status, created, edited, commentId, projectId);
}
// prettier-ignore
@Override
public String toString() {
return "TaskCriteria{" +
(id != null ? "id=" + id + ", " : "") +
(author != null ? "author=" + author + ", " : "") +
(implementer != null ? "implementer=" + implementer + ", " : "") +
(name != null ? "name=" + name + ", " : "") +
(text != null ? "text=" + text + ", " : "") +
(comment != null ? "comment=" + comment + ", " : "") +
(status != null ? "status=" + status + ", " : "") +
(created != null ? "created=" + created + ", " : "") +
(edited != null ? "edited=" + edited + ", " : "") +
(commentId != null ? "commentId=" + commentId + ", " : "") +
(projectId != null ? "projectId=" + projectId + ", " : "") +
"}";
}
}
| 8,396 | 0.594926 | 0.59445 | 300 | 26.986666 | 24.319946 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.42 | false | false |
12
|
0588d9c5d206cb84245a9762b436d20fb2f1d786
| 19,920,058,379,448 |
56018763d3aee2d7709b75b29846ac5fe4bb4368
|
/app/src/main/java/com/beans/FoodItem.java
|
e9d8a6993d8c37568cba12e036ffae14d860aacc
|
[] |
no_license
|
Institute-for-Future-Health/food-journal
|
https://github.com/Institute-for-Future-Health/food-journal
|
42a7faff7f5a5f5f3cc3f33d044d8d4bc84f43d5
|
d01eb8fbe850b47899c843469e0e50838d1d2457
|
refs/heads/master
| 2020-03-23T15:18:20.515000 | 2018-07-27T00:03:43 | 2018-07-27T00:03:43 | 141,736,901 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.beans;
class FoodItem{
private FoodBean [] ItemList;
public FoodItem(FoodBean[] itemList) {
ItemList = itemList;
}
public FoodBean[] getItemList() {
return ItemList;
}
public void setItemList(FoodBean[] itemList) {
ItemList = itemList;
}
}
|
UTF-8
|
Java
| 308 |
java
|
FoodItem.java
|
Java
|
[] | null |
[] |
package com.beans;
class FoodItem{
private FoodBean [] ItemList;
public FoodItem(FoodBean[] itemList) {
ItemList = itemList;
}
public FoodBean[] getItemList() {
return ItemList;
}
public void setItemList(FoodBean[] itemList) {
ItemList = itemList;
}
}
| 308 | 0.613636 | 0.613636 | 17 | 17.117647 | 16.287428 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.294118 | false | false |
12
|
e8763a9e2a300d67cca1fb60df59b19ea2b7f513
| 29,738,353,563,350 |
cf00ccef2f54f818e907d5d2dd2a6b94e4e3f819
|
/HnitFleaMarket-service/src/main/java/org/hnitacm/service/impl/OrderInfoServiceImpl.java
|
95fa19560a83ca9b5a054b6720d45e2b748066bc
|
[] |
no_license
|
Qoudao/HnitFleaMarket
|
https://github.com/Qoudao/HnitFleaMarket
|
8a6e0e0cea88d0524251749765c89b877c9e4724
|
66b71e425dc4fa77a6da5d0402ed0215af007dbd
|
refs/heads/master
| 2022-09-13T01:12:24.381000 | 2020-05-21T19:33:54 | 2020-05-21T19:33:54 | 265,971,674 | 1 | 1 | null | true | 2020-05-21T23:16:54 | 2020-05-21T23:16:53 | 2020-05-21T19:34:04 | 2020-05-21T19:34:02 | 195 | 0 | 0 | 0 | null | false | false |
package org.hnitacm.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.hnitacm.mapper.OrderInfoMapper;
import org.hnitacm.pojo.OrderInfo;
import org.hnitacm.service.OrderInfoService;
import org.springframework.stereotype.Service;
/**
* <p>
* 服务实现类
* </p>
*
* @author Leo
* @since 2020-05-21
*/
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {
}
|
UTF-8
|
Java
| 481 |
java
|
OrderInfoServiceImpl.java
|
Java
|
[
{
"context": "rvice;\n\n/**\n * <p>\n * 服务实现类\n * </p>\n *\n * @author Leo\n * @since 2020-05-21\n */\n@Service\npublic class Or",
"end": 321,
"score": 0.9041601419448853,
"start": 318,
"tag": "NAME",
"value": "Leo"
}
] | null |
[] |
package org.hnitacm.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.hnitacm.mapper.OrderInfoMapper;
import org.hnitacm.pojo.OrderInfo;
import org.hnitacm.service.OrderInfoService;
import org.springframework.stereotype.Service;
/**
* <p>
* 服务实现类
* </p>
*
* @author Leo
* @since 2020-05-21
*/
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {
}
| 481 | 0.781316 | 0.764331 | 21 | 21.428572 | 27.669085 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false |
12
|
e87d52ed4aca80e539cbd9856d9eec173ccc3691
| 29,094,108,479,126 |
81f94829d7096332efb35f64d66c3c68cbb48133
|
/src/Excercises/SimpleConditions/SumSeconds.java
|
810c6631a6f3968261f9488af887e9a870c9c41f
|
[] |
no_license
|
alveree/ProgrammingBasicsJavaSeptember
|
https://github.com/alveree/ProgrammingBasicsJavaSeptember
|
25fad93fce4363039e7f8eed11e0169b360aa82c
|
f28e344e94dbddf8b039d1569a9dfc5b9a9b172d
|
refs/heads/master
| 2020-07-02T22:06:43.191000 | 2016-11-04T19:12:23 | 2016-11-04T19:12:23 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Excercises.SimpleConditions;
import java.util.Scanner;
public class SumSeconds {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int firstRacerTimeInSeconds = Integer.parseInt(
console.nextLine());
int secondRacerTimeInSeconds = Integer.parseInt(
console.nextLine());
int thirdRacerTimeInSeconds = Integer.parseInt(
console.nextLine());
int totalSeconds = firstRacerTimeInSeconds +
secondRacerTimeInSeconds +
thirdRacerTimeInSeconds;
int minutesInTotalSeconds = totalSeconds / 60;
int pureSecondsInTotalSeconds = totalSeconds % 60;
System.out.printf("%d:%02d",
minutesInTotalSeconds,
pureSecondsInTotalSeconds);
}
}
|
UTF-8
|
Java
| 849 |
java
|
SumSeconds.java
|
Java
|
[] | null |
[] |
package Excercises.SimpleConditions;
import java.util.Scanner;
public class SumSeconds {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int firstRacerTimeInSeconds = Integer.parseInt(
console.nextLine());
int secondRacerTimeInSeconds = Integer.parseInt(
console.nextLine());
int thirdRacerTimeInSeconds = Integer.parseInt(
console.nextLine());
int totalSeconds = firstRacerTimeInSeconds +
secondRacerTimeInSeconds +
thirdRacerTimeInSeconds;
int minutesInTotalSeconds = totalSeconds / 60;
int pureSecondsInTotalSeconds = totalSeconds % 60;
System.out.printf("%d:%02d",
minutesInTotalSeconds,
pureSecondsInTotalSeconds);
}
}
| 849 | 0.631331 | 0.624264 | 27 | 30.444445 | 20.98912 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false |
12
|
a9fd338628477c9f4a9b4ec92ea61fe7b6b6309c
| 3,341,484,593,746 |
16cbad462a7c4bafa14208c795e97359d154d769
|
/src/com/interfaces/Arac.java
|
99f0785169cddebda6769cf39c498630bb0204e4
|
[] |
no_license
|
cn-k/collection
|
https://github.com/cn-k/collection
|
f93c30cda85ace9ca930e2ec3755aa0dc26d8bcf
|
9d3abd4ba54f5e9472069b5342acbdca009303be
|
refs/heads/master
| 2020-04-06T06:27:46.318000 | 2016-10-05T21:34:42 | 2016-10-05T21:34:42 | 70,101,523 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.interfaces;
/**
* Created by cenk.akdeniz on 05.10.2016.
*/
public class Arac {
}
|
UTF-8
|
Java
| 98 |
java
|
Arac.java
|
Java
|
[
{
"context": "package com.interfaces;\n\n/**\n * Created by cenk.akdeniz on 05.10.2016.\n */\npublic class Arac {\n\n}\n",
"end": 53,
"score": 0.7432971000671387,
"start": 43,
"tag": "USERNAME",
"value": "cenk.akden"
},
{
"context": "kage com.interfaces;\n\n/**\n * Created by cenk.akdeniz on 05.10.2016.\n */\npublic class Arac {\n\n}\n",
"end": 55,
"score": 0.5525144934654236,
"start": 53,
"tag": "NAME",
"value": "iz"
}
] | null |
[] |
package com.interfaces;
/**
* Created by cenk.akdeniz on 05.10.2016.
*/
public class Arac {
}
| 98 | 0.663265 | 0.581633 | 8 | 11.25 | 14.042347 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.125 | false | false |
12
|
9a57174061f1a2d3b183677ba7aa1b914d085009
| 2,731,599,259,093 |
275eecab4d9893533cc1fc47d59ffd5d00dbf1ea
|
/hackrank/src/testHackrank.java
|
a877b25c6cd29676606ce93364de4b0cafe11daf
|
[] |
no_license
|
tranthanhhieuthao/thuattoan
|
https://github.com/tranthanhhieuthao/thuattoan
|
374e2d20f1416cf25172f06b3888e7d386e3766f
|
cd3ce02723c5ff2eaf932e8a2079beaec37ad26d
|
refs/heads/master
| 2023-03-11T22:05:23.283000 | 2021-02-27T08:18:45 | 2021-02-27T08:18:45 | 342,805,677 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.util.HashMap;
import java.util.Map;
public class testHackrank {
public static String baitoan(String s, int k) {
if (testnow(s) == 0) return "Not found!";
Map<Integer, String> mapTest = new HashMap<>();
int max = 0;
int length = s.length();
for (int i =0; i< length;i++) {
if ((i* k) < s.length() && (i* k + k) < s.length()) {
String check = s.substring(i * k, k + i * k);
mapTest.put(testnow(check), check);
}
}
for (Integer elm : mapTest.keySet()) {
if (elm > max) max = elm;
}
return mapTest.get(max);
}
public static Integer testnow(String s) {
String[] vowels = {"a","e","i","o","u"};
int count = 0;
for (String el : vowels) {
if (s.indexOf(el) != -1) count++;
}
return count;
}
public static void main(String[] args) {
String result = baitoan("mlaiocvfioauekdjhaihgioeuiuaf", 7);
System.out.println(result);
}
}
|
UTF-8
|
Java
| 1,065 |
java
|
testHackrank.java
|
Java
|
[] | null |
[] |
import java.util.HashMap;
import java.util.Map;
public class testHackrank {
public static String baitoan(String s, int k) {
if (testnow(s) == 0) return "Not found!";
Map<Integer, String> mapTest = new HashMap<>();
int max = 0;
int length = s.length();
for (int i =0; i< length;i++) {
if ((i* k) < s.length() && (i* k + k) < s.length()) {
String check = s.substring(i * k, k + i * k);
mapTest.put(testnow(check), check);
}
}
for (Integer elm : mapTest.keySet()) {
if (elm > max) max = elm;
}
return mapTest.get(max);
}
public static Integer testnow(String s) {
String[] vowels = {"a","e","i","o","u"};
int count = 0;
for (String el : vowels) {
if (s.indexOf(el) != -1) count++;
}
return count;
}
public static void main(String[] args) {
String result = baitoan("mlaiocvfioauekdjhaihgioeuiuaf", 7);
System.out.println(result);
}
}
| 1,065 | 0.50047 | 0.494836 | 36 | 28.583334 | 20.493053 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false |
12
|
895004db4d6ca8a94246ff2bf2c46011a31bf87c
| 16,260,746,186,235 |
0450213968ee34d830f69b8167ec5095bd7b4c97
|
/pcc-service/src/main/java/org/sep/pccservice/api/PccRequest.java
|
83dd89b82b80a3145d91c20e3989b56d6d08587e
|
[] |
no_license
|
tayduivn/PaymentHub
|
https://github.com/tayduivn/PaymentHub
|
1c7ffaeb510d903304d93c28dada82d84532d576
|
fd1b3481e87ee2e3767f007c90bdbae466b3c880
|
refs/heads/master
| 2022-03-31T16:26:29.020000 | 2020-01-31T19:28:40 | 2020-01-31T19:28:40 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.sep.pccservice.api;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class PccRequest {
private String acquirerOrderId;
private LocalDateTime acquirerTimestamp;
private Double amount;
private String pan;
private String ccv;
private LocalDate expirationDate;
private String cardholderName;
}
|
UTF-8
|
Java
| 516 |
java
|
PccRequest.java
|
Java
|
[] | null |
[] |
package org.sep.pccservice.api;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class PccRequest {
private String acquirerOrderId;
private LocalDateTime acquirerTimestamp;
private Double amount;
private String pan;
private String ccv;
private LocalDate expirationDate;
private String cardholderName;
}
| 516 | 0.794574 | 0.794574 | 23 | 21.434782 | 12.957543 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.608696 | false | false |
12
|
ee6ab87988a18ad1f6a42af5d5cc93fcb87af2e2
| 8,022,998,960,875 |
453b5e76a6e3a9b87a59badc422368e81963a7b6
|
/JavaInterviewQuetionDemo/src/in/co/brings/SwapTwoNumber.java
|
17e751a76f3d39aaae11180ca3486b628cd28773
|
[] |
no_license
|
mh24ap1913/InterviewQuetion
|
https://github.com/mh24ap1913/InterviewQuetion
|
d9fccf1768cc4b407df6698e82c41c4ca7b7a7f4
|
6af4997be39ccb8b74b98afd34cd8de9f20cd9b0
|
refs/heads/master
| 2020-07-15T12:13:15.800000 | 2019-09-01T18:49:38 | 2019-09-01T18:49:38 | 205,558,954 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package in.co.brings;
import java.util.Scanner;
public class SwapTwoNumber {
public static void main(String[] args) {
int x,y,temp;
Scanner sc=new Scanner(System.in);
System.out.println("Enter first num");
x=sc.nextInt();
System.out.println("Enter second number");
y=sc.nextInt();
System.out.println("before swaping:-"+ x +y);
temp=x;
x=y;
y=temp;
System.out.println("After swapping"+x+y);
}
}
|
UTF-8
|
Java
| 445 |
java
|
SwapTwoNumber.java
|
Java
|
[] | null |
[] |
package in.co.brings;
import java.util.Scanner;
public class SwapTwoNumber {
public static void main(String[] args) {
int x,y,temp;
Scanner sc=new Scanner(System.in);
System.out.println("Enter first num");
x=sc.nextInt();
System.out.println("Enter second number");
y=sc.nextInt();
System.out.println("before swaping:-"+ x +y);
temp=x;
x=y;
y=temp;
System.out.println("After swapping"+x+y);
}
}
| 445 | 0.638202 | 0.638202 | 21 | 19.190475 | 16.471098 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.952381 | false | false |
12
|
be02a82443eaa262ad9e66d8452a10cbb3363835
| 6,828,998,007,721 |
4e9b195be0254b6d61619811e633294a3e313b87
|
/sources/org/cybergarage/upnp/ssdp/HTTPMUSocket.java
|
63104b94f92cbc1eb57c5d427d49e082e6095216
|
[] |
no_license
|
TonyDongGuaPi/mihome-src
|
https://github.com/TonyDongGuaPi/mihome-src
|
2fb9c950ce8220a26525599b1b1ae1d05767f707
|
19c0df3277d2bc652f16f8fe825ce5f5f323e9a1
|
refs/heads/master
| 2022-04-08T16:27:09.759000 | 2020-03-03T21:40:30 | 2020-03-03T21:40:30 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.cybergarage.upnp.ssdp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;
import java.net.SocketAddress;
import java.util.Enumeration;
import org.cybergarage.http.HTTPRequest;
import org.cybergarage.upnp.UPnP;
import org.cybergarage.util.Debug;
public class HTTPMUSocket {
private InetSocketAddress ssdpMultiGroup = null;
private NetworkInterface ssdpMultiIf = null;
private MulticastSocket ssdpMultiSock = null;
public HTTPMUSocket() {
}
public HTTPMUSocket(String str, int i, String str2) {
open(str, i, str2);
}
/* access modifiers changed from: protected */
public void finalize() {
close();
}
public String getLocalAddress() {
if (this.ssdpMultiGroup == null || this.ssdpMultiIf == null) {
return "";
}
InetAddress address = this.ssdpMultiGroup.getAddress();
Enumeration<InetAddress> inetAddresses = this.ssdpMultiIf.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress nextElement = inetAddresses.nextElement();
if ((address instanceof Inet6Address) && (nextElement instanceof Inet6Address)) {
return nextElement.getHostAddress();
}
if ((address instanceof Inet4Address) && (nextElement instanceof Inet4Address)) {
return nextElement.getHostAddress();
}
}
return "";
}
public int getMulticastPort() {
return this.ssdpMultiGroup.getPort();
}
public int getLocalPort() {
return this.ssdpMultiSock.getLocalPort();
}
public MulticastSocket getSocket() {
return this.ssdpMultiSock;
}
public InetAddress getMulticastInetAddress() {
if (this.ssdpMultiGroup == null) {
return null;
}
return this.ssdpMultiGroup.getAddress();
}
public String getMulticastAddress() {
return getMulticastInetAddress().getHostAddress();
}
public boolean open(String str, int i, InetAddress inetAddress) {
try {
this.ssdpMultiSock = new MulticastSocket((SocketAddress) null);
this.ssdpMultiSock.setReuseAddress(true);
this.ssdpMultiSock.bind(new InetSocketAddress(i));
this.ssdpMultiGroup = new InetSocketAddress(InetAddress.getByName(str), i);
this.ssdpMultiIf = NetworkInterface.getByInetAddress(inetAddress);
this.ssdpMultiSock.joinGroup(this.ssdpMultiGroup, this.ssdpMultiIf);
return true;
} catch (Exception e) {
Debug.warning(e);
return false;
}
}
public boolean open(String str, int i, String str2) {
try {
return open(str, i, InetAddress.getByName(str2));
} catch (Exception e) {
Debug.warning(e);
return false;
}
}
public boolean close() {
if (this.ssdpMultiSock == null) {
return true;
}
try {
this.ssdpMultiSock.leaveGroup(this.ssdpMultiGroup, this.ssdpMultiIf);
this.ssdpMultiSock.close();
this.ssdpMultiSock = null;
return true;
} catch (Exception unused) {
return false;
}
}
public boolean send(String str, String str2, int i) {
MulticastSocket multicastSocket;
if (str2 == null || i <= 0) {
multicastSocket = new MulticastSocket();
} else {
try {
multicastSocket = new MulticastSocket((SocketAddress) null);
multicastSocket.bind(new InetSocketAddress(str2, i));
} catch (Exception e) {
Debug.warning(e);
return false;
}
}
DatagramPacket datagramPacket = new DatagramPacket(str.getBytes(), str.length(), this.ssdpMultiGroup);
multicastSocket.setTimeToLive(UPnP.getTimeToLive());
multicastSocket.send(datagramPacket);
multicastSocket.close();
return true;
}
public boolean send(String str) {
return send(str, (String) null, -1);
}
public boolean post(HTTPRequest hTTPRequest, String str, int i) {
return send(hTTPRequest.toString(), str, i);
}
public boolean post(HTTPRequest hTTPRequest) {
return send(hTTPRequest.toString(), (String) null, -1);
}
public SSDPPacket receive() throws IOException {
byte[] bArr = new byte[1024];
SSDPPacket sSDPPacket = new SSDPPacket(bArr, bArr.length);
sSDPPacket.setLocalAddress(getLocalAddress());
if (this.ssdpMultiSock != null) {
this.ssdpMultiSock.receive(sSDPPacket.getDatagramPacket());
sSDPPacket.setTimeStamp(System.currentTimeMillis());
return sSDPPacket;
}
throw new IOException("Multicast socket has already been closed.");
}
}
|
UTF-8
|
Java
| 5,107 |
java
|
HTTPMUSocket.java
|
Java
|
[] | null |
[] |
package org.cybergarage.upnp.ssdp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;
import java.net.SocketAddress;
import java.util.Enumeration;
import org.cybergarage.http.HTTPRequest;
import org.cybergarage.upnp.UPnP;
import org.cybergarage.util.Debug;
public class HTTPMUSocket {
private InetSocketAddress ssdpMultiGroup = null;
private NetworkInterface ssdpMultiIf = null;
private MulticastSocket ssdpMultiSock = null;
public HTTPMUSocket() {
}
public HTTPMUSocket(String str, int i, String str2) {
open(str, i, str2);
}
/* access modifiers changed from: protected */
public void finalize() {
close();
}
public String getLocalAddress() {
if (this.ssdpMultiGroup == null || this.ssdpMultiIf == null) {
return "";
}
InetAddress address = this.ssdpMultiGroup.getAddress();
Enumeration<InetAddress> inetAddresses = this.ssdpMultiIf.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress nextElement = inetAddresses.nextElement();
if ((address instanceof Inet6Address) && (nextElement instanceof Inet6Address)) {
return nextElement.getHostAddress();
}
if ((address instanceof Inet4Address) && (nextElement instanceof Inet4Address)) {
return nextElement.getHostAddress();
}
}
return "";
}
public int getMulticastPort() {
return this.ssdpMultiGroup.getPort();
}
public int getLocalPort() {
return this.ssdpMultiSock.getLocalPort();
}
public MulticastSocket getSocket() {
return this.ssdpMultiSock;
}
public InetAddress getMulticastInetAddress() {
if (this.ssdpMultiGroup == null) {
return null;
}
return this.ssdpMultiGroup.getAddress();
}
public String getMulticastAddress() {
return getMulticastInetAddress().getHostAddress();
}
public boolean open(String str, int i, InetAddress inetAddress) {
try {
this.ssdpMultiSock = new MulticastSocket((SocketAddress) null);
this.ssdpMultiSock.setReuseAddress(true);
this.ssdpMultiSock.bind(new InetSocketAddress(i));
this.ssdpMultiGroup = new InetSocketAddress(InetAddress.getByName(str), i);
this.ssdpMultiIf = NetworkInterface.getByInetAddress(inetAddress);
this.ssdpMultiSock.joinGroup(this.ssdpMultiGroup, this.ssdpMultiIf);
return true;
} catch (Exception e) {
Debug.warning(e);
return false;
}
}
public boolean open(String str, int i, String str2) {
try {
return open(str, i, InetAddress.getByName(str2));
} catch (Exception e) {
Debug.warning(e);
return false;
}
}
public boolean close() {
if (this.ssdpMultiSock == null) {
return true;
}
try {
this.ssdpMultiSock.leaveGroup(this.ssdpMultiGroup, this.ssdpMultiIf);
this.ssdpMultiSock.close();
this.ssdpMultiSock = null;
return true;
} catch (Exception unused) {
return false;
}
}
public boolean send(String str, String str2, int i) {
MulticastSocket multicastSocket;
if (str2 == null || i <= 0) {
multicastSocket = new MulticastSocket();
} else {
try {
multicastSocket = new MulticastSocket((SocketAddress) null);
multicastSocket.bind(new InetSocketAddress(str2, i));
} catch (Exception e) {
Debug.warning(e);
return false;
}
}
DatagramPacket datagramPacket = new DatagramPacket(str.getBytes(), str.length(), this.ssdpMultiGroup);
multicastSocket.setTimeToLive(UPnP.getTimeToLive());
multicastSocket.send(datagramPacket);
multicastSocket.close();
return true;
}
public boolean send(String str) {
return send(str, (String) null, -1);
}
public boolean post(HTTPRequest hTTPRequest, String str, int i) {
return send(hTTPRequest.toString(), str, i);
}
public boolean post(HTTPRequest hTTPRequest) {
return send(hTTPRequest.toString(), (String) null, -1);
}
public SSDPPacket receive() throws IOException {
byte[] bArr = new byte[1024];
SSDPPacket sSDPPacket = new SSDPPacket(bArr, bArr.length);
sSDPPacket.setLocalAddress(getLocalAddress());
if (this.ssdpMultiSock != null) {
this.ssdpMultiSock.receive(sSDPPacket.getDatagramPacket());
sSDPPacket.setTimeStamp(System.currentTimeMillis());
return sSDPPacket;
}
throw new IOException("Multicast socket has already been closed.");
}
}
| 5,107 | 0.624633 | 0.620717 | 156 | 31.737179 | 25.02207 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.653846 | false | false |
12
|
996ff783df359cce0bbd96fc52e3ce19cd73f925
| 2,448,131,412,941 |
9e3554371d527d9e943857f4a0cd1c35161e5b35
|
/job06/src/main/java/ru/otus/job06/controller/impl/GenreControllerImpl.java
|
c156957ebdaaf5fc9f0dbf93ad4b38c4ada3e5b5
|
[] |
no_license
|
st-gert/2020-02-otus-spring-gertovskiy
|
https://github.com/st-gert/2020-02-otus-spring-gertovskiy
|
825cbdf81bd144bca337efd0a6d44ceb0bff3d69
|
ea4c1bedd5eeaeeed66b9cf2d31131f2e321ddbd
|
refs/heads/master
| 2022-09-16T08:41:10.392000 | 2020-07-10T18:39:36 | 2020-07-10T18:39:36 | 243,282,471 | 0 | 0 | null | false | 2022-02-16T01:07:40 | 2020-02-26T14:28:13 | 2021-03-12T12:50:00 | 2022-02-16T01:07:38 | 438 | 0 | 0 | 1 |
Java
| false | false |
package ru.otus.job06.controller.impl;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.stereotype.Service;
import ru.otus.job06.controller.GenreController;
import ru.otus.job06.model.Genre;
import ru.otus.job06.service.GenreService;
import java.util.List;
@Service
public class GenreControllerImpl implements GenreController {
private final GenreService service;
private final ResultUtil resultUtil;
public GenreControllerImpl(GenreService service, ResultUtil resultUtil) {
this.service = service;
this.resultUtil = resultUtil;
}
@Override
public Pair<List<Genre>, String> getGenreList() {
try {
return resultUtil.handleList(service.getGenreList());
} catch (Exception e) {
return Pair.<List<Genre>, String>of(null, resultUtil.handleException(e));
}
}
@Override
public Pair<Long, String> addGenre(String genre) {
try {
return Pair.of(service.addGenre(new Genre(null, genre)), null);
} catch (Exception e) {
return Pair.<Long, String>of(null, resultUtil.handleException(e));
}
}
@Override
public String updateGenre(Long genreId, String genre) {
try {
service.updateGenre(new Genre(genreId, genre));
return null;
} catch (Exception e) {
return resultUtil.handleException(e);
}
}
@Override
public String deleteGenre(Long genreId) {
try {
service.deleteGenre(genreId);
return null;
} catch (Exception e) {
return resultUtil.handleException(e);
}
}
}
|
UTF-8
|
Java
| 1,675 |
java
|
GenreControllerImpl.java
|
Java
|
[] | null |
[] |
package ru.otus.job06.controller.impl;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.stereotype.Service;
import ru.otus.job06.controller.GenreController;
import ru.otus.job06.model.Genre;
import ru.otus.job06.service.GenreService;
import java.util.List;
@Service
public class GenreControllerImpl implements GenreController {
private final GenreService service;
private final ResultUtil resultUtil;
public GenreControllerImpl(GenreService service, ResultUtil resultUtil) {
this.service = service;
this.resultUtil = resultUtil;
}
@Override
public Pair<List<Genre>, String> getGenreList() {
try {
return resultUtil.handleList(service.getGenreList());
} catch (Exception e) {
return Pair.<List<Genre>, String>of(null, resultUtil.handleException(e));
}
}
@Override
public Pair<Long, String> addGenre(String genre) {
try {
return Pair.of(service.addGenre(new Genre(null, genre)), null);
} catch (Exception e) {
return Pair.<Long, String>of(null, resultUtil.handleException(e));
}
}
@Override
public String updateGenre(Long genreId, String genre) {
try {
service.updateGenre(new Genre(genreId, genre));
return null;
} catch (Exception e) {
return resultUtil.handleException(e);
}
}
@Override
public String deleteGenre(Long genreId) {
try {
service.deleteGenre(genreId);
return null;
} catch (Exception e) {
return resultUtil.handleException(e);
}
}
}
| 1,675 | 0.639403 | 0.63403 | 60 | 26.916666 | 23.76853 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.533333 | false | false |
12
|
ae8c9b9d66cb417e4aacab0cd03faf8cbf5ad5fd
| 27,006,754,403,575 |
86fa729606d159d001f299151610ea036e2460a8
|
/app/src/main/java/cn/com/broadlink/blappsdkdemo/data/FilePostParam.java
|
c76ab66a15c7b321ed861806de3f9f9aa740dcb6
|
[] |
no_license
|
ibroadlink/APPSDK_Android_Demo
|
https://github.com/ibroadlink/APPSDK_Android_Demo
|
d27e04d652fc5c7141fd50f21b369dcaae9ec08a
|
f8db69151820d9ea94096371fbac36a55962c388
|
refs/heads/master
| 2021-07-13T13:32:10.669000 | 2020-05-21T07:20:47 | 2020-05-21T07:20:47 | 140,553,214 | 10 | 5 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package cn.com.broadlink.blappsdkdemo.data;
import java.io.File;
public class FilePostParam {
private byte[] text;
private File picdata;
private File file;
public byte[] getText() {
return text;
}
public void setText(byte[] text) {
this.text = text;
}
public File getPicdata() {
return picdata;
}
public void setPicdata(File picdata) {
this.picdata = picdata;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
}
|
UTF-8
|
Java
| 576 |
java
|
FilePostParam.java
|
Java
|
[] | null |
[] |
package cn.com.broadlink.blappsdkdemo.data;
import java.io.File;
public class FilePostParam {
private byte[] text;
private File picdata;
private File file;
public byte[] getText() {
return text;
}
public void setText(byte[] text) {
this.text = text;
}
public File getPicdata() {
return picdata;
}
public void setPicdata(File picdata) {
this.picdata = picdata;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
}
| 576 | 0.581597 | 0.581597 | 37 | 14.567568 | 14.26684 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.297297 | false | false |
12
|
e2ca730f7abaede413af0313f80fe855a66af541
| 10,333,691,327,950 |
15517d76e17f47f0a7771aba89646fac695f4d8d
|
/job/src/main/java/com/ldz/job/job/obd/GpsObdSaveJob.java
|
4879697278254190f55328daf86b7a5c6672f8e9
|
[] |
no_license
|
slu12/sh
|
https://github.com/slu12/sh
|
56b63da013336fdbe2601d7f583388730c9272e1
|
f3b279950351f8755d8b57e772609230d165e94b
|
refs/heads/master
| 2022-09-15T02:10:08.273000 | 2021-05-19T02:22:05 | 2021-05-19T02:22:05 | 226,773,685 | 1 | 3 | null | false | 2022-09-01T23:18:11 | 2019-12-09T03:08:22 | 2021-05-19T02:22:24 | 2022-09-01T23:18:09 | 54,996 | 0 | 2 | 16 |
Vue
| false | false |
package com.ldz.job.job.obd;
import com.ldz.dao.obd.mapper.GpsObdMapper;
import com.ldz.dao.obd.model.GpsObdMessageBean;
import com.ldz.util.commonUtil.JsonUtil;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import java.util.ArrayList;
import java.util.List;
public class GpsObdSaveJob implements Job {
@Autowired
private RedisTemplate redisTemplate;
Logger errorLog = LoggerFactory.getLogger("error_info");
@Autowired
private GpsObdMapper gpsObdMapper;
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
errorLog.info("gps obd存储job");
BoundListOperations operations = redisTemplate.boundListOps("gps_obd");
long size = operations.size();
if (size == 0) return;
List<GpsObdMessageBean> list = new ArrayList<>();
errorLog.info("obd gps list size , " + list.size());
errorLog.info("obd gps list content , " + JsonUtil.toJson(list));
for (long i = 0; i < size; i++) {
GpsObdMessageBean bean = (GpsObdMessageBean) operations.rightPop();
errorLog.info("obd_gps 存储 , " + JsonUtil.toJson(bean));
list.add(bean);
}
gpsObdMapper.insertList(list);
}
}
|
UTF-8
|
Java
| 1,551 |
java
|
GpsObdSaveJob.java
|
Java
|
[] | null |
[] |
package com.ldz.job.job.obd;
import com.ldz.dao.obd.mapper.GpsObdMapper;
import com.ldz.dao.obd.model.GpsObdMessageBean;
import com.ldz.util.commonUtil.JsonUtil;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import java.util.ArrayList;
import java.util.List;
public class GpsObdSaveJob implements Job {
@Autowired
private RedisTemplate redisTemplate;
Logger errorLog = LoggerFactory.getLogger("error_info");
@Autowired
private GpsObdMapper gpsObdMapper;
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
errorLog.info("gps obd存储job");
BoundListOperations operations = redisTemplate.boundListOps("gps_obd");
long size = operations.size();
if (size == 0) return;
List<GpsObdMessageBean> list = new ArrayList<>();
errorLog.info("obd gps list size , " + list.size());
errorLog.info("obd gps list content , " + JsonUtil.toJson(list));
for (long i = 0; i < size; i++) {
GpsObdMessageBean bean = (GpsObdMessageBean) operations.rightPop();
errorLog.info("obd_gps 存储 , " + JsonUtil.toJson(bean));
list.add(bean);
}
gpsObdMapper.insertList(list);
}
}
| 1,551 | 0.716137 | 0.713545 | 40 | 37.575001 | 23.602846 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.825 | false | false |
12
|
50e820ec756e8a8e6fd999524f72e026b7eec922
| 523,986,011,576 |
e389a2f1dfc0426c72d1f930b267646e2116a8cd
|
/No_One_Knows/src/main/java/net/developia/board/dao/ThemeDAO.java
|
31387425f808eb83a6127eb0677076a888a4f70f
|
[] |
no_license
|
thx1010/Tour_Schedule_Sharing_Web_with_Map_Production
|
https://github.com/thx1010/Tour_Schedule_Sharing_Web_with_Map_Production
|
fe848986dea9ce73e723d606b2cf5a84bc4f6b59
|
e50c760c5cfb03cca3230f4e1aa463c1ccad689e
|
refs/heads/master
| 2023-05-08T02:24:52.940000 | 2021-06-06T14:16:09 | 2021-06-06T14:16:09 | 370,522,449 | 0 | 0 | null | false | 2021-06-01T03:32:28 | 2021-05-25T00:46:49 | 2021-06-01T02:56:28 | 2021-06-01T03:32:27 | 31,069 | 0 | 0 | 0 |
CSS
| false | false |
package net.developia.board.dao;
import java.sql.SQLException;
import java.util.List;
import net.developia.board.dto.ThemeDTO;
public interface ThemeDAO {
public List<ThemeDTO> getThemeList() throws SQLException;
public ThemeDTO getThemForThemeNo(long theme_no) throws SQLException;
}
|
UTF-8
|
Java
| 307 |
java
|
ThemeDAO.java
|
Java
|
[] | null |
[] |
package net.developia.board.dao;
import java.sql.SQLException;
import java.util.List;
import net.developia.board.dto.ThemeDTO;
public interface ThemeDAO {
public List<ThemeDTO> getThemeList() throws SQLException;
public ThemeDTO getThemForThemeNo(long theme_no) throws SQLException;
}
| 307 | 0.765472 | 0.765472 | 14 | 19.928572 | 22.964148 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false |
12
|
9ae523014e36f4bc3ff0f73de25c846bfb4c6d45
| 11,819,750,006,100 |
80baab945c3d1448e8baf34712bde1682cd9510b
|
/perun-core/src/main/java/cz/metacentrum/perun/core/implApi/modules/attributes/UserVirtualAttributeCollectedFromUserExtSource.java
|
cb42ec4f4116313771571d755734b238150a2bfe
|
[
"BSD-2-Clause"
] |
permissive
|
CESNET/perun
|
https://github.com/CESNET/perun
|
e4a4769976130c8511238b87edf6977da53859a8
|
f0d90249c7a3a9e3fcf6c414485e27b5a05dbf66
|
refs/heads/master
| 2023-09-02T23:06:17.073000 | 2023-09-01T08:28:12 | 2023-09-01T08:28:12 | 4,085,998 | 58 | 69 |
BSD-2-Clause
| false | 2023-09-14T12:40:54 | 2012-04-20T11:55:38 | 2023-08-30T08:48:01 | 2023-09-14T12:40:54 | 62,679 | 57 | 70 | 16 |
Java
| false | false |
package cz.metacentrum.perun.core.implApi.modules.attributes;
import cz.metacentrum.perun.audit.events.AttributesManagerEvents.AllAttributesRemovedForUserExtSource;
import cz.metacentrum.perun.audit.events.AttributesManagerEvents.AttributeChangedForUser;
import cz.metacentrum.perun.audit.events.AttributesManagerEvents.AttributeRemovedForUes;
import cz.metacentrum.perun.audit.events.AttributesManagerEvents.AttributeSetForUes;
import cz.metacentrum.perun.audit.events.AuditEvent;
import cz.metacentrum.perun.core.api.Attribute;
import cz.metacentrum.perun.core.api.AttributeDefinition;
import cz.metacentrum.perun.core.api.AttributesManager;
import cz.metacentrum.perun.core.api.BeansUtils;
import cz.metacentrum.perun.core.api.ExtSourcesManager;
import cz.metacentrum.perun.core.api.PerunSession;
import cz.metacentrum.perun.core.api.User;
import cz.metacentrum.perun.core.api.UserExtSource;
import cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.UserNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.WrongAttributeAssignmentException;
import cz.metacentrum.perun.core.api.exceptions.WrongReferenceAttributeValueException;
import cz.metacentrum.perun.core.bl.AttributesManagerBl;
import cz.metacentrum.perun.core.impl.PerunSessionImpl;
import cz.metacentrum.perun.core.impl.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
/**
* Common ancestor class for user virtual attributes that just collect values from userExtSource attributes.
* <p>
* For a given user, collects string values of userExtSource attributes with friendly name specified
* by getSourceAttributeFriendlyName(), and splits them at character ';' which is used by mod_shib to join multiple values,
* and stores all values into virtual user attribute with friendly name specified by
* getDestinationAttributeFriendlyName().
*
* @author Martin Kuba makub@ics.muni.cz
*/
public abstract class UserVirtualAttributeCollectedFromUserExtSource<T extends UserVirtualAttributeCollectedFromUserExtSource.ModifyValueContext> extends UserVirtualAttributesModuleAbstract {
private final Logger log = LoggerFactory.getLogger(this.getClass());
/**
* Specifies friendly (short) name of attribute from namespace urn:perun:ues:attribute-def:def
* whose values are to be collected.
*
* @return short name of userExtSource attribute which is source of values
*/
public abstract String getSourceAttributeFriendlyName();
/**
* Gets full URN of the UserExtSource attribute used for computing rhis attribute value.
* @return full source attribute URN
*/
public final String getSourceAttributeName() {
return AttributesManager.NS_UES_ATTR_DEF + ":" + getSourceAttributeFriendlyName();
}
/**
* Specifies friendly (short) name of attribute from namespace urn:perun:user:attribute-def:virt
* where values will be stored
*
* @return short name of user attribute which is destination for collected values
*/
public abstract String getDestinationAttributeFriendlyName();
/**
* Gets full URN of this virtual user attribute.
* @return full destination attribute URN
*/
public final String getDestinationAttributeName() {
return AttributesManager.NS_USER_ATTR_VIRT + ":" + getDestinationAttributeFriendlyName();
}
public String getDestinationAttributeDisplayName() {
return getDestinationAttributeFriendlyName();
}
public String getDestinationAttributeDescription() {
return "Collected values of userExtSource attribute " + getDestinationAttributeFriendlyName();
}
/**
* Override this method if you need to modify the original values. The default implementation makes no modification.
* Return null if the value should be skipped.
*
* @param session PerunSession
* @param ctx context initialized in initModifyValueContext method
* @param ues UserExtSource
* @param value of userExtSource attribute
* @return modified value or null to skip the value
*/
public String modifyValue(PerunSession session, T ctx, UserExtSource ues, String value) {
return value;
}
public static class ModifyValueContext {
private final PerunSessionImpl session;
private final User user;
private final AttributeDefinition destinationAttributeDefinition;
public ModifyValueContext(PerunSessionImpl session, User user, AttributeDefinition destinationAttributeDefinition) {
this.session = session;
this.user = user;
this.destinationAttributeDefinition = destinationAttributeDefinition;
}
public PerunSessionImpl getSession() {
return session;
}
public User getUser() {
return user;
}
@SuppressWarnings("unused")
public AttributeDefinition getDestinationAttributeDefinition() {
return destinationAttributeDefinition;
}
}
protected T initModifyValueContext(PerunSessionImpl sess, User user, AttributeDefinition destinationAttributeDefinition) {
//noinspection unchecked
return (T) new ModifyValueContext(sess, user, destinationAttributeDefinition);
}
@Override
public Attribute getAttributeValue(PerunSessionImpl sess, User user, AttributeDefinition destinationAttributeDefinition) {
T ctx = initModifyValueContext(sess, user, destinationAttributeDefinition);
Attribute destinationAttribute = new Attribute(destinationAttributeDefinition);
//for values use set because of avoiding duplicities
Set<String> valuesWithoutDuplicities = new HashSet<>();
List<String> attributeExceptions = BeansUtils.getCoreConfig().getIdpLoginValidityExceptions();
boolean skipLastAccessCheck = attributeExceptions != null && attributeExceptions.contains(this.getDestinationAttributeName());
String sourceAttributeFriendlyName = getSourceAttributeFriendlyName();
List<UserExtSource> userExtSources = sess.getPerunBl().getUsersManagerBl().getUserExtSources(sess, user);
AttributesManagerBl am = sess.getPerunBl().getAttributesManagerBl();
for (UserExtSource userExtSource : userExtSources) {
if (!skipLastAccessCheck && !isLastAccessValid(userExtSource)) {
continue;
}
try {
String sourceAttributeName = getSourceAttributeName();
Attribute a = am.getAttribute(sess, userExtSource, sourceAttributeName);
Object value = a.getValue();
if (value != null && value instanceof String) {
//Apache mod_shib joins multiple values with ';', split them again
String[] rawValues = ((String) value).split(";");
//add non-null values returned by modifyValue()
Arrays.stream(rawValues).map(v -> modifyValue(sess, ctx, userExtSource, v)).filter(Objects::nonNull).forEachOrdered(valuesWithoutDuplicities::add);
} else if (value != null && value instanceof ArrayList) {
//If values are already separated to list of strings
a.valueAsList().stream().map(v -> modifyValue(sess, ctx, userExtSource, v)).filter(Objects::nonNull).forEachOrdered(valuesWithoutDuplicities::add);
}
} catch (WrongAttributeAssignmentException | AttributeNotExistsException e) {
log.error("cannot read " + sourceAttributeFriendlyName + " from userExtSource " + userExtSource.getId() + " of user " + user.getId(), e);
}
}
//convert set to list (values in list will be without duplicities)
destinationAttribute.setValue(new ArrayList<>(valuesWithoutDuplicities));
return destinationAttribute;
}
/**
* Checks configuration properties idpLoginValidity if last access is not outdated. Skips non-idp ext sources.
* @param ues user extsource to be checked
* @return true if ues is of type IdP and its last access is not outdated, false otherwise
*/
private boolean isLastAccessValid(UserExtSource ues) {
if (!ExtSourcesManager.EXTSOURCE_IDP.equals(ues.getExtSource().getType())) {
return true;
}
LocalDateTime lastAccess = LocalDateTime.parse(ues.getLastAccess(), Utils.lastAccessFormatter);
return lastAccess.plusMonths(BeansUtils.getCoreConfig().getIdpLoginValidity()).isAfter(LocalDateTime.now());
}
/**
* Functional interface for controlling AuditEvents.
*
* Modules can overwrite method shouldBeEventHandled to change or add events that should
* handled. Events that should be handled are events which make modules to produce another
* AuditEvent.
*/
@FunctionalInterface
public interface AttributeHandleIdentifier {
/**
* Determines whether given auditEvent should be handled. If it should be the method
* returns userId of user from the auditEvent, otherwise returns null.
*
* @param auditEvent given auditEvent
* @return userId of user from auditEvent, otherwise null
*/
Integer shouldBeEventHandled(AuditEvent auditEvent);
}
public List<AttributeHandleIdentifier> getHandleIdentifiers() {
List<AttributeHandleIdentifier> handleIdenfiers = new ArrayList<>();
handleIdenfiers.add(auditEvent -> {
if (auditEvent instanceof AllAttributesRemovedForUserExtSource) {
return ((AllAttributesRemovedForUserExtSource) auditEvent).getUserExtSource().getUserId();
} else {
return null;
}
});
handleIdenfiers.add(auditEvent -> {
if (auditEvent instanceof AttributeRemovedForUes && ((AttributeRemovedForUes) auditEvent).getAttribute().getFriendlyName().equals(getSourceAttributeFriendlyName())) {
return ((AttributeRemovedForUes) auditEvent).getUes().getUserId();
} else {
return null;
}
});
handleIdenfiers.add(auditEvent -> {
if (auditEvent instanceof AttributeSetForUes &&((AttributeSetForUes) auditEvent).getAttribute().getFriendlyName().equals(getSourceAttributeFriendlyName())) {
return ((AttributeSetForUes) auditEvent).getUes().getUserId();
} else {
return null;
}
});
return handleIdenfiers;
}
@Override
public List<AuditEvent> resolveVirtualAttributeValueChange(PerunSessionImpl perunSession, AuditEvent message) throws WrongReferenceAttributeValueException, AttributeNotExistsException, WrongAttributeAssignmentException {
List<AuditEvent> resolvingMessages = new ArrayList<>();
if (message == null) return resolvingMessages;
List<AttributeHandleIdentifier> list = getHandleIdentifiers();
for (AttributeHandleIdentifier attributeHandleIdenfier : list) {
Integer userId = attributeHandleIdenfier.shouldBeEventHandled(message);
if (userId != null) {
try {
User user = perunSession.getPerunBl().getUsersManagerBl().getUserById(perunSession, userId);
AttributeDefinition attributeDefinition = perunSession.getPerunBl().getAttributesManagerBl().getAttributeDefinition(perunSession, getDestinationAttributeName());
resolvingMessages.add(new AttributeChangedForUser(new Attribute(attributeDefinition), user));
} catch (UserNotExistsException e) {
log.warn("User from UserExtSource doesn't exist in Perun. This occurred while parsing message: {}.", message);
}
}
}
return resolvingMessages;
}
public AttributeDefinition getAttributeDefinition() {
AttributeDefinition attr = new AttributeDefinition();
attr.setNamespace(AttributesManager.NS_USER_ATTR_VIRT);
String friendlyName = getDestinationAttributeFriendlyName();
attr.setFriendlyName(friendlyName);
attr.setDisplayName(getDestinationAttributeDisplayName());
attr.setType(ArrayList.class.getName());
attr.setDescription(getDestinationAttributeDescription());
return attr;
}
}
|
UTF-8
|
Java
| 11,421 |
java
|
UserVirtualAttributeCollectedFromUserExtSource.java
|
Java
|
[
{
"context": "tDestinationAttributeFriendlyName().\n *\n * @author Martin Kuba makub@ics.muni.cz\n */\npublic abstract class UserV",
"end": 2111,
"score": 0.9998690485954285,
"start": 2100,
"tag": "NAME",
"value": "Martin Kuba"
},
{
"context": "AttributeFriendlyName().\n *\n * @author Martin Kuba makub@ics.muni.cz\n */\npublic abstract class UserVirtualAttributeCol",
"end": 2129,
"score": 0.9999242424964905,
"start": 2112,
"tag": "EMAIL",
"value": "makub@ics.muni.cz"
}
] | null |
[] |
package cz.metacentrum.perun.core.implApi.modules.attributes;
import cz.metacentrum.perun.audit.events.AttributesManagerEvents.AllAttributesRemovedForUserExtSource;
import cz.metacentrum.perun.audit.events.AttributesManagerEvents.AttributeChangedForUser;
import cz.metacentrum.perun.audit.events.AttributesManagerEvents.AttributeRemovedForUes;
import cz.metacentrum.perun.audit.events.AttributesManagerEvents.AttributeSetForUes;
import cz.metacentrum.perun.audit.events.AuditEvent;
import cz.metacentrum.perun.core.api.Attribute;
import cz.metacentrum.perun.core.api.AttributeDefinition;
import cz.metacentrum.perun.core.api.AttributesManager;
import cz.metacentrum.perun.core.api.BeansUtils;
import cz.metacentrum.perun.core.api.ExtSourcesManager;
import cz.metacentrum.perun.core.api.PerunSession;
import cz.metacentrum.perun.core.api.User;
import cz.metacentrum.perun.core.api.UserExtSource;
import cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.UserNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.WrongAttributeAssignmentException;
import cz.metacentrum.perun.core.api.exceptions.WrongReferenceAttributeValueException;
import cz.metacentrum.perun.core.bl.AttributesManagerBl;
import cz.metacentrum.perun.core.impl.PerunSessionImpl;
import cz.metacentrum.perun.core.impl.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
/**
* Common ancestor class for user virtual attributes that just collect values from userExtSource attributes.
* <p>
* For a given user, collects string values of userExtSource attributes with friendly name specified
* by getSourceAttributeFriendlyName(), and splits them at character ';' which is used by mod_shib to join multiple values,
* and stores all values into virtual user attribute with friendly name specified by
* getDestinationAttributeFriendlyName().
*
* @author <NAME> <EMAIL>
*/
public abstract class UserVirtualAttributeCollectedFromUserExtSource<T extends UserVirtualAttributeCollectedFromUserExtSource.ModifyValueContext> extends UserVirtualAttributesModuleAbstract {
private final Logger log = LoggerFactory.getLogger(this.getClass());
/**
* Specifies friendly (short) name of attribute from namespace urn:perun:ues:attribute-def:def
* whose values are to be collected.
*
* @return short name of userExtSource attribute which is source of values
*/
public abstract String getSourceAttributeFriendlyName();
/**
* Gets full URN of the UserExtSource attribute used for computing rhis attribute value.
* @return full source attribute URN
*/
public final String getSourceAttributeName() {
return AttributesManager.NS_UES_ATTR_DEF + ":" + getSourceAttributeFriendlyName();
}
/**
* Specifies friendly (short) name of attribute from namespace urn:perun:user:attribute-def:virt
* where values will be stored
*
* @return short name of user attribute which is destination for collected values
*/
public abstract String getDestinationAttributeFriendlyName();
/**
* Gets full URN of this virtual user attribute.
* @return full destination attribute URN
*/
public final String getDestinationAttributeName() {
return AttributesManager.NS_USER_ATTR_VIRT + ":" + getDestinationAttributeFriendlyName();
}
public String getDestinationAttributeDisplayName() {
return getDestinationAttributeFriendlyName();
}
public String getDestinationAttributeDescription() {
return "Collected values of userExtSource attribute " + getDestinationAttributeFriendlyName();
}
/**
* Override this method if you need to modify the original values. The default implementation makes no modification.
* Return null if the value should be skipped.
*
* @param session PerunSession
* @param ctx context initialized in initModifyValueContext method
* @param ues UserExtSource
* @param value of userExtSource attribute
* @return modified value or null to skip the value
*/
public String modifyValue(PerunSession session, T ctx, UserExtSource ues, String value) {
return value;
}
public static class ModifyValueContext {
private final PerunSessionImpl session;
private final User user;
private final AttributeDefinition destinationAttributeDefinition;
public ModifyValueContext(PerunSessionImpl session, User user, AttributeDefinition destinationAttributeDefinition) {
this.session = session;
this.user = user;
this.destinationAttributeDefinition = destinationAttributeDefinition;
}
public PerunSessionImpl getSession() {
return session;
}
public User getUser() {
return user;
}
@SuppressWarnings("unused")
public AttributeDefinition getDestinationAttributeDefinition() {
return destinationAttributeDefinition;
}
}
protected T initModifyValueContext(PerunSessionImpl sess, User user, AttributeDefinition destinationAttributeDefinition) {
//noinspection unchecked
return (T) new ModifyValueContext(sess, user, destinationAttributeDefinition);
}
@Override
public Attribute getAttributeValue(PerunSessionImpl sess, User user, AttributeDefinition destinationAttributeDefinition) {
T ctx = initModifyValueContext(sess, user, destinationAttributeDefinition);
Attribute destinationAttribute = new Attribute(destinationAttributeDefinition);
//for values use set because of avoiding duplicities
Set<String> valuesWithoutDuplicities = new HashSet<>();
List<String> attributeExceptions = BeansUtils.getCoreConfig().getIdpLoginValidityExceptions();
boolean skipLastAccessCheck = attributeExceptions != null && attributeExceptions.contains(this.getDestinationAttributeName());
String sourceAttributeFriendlyName = getSourceAttributeFriendlyName();
List<UserExtSource> userExtSources = sess.getPerunBl().getUsersManagerBl().getUserExtSources(sess, user);
AttributesManagerBl am = sess.getPerunBl().getAttributesManagerBl();
for (UserExtSource userExtSource : userExtSources) {
if (!skipLastAccessCheck && !isLastAccessValid(userExtSource)) {
continue;
}
try {
String sourceAttributeName = getSourceAttributeName();
Attribute a = am.getAttribute(sess, userExtSource, sourceAttributeName);
Object value = a.getValue();
if (value != null && value instanceof String) {
//Apache mod_shib joins multiple values with ';', split them again
String[] rawValues = ((String) value).split(";");
//add non-null values returned by modifyValue()
Arrays.stream(rawValues).map(v -> modifyValue(sess, ctx, userExtSource, v)).filter(Objects::nonNull).forEachOrdered(valuesWithoutDuplicities::add);
} else if (value != null && value instanceof ArrayList) {
//If values are already separated to list of strings
a.valueAsList().stream().map(v -> modifyValue(sess, ctx, userExtSource, v)).filter(Objects::nonNull).forEachOrdered(valuesWithoutDuplicities::add);
}
} catch (WrongAttributeAssignmentException | AttributeNotExistsException e) {
log.error("cannot read " + sourceAttributeFriendlyName + " from userExtSource " + userExtSource.getId() + " of user " + user.getId(), e);
}
}
//convert set to list (values in list will be without duplicities)
destinationAttribute.setValue(new ArrayList<>(valuesWithoutDuplicities));
return destinationAttribute;
}
/**
* Checks configuration properties idpLoginValidity if last access is not outdated. Skips non-idp ext sources.
* @param ues user extsource to be checked
* @return true if ues is of type IdP and its last access is not outdated, false otherwise
*/
private boolean isLastAccessValid(UserExtSource ues) {
if (!ExtSourcesManager.EXTSOURCE_IDP.equals(ues.getExtSource().getType())) {
return true;
}
LocalDateTime lastAccess = LocalDateTime.parse(ues.getLastAccess(), Utils.lastAccessFormatter);
return lastAccess.plusMonths(BeansUtils.getCoreConfig().getIdpLoginValidity()).isAfter(LocalDateTime.now());
}
/**
* Functional interface for controlling AuditEvents.
*
* Modules can overwrite method shouldBeEventHandled to change or add events that should
* handled. Events that should be handled are events which make modules to produce another
* AuditEvent.
*/
@FunctionalInterface
public interface AttributeHandleIdentifier {
/**
* Determines whether given auditEvent should be handled. If it should be the method
* returns userId of user from the auditEvent, otherwise returns null.
*
* @param auditEvent given auditEvent
* @return userId of user from auditEvent, otherwise null
*/
Integer shouldBeEventHandled(AuditEvent auditEvent);
}
public List<AttributeHandleIdentifier> getHandleIdentifiers() {
List<AttributeHandleIdentifier> handleIdenfiers = new ArrayList<>();
handleIdenfiers.add(auditEvent -> {
if (auditEvent instanceof AllAttributesRemovedForUserExtSource) {
return ((AllAttributesRemovedForUserExtSource) auditEvent).getUserExtSource().getUserId();
} else {
return null;
}
});
handleIdenfiers.add(auditEvent -> {
if (auditEvent instanceof AttributeRemovedForUes && ((AttributeRemovedForUes) auditEvent).getAttribute().getFriendlyName().equals(getSourceAttributeFriendlyName())) {
return ((AttributeRemovedForUes) auditEvent).getUes().getUserId();
} else {
return null;
}
});
handleIdenfiers.add(auditEvent -> {
if (auditEvent instanceof AttributeSetForUes &&((AttributeSetForUes) auditEvent).getAttribute().getFriendlyName().equals(getSourceAttributeFriendlyName())) {
return ((AttributeSetForUes) auditEvent).getUes().getUserId();
} else {
return null;
}
});
return handleIdenfiers;
}
@Override
public List<AuditEvent> resolveVirtualAttributeValueChange(PerunSessionImpl perunSession, AuditEvent message) throws WrongReferenceAttributeValueException, AttributeNotExistsException, WrongAttributeAssignmentException {
List<AuditEvent> resolvingMessages = new ArrayList<>();
if (message == null) return resolvingMessages;
List<AttributeHandleIdentifier> list = getHandleIdentifiers();
for (AttributeHandleIdentifier attributeHandleIdenfier : list) {
Integer userId = attributeHandleIdenfier.shouldBeEventHandled(message);
if (userId != null) {
try {
User user = perunSession.getPerunBl().getUsersManagerBl().getUserById(perunSession, userId);
AttributeDefinition attributeDefinition = perunSession.getPerunBl().getAttributesManagerBl().getAttributeDefinition(perunSession, getDestinationAttributeName());
resolvingMessages.add(new AttributeChangedForUser(new Attribute(attributeDefinition), user));
} catch (UserNotExistsException e) {
log.warn("User from UserExtSource doesn't exist in Perun. This occurred while parsing message: {}.", message);
}
}
}
return resolvingMessages;
}
public AttributeDefinition getAttributeDefinition() {
AttributeDefinition attr = new AttributeDefinition();
attr.setNamespace(AttributesManager.NS_USER_ATTR_VIRT);
String friendlyName = getDestinationAttributeFriendlyName();
attr.setFriendlyName(friendlyName);
attr.setDisplayName(getDestinationAttributeDisplayName());
attr.setType(ArrayList.class.getName());
attr.setDescription(getDestinationAttributeDescription());
return attr;
}
}
| 11,406 | 0.783644 | 0.783469 | 265 | 42.098114 | 41.203655 | 221 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.030189 | false | false |
12
|
27cf36feed6875239b29fd70e015e18a6950556c
| 13,116,830,127,268 |
cfab485f5ff8438f881816c92e96d9571984b98e
|
/wifi4eu-portal/wifi4eu-portal-service/src/main/java/wifi4eu/wifi4eu/mapper/thread/ThreadMapper.java
|
11cd77ccd2867c67ef45531c7ee89e824f6aedcd
|
[] |
no_license
|
wifi4eu/master
|
https://github.com/wifi4eu/master
|
f9f0b7d9a29e997cd6ab0a5087bdfe91cd55f2d6
|
cc4c60449e7b7ea23a47183b42869e8df2092d54
|
refs/heads/master
| 2021-09-25T01:16:53.953000 | 2018-10-16T07:54:45 | 2018-10-16T07:54:45 | 153,153,932 | 8 | 5 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package wifi4eu.wifi4eu.mapper.thread;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import wifi4eu.wifi4eu.common.dto.model.ThreadDTO;
import wifi4eu.wifi4eu.common.dto.model.ThreadMessageDTO;
import wifi4eu.wifi4eu.entity.thread.Thread;
import wifi4eu.wifi4eu.entity.thread.ThreadMessage;
import java.util.List;
@Mapper(componentModel = "spring")
public interface ThreadMapper {
// @Mapping(source = "entity.lau.id", target = "lauId")
ThreadDTO toDTO(Thread entity);
// @Mapping(source = "vo.lauId", target = "lau.id")
Thread toEntity(ThreadDTO vo);
@Mappings({
@Mapping(source = "entity.thread.id", target = "threadId"),
@Mapping(source = "entity.author.id", target = "authorId")
})
ThreadMessageDTO toDTO(ThreadMessage entity);
@Mappings({
@Mapping(source = "vo.threadId", target = "thread.id"),
@Mapping(source = "vo.authorId", target = "author.id")
})
ThreadMessage toEntity(ThreadMessageDTO vo);
List<ThreadDTO> toDTOList(List<Thread> list);
List<Thread> toEntityList(List<ThreadDTO> list);
}
|
UTF-8
|
Java
| 1,155 |
java
|
ThreadMapper.java
|
Java
|
[] | null |
[] |
package wifi4eu.wifi4eu.mapper.thread;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import wifi4eu.wifi4eu.common.dto.model.ThreadDTO;
import wifi4eu.wifi4eu.common.dto.model.ThreadMessageDTO;
import wifi4eu.wifi4eu.entity.thread.Thread;
import wifi4eu.wifi4eu.entity.thread.ThreadMessage;
import java.util.List;
@Mapper(componentModel = "spring")
public interface ThreadMapper {
// @Mapping(source = "entity.lau.id", target = "lauId")
ThreadDTO toDTO(Thread entity);
// @Mapping(source = "vo.lauId", target = "lau.id")
Thread toEntity(ThreadDTO vo);
@Mappings({
@Mapping(source = "entity.thread.id", target = "threadId"),
@Mapping(source = "entity.author.id", target = "authorId")
})
ThreadMessageDTO toDTO(ThreadMessage entity);
@Mappings({
@Mapping(source = "vo.threadId", target = "thread.id"),
@Mapping(source = "vo.authorId", target = "author.id")
})
ThreadMessage toEntity(ThreadMessageDTO vo);
List<ThreadDTO> toDTOList(List<Thread> list);
List<Thread> toEntityList(List<ThreadDTO> list);
}
| 1,155 | 0.690909 | 0.682251 | 36 | 31.055555 | 24.062355 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.638889 | false | false |
12
|
80d825571ac442170fc4095d216038377e16fcec
| 18,597,208,398,661 |
47b630e49ba403052682524b320654b769efb34c
|
/core/src/main/java/org/utahgtug/asteroids/core/entities/Asteroid.java
|
ea8510ca3c5cf9422c939b653c476d39dae689f3
|
[] |
no_license
|
jribble/playn-asteroids
|
https://github.com/jribble/playn-asteroids
|
9f89f264eafa9d85d1583d4b26e5c14866ee4049
|
b6c27794cec990bddf76bf329be992858fe3ae1b
|
refs/heads/master
| 2020-05-19T08:54:27.589000 | 2012-03-20T16:13:55 | 2012-03-20T16:13:55 | 32,339,551 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* Copyright 2011 The ForPlay 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.utahgtug.asteroids.core.entities;
import static playn.core.PlayN.assets;
import org.jbox2d.collision.shapes.CircleShape;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.BodyType;
import org.jbox2d.dynamics.FixtureDef;
import org.jbox2d.dynamics.World;
import playn.core.Sound;
import org.utahgtug.asteroids.core.AsteroidsWorld;
public class Asteroid extends DynamicPhysicsEntity implements PhysicsEntity.HasContactListener {
public static String TYPE = "Asteroid";
private float destroyTTL = 100;
private boolean destroying = false;
private Sound bangSound;
public Asteroid(AsteroidsWorld asteroidWorld, World world, float x, float y, float angle) {
super(asteroidWorld, world, x, y, angle);
bangSound = assets().getSound("audio/bangLarge");
}
@Override
Body initPhysicsBody(World world, float x, float y, float angle) {
FixtureDef fixtureDef = new FixtureDef();
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyType.DYNAMIC;
bodyDef.position = new Vec2(0, 0);
Body body = world.createBody(bodyDef);
CircleShape circleShape = new CircleShape();
circleShape.m_radius = getRadius();
fixtureDef.shape = circleShape;
fixtureDef.density = 0.4f;
fixtureDef.friction = 0.1f;
fixtureDef.restitution = 0.35f;
circleShape.m_p.set(0, 0);
body.createFixture(fixtureDef);
body.setLinearDamping(0.0f);
body.setTransform(new Vec2(x, y), angle);
return body;
}
@Override
float getWidth() {
return 2 * getRadius();
}
@Override
float getHeight() {
return 2 * getRadius();
}
float getRadius() {
// return 1.50f;
return 0.5f;
}
@Override
public String getImagePath() {
// return "images/chrome.png";
return destroying ? "images/explosion.png" : "images/largeasteroid.png";
}
@Override
public void contact(PhysicsEntity other) {
if(other instanceof Wall) return;
if(other instanceof Asteroid) return;
destroying = true;
destroyImageLayer();
loadImageLayer();
bangSound.play();
}
@Override
public boolean update(float delta) {
if(!destroying){
return super.update(delta);
}
destroyTTL = destroyTTL - delta;
if(destroyTTL <= 0) {
getWorld().getWorld().destroyBody(getBody());
destroyImageLayer();
return true;
}
return false;
}
}
|
UTF-8
|
Java
| 2,944 |
java
|
Asteroid.java
|
Java
|
[] | null |
[] |
/**
* Copyright 2011 The ForPlay 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.utahgtug.asteroids.core.entities;
import static playn.core.PlayN.assets;
import org.jbox2d.collision.shapes.CircleShape;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.BodyType;
import org.jbox2d.dynamics.FixtureDef;
import org.jbox2d.dynamics.World;
import playn.core.Sound;
import org.utahgtug.asteroids.core.AsteroidsWorld;
public class Asteroid extends DynamicPhysicsEntity implements PhysicsEntity.HasContactListener {
public static String TYPE = "Asteroid";
private float destroyTTL = 100;
private boolean destroying = false;
private Sound bangSound;
public Asteroid(AsteroidsWorld asteroidWorld, World world, float x, float y, float angle) {
super(asteroidWorld, world, x, y, angle);
bangSound = assets().getSound("audio/bangLarge");
}
@Override
Body initPhysicsBody(World world, float x, float y, float angle) {
FixtureDef fixtureDef = new FixtureDef();
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyType.DYNAMIC;
bodyDef.position = new Vec2(0, 0);
Body body = world.createBody(bodyDef);
CircleShape circleShape = new CircleShape();
circleShape.m_radius = getRadius();
fixtureDef.shape = circleShape;
fixtureDef.density = 0.4f;
fixtureDef.friction = 0.1f;
fixtureDef.restitution = 0.35f;
circleShape.m_p.set(0, 0);
body.createFixture(fixtureDef);
body.setLinearDamping(0.0f);
body.setTransform(new Vec2(x, y), angle);
return body;
}
@Override
float getWidth() {
return 2 * getRadius();
}
@Override
float getHeight() {
return 2 * getRadius();
}
float getRadius() {
// return 1.50f;
return 0.5f;
}
@Override
public String getImagePath() {
// return "images/chrome.png";
return destroying ? "images/explosion.png" : "images/largeasteroid.png";
}
@Override
public void contact(PhysicsEntity other) {
if(other instanceof Wall) return;
if(other instanceof Asteroid) return;
destroying = true;
destroyImageLayer();
loadImageLayer();
bangSound.play();
}
@Override
public boolean update(float delta) {
if(!destroying){
return super.update(delta);
}
destroyTTL = destroyTTL - delta;
if(destroyTTL <= 0) {
getWorld().getWorld().destroyBody(getBody());
destroyImageLayer();
return true;
}
return false;
}
}
| 2,944 | 0.728261 | 0.713995 | 115 | 24.6 | 22.922098 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.652174 | false | false |
12
|
4a81215a35c2ab9d58949be4e5b1df4b028c6e0e
| 25,933,012,539,230 |
9cf64bc88c749a63060a21e2739006687110fa3f
|
/src/main/java/duke/task/Find.java
|
56f9827a201ce4672f04aa640c24db0df95c180a
|
[] |
no_license
|
rebeccalaujx/ip
|
https://github.com/rebeccalaujx/ip
|
a5f6ee770d1a62ec98d45c3cd49d981fc5ba0329
|
da29a26947b9ba4ae045c54db9f41e09c1d4af71
|
refs/heads/master
| 2023-08-16T17:36:05.372000 | 2021-09-17T16:38:41 | 2021-09-17T16:38:41 | 397,993,260 | 0 | 0 | null | true | 2021-09-16T12:44:02 | 2021-08-19T15:39:27 | 2021-09-16T12:08:35 | 2021-09-16T12:44:01 | 1,693 | 0 | 0 | 1 |
Java
| false | false |
package duke.task;
import duke.Ui;
/**
* Class that encapsulates searches for keywords among current Tasks.
*/
public class Find {
private boolean isFound;
private String word;
private TaskList ls;
private String result;
private Ui ui = new Ui();
/**
* Constructor for Find.
*
* @param word Keyword.
* @param ls Current TaskList.
*/
public Find(String word, TaskList ls) {
this.isFound = false;
this.word = word;
this.ls = ls;
}
/**
* Prints out the list of Tasks that include the keyword.
*/
public String findWord() {
if (!this.isFound) {
return this.result = ui.printListWithKeyword(ls, word, this);
}
if (this.result.isEmpty()) {
return ui.noResultsFound(word);
} else {
return this.result;
}
}
/**
* Signals that there are Tasks with the keyword by setting the isFound boolean to true.
*/
public void setFound() {
this.isFound = true;
}
}
|
UTF-8
|
Java
| 1,062 |
java
|
Find.java
|
Java
|
[] | null |
[] |
package duke.task;
import duke.Ui;
/**
* Class that encapsulates searches for keywords among current Tasks.
*/
public class Find {
private boolean isFound;
private String word;
private TaskList ls;
private String result;
private Ui ui = new Ui();
/**
* Constructor for Find.
*
* @param word Keyword.
* @param ls Current TaskList.
*/
public Find(String word, TaskList ls) {
this.isFound = false;
this.word = word;
this.ls = ls;
}
/**
* Prints out the list of Tasks that include the keyword.
*/
public String findWord() {
if (!this.isFound) {
return this.result = ui.printListWithKeyword(ls, word, this);
}
if (this.result.isEmpty()) {
return ui.noResultsFound(word);
} else {
return this.result;
}
}
/**
* Signals that there are Tasks with the keyword by setting the isFound boolean to true.
*/
public void setFound() {
this.isFound = true;
}
}
| 1,062 | 0.568738 | 0.568738 | 49 | 20.67347 | 20.364422 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.346939 | false | false |
12
|
012ea4091a27a708ed920069eff97c79c395658b
| 28,346,784,158,333 |
9658532b8cac9fcbf75bc2a0f54c596e703564c2
|
/src/main/java/settings/Quiz.java
|
9455f57339381381a897cfbd3c6b4fb283835e2b
|
[] |
no_license
|
jakub-aniol/Quiz
|
https://github.com/jakub-aniol/Quiz
|
173d11fe588f5420dae1aeaf437b4fd9ca4f88ec
|
b6f1a0433873ab006065bee9d1965e072f5815f9
|
refs/heads/master
| 2021-01-01T05:29:33.708000 | 2016-05-08T22:54:41 | 2016-05-08T22:54:41 | 56,751,657 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package settings;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
/**
* Object for storying information about the whole Quiz
* Created by Jakub
* Since 2016-04-30.
*/
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Quiz {
@Id
@GeneratedValue
private int Id;
private String quizName;
private String quizDescription;
private String answerAfterPassing;
private int maxPointsQuiz;
private int pointsToPass;
private int numberOfQuestions;
@OneToMany(mappedBy = "quiz", fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
private List<Question> qusetionsList;
public Quiz() {
}
public Quiz(Quiz quiz) {
this.quizName=quiz.quizName;
this.quizDescription=quiz.quizDescription;
this.answerAfterPassing=quiz.answerAfterPassing;
this.maxPointsQuiz=quiz.maxPointsQuiz;
this.pointsToPass=quiz.pointsToPass;
this.numberOfQuestions=quiz.numberOfQuestions;
this.qusetionsList=new ArrayList<>(quiz.qusetionsList);
}
/**
* Constructor, Question must have:
* Now you can provide only Lit of question to create Quiz it is only one implementation of a constructor
* Additionally quiz couts maxPopintsQuiz by itself using method countMaxPointForQuiz()
*
* @param questionsList - List with objects Question {@link settings.Question}
*/
public Quiz(List<Question> questionsList) {
this.setQusetionsList(questionsList);
countMaxPointForQuiz();
}
public int getMaxPointsQuiz() {
return maxPointsQuiz;
}
public void setMaxPointsQuiz(int maxPointsQuiz) {
this.maxPointsQuiz = maxPointsQuiz;
}
public String getQuizName() {
return this.quizName;
}
public void setQuizName(String quizName) {
this.quizName = quizName;
}
public List<Question> getQuestionList() {
return this.getQusetionsList();
}
public int getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
public String getQuizDescription() {
return quizDescription;
}
public void setQuizDescription(String quizDescription) {
this.quizDescription = quizDescription;
}
public String getAnswerAfterPassing() {
return answerAfterPassing;
}
public void setAnswerAfterPassing(String answerAfterPassing) {
this.answerAfterPassing = answerAfterPassing;
}
public int getPointsToPass() {
return pointsToPass;
}
public void setPointsToPass(int pointsToPass) {
this.pointsToPass = pointsToPass;
}
public int getNumberOfQuestions() {
return numberOfQuestions;
}
public void setNumberOfQuestions(int numberOfQuestions) {
this.numberOfQuestions = numberOfQuestions;
}
List<Question> getQusetionsList() {
return qusetionsList;
}
public void setQusetionsList(List<Question> qusetionsList) {
this.qusetionsList = qusetionsList;
}
/**
* Method for counting points one can get for a quiz
* It uses a method countingMaxPoints() in a loop to count maxPoints by adding points from one question to another {@link settings.Question}
*/
public void countMaxPointForQuiz() {
int maxPoint = 0;
for (Question que : this.getQuestionList()) {
que.countingMaxPoints();
maxPoint += que.getMaxPoints();
}
this.setMaxPointsQuiz(maxPoint);
}
public String toString() {
String strReturn = "";
strReturn += this.getQuizName();
strReturn += "\n";
strReturn += this.getQusetionsList();
return strReturn;
}
}
|
UTF-8
|
Java
| 3,775 |
java
|
Quiz.java
|
Java
|
[
{
"context": "ing information about the whole Quiz\n * Created by Jakub\n * Since 2016-04-30.\n */\n@Entity\n@Inheritance(str",
"end": 178,
"score": 0.9967858791351318,
"start": 173,
"tag": "NAME",
"value": "Jakub"
}
] | null |
[] |
package settings;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
/**
* Object for storying information about the whole Quiz
* Created by Jakub
* Since 2016-04-30.
*/
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Quiz {
@Id
@GeneratedValue
private int Id;
private String quizName;
private String quizDescription;
private String answerAfterPassing;
private int maxPointsQuiz;
private int pointsToPass;
private int numberOfQuestions;
@OneToMany(mappedBy = "quiz", fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
private List<Question> qusetionsList;
public Quiz() {
}
public Quiz(Quiz quiz) {
this.quizName=quiz.quizName;
this.quizDescription=quiz.quizDescription;
this.answerAfterPassing=quiz.answerAfterPassing;
this.maxPointsQuiz=quiz.maxPointsQuiz;
this.pointsToPass=quiz.pointsToPass;
this.numberOfQuestions=quiz.numberOfQuestions;
this.qusetionsList=new ArrayList<>(quiz.qusetionsList);
}
/**
* Constructor, Question must have:
* Now you can provide only Lit of question to create Quiz it is only one implementation of a constructor
* Additionally quiz couts maxPopintsQuiz by itself using method countMaxPointForQuiz()
*
* @param questionsList - List with objects Question {@link settings.Question}
*/
public Quiz(List<Question> questionsList) {
this.setQusetionsList(questionsList);
countMaxPointForQuiz();
}
public int getMaxPointsQuiz() {
return maxPointsQuiz;
}
public void setMaxPointsQuiz(int maxPointsQuiz) {
this.maxPointsQuiz = maxPointsQuiz;
}
public String getQuizName() {
return this.quizName;
}
public void setQuizName(String quizName) {
this.quizName = quizName;
}
public List<Question> getQuestionList() {
return this.getQusetionsList();
}
public int getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
public String getQuizDescription() {
return quizDescription;
}
public void setQuizDescription(String quizDescription) {
this.quizDescription = quizDescription;
}
public String getAnswerAfterPassing() {
return answerAfterPassing;
}
public void setAnswerAfterPassing(String answerAfterPassing) {
this.answerAfterPassing = answerAfterPassing;
}
public int getPointsToPass() {
return pointsToPass;
}
public void setPointsToPass(int pointsToPass) {
this.pointsToPass = pointsToPass;
}
public int getNumberOfQuestions() {
return numberOfQuestions;
}
public void setNumberOfQuestions(int numberOfQuestions) {
this.numberOfQuestions = numberOfQuestions;
}
List<Question> getQusetionsList() {
return qusetionsList;
}
public void setQusetionsList(List<Question> qusetionsList) {
this.qusetionsList = qusetionsList;
}
/**
* Method for counting points one can get for a quiz
* It uses a method countingMaxPoints() in a loop to count maxPoints by adding points from one question to another {@link settings.Question}
*/
public void countMaxPointForQuiz() {
int maxPoint = 0;
for (Question que : this.getQuestionList()) {
que.countingMaxPoints();
maxPoint += que.getMaxPoints();
}
this.setMaxPointsQuiz(maxPoint);
}
public String toString() {
String strReturn = "";
strReturn += this.getQuizName();
strReturn += "\n";
strReturn += this.getQusetionsList();
return strReturn;
}
}
| 3,775 | 0.664106 | 0.661722 | 144 | 25.215279 | 24.713684 | 144 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.347222 | false | false |
12
|
912f591106ddcc8c9ca069d648325e3d03d6b94f
| 29,944,511,994,955 |
57dbaf6e94f9e1cc3b86d36236e83abf75c38ce2
|
/src/es/uv/eu/linespainter/view/LinesPainterView.java
|
63e224553301ffb4be19d4723e7fdbfe73d6a313
|
[] |
no_license
|
Marcel88888/LinesPainter
|
https://github.com/Marcel88888/LinesPainter
|
a1b7a2d309f6d81919de4db44556e32f7c1d0881
|
1ec7c186694a1dd9f57f1c02faa22c33c2e490ec
|
refs/heads/master
| 2023-01-10T12:12:16.416000 | 2020-10-24T18:30:22 | 2020-10-24T18:30:22 | 254,909,679 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package es.uv.eu.linespainter.view;
import es.uv.eu.linespainter.model.LinesPainterModel;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.event.ChangeListener;
public class LinesPainterView extends JFrame {
private LinesPainterModel model;
private ImagePanel imagePanel;
private WidthPanel widthPanel;
private StatusPanel statusPanel;
private SelectPanel selectPanel;
private LinesPainterMenuBar menu;
public LinesPainterView(LinesPainterModel model) {
super("LinesPainter");
this.setLayout(new BorderLayout(17, 8));
this.setSize(1675, 1000);
this.model = model;
this.imagePanel = new ImagePanel(model);
this.widthPanel = new WidthPanel(this);
this.statusPanel = new StatusPanel(this);
this.selectPanel = new SelectPanel();
this.menu = new LinesPainterMenuBar();
this.add(imagePanel, BorderLayout.CENTER);
this.add(widthPanel, BorderLayout.NORTH);
this.add(statusPanel, BorderLayout.SOUTH);
this.add(selectPanel, BorderLayout.WEST);
this.setJMenuBar(menu);
getRootPane().setBorder(BorderFactory.createMatteBorder(8, 8, 8, 8, this.getBackground()));
this.setVisible(true);
}
public LinesPainterModel getModel() {
return model;
}
public StatusPanel getStatusPanel() {
return statusPanel;
}
public SelectPanel getSelectPanel() {
return selectPanel;
}
public ImagePanel getImagePanel() {
return imagePanel;
}
public WidthPanel getWidthPanel() {
return widthPanel;
}
public void setChangeListener(ChangeListener cl) {
widthPanel.setChangeListener(cl);
}
public void setActionListener(ActionListener al) {
selectPanel.setActionListener(al);
menu.setActionListener(al);
}
public void setMouseListener(MouseAdapter ma) {
imagePanel.setMouseListener(ma);
}
public void updateStatusPanelWidthValue(int width) {
statusPanel.updateWidthValueLabel(width);
}
public void updateStatusPanelColor1(Color color1) {
statusPanel.getColor1().setBackground(color1);
}
public void updateStatusPanelColor2(Color color2) {
statusPanel.getColor2().setBackground(color2);
}
public Color getColor1ByButton(JButton button) {
return selectPanel.getColor1ByButton(button);
}
public Color getColor2ByButton(JButton button) {
return selectPanel.getColor2ByButton(button);
}
}
|
UTF-8
|
Java
| 2,805 |
java
|
LinesPainterView.java
|
Java
|
[] | null |
[] |
package es.uv.eu.linespainter.view;
import es.uv.eu.linespainter.model.LinesPainterModel;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.event.ChangeListener;
public class LinesPainterView extends JFrame {
private LinesPainterModel model;
private ImagePanel imagePanel;
private WidthPanel widthPanel;
private StatusPanel statusPanel;
private SelectPanel selectPanel;
private LinesPainterMenuBar menu;
public LinesPainterView(LinesPainterModel model) {
super("LinesPainter");
this.setLayout(new BorderLayout(17, 8));
this.setSize(1675, 1000);
this.model = model;
this.imagePanel = new ImagePanel(model);
this.widthPanel = new WidthPanel(this);
this.statusPanel = new StatusPanel(this);
this.selectPanel = new SelectPanel();
this.menu = new LinesPainterMenuBar();
this.add(imagePanel, BorderLayout.CENTER);
this.add(widthPanel, BorderLayout.NORTH);
this.add(statusPanel, BorderLayout.SOUTH);
this.add(selectPanel, BorderLayout.WEST);
this.setJMenuBar(menu);
getRootPane().setBorder(BorderFactory.createMatteBorder(8, 8, 8, 8, this.getBackground()));
this.setVisible(true);
}
public LinesPainterModel getModel() {
return model;
}
public StatusPanel getStatusPanel() {
return statusPanel;
}
public SelectPanel getSelectPanel() {
return selectPanel;
}
public ImagePanel getImagePanel() {
return imagePanel;
}
public WidthPanel getWidthPanel() {
return widthPanel;
}
public void setChangeListener(ChangeListener cl) {
widthPanel.setChangeListener(cl);
}
public void setActionListener(ActionListener al) {
selectPanel.setActionListener(al);
menu.setActionListener(al);
}
public void setMouseListener(MouseAdapter ma) {
imagePanel.setMouseListener(ma);
}
public void updateStatusPanelWidthValue(int width) {
statusPanel.updateWidthValueLabel(width);
}
public void updateStatusPanelColor1(Color color1) {
statusPanel.getColor1().setBackground(color1);
}
public void updateStatusPanelColor2(Color color2) {
statusPanel.getColor2().setBackground(color2);
}
public Color getColor1ByButton(JButton button) {
return selectPanel.getColor1ByButton(button);
}
public Color getColor2ByButton(JButton button) {
return selectPanel.getColor2ByButton(button);
}
}
| 2,805 | 0.677362 | 0.667736 | 98 | 27.62245 | 20.871578 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false |
12
|
7b913d6c9344c22e35c21b5ced0d7e2bc842d2fd
| 33,011,118,644,015 |
a1230aa5a2ec1cddb0dba58b90266f69ebc7e85b
|
/JyAA_2014-Entrega_Final_V1.1/src/com/CEDICA/dao/IFamiliarDao.java
|
770a88bea0da61f4e3a6939e70ad19a67a454415
|
[] |
no_license
|
tole22/Java_y_aplicaciones_sobre_internet
|
https://github.com/tole22/Java_y_aplicaciones_sobre_internet
|
c2ef43327a5ef920a1fd1d26a11836f59853d919
|
5b3c2aa1176d27a79b073f6635c5fdf5ab86c457
|
refs/heads/master
| 2020-03-29T14:33:03.732000 | 2018-09-23T20:40:12 | 2018-09-23T20:40:12 | 150,022,929 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.CEDICA.dao;
import com.CEDICA.dao.generic.GenericDao;
import com.CEDICA.model.Familiar;
public interface IFamiliarDao extends GenericDao<Familiar> {
}
|
UTF-8
|
Java
| 166 |
java
|
IFamiliarDao.java
|
Java
|
[] | null |
[] |
package com.CEDICA.dao;
import com.CEDICA.dao.generic.GenericDao;
import com.CEDICA.model.Familiar;
public interface IFamiliarDao extends GenericDao<Familiar> {
}
| 166 | 0.807229 | 0.807229 | 8 | 19.75 | 21.735628 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false |
12
|
cea0a76d31b0cc6569cf841a51db2c9667d22de0
| 33,011,118,645,567 |
39f94f622c094f4dabff0e4e8f7f760cc7014489
|
/all/src/test/java/io/atomix/AtomixLeaderElectionTest.java
|
4f4de10feac5e75b23bfb5f31ac2cd19dfe6ffd9
|
[
"Apache-2.0"
] |
permissive
|
WangBaoling/atomix
|
https://github.com/WangBaoling/atomix
|
a084f4cceb1b6c6a82ee4ff9a74974d05daa1bc1
|
09e68ea477c62f2ac7ae139ae35f443a86600948
|
refs/heads/master
| 2020-12-03T07:57:15.176000 | 2015-12-22T19:09:40 | 2015-12-22T19:09:40 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* Copyright 2015 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.atomix;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import io.atomix.atomix.testing.AbstractAtomixTest;
import io.atomix.coordination.DistributedLeaderElection;
/**
* Atomix leader election test.
*
* @author <a href="http://github.com/kuujo>Jordan Halterman</a>
*/
@Test
public class AtomixLeaderElectionTest extends AbstractAtomixTest {
@BeforeClass
protected void setupCluster() throws Throwable {
createReplicas(5);
}
public void testClientLeaderElectionGet() throws Throwable {
Atomix client1 = createClient();
Atomix client2 = createClient();
testLeaderElection(client1, client2, get("test-client-election-get", DistributedLeaderElection.TYPE));
}
public void testClientLeaderElectionCreate() throws Throwable {
Atomix client1 = createClient();
Atomix client2 = createClient();
testLeaderElection(client1, client2, create("test-client-election-create", DistributedLeaderElection.TYPE));
}
public void testReplicaLeaderElectionGet() throws Throwable {
testLeaderElection(createClient(), replicas.get(1), get("test-replica-election-get", DistributedLeaderElection.TYPE));
}
public void testReplicaLeaderElectionCreate() throws Throwable {
testLeaderElection(createClient(), replicas.get(1), create("test-replica-election-create", DistributedLeaderElection.TYPE));
}
/**
* Tests a leader election.
*/
private void testLeaderElection(Atomix client1, Atomix client2, Function<Atomix, DistributedLeaderElection> factory) throws Throwable {
DistributedLeaderElection election1 = factory.apply(client1);
DistributedLeaderElection election2 = factory.apply(client2);
AtomicLong lastEpoch = new AtomicLong(0);
election1.onElection(epoch -> {
threadAssertTrue(epoch > lastEpoch.get());
lastEpoch.set(epoch);
resume();
}).join();
await(10000);
election2.onElection(epoch -> {
threadAssertTrue(epoch > lastEpoch.get());
lastEpoch.set(epoch);
resume();
}).join();
client1.close();
await(10000);
}
}
|
UTF-8
|
Java
| 2,797 |
java
|
AtomixLeaderElectionTest.java
|
Java
|
[
{
"context": "on test.\n *\n * @author <a href=\"http://github.com/kuujo>Jordan Halterman</a>\n */\n@Test\npublic class Atomi",
"end": 986,
"score": 0.9968478083610535,
"start": 981,
"tag": "USERNAME",
"value": "kuujo"
},
{
"context": "t.\n *\n * @author <a href=\"http://github.com/kuujo>Jordan Halterman</a>\n */\n@Test\npublic class AtomixLeaderElectionTe",
"end": 1003,
"score": 0.9997280240058899,
"start": 987,
"tag": "NAME",
"value": "Jordan Halterman"
}
] | null |
[] |
/*
* Copyright 2015 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.atomix;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import io.atomix.atomix.testing.AbstractAtomixTest;
import io.atomix.coordination.DistributedLeaderElection;
/**
* Atomix leader election test.
*
* @author <a href="http://github.com/kuujo><NAME></a>
*/
@Test
public class AtomixLeaderElectionTest extends AbstractAtomixTest {
@BeforeClass
protected void setupCluster() throws Throwable {
createReplicas(5);
}
public void testClientLeaderElectionGet() throws Throwable {
Atomix client1 = createClient();
Atomix client2 = createClient();
testLeaderElection(client1, client2, get("test-client-election-get", DistributedLeaderElection.TYPE));
}
public void testClientLeaderElectionCreate() throws Throwable {
Atomix client1 = createClient();
Atomix client2 = createClient();
testLeaderElection(client1, client2, create("test-client-election-create", DistributedLeaderElection.TYPE));
}
public void testReplicaLeaderElectionGet() throws Throwable {
testLeaderElection(createClient(), replicas.get(1), get("test-replica-election-get", DistributedLeaderElection.TYPE));
}
public void testReplicaLeaderElectionCreate() throws Throwable {
testLeaderElection(createClient(), replicas.get(1), create("test-replica-election-create", DistributedLeaderElection.TYPE));
}
/**
* Tests a leader election.
*/
private void testLeaderElection(Atomix client1, Atomix client2, Function<Atomix, DistributedLeaderElection> factory) throws Throwable {
DistributedLeaderElection election1 = factory.apply(client1);
DistributedLeaderElection election2 = factory.apply(client2);
AtomicLong lastEpoch = new AtomicLong(0);
election1.onElection(epoch -> {
threadAssertTrue(epoch > lastEpoch.get());
lastEpoch.set(epoch);
resume();
}).join();
await(10000);
election2.onElection(epoch -> {
threadAssertTrue(epoch > lastEpoch.get());
lastEpoch.set(epoch);
resume();
}).join();
client1.close();
await(10000);
}
}
| 2,787 | 0.739006 | 0.725063 | 86 | 31.523256 | 32.867855 | 137 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.581395 | false | false |
12
|
6d54c8784b6eac5ddecc3093d021268ba62a0244
| 523,986,021,560 |
cec628def1aad94ccbefa814d2a0dbd51588e9bd
|
/php.smarty/src/org/netbeans/modules/php/smarty/editor/completion/TplCompletionProvider.java
|
395ec3aa83f1fc2e06cbd4a5c04760284e5970d0
|
[] |
no_license
|
emilianbold/netbeans-releases
|
https://github.com/emilianbold/netbeans-releases
|
ad6e6e52a896212cb628d4522a4f8ae685d84d90
|
2fd6dc84c187e3c79a959b3ddb4da1a9703659c7
|
refs/heads/master
| 2021-01-12T04:58:24.877000 | 2017-10-17T14:38:27 | 2017-10-17T14:38:27 | 78,269,363 | 30 | 15 | null | false | 2020-10-13T08:36:08 | 2017-01-07T09:07:28 | 2020-10-03T06:33:28 | 2020-10-13T08:36:06 | 965,667 | 16 | 11 | 5 | null | false | false |
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
*
* Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.modules.php.smarty.editor.completion;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.swing.Action;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import org.netbeans.api.lexer.TokenHierarchy;
import org.netbeans.api.lexer.TokenSequence;
import org.netbeans.editor.BaseDocument;
import org.netbeans.modules.parsing.spi.ParseException;
import org.netbeans.spi.editor.completion.CompletionDocumentation;
import org.netbeans.spi.editor.completion.CompletionItem;
import org.netbeans.spi.editor.completion.CompletionResultSet;
import org.netbeans.spi.editor.completion.CompletionProvider;
import org.netbeans.spi.editor.completion.CompletionTask;
import org.netbeans.spi.editor.completion.support.AsyncCompletionQuery;
import org.netbeans.spi.editor.completion.support.AsyncCompletionTask;
import org.openide.util.Exceptions;
/**
* Implementation of {@link CompletionProvider} for Tpl documents.
*
* @author Martin Fousek
*/
public class TplCompletionProvider implements CompletionProvider {
@Override
public int getAutoQueryTypes(JTextComponent component, String typedText) {
// Document doc = component.getDocument();
// int dotPos = component.getCaret().getDot();
// boolean openCC = checkOpenCompletion(doc, dotPos, typedText);
// return openCC ? COMPLETION_QUERY_TYPE + DOCUMENTATION_QUERY_TYPE : 0;
return 0;
}
@Override
public CompletionTask createTask(int queryType, JTextComponent component) {
AsyncCompletionTask task = null;
if ((queryType & COMPLETION_QUERY_TYPE & COMPLETION_ALL_QUERY_TYPE) != 0) {
task = new AsyncCompletionTask(new Query(), component);
}
return task;
}
private static class Query extends AbstractQuery {
private volatile Set<TplCompletionItem> items = new HashSet<>();
private JTextComponent component;
@Override
protected void prepareQuery(JTextComponent component) {
this.component = component;
}
@Override
protected void doQuery(CompletionResultSet resultSet, final Document doc, final int caretOffset) {
try {
final TplCompletionQuery.CompletionResult result = new TplCompletionQuery(doc).query();
if (result != null) {
doc.render(new Runnable() {
@Override
public void run() {
items = getItems(result, doc, caretOffset);
}
});
} else {
items = Collections.<TplCompletionItem>emptySet();
}
resultSet.addAllItems(items);
} catch (ParseException ex) {
Exceptions.printStackTrace(ex);
}
}
private Set<TplCompletionItem> getItems(TplCompletionQuery.CompletionResult result, Document doc, int offset) {
Set<TplCompletionItem> entries = new HashSet<>();
ArrayList<String> commands; boolean inSmarty = false;
if (CodeCompletionUtils.insideSmartyCode(doc, offset)) {
if (CodeCompletionUtils.inVariableModifiers(doc, offset)) {
entries.addAll(result.getVariableModifiers());
inSmarty = true;
}
commands = CodeCompletionUtils.afterSmartyCommand(doc, offset);
if (!commands.isEmpty()) {
entries.addAll(result.getParamsForCommand(commands));
inSmarty = true;
}
if (!inSmarty) {
if (result != null) {
entries.addAll(result.getFunctions());
}
}
}
return entries;
}
@Override
protected boolean canFilter(JTextComponent component) {
try {
if (component.getText(component.getCaretPosition() - 1, 1).toString().equals("|")) {
return false;
}
} catch (BadLocationException ex) {
return false;
}
String prefix = CodeCompletionUtils.getTextPrefix(component.getDocument(), component.getCaretPosition());
//check the items
for (CompletionItem item : items) {
if (CodeCompletionUtils.startsWithIgnoreCase(((TplCompletionItem) item).getItemText(), prefix)) {
return true; //at least one item will remain
}
}
return false;
}
@Override
protected void filter(CompletionResultSet resultSet) {
String prefix = CodeCompletionUtils.getTextPrefix(component.getDocument(), component.getCaretPosition());
//check the items
for (CompletionItem item : items) {
if (CodeCompletionUtils.startsWithIgnoreCase(((TplCompletionItem) item).getItemText(), prefix)) {
resultSet.addItem(item);
}
}
resultSet.finish();
}
}
public static class DocQuery extends AbstractQuery {
private CompletionItem item;
public DocQuery(TplCompletionItem item) {
this.item = item;
}
@Override
protected void doQuery(CompletionResultSet resultSet, Document doc, int caretOffset) {
if (item == null) {
try {
//item == null means that the DocQuery is invoked
//based on the explicit documentation opening request
//(not ivoked by selecting a completion item in the list)
TplCompletionQuery.CompletionResult result = new TplCompletionQuery(doc).query();
if (result != null && result.getFunctions().size() > 0) {
item = result.getFunctions().iterator().next();
}
} catch (ParseException ex) {
Exceptions.printStackTrace(ex);
}
}
TplCompletionItem tplItem = (TplCompletionItem) item;
if (tplItem != null && tplItem.getHelp() != null) {
resultSet.setDocumentation(new DocItem(tplItem));
}
}
}
private static abstract class AbstractQuery extends AsyncCompletionQuery {
@Override
protected void preQueryUpdate(JTextComponent component) {
checkHideCompletion((BaseDocument) component.getDocument(), component.getCaretPosition());
}
@Override
protected void query(CompletionResultSet resultSet, Document doc, int caretOffset) {
try {
doQuery(resultSet, doc, caretOffset);
} finally {
resultSet.finish();
}
}
abstract void doQuery(CompletionResultSet resultSet, Document doc, int caretOffset);
}
private static void checkHideCompletion(final BaseDocument doc, final int caretOffset) {
//test whether we are just in text and eventually close the opened completion
//this is handy after end tag autocompletion when user doesn't complete the
//end tag and just types a text
//test whether the user typed an ending quotation in the attribute value
doc.render(new Runnable() {
@Override
public void run() {
TokenHierarchy tokenHierarchy = TokenHierarchy.get(doc);
TokenSequence tokenSequence = tokenHierarchy.tokenSequence();
tokenSequence.move(caretOffset == 0 ? 0 : caretOffset - 1);
if (!tokenSequence.moveNext()) {
return;
}
}
});
}
private static class DocItem implements CompletionDocumentation {
TplCompletionItem item;
public DocItem(TplCompletionItem tci) {
this.item = tci;
}
@Override
public String getText() {
return item.getHelp();
}
@Override
public URL getURL() {
return item.getHelpURL();
}
@Override
public CompletionDocumentation resolveLink(String link) {
return null;
}
@Override
public Action getGotoSourceAction() {
return null;
}
}
}
|
UTF-8
|
Java
| 10,877 |
java
|
TplCompletionProvider.java
|
Java
|
[
{
"context": "mpletionProvider} for Tpl documents.\n *\n * @author Martin Fousek\n */\npublic class TplCompletionProvider implements",
"end": 3367,
"score": 0.9997031092643738,
"start": 3354,
"tag": "NAME",
"value": "Martin Fousek"
}
] | null |
[] |
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
*
* Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.modules.php.smarty.editor.completion;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.swing.Action;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import org.netbeans.api.lexer.TokenHierarchy;
import org.netbeans.api.lexer.TokenSequence;
import org.netbeans.editor.BaseDocument;
import org.netbeans.modules.parsing.spi.ParseException;
import org.netbeans.spi.editor.completion.CompletionDocumentation;
import org.netbeans.spi.editor.completion.CompletionItem;
import org.netbeans.spi.editor.completion.CompletionResultSet;
import org.netbeans.spi.editor.completion.CompletionProvider;
import org.netbeans.spi.editor.completion.CompletionTask;
import org.netbeans.spi.editor.completion.support.AsyncCompletionQuery;
import org.netbeans.spi.editor.completion.support.AsyncCompletionTask;
import org.openide.util.Exceptions;
/**
* Implementation of {@link CompletionProvider} for Tpl documents.
*
* @author <NAME>
*/
public class TplCompletionProvider implements CompletionProvider {
@Override
public int getAutoQueryTypes(JTextComponent component, String typedText) {
// Document doc = component.getDocument();
// int dotPos = component.getCaret().getDot();
// boolean openCC = checkOpenCompletion(doc, dotPos, typedText);
// return openCC ? COMPLETION_QUERY_TYPE + DOCUMENTATION_QUERY_TYPE : 0;
return 0;
}
@Override
public CompletionTask createTask(int queryType, JTextComponent component) {
AsyncCompletionTask task = null;
if ((queryType & COMPLETION_QUERY_TYPE & COMPLETION_ALL_QUERY_TYPE) != 0) {
task = new AsyncCompletionTask(new Query(), component);
}
return task;
}
private static class Query extends AbstractQuery {
private volatile Set<TplCompletionItem> items = new HashSet<>();
private JTextComponent component;
@Override
protected void prepareQuery(JTextComponent component) {
this.component = component;
}
@Override
protected void doQuery(CompletionResultSet resultSet, final Document doc, final int caretOffset) {
try {
final TplCompletionQuery.CompletionResult result = new TplCompletionQuery(doc).query();
if (result != null) {
doc.render(new Runnable() {
@Override
public void run() {
items = getItems(result, doc, caretOffset);
}
});
} else {
items = Collections.<TplCompletionItem>emptySet();
}
resultSet.addAllItems(items);
} catch (ParseException ex) {
Exceptions.printStackTrace(ex);
}
}
private Set<TplCompletionItem> getItems(TplCompletionQuery.CompletionResult result, Document doc, int offset) {
Set<TplCompletionItem> entries = new HashSet<>();
ArrayList<String> commands; boolean inSmarty = false;
if (CodeCompletionUtils.insideSmartyCode(doc, offset)) {
if (CodeCompletionUtils.inVariableModifiers(doc, offset)) {
entries.addAll(result.getVariableModifiers());
inSmarty = true;
}
commands = CodeCompletionUtils.afterSmartyCommand(doc, offset);
if (!commands.isEmpty()) {
entries.addAll(result.getParamsForCommand(commands));
inSmarty = true;
}
if (!inSmarty) {
if (result != null) {
entries.addAll(result.getFunctions());
}
}
}
return entries;
}
@Override
protected boolean canFilter(JTextComponent component) {
try {
if (component.getText(component.getCaretPosition() - 1, 1).toString().equals("|")) {
return false;
}
} catch (BadLocationException ex) {
return false;
}
String prefix = CodeCompletionUtils.getTextPrefix(component.getDocument(), component.getCaretPosition());
//check the items
for (CompletionItem item : items) {
if (CodeCompletionUtils.startsWithIgnoreCase(((TplCompletionItem) item).getItemText(), prefix)) {
return true; //at least one item will remain
}
}
return false;
}
@Override
protected void filter(CompletionResultSet resultSet) {
String prefix = CodeCompletionUtils.getTextPrefix(component.getDocument(), component.getCaretPosition());
//check the items
for (CompletionItem item : items) {
if (CodeCompletionUtils.startsWithIgnoreCase(((TplCompletionItem) item).getItemText(), prefix)) {
resultSet.addItem(item);
}
}
resultSet.finish();
}
}
public static class DocQuery extends AbstractQuery {
private CompletionItem item;
public DocQuery(TplCompletionItem item) {
this.item = item;
}
@Override
protected void doQuery(CompletionResultSet resultSet, Document doc, int caretOffset) {
if (item == null) {
try {
//item == null means that the DocQuery is invoked
//based on the explicit documentation opening request
//(not ivoked by selecting a completion item in the list)
TplCompletionQuery.CompletionResult result = new TplCompletionQuery(doc).query();
if (result != null && result.getFunctions().size() > 0) {
item = result.getFunctions().iterator().next();
}
} catch (ParseException ex) {
Exceptions.printStackTrace(ex);
}
}
TplCompletionItem tplItem = (TplCompletionItem) item;
if (tplItem != null && tplItem.getHelp() != null) {
resultSet.setDocumentation(new DocItem(tplItem));
}
}
}
private static abstract class AbstractQuery extends AsyncCompletionQuery {
@Override
protected void preQueryUpdate(JTextComponent component) {
checkHideCompletion((BaseDocument) component.getDocument(), component.getCaretPosition());
}
@Override
protected void query(CompletionResultSet resultSet, Document doc, int caretOffset) {
try {
doQuery(resultSet, doc, caretOffset);
} finally {
resultSet.finish();
}
}
abstract void doQuery(CompletionResultSet resultSet, Document doc, int caretOffset);
}
private static void checkHideCompletion(final BaseDocument doc, final int caretOffset) {
//test whether we are just in text and eventually close the opened completion
//this is handy after end tag autocompletion when user doesn't complete the
//end tag and just types a text
//test whether the user typed an ending quotation in the attribute value
doc.render(new Runnable() {
@Override
public void run() {
TokenHierarchy tokenHierarchy = TokenHierarchy.get(doc);
TokenSequence tokenSequence = tokenHierarchy.tokenSequence();
tokenSequence.move(caretOffset == 0 ? 0 : caretOffset - 1);
if (!tokenSequence.moveNext()) {
return;
}
}
});
}
private static class DocItem implements CompletionDocumentation {
TplCompletionItem item;
public DocItem(TplCompletionItem tci) {
this.item = tci;
}
@Override
public String getText() {
return item.getHelp();
}
@Override
public URL getURL() {
return item.getHelpURL();
}
@Override
public CompletionDocumentation resolveLink(String link) {
return null;
}
@Override
public Action getGotoSourceAction() {
return null;
}
}
}
| 10,870 | 0.627563 | 0.624345 | 281 | 37.708183 | 30.085529 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.430605 | false | false |
12
|
c8e32980d65a81e158001709d7798a1d0a0e317a
| 6,158,983,115,794 |
e9b0b688976485d5ec106b9b2a7a6fad0c521342
|
/core/bootstrap/src/main/java/org/wildfly/swarm/bootstrap/modules/BootModuleLoader.java
|
d7b53e97d8a85c035813655e06effee9895c9227
|
[
"Apache-2.0"
] |
permissive
|
heiko-braun/wildfly-swarm-1
|
https://github.com/heiko-braun/wildfly-swarm-1
|
92a7987428ac3c53f3b3a2a26afd89a78f6e87c6
|
ac1ae8de5cffd9ea7ea5cb14fb97f2a089ed5d13
|
refs/heads/master
| 2021-01-21T02:56:40.818000 | 2017-08-23T17:34:05 | 2017-08-23T17:34:05 | 64,420,477 | 0 | 1 |
Apache-2.0
| true | 2018-04-03T17:04:10 | 2016-07-28T18:54:35 | 2016-07-28T18:54:37 | 2018-04-03T17:04:10 | 17,046 | 0 | 0 | 0 |
Java
| false | null |
/**
* Copyright 2015-2016 Red Hat, Inc, and individual contributors.
*
* 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.wildfly.swarm.bootstrap.modules;
import java.io.IOException;
import org.jboss.modules.ModuleFinder;
import org.jboss.modules.ModuleLoader;
/**
* @author Bob McWhirter
*/
public class BootModuleLoader extends ModuleLoader {
public BootModuleLoader() throws IOException {
super(new ModuleFinder[]{
new BootstrapClasspathModuleFinder(),
new BootstrapModuleFinder(),
new ClasspathModuleFinder(),
new ContainerModuleFinder(),
new ApplicationModuleFinder(),
new DynamicModuleFinder(),
});
}
}
|
UTF-8
|
Java
| 1,253 |
java
|
BootModuleLoader.java
|
Java
|
[
{
"context": "rt org.jboss.modules.ModuleLoader;\n\n/**\n * @author Bob McWhirter\n */\npublic class BootModuleLoader extends ModuleL",
"end": 810,
"score": 0.9995239973068237,
"start": 797,
"tag": "NAME",
"value": "Bob McWhirter"
}
] | null |
[] |
/**
* Copyright 2015-2016 Red Hat, Inc, and individual contributors.
*
* 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.wildfly.swarm.bootstrap.modules;
import java.io.IOException;
import org.jboss.modules.ModuleFinder;
import org.jboss.modules.ModuleLoader;
/**
* @author <NAME>
*/
public class BootModuleLoader extends ModuleLoader {
public BootModuleLoader() throws IOException {
super(new ModuleFinder[]{
new BootstrapClasspathModuleFinder(),
new BootstrapModuleFinder(),
new ClasspathModuleFinder(),
new ContainerModuleFinder(),
new ApplicationModuleFinder(),
new DynamicModuleFinder(),
});
}
}
| 1,246 | 0.694334 | 0.684757 | 38 | 31.973684 | 25.268543 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.473684 | false | false |
12
|
5c8d26d70db10fa417cfdd209e7ae726bfd6219d
| 27,539,330,313,003 |
8d449a00839eef5ebed1dd45f4547992b082af02
|
/app/src/main/java/com/yapsa/testapplication/ILog.java
|
314fce022e45412e3e9aacb270e63bae75a8022a
|
[] |
no_license
|
sakamotopaya/ParseAndroidQueryDeadlockSampleCode
|
https://github.com/sakamotopaya/ParseAndroidQueryDeadlockSampleCode
|
94c1d7e15b1253c1b6460f20c9ff0d37c93d11c8
|
58a328be32e3f995ed27d038b5ec458560ff2035
|
refs/heads/master
| 2021-01-19T19:33:23.088000 | 2014-11-18T13:52:23 | 2014-11-18T13:52:23 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.yapsa.testapplication;
public interface ILog {
void log(String text);
}
|
UTF-8
|
Java
| 89 |
java
|
ILog.java
|
Java
|
[] | null |
[] |
package com.yapsa.testapplication;
public interface ILog {
void log(String text);
}
| 89 | 0.741573 | 0.741573 | 5 | 16.799999 | 13.789851 | 34 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false |
12
|
a0c445764de875ad72cf8c363c1202dac776eeeb
| 1,039,382,102,969 |
4cbf1bb4c6c9180386c0c140130ee8847080215d
|
/app/src/main/java/com/dream/example/presenter/base/AppBaseActivityPresenter.java
|
b3ef4646089dbfc0d41379e6205b96bcac7b198a
|
[
"Apache-2.0"
] |
permissive
|
jay-y/yApp
|
https://github.com/jay-y/yApp
|
43a750ea56ba12a397aec474eede7d69c013fe8d
|
d6f99450c58d12483338636b1aaf1bfc565a9293
|
refs/heads/master
| 2022-02-28T19:26:28.646000 | 2017-09-02T03:39:19 | 2017-09-02T03:39:19 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.dream.example.presenter.base;
import android.content.Context;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.dream.example.App;
import com.dream.example.R;
import com.dream.example.data.support.DataSupports;
import com.dream.example.data.support.HttpFactory;
import com.dream.example.ui.activity.base.AppBaseAppCompatActivity;
import com.dream.example.ui.widget.LoadingDialog;
import com.dream.example.view.IAppBaseView;
import org.yapp.core.presenter.BaseActivityPresenter;
import org.yapp.core.ui.inject.annotation.ViewInject;
import org.yapp.utils.Callback;
import org.yapp.utils.Log;
/**
* Description: App Activity主持层抽象基类. <br>
* Date: 2016/3/17 10:32 <br>
* Author: ysj
*/
public abstract class AppBaseActivityPresenter extends BaseActivityPresenter<AppBaseAppCompatActivity, App> implements IAppBaseView {
@ViewInject(R.id.toolbar)
protected Toolbar mToolbar;
@ViewInject(R.id.toolbar_title)
protected TextView mTitle;
protected InputMethodManager mImm;
protected LoadingDialog mLoadingDialog;
protected MaterialDialog mMaterialDialog;
public Menu mMenu;
public ActionBarDrawerToggle mToggle;
public DataSupports getDataSupports() {
return HttpFactory.getMainDataSupports();
}
public boolean onCreateOptionsMenu(Menu menu) {
int menuId = getMenuRes();
if (menuId < 0) return true;
getContext().getMenuInflater().inflate(menuId, menu);
mMenu = menu;
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
if (null != this.mToggle && this.mToggle.onOptionsItemSelected(item)) {
return true;
} else {
if (android.R.id.home == item.getItemId()) {
getContext().onBackPressed();
}
return false;
}
}
/**
* set the id of menu
*
* @return if values is less then zero ,and the activity will not show menu
*/
public int getMenuRes() {
return -1;
}
/**
* 设置标题
*
* @param strId
*/
public void setTitle(int strId) {
String strTitle = getContext().getString(strId);
setTitle(strTitle, true, -1);
}
/**
* 设置标题
*
* @param strTitle
*/
public void setTitle(String strTitle) {
setTitle(strTitle, true, -1);
}
/**
* 设置标题
*
* @param resId
*/
public void setTitle(int strId, boolean isShowHome, int resId) {
String strTitle = getContext().getString(strId);
setTitle(strTitle, isShowHome, resId);
}
/**
* 设置标题
*
* @param strTitle
* @param isShowHome
*/
public void setTitle(String strTitle, boolean isShowHome, int resId) {
if (strTitle.length() > 10) strTitle = strTitle.substring(0, 10) + "...";
if (null != mTitle) {
mTitle.setText(strTitle); //设置自定义标题文字
getContext().getSupportActionBar().setDisplayShowTitleEnabled(false); //隐藏Toolbar标题
} else if (null != mToolbar) {
mToolbar.setTitle(strTitle);
}
getContext().getSupportActionBar().setDisplayShowHomeEnabled(isShowHome);
getContext().getSupportActionBar().setDisplayHomeAsUpEnabled(isShowHome);
if (resId != -1) {
getContext().getSupportActionBar().setHomeAsUpIndicator(resId);
}
}
/**
* 释放图片视图
*
* @param obj
*/
public void releaseImageView(ImageView obj) {
if (null != obj.getDrawable())
obj.getDrawable().setCallback(null);
obj.setImageDrawable(null);
obj.setBackgroundDrawable(null);
obj = null;
}
@Override
public void onBuild(Context context) {
super.onBuild(context);
initToolBar();
mImm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
}
@Override
public void onClear() {
Log.w("Do you need to release memory , Please override the onClear() method in " + this.getClass().getSimpleName() + ".");
}
@Override
public void onDestroy() {
onClear();
mToolbar = null;
mTitle = null;
mImm = null;
mLoadingDialog = null;
mMenu = null;
mToggle = null;
super.onDestroy();
}
/**
* 弹出Dialog
*
* @param msg
* @param title
* @param callback
*/
@Override
public void showDialog(String msg, String title, final Callback.DialogCallback callback) {
if (null == mMaterialDialog) {
mMaterialDialog = new MaterialDialog.Builder(getContext())
.cancelable(true)
.title(TextUtils.isEmpty(title) ? getContext().getString(R.string.app_name) : title)
.content(TextUtils.isEmpty(msg) ? "" : msg)
.positiveText(R.string.action_ok)
.negativeText(R.string.action_cancle)
.onPositive(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(MaterialDialog dialog, DialogAction which) {
if (null != callback) callback.onPositive();
}
})
.onNegative(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(MaterialDialog dialog, DialogAction which) {
if (null != callback) callback.onNegative();
}
})
.build();
} else {
mMaterialDialog.setTitle(TextUtils.isEmpty(title) ? getContext().getString(R.string.app_name) : title);
mMaterialDialog.setContent(TextUtils.isEmpty(msg) ? "" : msg);
mMaterialDialog.getBuilder().onPositive(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(MaterialDialog dialog, DialogAction which) {
if (null != callback) callback.onPositive();
}
});
mMaterialDialog.getBuilder().onNegative(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(MaterialDialog dialog, DialogAction which) {
if (null != callback) callback.onNegative();
}
});
}
mMaterialDialog.show();
}
public void showDialog(String msg, String title) {
showDialog(msg, title, null);
}
public void showDialog(String msg) {
showDialog(msg, null);
}
@Override
public void closeDialog() {
if (null != mMaterialDialog) {
mMaterialDialog.dismiss();
}
}
@Override
public void showLoading() {
if (null == mLoadingDialog) {
mLoadingDialog = new LoadingDialog(getContext());
}
mLoadingDialog.show();
}
@Override
public void closeLoading() {
if (null != mLoadingDialog && mLoadingDialog.isShowing()) {
mLoadingDialog.dismiss();
mLoadingDialog = null;
}
}
@Override
public boolean isLoading() {
if (null != mLoadingDialog) {
return mLoadingDialog.isShowing();
} else {
return false;
}
}
private void initToolBar() {
if (null == mToolbar) mToolbar = (Toolbar) getContext().findViewById(R.id.toolbar);
if (null == mTitle) mTitle = (TextView) getContext().findViewById(R.id.toolbar_title);
if (null != mToolbar) getContext().setSupportActionBar(mToolbar);
}
}
|
UTF-8
|
Java
| 8,165 |
java
|
AppBaseActivityPresenter.java
|
Java
|
[
{
"context": "象基类. <br>\n * Date: 2016/3/17 10:32 <br>\n * Author: ysj\n */\npublic abstract class AppBaseActivityPresente",
"end": 1063,
"score": 0.9996292591094971,
"start": 1060,
"tag": "USERNAME",
"value": "ysj"
}
] | null |
[] |
package com.dream.example.presenter.base;
import android.content.Context;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.dream.example.App;
import com.dream.example.R;
import com.dream.example.data.support.DataSupports;
import com.dream.example.data.support.HttpFactory;
import com.dream.example.ui.activity.base.AppBaseAppCompatActivity;
import com.dream.example.ui.widget.LoadingDialog;
import com.dream.example.view.IAppBaseView;
import org.yapp.core.presenter.BaseActivityPresenter;
import org.yapp.core.ui.inject.annotation.ViewInject;
import org.yapp.utils.Callback;
import org.yapp.utils.Log;
/**
* Description: App Activity主持层抽象基类. <br>
* Date: 2016/3/17 10:32 <br>
* Author: ysj
*/
public abstract class AppBaseActivityPresenter extends BaseActivityPresenter<AppBaseAppCompatActivity, App> implements IAppBaseView {
@ViewInject(R.id.toolbar)
protected Toolbar mToolbar;
@ViewInject(R.id.toolbar_title)
protected TextView mTitle;
protected InputMethodManager mImm;
protected LoadingDialog mLoadingDialog;
protected MaterialDialog mMaterialDialog;
public Menu mMenu;
public ActionBarDrawerToggle mToggle;
public DataSupports getDataSupports() {
return HttpFactory.getMainDataSupports();
}
public boolean onCreateOptionsMenu(Menu menu) {
int menuId = getMenuRes();
if (menuId < 0) return true;
getContext().getMenuInflater().inflate(menuId, menu);
mMenu = menu;
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
if (null != this.mToggle && this.mToggle.onOptionsItemSelected(item)) {
return true;
} else {
if (android.R.id.home == item.getItemId()) {
getContext().onBackPressed();
}
return false;
}
}
/**
* set the id of menu
*
* @return if values is less then zero ,and the activity will not show menu
*/
public int getMenuRes() {
return -1;
}
/**
* 设置标题
*
* @param strId
*/
public void setTitle(int strId) {
String strTitle = getContext().getString(strId);
setTitle(strTitle, true, -1);
}
/**
* 设置标题
*
* @param strTitle
*/
public void setTitle(String strTitle) {
setTitle(strTitle, true, -1);
}
/**
* 设置标题
*
* @param resId
*/
public void setTitle(int strId, boolean isShowHome, int resId) {
String strTitle = getContext().getString(strId);
setTitle(strTitle, isShowHome, resId);
}
/**
* 设置标题
*
* @param strTitle
* @param isShowHome
*/
public void setTitle(String strTitle, boolean isShowHome, int resId) {
if (strTitle.length() > 10) strTitle = strTitle.substring(0, 10) + "...";
if (null != mTitle) {
mTitle.setText(strTitle); //设置自定义标题文字
getContext().getSupportActionBar().setDisplayShowTitleEnabled(false); //隐藏Toolbar标题
} else if (null != mToolbar) {
mToolbar.setTitle(strTitle);
}
getContext().getSupportActionBar().setDisplayShowHomeEnabled(isShowHome);
getContext().getSupportActionBar().setDisplayHomeAsUpEnabled(isShowHome);
if (resId != -1) {
getContext().getSupportActionBar().setHomeAsUpIndicator(resId);
}
}
/**
* 释放图片视图
*
* @param obj
*/
public void releaseImageView(ImageView obj) {
if (null != obj.getDrawable())
obj.getDrawable().setCallback(null);
obj.setImageDrawable(null);
obj.setBackgroundDrawable(null);
obj = null;
}
@Override
public void onBuild(Context context) {
super.onBuild(context);
initToolBar();
mImm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
}
@Override
public void onClear() {
Log.w("Do you need to release memory , Please override the onClear() method in " + this.getClass().getSimpleName() + ".");
}
@Override
public void onDestroy() {
onClear();
mToolbar = null;
mTitle = null;
mImm = null;
mLoadingDialog = null;
mMenu = null;
mToggle = null;
super.onDestroy();
}
/**
* 弹出Dialog
*
* @param msg
* @param title
* @param callback
*/
@Override
public void showDialog(String msg, String title, final Callback.DialogCallback callback) {
if (null == mMaterialDialog) {
mMaterialDialog = new MaterialDialog.Builder(getContext())
.cancelable(true)
.title(TextUtils.isEmpty(title) ? getContext().getString(R.string.app_name) : title)
.content(TextUtils.isEmpty(msg) ? "" : msg)
.positiveText(R.string.action_ok)
.negativeText(R.string.action_cancle)
.onPositive(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(MaterialDialog dialog, DialogAction which) {
if (null != callback) callback.onPositive();
}
})
.onNegative(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(MaterialDialog dialog, DialogAction which) {
if (null != callback) callback.onNegative();
}
})
.build();
} else {
mMaterialDialog.setTitle(TextUtils.isEmpty(title) ? getContext().getString(R.string.app_name) : title);
mMaterialDialog.setContent(TextUtils.isEmpty(msg) ? "" : msg);
mMaterialDialog.getBuilder().onPositive(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(MaterialDialog dialog, DialogAction which) {
if (null != callback) callback.onPositive();
}
});
mMaterialDialog.getBuilder().onNegative(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(MaterialDialog dialog, DialogAction which) {
if (null != callback) callback.onNegative();
}
});
}
mMaterialDialog.show();
}
public void showDialog(String msg, String title) {
showDialog(msg, title, null);
}
public void showDialog(String msg) {
showDialog(msg, null);
}
@Override
public void closeDialog() {
if (null != mMaterialDialog) {
mMaterialDialog.dismiss();
}
}
@Override
public void showLoading() {
if (null == mLoadingDialog) {
mLoadingDialog = new LoadingDialog(getContext());
}
mLoadingDialog.show();
}
@Override
public void closeLoading() {
if (null != mLoadingDialog && mLoadingDialog.isShowing()) {
mLoadingDialog.dismiss();
mLoadingDialog = null;
}
}
@Override
public boolean isLoading() {
if (null != mLoadingDialog) {
return mLoadingDialog.isShowing();
} else {
return false;
}
}
private void initToolBar() {
if (null == mToolbar) mToolbar = (Toolbar) getContext().findViewById(R.id.toolbar);
if (null == mTitle) mTitle = (TextView) getContext().findViewById(R.id.toolbar_title);
if (null != mToolbar) getContext().setSupportActionBar(mToolbar);
}
}
| 8,165 | 0.600718 | 0.59787 | 258 | 30.306202 | 27.0557 | 133 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.445736 | false | false |
12
|
8526e2eba634c1e08aee35b646fef04c5ecf581e
| 8,194,797,617,414 |
caa6c93c041d200c5ca39cc4eef239639bf3aa36
|
/gmall-pms/src/test/java/com/atguigu/gmall/pms/GmallPmsApplicationTests.java
|
99b79acf0ab93fe346f541ea44b8786c1d308761
|
[] |
no_license
|
JiangKcoder/gmall-1111
|
https://github.com/JiangKcoder/gmall-1111
|
193897a3762b2d6e98edfba2fb66c093330919a6
|
82918f4b0e2a8f9368ea5af539dd4adfe89ce656
|
refs/heads/master
| 2022-07-17T19:26:23.610000 | 2020-02-24T12:38:11 | 2020-02-24T12:38:17 | 242,657,125 | 0 | 0 | null | false | 2022-06-21T02:51:20 | 2020-02-24T05:50:55 | 2020-02-24T12:39:09 | 2022-06-21T02:51:19 | 89 | 0 | 0 | 3 |
Java
| false | false |
package com.atguigu.gmall.pms;
import com.atguigu.gmall.pms.entity.Brand;
import com.atguigu.gmall.pms.entity.Product;
import com.atguigu.gmall.pms.service.BrandService;
import com.atguigu.gmall.pms.service.ProductService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class GmallPmsApplicationTests {
@Autowired
ProductService productService;
@Autowired
BrandService brandService;
@Test
public void contextLoads() {
// Product product = productService.getById(1);
// System.out.println(product.getName());
//测试增删改在主库,查在从库
Brand brand = new Brand();
brand.setName("哈哈哈");
brandService.save(brand);
}
}
|
UTF-8
|
Java
| 850 |
java
|
GmallPmsApplicationTests.java
|
Java
|
[] | null |
[] |
package com.atguigu.gmall.pms;
import com.atguigu.gmall.pms.entity.Brand;
import com.atguigu.gmall.pms.entity.Product;
import com.atguigu.gmall.pms.service.BrandService;
import com.atguigu.gmall.pms.service.ProductService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class GmallPmsApplicationTests {
@Autowired
ProductService productService;
@Autowired
BrandService brandService;
@Test
public void contextLoads() {
// Product product = productService.getById(1);
// System.out.println(product.getName());
//测试增删改在主库,查在从库
Brand brand = new Brand();
brand.setName("哈哈哈");
brandService.save(brand);
}
}
| 850 | 0.731051 | 0.729829 | 30 | 26.266666 | 19.887909 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
12
|
aa80b5733322aaa96c983c0ccb2c714903382060
| 5,360,119,202,670 |
0a83d61a9c1c957d78af0f3628e6f3cac51c900f
|
/BinarySearch/src/Main.java
|
cfd5fbea510fbd99ec6a3c0f95ed46d1fa373a0d
|
[] |
no_license
|
Andxtorres/estructura-de-datos-ago-dic-2019
|
https://github.com/Andxtorres/estructura-de-datos-ago-dic-2019
|
09d8ca84afee36d2fb090e5fffc55d9dd0be88ff
|
005eaf2bc53fa8602c8f088527e15752bf8b8365
|
refs/heads/master
| 2020-07-05T20:36:39.185000 | 2019-11-22T19:04:21 | 2019-11-22T19:04:21 | 202,766,839 | 5 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class Main {
public static void main(String args[]) {
ListaLigada<Integer> lista= new ListaLigada<>();
lista.insertarAlUltimo(20);
lista.insertarAlUltimo(25);
lista.insertarAlUltimo(30);
lista.insertarAlUltimo(35);
lista.imprimeLista();
System.out.println("El elemento 40 esta en la pos: "+lista.busquedaBinaria(40));
}
}
|
UTF-8
|
Java
| 346 |
java
|
Main.java
|
Java
|
[] | null |
[] |
public class Main {
public static void main(String args[]) {
ListaLigada<Integer> lista= new ListaLigada<>();
lista.insertarAlUltimo(20);
lista.insertarAlUltimo(25);
lista.insertarAlUltimo(30);
lista.insertarAlUltimo(35);
lista.imprimeLista();
System.out.println("El elemento 40 esta en la pos: "+lista.busquedaBinaria(40));
}
}
| 346 | 0.728324 | 0.693642 | 11 | 30.363636 | 21.368084 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.090909 | false | false |
12
|
154efda8c385b340e53fbd9530ae2ada4222a756
| 1,906,965,484,491 |
91729e5e90603599afa7b8bc9f3de6f68f2b0578
|
/src/main/java/ocp/concurrency/cyclicbarrier/CabService.java
|
8f690ecec9bfc4f1f5574f09816ec824a21e26d1
|
[] |
no_license
|
Kaisum/java-ocp-ex
|
https://github.com/Kaisum/java-ocp-ex
|
5bf0df203fcccc188d5fe626e7bf6faab7fe59f8
|
e952bf1210afd4280624b4f94de45f51b51e2db1
|
refs/heads/master
| 2020-04-19T03:22:26.900000 | 2019-02-14T15:12:17 | 2019-02-14T15:12:17 | 167,932,266 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ocp.concurrency.cyclicbarrier;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CabService implements Runnable{
CyclicBarrier cyclicBarrier;
public CabService(CyclicBarrier cyclicBarrier) {
this.cyclicBarrier = cyclicBarrier;
}
@Override
public void run() {
try{
System.out.println("+++++++++++" + Thread.currentThread().getName() + " had arrived");
System.out.println();
try{
cyclicBarrier.await();
}catch (BrokenBarrierException ex){
ex.printStackTrace();
}
System.out.println("*************" + Thread.currentThread().getName() + " is going to board the cab");
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
|
UTF-8
|
Java
| 867 |
java
|
CabService.java
|
Java
|
[] | null |
[] |
package ocp.concurrency.cyclicbarrier;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CabService implements Runnable{
CyclicBarrier cyclicBarrier;
public CabService(CyclicBarrier cyclicBarrier) {
this.cyclicBarrier = cyclicBarrier;
}
@Override
public void run() {
try{
System.out.println("+++++++++++" + Thread.currentThread().getName() + " had arrived");
System.out.println();
try{
cyclicBarrier.await();
}catch (BrokenBarrierException ex){
ex.printStackTrace();
}
System.out.println("*************" + Thread.currentThread().getName() + " is going to board the cab");
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
| 867 | 0.596309 | 0.596309 | 29 | 28.896551 | 27.443163 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.37931 | false | false |
12
|
2668c3b258406d052b52dcfda57dc7cf630a23a2
| 3,384,434,234,739 |
fa91450deb625cda070e82d5c31770be5ca1dec6
|
/Diff-Raw-Data/25/25_3a0509e7eb6c3f024433d098207281d3a0184de2/CaleydoProjectWizard/25_3a0509e7eb6c3f024433d098207281d3a0184de2_CaleydoProjectWizard_t.java
|
38b5ad576c8f4a4e4dd6d43e250848eb510b3d26
|
[] |
no_license
|
zhongxingyu/Seer
|
https://github.com/zhongxingyu/Seer
|
48e7e5197624d7afa94d23f849f8ea2075bcaec0
|
c11a3109fdfca9be337e509ecb2c085b60076213
|
refs/heads/master
| 2023-07-06T12:48:55.516000 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | false | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | 2023-06-21T00:53:27 | 2023-06-22T07:55:57 | 2,849,868 | 2 | 2 | 0 | null | false | false |
/*******************************************************************************
* Caleydo - Visualization for Molecular Biology - http://caleydo.org
* Copyright (c) The Caleydo Team. All rights reserved.
* Licensed under the new BSD license, available at http://caleydo.org/license
******************************************************************************/
package org.caleydo.core.internal.gui;
import java.util.Map;
import org.caleydo.core.internal.MyPreferences;
import org.caleydo.core.startup.IStartupAddon;
import org.caleydo.core.startup.IStartupProcedure;
import org.caleydo.core.util.collection.Pair;
import org.eclipse.jface.wizard.Wizard;
/**
* Wizard that appears after Caleydo startup.
*
* @author Marc Streit
* @author Werner Puff
* @author Alexander Lex
*/
public class CaleydoProjectWizard
extends Wizard {
private IStartupProcedure result;
private final Map<String, IStartupAddon> addons;
/**
* Constructor.
*/
public CaleydoProjectWizard(Map<String, IStartupAddon> addons) {
this.setWindowTitle("Caleydo - Choose Data Source");
this.addons = addons;
}
@Override
public void addPages() {
addPage(new ChooseProjectTypePage(addons));
}
private ChooseProjectTypePage getChosenProjectTypePage() {
return (ChooseProjectTypePage) getPage(ChooseProjectTypePage.PAGE_NAME);
}
@Override
public boolean canFinish() {
return (getChosenProjectTypePage().isPageComplete());
}
@Override
public boolean performFinish() {
ChooseProjectTypePage page = getChosenProjectTypePage();
Pair<String, IStartupAddon> addon = page.getSelectedAddon();
if (page.isPageComplete() && addon.getSecond().validate()) {
MyPreferences.setLastChosenProjectMode(addon.getFirst());
MyPreferences.flush();
setResult(addon.getSecond().create());
return true;
}
return false;
}
/**
* @param result
* setter, see {@link result}
*/
public void setResult(IStartupProcedure result) {
this.result = result;
}
/**
* @return the result, see {@link #result}
*/
public IStartupProcedure getResult() {
return result;
}
@Override
public boolean performCancel() {
return true;
}
}
|
UTF-8
|
Java
| 2,247 |
java
|
25_3a0509e7eb6c3f024433d098207281d3a0184de2_CaleydoProjectWizard_t.java
|
Java
|
[
{
"context": "hat appears after Caleydo startup.\n *\n * @author Marc Streit\n * @author Werner Puff\n * @author Alexander Lex",
"end": 757,
"score": 0.9998708963394165,
"start": 746,
"tag": "NAME",
"value": "Marc Streit"
},
{
"context": "o startup.\n *\n * @author Marc Streit\n * @author Werner Puff\n * @author Alexander Lex\n */\n public class Cale",
"end": 781,
"score": 0.9998795390129089,
"start": 770,
"tag": "NAME",
"value": "Werner Puff"
},
{
"context": "or Marc Streit\n * @author Werner Puff\n * @author Alexander Lex\n */\n public class CaleydoProjectWizard\n \textends",
"end": 807,
"score": 0.9998586773872375,
"start": 794,
"tag": "NAME",
"value": "Alexander Lex"
}
] | null |
[] |
/*******************************************************************************
* Caleydo - Visualization for Molecular Biology - http://caleydo.org
* Copyright (c) The Caleydo Team. All rights reserved.
* Licensed under the new BSD license, available at http://caleydo.org/license
******************************************************************************/
package org.caleydo.core.internal.gui;
import java.util.Map;
import org.caleydo.core.internal.MyPreferences;
import org.caleydo.core.startup.IStartupAddon;
import org.caleydo.core.startup.IStartupProcedure;
import org.caleydo.core.util.collection.Pair;
import org.eclipse.jface.wizard.Wizard;
/**
* Wizard that appears after Caleydo startup.
*
* @author <NAME>
* @author <NAME>
* @author <NAME>
*/
public class CaleydoProjectWizard
extends Wizard {
private IStartupProcedure result;
private final Map<String, IStartupAddon> addons;
/**
* Constructor.
*/
public CaleydoProjectWizard(Map<String, IStartupAddon> addons) {
this.setWindowTitle("Caleydo - Choose Data Source");
this.addons = addons;
}
@Override
public void addPages() {
addPage(new ChooseProjectTypePage(addons));
}
private ChooseProjectTypePage getChosenProjectTypePage() {
return (ChooseProjectTypePage) getPage(ChooseProjectTypePage.PAGE_NAME);
}
@Override
public boolean canFinish() {
return (getChosenProjectTypePage().isPageComplete());
}
@Override
public boolean performFinish() {
ChooseProjectTypePage page = getChosenProjectTypePage();
Pair<String, IStartupAddon> addon = page.getSelectedAddon();
if (page.isPageComplete() && addon.getSecond().validate()) {
MyPreferences.setLastChosenProjectMode(addon.getFirst());
MyPreferences.flush();
setResult(addon.getSecond().create());
return true;
}
return false;
}
/**
* @param result
* setter, see {@link result}
*/
public void setResult(IStartupProcedure result) {
this.result = result;
}
/**
* @return the result, see {@link #result}
*/
public IStartupProcedure getResult() {
return result;
}
@Override
public boolean performCancel() {
return true;
}
}
| 2,230 | 0.653761 | 0.653761 | 85 | 25.423529 | 23.96192 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.188235 | false | false |
12
|
de71a0d3f8cc1db15af9d569532781da2fc01390
| 6,906,307,420,634 |
df60589e74fa1e543c712fb1ee66d4ce06650030
|
/taghawkapp-master/app/src/main/java/com/taghawk/model/tag/MyTagResult.java
|
ebef0ab70691686a5139e973ced20c283fc35606
|
[] |
no_license
|
cckmit/taghawkapp-master
|
https://github.com/cckmit/taghawkapp-master
|
6ab4dbfb2b37d5c89c6fd27071a5a28f3a21421f
|
9f5569d18feea704908ced511209f023b0936de9
|
refs/heads/master
| 2023-01-05T01:33:13.992000 | 2020-08-25T06:29:22 | 2020-08-25T06:29:22 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.taghawk.model.tag;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.taghawk.model.pendingRequests.PendingRequest;
import java.util.ArrayList;
public class MyTagResult {
@SerializedName("data")
@Expose
private ArrayList<TagData> tagData = null;
public ArrayList<TagData> getTagData() {
return tagData;
}
public void setTagData(ArrayList<TagData> tagData) {
this.tagData = tagData;
}
}
|
UTF-8
|
Java
| 503 |
java
|
MyTagResult.java
|
Java
|
[] | null |
[] |
package com.taghawk.model.tag;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.taghawk.model.pendingRequests.PendingRequest;
import java.util.ArrayList;
public class MyTagResult {
@SerializedName("data")
@Expose
private ArrayList<TagData> tagData = null;
public ArrayList<TagData> getTagData() {
return tagData;
}
public void setTagData(ArrayList<TagData> tagData) {
this.tagData = tagData;
}
}
| 503 | 0.723658 | 0.723658 | 22 | 21.818182 | 20.012806 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.363636 | false | false |
12
|
08ac5c7417869e24f936d2b1f1386f9548661c61
| 24,799,141,172,014 |
fe69d1d24536bb2c29401476a703dab105f21556
|
/src/main/java/design/builder/MyStringBuilder.java
|
9bd3ddf411caa31f92168004c2972008d8667106
|
[
"Apache-2.0"
] |
permissive
|
mxuexxmy/CodingInterview
|
https://github.com/mxuexxmy/CodingInterview
|
59b7a09ed23ac17c7203ea8b166bd2aa8ae117c4
|
007884a15cbc6f68508fd5aa3034b05e6fa729c9
|
refs/heads/master
| 2020-04-22T04:58:37.215000 | 2019-02-10T12:13:09 | 2019-02-10T12:13:09 | 170,142,535 | 1 | 0 |
Apache-2.0
| true | 2019-02-11T14:27:57 | 2019-02-11T14:27:57 | 2019-02-11T14:27:53 | 2019-02-10T12:13:18 | 8,452 | 0 | 0 | 0 | null | false | null |
package design.builder;
/**
* @author: mayuan
* @desc:
* @date: 2018/07/14
*/
public class MyStringBuilder extends AbstractStringBuilder {
public MyStringBuilder() {
super(16);
}
@Override
public String toString() {
return new String(value, 0, count);
}
}
|
UTF-8
|
Java
| 298 |
java
|
MyStringBuilder.java
|
Java
|
[
{
"context": "package design.builder;\n\n/**\n * @author: mayuan\n * @desc:\n * @date: 2018/07/14\n */\npublic class M",
"end": 47,
"score": 0.8199190497398376,
"start": 41,
"tag": "NAME",
"value": "mayuan"
}
] | null |
[] |
package design.builder;
/**
* @author: mayuan
* @desc:
* @date: 2018/07/14
*/
public class MyStringBuilder extends AbstractStringBuilder {
public MyStringBuilder() {
super(16);
}
@Override
public String toString() {
return new String(value, 0, count);
}
}
| 298 | 0.61745 | 0.580537 | 17 | 16.529411 | 16.27021 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.294118 | false | false |
12
|
585274208d17361b14546b0c6e697fc3ba2aed70
| 25,228,637,903,043 |
65125873799e29045c8a9cf1840ef503deb2a5bd
|
/Ch12_Collections/AnsweredQueue.java
|
72750fb89c2e81e38a91114e6cc0311e804fc223
|
[] |
no_license
|
phm1234567/Java-Software-Solutions
|
https://github.com/phm1234567/Java-Software-Solutions
|
15a225287573d5c982756e835ea22ef818b3a7d4
|
b577ac2ff7643261348fd98080deb9b54e3d2958
|
refs/heads/master
| 2022-11-17T04:35:42.747000 | 2020-07-08T19:39:13 | 2020-07-08T19:39:13 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
//********************************************************************************
// AnsweredQueue.java Author: Hyunryung Kim
//
// Represents a queue that stores answered questions.
//********************************************************************************
import java.util.LinkedList;
public class AnsweredQueue extends Queue
{
private LinkedList<Question> answeredList = new LinkedList<Question>();
private int count; // Total number of questions for this queue
Question answeredQ;
//----------------------------------------------------------------------------
// Constructor: Initializes the counter.
//----------------------------------------------------------------------------
public AnsweredQueue ()
{
count = 0;
}
//----------------------------------------------------------------------------
// Puts a question in the rear of the queue.
//----------------------------------------------------------------------------
public void enqueue ()
{
count++;
answeredList.add(answeredQ);
int numQ = answeredQ.getQNum();
System.out.println("Question #"+ numQ + " is added to the answered queue.");
}
//----------------------------------------------------------------------------
// Puts a question in the rear of the queue.
//----------------------------------------------------------------------------
public void addAnsweredQ (Question Q)
{
answeredQ = Q;
enqueue();
}
//----------------------------------------------------------------------------
// Removes a question from the front of the queue.
//----------------------------------------------------------------------------
public void dequeue()
{
System.out.println("Question #"+ answeredList.get(0)
+ " is removed from the answered queue.");
answeredList.remove(0);
count--;
}
//----------------------------------------------------------------------------
// Returns the size of the queue
//----------------------------------------------------------------------------
public int getSize()
{
return answeredList.size();
}
//----------------------------------------------------------------------------
// Returns true if the queue is empty.
//----------------------------------------------------------------------------
public boolean empty()
{
return answeredList.isEmpty();
}
//----------------------------------------------------------------------------
// Returns a report describing the current queue.
//----------------------------------------------------------------------------
public String toString()
{
String report = "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
report += "Current Answered Queue Status\n\n";
//for (Question question : answeredList)
// report += question.toString() + " ";
for (int i = 0; i < answeredList.size();i++)
report += "Q." + (i+1) + " " + answeredList.get(i) + "\n";
return report;
}
}
|
UTF-8
|
Java
| 3,272 |
java
|
AnsweredQueue.java
|
Java
|
[
{
"context": "**************\n// AnsweredQueue.java Author: Hyunryung Kim\n//\n// Represents a queue that stores answered qu",
"end": 132,
"score": 0.999832808971405,
"start": 119,
"tag": "NAME",
"value": "Hyunryung Kim"
}
] | null |
[] |
//********************************************************************************
// AnsweredQueue.java Author: <NAME>
//
// Represents a queue that stores answered questions.
//********************************************************************************
import java.util.LinkedList;
public class AnsweredQueue extends Queue
{
private LinkedList<Question> answeredList = new LinkedList<Question>();
private int count; // Total number of questions for this queue
Question answeredQ;
//----------------------------------------------------------------------------
// Constructor: Initializes the counter.
//----------------------------------------------------------------------------
public AnsweredQueue ()
{
count = 0;
}
//----------------------------------------------------------------------------
// Puts a question in the rear of the queue.
//----------------------------------------------------------------------------
public void enqueue ()
{
count++;
answeredList.add(answeredQ);
int numQ = answeredQ.getQNum();
System.out.println("Question #"+ numQ + " is added to the answered queue.");
}
//----------------------------------------------------------------------------
// Puts a question in the rear of the queue.
//----------------------------------------------------------------------------
public void addAnsweredQ (Question Q)
{
answeredQ = Q;
enqueue();
}
//----------------------------------------------------------------------------
// Removes a question from the front of the queue.
//----------------------------------------------------------------------------
public void dequeue()
{
System.out.println("Question #"+ answeredList.get(0)
+ " is removed from the answered queue.");
answeredList.remove(0);
count--;
}
//----------------------------------------------------------------------------
// Returns the size of the queue
//----------------------------------------------------------------------------
public int getSize()
{
return answeredList.size();
}
//----------------------------------------------------------------------------
// Returns true if the queue is empty.
//----------------------------------------------------------------------------
public boolean empty()
{
return answeredList.isEmpty();
}
//----------------------------------------------------------------------------
// Returns a report describing the current queue.
//----------------------------------------------------------------------------
public String toString()
{
String report = "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
report += "Current Answered Queue Status\n\n";
//for (Question question : answeredList)
// report += question.toString() + " ";
for (int i = 0; i < answeredList.size();i++)
report += "Q." + (i+1) + " " + answeredList.get(i) + "\n";
return report;
}
}
| 3,265 | 0.323044 | 0.321516 | 88 | 36.18182 | 30.301344 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.261364 | false | false |
12
|
cffa94f8c6a6bdc97795c6f934f1af4972b3fc79
| 5,299,989,656,538 |
7cdeaa56350c014017d8e714afee6496b8102bd1
|
/src/Tests.java
|
96d02c3f10778c638bffcdb537f8a8083e60c62f
|
[] |
no_license
|
fransgustaf/number_check
|
https://github.com/fransgustaf/number_check
|
033020ddce99239cbd0988f32d03cebcbc254b26
|
40bce422422d44b080508779930bedc4bfb4ec62
|
refs/heads/master
| 2023-03-09T07:53:12.726000 | 2021-02-15T11:10:19 | 2021-02-15T11:10:19 | 339,042,346 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import static org.junit.Assert.*;
import java.util.List;
import org.junit.Test;
public class Tests {
@Test
public void verifyPersonNumber() {
List<String> list = List.of("850717-5019", "201701102384", "141206-2380", "20080903-2386", "7101169295", "198107249289", "19021214-9819", "190910199827", "191006089807", "192109099180", "4607137454", "194510168885", "900118+9811", "189102279800", "189912299816");
for(var number: list) {
InputNumber inputNumber = new InputNumber(number);
inputNumber.setup();
assertTrue(inputNumber.verifyInput());
}
}
@Test
public void verifyWrongPersonNumber() {
List<String> list = List.of("201701272394", "190302299813");
for(var number: list) {
InputNumber inputNumber = new InputNumber(number);
inputNumber.setup();
assertFalse(inputNumber.verifyInput());
}
}
@Test
public void verifySamordningNumber() {
List<String> list = List.of("190910799824");
for(var number: list) {
InputNumber inputNumber = new InputNumber(number);
inputNumber.setup();
assertTrue(inputNumber.verifyInput());
}
}
@Test
public void verifyOrganisationNumber() {
List<String> list = List.of("556614-3185", "16556601-6399", "262000-1111", "857202-7566");
for(var number: list) {
InputNumber inputNumber = new InputNumber(number);
inputNumber.setup();
assertTrue(inputNumber.verifyInput());
}
}
}
|
UTF-8
|
Java
| 1,605 |
java
|
Tests.java
|
Java
|
[] | null |
[] |
import static org.junit.Assert.*;
import java.util.List;
import org.junit.Test;
public class Tests {
@Test
public void verifyPersonNumber() {
List<String> list = List.of("850717-5019", "201701102384", "141206-2380", "20080903-2386", "7101169295", "198107249289", "19021214-9819", "190910199827", "191006089807", "192109099180", "4607137454", "194510168885", "900118+9811", "189102279800", "189912299816");
for(var number: list) {
InputNumber inputNumber = new InputNumber(number);
inputNumber.setup();
assertTrue(inputNumber.verifyInput());
}
}
@Test
public void verifyWrongPersonNumber() {
List<String> list = List.of("201701272394", "190302299813");
for(var number: list) {
InputNumber inputNumber = new InputNumber(number);
inputNumber.setup();
assertFalse(inputNumber.verifyInput());
}
}
@Test
public void verifySamordningNumber() {
List<String> list = List.of("190910799824");
for(var number: list) {
InputNumber inputNumber = new InputNumber(number);
inputNumber.setup();
assertTrue(inputNumber.verifyInput());
}
}
@Test
public void verifyOrganisationNumber() {
List<String> list = List.of("556614-3185", "16556601-6399", "262000-1111", "857202-7566");
for(var number: list) {
InputNumber inputNumber = new InputNumber(number);
inputNumber.setup();
assertTrue(inputNumber.verifyInput());
}
}
}
| 1,605 | 0.606854 | 0.452336 | 51 | 30.450981 | 41.252602 | 271 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.72549 | false | false |
12
|
8aee372299b96831eb53e15526a0925624a53884
| 22,926,535,438,026 |
960866ca11617a3240ae5d5064b41dfb977b3694
|
/java/com/haeyo/biz/board/BoardVO.java
|
0fee8f5bc58d088a75931eb968f1446440f92099
|
[] |
no_license
|
yein920/Final_project_haeyo
|
https://github.com/yein920/Final_project_haeyo
|
a89de529689057a4e7aeb6db9fcbfc77d0af34ea
|
e6dc8034c558942d59243fd9fd1699e94e399d00
|
refs/heads/main
| 2023-04-25T04:22:00.300000 | 2021-05-23T16:36:57 | 2021-05-23T16:36:57 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.haeyo.biz.board;
public interface BoardVO {
}
|
UTF-8
|
Java
| 65 |
java
|
BoardVO.java
|
Java
|
[] | null |
[] |
package com.haeyo.biz.board;
public interface BoardVO {
}
| 65 | 0.692308 | 0.692308 | 5 | 11 | 13.084342 | 28 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false |
12
|
5db04b8aac14fcbce08d2da41bf939e75da8f0ac
| 22,900,765,682,892 |
4f1bae3ed6f3bb73c51f93928c544ec2acbf588b
|
/rest-server-driver/src/test/java/com/github/restdriver/serverdriver/acceptance/HeadAcceptanceTest.java
|
dd031fea7b5e15419c91584fa9c291970bf3677a
|
[
"Apache-2.0"
] |
permissive
|
rest-driver/rest-driver
|
https://github.com/rest-driver/rest-driver
|
8c69c4e0c7459170c56e9e75348358b95874bf9d
|
fb189338aa9b34ae827147d7756674324e6f9477
|
refs/heads/master
| 2023-08-17T01:36:10.526000 | 2022-07-11T01:09:27 | 2022-07-11T01:09:27 | 1,644,585 | 100 | 47 |
NOASSERTION
| false | 2023-06-20T00:39:55 | 2011-04-21T08:57:51 | 2022-07-11T01:09:31 | 2023-06-20T00:39:55 | 1,474 | 167 | 58 | 37 |
Java
| false | false |
/**
* Copyright © 2010-2011 Nokia
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.restdriver.serverdriver.acceptance;
import static com.github.restdriver.serverdriver.Matchers.*;
import static com.github.restdriver.serverdriver.RestServerDriver.*;
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
import java.util.List;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import com.github.restdriver.clientdriver.ClientDriverRequest;
import com.github.restdriver.clientdriver.ClientDriverRequest.Method;
import com.github.restdriver.clientdriver.ClientDriverResponse;
import com.github.restdriver.clientdriver.ClientDriverRule;
import com.github.restdriver.serverdriver.http.Header;
import com.github.restdriver.serverdriver.http.response.Response;
public class HeadAcceptanceTest {
@Rule
public ClientDriverRule driver = new ClientDriverRule();
private String baseUrl;
@Before
public void getServerDetails() {
baseUrl = driver.getBaseUrl();
}
@Test
public void simpleHeadRetrievesStatus() {
driver.addExpectation(
new ClientDriverRequest("/").withMethod(Method.HEAD),
new ClientDriverResponse());
Response response = head(baseUrl);
assertThat(response, hasStatusCode(204));
}
@Test
public void headIgnoresEntity() {
driver.addExpectation(
new ClientDriverRequest("/").withMethod(Method.HEAD),
new ClientDriverResponse("some content", "text/plain"));
Response response = headOf(baseUrl);
assertThat(response.getContent(), nullValue());
}
@Test
public void getOnSameResourceAsHeadRequestRetrievesSameHeadersButWithAnEntity() {
driver.addExpectation(
new ClientDriverRequest("/").withMethod(Method.HEAD),
new ClientDriverResponse("Content", "text/plain"));
Response headResponse = doHeadOf(baseUrl);
assertThat(headResponse, hasStatusCode(200));
driver.addExpectation(
new ClientDriverRequest("/").withMethod(Method.GET),
new ClientDriverResponse("Content", "text/plain"));
Response getResponse = get(baseUrl);
assertThat(getResponse, hasStatusCode(200));
assertThat(getResponse.getContent(), not(nullValue()));
List<Header> getHeaders = getResponse.getHeaders();
List<Header> headHeaders = headResponse.getHeaders();
for (Header getHeader : getHeaders) {
assertThat("The GET request had a header that the HEAD headers did not.", headHeaders, hasItem(getHeader));
}
for (Header headHeader : headHeaders) {
assertThat("The HEAD request had a header that the GET headers did not.", getHeaders, hasItem(headHeader));
}
}
@Test
public void headRetrievesHeaders() {
driver.addExpectation(
new ClientDriverRequest("/").withMethod(Method.HEAD),
new ClientDriverResponse("", null).withStatus(409).withHeader("X-foo", "barrr"));
Response response = head(baseUrl);
assertThat(response, hasStatusCode(409));
assertThat(response, hasHeaderWithValue("X-foo", equalTo("barrr")));
}
@Test
public void headIncludesResponseTime() {
driver.addExpectation(
new ClientDriverRequest("/").withMethod(Method.HEAD),
new ClientDriverResponse());
Response response = head(baseUrl);
assertThat(response.getResponseTime(), greaterThanOrEqualTo(0L));
}
@Test
public void headSendsHeaders() {
driver.addExpectation(
new ClientDriverRequest("/")
.withMethod(Method.HEAD)
.withHeader("Accept", "Nothing"),
new ClientDriverResponse("Hello", "text/plain"));
Response response = head(baseUrl, header("Accept: Nothing"));
assertThat(response.getResponseTime(), greaterThanOrEqualTo(0L));
}
@Test
public void headDoesntFollowRedirects() {
driver.addExpectation(
new ClientDriverRequest("/").withMethod(Method.HEAD),
new ClientDriverResponse("", null)
.withStatus(303)
.withHeader("Location", "http://foobar"));
Response response = head(baseUrl);
assertThat(response, hasStatusCode(303));
assertThat(response, hasHeader("Location", "http://foobar"));
}
}
|
UTF-8
|
Java
| 5,296 |
java
|
HeadAcceptanceTest.java
|
Java
|
[] | null |
[] |
/**
* Copyright © 2010-2011 Nokia
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.restdriver.serverdriver.acceptance;
import static com.github.restdriver.serverdriver.Matchers.*;
import static com.github.restdriver.serverdriver.RestServerDriver.*;
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
import java.util.List;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import com.github.restdriver.clientdriver.ClientDriverRequest;
import com.github.restdriver.clientdriver.ClientDriverRequest.Method;
import com.github.restdriver.clientdriver.ClientDriverResponse;
import com.github.restdriver.clientdriver.ClientDriverRule;
import com.github.restdriver.serverdriver.http.Header;
import com.github.restdriver.serverdriver.http.response.Response;
public class HeadAcceptanceTest {
@Rule
public ClientDriverRule driver = new ClientDriverRule();
private String baseUrl;
@Before
public void getServerDetails() {
baseUrl = driver.getBaseUrl();
}
@Test
public void simpleHeadRetrievesStatus() {
driver.addExpectation(
new ClientDriverRequest("/").withMethod(Method.HEAD),
new ClientDriverResponse());
Response response = head(baseUrl);
assertThat(response, hasStatusCode(204));
}
@Test
public void headIgnoresEntity() {
driver.addExpectation(
new ClientDriverRequest("/").withMethod(Method.HEAD),
new ClientDriverResponse("some content", "text/plain"));
Response response = headOf(baseUrl);
assertThat(response.getContent(), nullValue());
}
@Test
public void getOnSameResourceAsHeadRequestRetrievesSameHeadersButWithAnEntity() {
driver.addExpectation(
new ClientDriverRequest("/").withMethod(Method.HEAD),
new ClientDriverResponse("Content", "text/plain"));
Response headResponse = doHeadOf(baseUrl);
assertThat(headResponse, hasStatusCode(200));
driver.addExpectation(
new ClientDriverRequest("/").withMethod(Method.GET),
new ClientDriverResponse("Content", "text/plain"));
Response getResponse = get(baseUrl);
assertThat(getResponse, hasStatusCode(200));
assertThat(getResponse.getContent(), not(nullValue()));
List<Header> getHeaders = getResponse.getHeaders();
List<Header> headHeaders = headResponse.getHeaders();
for (Header getHeader : getHeaders) {
assertThat("The GET request had a header that the HEAD headers did not.", headHeaders, hasItem(getHeader));
}
for (Header headHeader : headHeaders) {
assertThat("The HEAD request had a header that the GET headers did not.", getHeaders, hasItem(headHeader));
}
}
@Test
public void headRetrievesHeaders() {
driver.addExpectation(
new ClientDriverRequest("/").withMethod(Method.HEAD),
new ClientDriverResponse("", null).withStatus(409).withHeader("X-foo", "barrr"));
Response response = head(baseUrl);
assertThat(response, hasStatusCode(409));
assertThat(response, hasHeaderWithValue("X-foo", equalTo("barrr")));
}
@Test
public void headIncludesResponseTime() {
driver.addExpectation(
new ClientDriverRequest("/").withMethod(Method.HEAD),
new ClientDriverResponse());
Response response = head(baseUrl);
assertThat(response.getResponseTime(), greaterThanOrEqualTo(0L));
}
@Test
public void headSendsHeaders() {
driver.addExpectation(
new ClientDriverRequest("/")
.withMethod(Method.HEAD)
.withHeader("Accept", "Nothing"),
new ClientDriverResponse("Hello", "text/plain"));
Response response = head(baseUrl, header("Accept: Nothing"));
assertThat(response.getResponseTime(), greaterThanOrEqualTo(0L));
}
@Test
public void headDoesntFollowRedirects() {
driver.addExpectation(
new ClientDriverRequest("/").withMethod(Method.HEAD),
new ClientDriverResponse("", null)
.withStatus(303)
.withHeader("Location", "http://foobar"));
Response response = head(baseUrl);
assertThat(response, hasStatusCode(303));
assertThat(response, hasHeader("Location", "http://foobar"));
}
}
| 5,296 | 0.639093 | 0.632483 | 150 | 34.299999 | 27.49806 | 119 | false | false | 0 | 0 | 0 | 0 | 65 | 0.012276 | 0.593333 | false | false |
12
|
d49673b5f56396ef52268baf9a8ef4bf7a436426
| 19,181,323,948,798 |
d01f159330f219f7ce3cb3f79924052fbca4717b
|
/modules/web/src/eu/maryns/romeo/kinderkankerfonds/web/widgets/OpvangpresatiesPerJaarWidget.java
|
20e33842bc4115f596ac39d2d326528cf17e1d4e
|
[] |
no_license
|
romeomaryns/Kinderkankerfonds
|
https://github.com/romeomaryns/Kinderkankerfonds
|
4883fad3651ea8667893f6d4b9b8a32ec9cb3871
|
e3d6e25e1b11605b2ee2283c0136c51372cc0176
|
refs/heads/master
| 2021-06-12T03:50:32.664000 | 2021-03-04T18:38:08 | 2021-03-04T18:38:08 | 136,209,150 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package eu.maryns.romeo.kinderkankerfonds.web.widgets;
import com.haulmont.addon.dashboard.web.annotation.DashboardWidget;
import com.haulmont.cuba.gui.screen.ScreenFragment;
import com.haulmont.cuba.gui.screen.UiController;
import com.haulmont.cuba.gui.screen.UiDescriptor;
@UiController("kinderkankerfonds_OpvangpresatiesPerJaarWidget")
@UiDescriptor("opvangpresaties-per-jaar-widget.xml")
@DashboardWidget(name = "Opvangprestaties/Jaar")
public class OpvangpresatiesPerJaarWidget extends ScreenFragment {
}
|
UTF-8
|
Java
| 512 |
java
|
OpvangpresatiesPerJaarWidget.java
|
Java
|
[] | null |
[] |
package eu.maryns.romeo.kinderkankerfonds.web.widgets;
import com.haulmont.addon.dashboard.web.annotation.DashboardWidget;
import com.haulmont.cuba.gui.screen.ScreenFragment;
import com.haulmont.cuba.gui.screen.UiController;
import com.haulmont.cuba.gui.screen.UiDescriptor;
@UiController("kinderkankerfonds_OpvangpresatiesPerJaarWidget")
@UiDescriptor("opvangpresaties-per-jaar-widget.xml")
@DashboardWidget(name = "Opvangprestaties/Jaar")
public class OpvangpresatiesPerJaarWidget extends ScreenFragment {
}
| 512 | 0.845703 | 0.845703 | 13 | 38.46154 | 26.18166 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.384615 | false | false |
12
|
cf11c84e4ab3678975ee779c0f594cd188378292
| 1,408,749,339,612 |
ffcd04f49d6d27573dfb10437e186cceda7c9c85
|
/sanfang/PhotoNoter-master/app/src/main/java/com/yydcdut/note/model/camera/impl/CameraModelImpl.java
|
4d9b870d9ef37e81766431b9ebe76958e9fcd1b2
|
[
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] |
permissive
|
15121144267/helei
|
https://github.com/15121144267/helei
|
89db11d48c9f8f49fb03cc5633d02e986d198c8d
|
e32cc6e4a4fba4b78b3d2f8c4bbd83901c6e164b
|
refs/heads/master
| 2017-12-16T22:19:08.699000 | 2017-03-31T03:52:01 | 2017-03-31T03:52:01 | 77,442,402 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.yydcdut.note.model.camera.impl;
import android.content.Context;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import com.yydcdut.note.model.camera.ICameraFocus;
import com.yydcdut.note.model.camera.ICameraModel;
import com.yydcdut.note.model.camera.ICaptureModel;
import com.yydcdut.note.model.camera.IPreviewModel;
import com.yydcdut.note.utils.YLog;
import com.yydcdut.note.utils.camera.param.Size;
import com.yydcdut.note.widget.camera.AutoFitPreviewView;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
/**
* Created by yuyidong on 16/2/3.
*/
public class CameraModelImpl implements ICameraModel {
private static final String TAG = CameraModelImpl.class.getSimpleName();
private Camera mCamera;
private static final int STATE_CAMERA_CLOSE = 0;
private static final int STATE_CAMERA_OPEN = 1;
private static final int STATE_CAMERA_PREVIEW = 2;
private static final int STATE_CAMERA_CAPTURE = 3;
private int mCameraState = STATE_CAMERA_CLOSE;
private CameraSettingModel mCameraSettingModel;
private CameraFocusModel mCameraFocusModel;
private PreviewModel mPreviewModel;
private CaptureModel mCaptureModel;
private PicturesPreviewCallback mPicturesPreviewCallback;
@Singleton
@Inject
public CameraModelImpl() {
}
@Override
public void openCamera(String id, OnCameraOpenedCallback callback, int orientation, Size pictureSize) {
if (mCameraState != STATE_CAMERA_CLOSE) {
return;
}
if (callback == null) {
throw new IllegalArgumentException("");
}
if (mCameraState == STATE_CAMERA_CLOSE && mCamera == null) {
int cameraId = 0;
try {
cameraId = Integer.parseInt(id);
} catch (Exception e) {
//String转int失败,id不是数字
}
mCamera = Camera.open(cameraId);
mCamera.setDisplayOrientation(orientation);
mCameraState = STATE_CAMERA_OPEN;
mPreviewModel = new PreviewModel();
} else {
printLog("openCamera");
}
mCameraSettingModel = new CameraSettingModel(mCamera);
if (pictureSize == null) {
List<Size> list = mCameraSettingModel.getSupportPictureSizes();
Collections.sort(list, new Comparator<Size>() {
@Override
public int compare(Size lhs, Size rhs) {
return -(rhs.getWidth() * rhs.getHeight() - lhs.getWidth() * lhs.getHeight());
}
});
pictureSize = list.get(list.size() - 1);
}
mCameraSettingModel.setPictureSize(pictureSize.getWidth(), pictureSize.getHeight());
callback.onOpen(mPreviewModel, mCameraSettingModel);
}
public class PreviewModel implements IPreviewModel {
@Override
public void startPreview(AutoFitPreviewView.PreviewSurface previewSurface,
OnCameraPreviewCallback callback, Size previewSize) {
if (callback == null) {
throw new IllegalArgumentException("");
}
if (mCameraState == STATE_CAMERA_OPEN && mCamera != null) {
try {
mCameraSettingModel.setPreviewSize(previewSize.getWidth(), previewSize.getHeight());
if (previewSurface.getSurfaceHolder() != null) {
mCamera.setPreviewDisplay(previewSurface.getSurfaceHolder());
} else {
mCamera.setPreviewTexture(previewSurface.getSurfaceTexture());
}
} catch (IOException e) {
e.printStackTrace();
callback.onPreviewError();
return;
}
mCamera.startPreview();
mCaptureModel = new CaptureModel();
mCameraState = STATE_CAMERA_PREVIEW;
} else {
printLog("startPreview");
}
mCameraFocusModel = new CameraFocusModel(mCamera, previewSize.getWidth(), previewSize.getHeight());
callback.onPreview(mCaptureModel, mCameraFocusModel);
}
@Override
public void continuePreview() {
mCamera.startPreview();
mCameraState = STATE_CAMERA_PREVIEW;
}
@Override
public void stopPreview() {
if (mCameraState == STATE_CAMERA_PREVIEW && mCamera != null) {
mCamera.stopPreview();
mCameraState = STATE_CAMERA_OPEN;
mCameraFocusModel = null;
} else {
printLog("stopPreview");
}
}
@Override
public boolean isPreview() {
return mCameraState == STATE_CAMERA_PREVIEW;
}
}
public class CaptureModel implements ICaptureModel {
@Override
public long capture(PictureReturnCallback pictureReturnCallback) {
long time = 0l;
if (mCameraFocusModel != null && mCameraFocusModel.getFocusState() != ICameraFocus.FOCUS_STATE_FOCUSING
&& mCameraState == STATE_CAMERA_PREVIEW && pictureReturnCallback != null) {
time = System.currentTimeMillis();
try {
// mCamera.takePicture(sound ? new SoundCallBack() : null, null, new PictureCallBack(time, mCategoryId, ratio, isMirror));
mCamera.takePicture(null, null, new PictureCallBack(time, pictureReturnCallback));
mCameraState = STATE_CAMERA_CAPTURE;
} catch (Exception e) {
pictureReturnCallback.onPictureTaken(false, null, 0l);
}
} else {
YLog.i(TAG, "capture focusState--->" + mCameraFocusModel.getFocusState() + " CameraState--->" + mCameraState);
}
return time;
}
@Override
public void startStillCapture(StillPictureReturnCallback stillPictureReturnCallback) {
if (mCameraFocusModel != null && mCameraFocusModel.getFocusState() != ICameraFocus.FOCUS_STATE_FOCUSING
&& mCameraState == STATE_CAMERA_PREVIEW) {
if (mPicturesPreviewCallback == null) {
mPicturesPreviewCallback = new PicturesPreviewCallback(stillPictureReturnCallback);
} else {
if (mPicturesPreviewCallback.stillPictureReturnCallback != stillPictureReturnCallback) {
mPicturesPreviewCallback = null;
mPicturesPreviewCallback = new PicturesPreviewCallback(stillPictureReturnCallback);
}
}
mCamera.setPreviewCallback(mPicturesPreviewCallback);
} else {
YLog.i(TAG, "capture focusState--->" + mCameraFocusModel.getFocusState() + " CameraState--->" + mCameraState);
}
}
@Override
public void stopStillCapture() {
mCamera.setPreviewCallback(null);
mPicturesPreviewCallback = null;
}
}
private class PicturesPreviewCallback implements Camera.PreviewCallback {
private ICaptureModel.StillPictureReturnCallback stillPictureReturnCallback;
public PicturesPreviewCallback(ICaptureModel.StillPictureReturnCallback stillPictureReturnCallback) {
this.stillPictureReturnCallback = stillPictureReturnCallback;
}
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
if (stillPictureReturnCallback != null) {
stillPictureReturnCallback.onStillPictureTaken(ImageFormat.NV21, data, System.currentTimeMillis(),
mCameraSettingModel.getPreviewSize().getWidth(), mCameraSettingModel.getPreviewSize().getHeight());
}
}
}
@Override
public void closeCamera() {
if (mCameraState == STATE_CAMERA_OPEN && mCamera != null) {
mCamera.release();
mCamera = null;
mCameraSettingModel = null;
mCameraState = STATE_CAMERA_CLOSE;
} else {
printLog("closeCamera");
}
}
@Override
public boolean isOpen() {
return mCameraState == STATE_CAMERA_OPEN;
}
@Override
public int getCameraNumber(Context context) {
return Camera.getNumberOfCameras();
}
/**
* 创建jpeg图片回调数据对象
*/
private class PictureCallBack implements Camera.PictureCallback {
private long time;
private ICaptureModel.PictureReturnCallback pictureReturnCallback;
public PictureCallBack(long time, ICaptureModel.PictureReturnCallback pictureReturnCallback) {
this.time = time;
this.pictureReturnCallback = pictureReturnCallback;
}
@Override
public void onPictureTaken(byte[] data, Camera camera) {
if (pictureReturnCallback != null) {
pictureReturnCallback.onPictureTaken(true, data, time);
}
// //这里经常崩溃,做个延时处理
// new Handler().postDelayed(new Runnable() {
// @Override
// public void run() {
// reStartPreview();
// }
// }, 300);
}
}
private class SoundCallBack implements Camera.ShutterCallback {
@Override
public void onShutter() {
// try {
// AudioManager meng = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
// int volume = meng.getStreamVolume(AudioManager.STREAM_NOTIFICATION);
// if (volume != 0) {
// if (mShootSound == null) {
// mShootSound = MediaPlayer.create(mContext, Uri.parse("file:///system/media/audio/ui/camera_click.ogg"));
// }
// if (mShootSound != null) {
// mShootSound.start();
// }
// }
// } catch (Exception e) {
// e.getStackTrace();
// }
}
}
private void printLog(String method) {
StringBuilder sb = new StringBuilder(method + " ");
switch (mCameraState) {
case STATE_CAMERA_OPEN:
sb.append("STATE_CAMERA_OPEN");
break;
case STATE_CAMERA_PREVIEW:
sb.append("STATE_CAMERA_PREVIEW");
break;
case STATE_CAMERA_CLOSE:
sb.append("STATE_CAMERA_CLOSE");
break;
case STATE_CAMERA_CAPTURE:
sb.append("STATE_CAMERA_CAPTURE");
break;
}
YLog.i(TAG, "State--->" + sb.toString() + " Camera == null --->" + (mCamera == null));
}
}
|
UTF-8
|
Java
| 11,066 |
java
|
CameraModelImpl.java
|
Java
|
[
{
"context": "\nimport javax.inject.Singleton;\n\n/**\n * Created by yuyidong on 16/2/3.\n */\npublic class CameraModelImpl imple",
"end": 694,
"score": 0.9985371828079224,
"start": 686,
"tag": "USERNAME",
"value": "yuyidong"
}
] | null |
[] |
package com.yydcdut.note.model.camera.impl;
import android.content.Context;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import com.yydcdut.note.model.camera.ICameraFocus;
import com.yydcdut.note.model.camera.ICameraModel;
import com.yydcdut.note.model.camera.ICaptureModel;
import com.yydcdut.note.model.camera.IPreviewModel;
import com.yydcdut.note.utils.YLog;
import com.yydcdut.note.utils.camera.param.Size;
import com.yydcdut.note.widget.camera.AutoFitPreviewView;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
/**
* Created by yuyidong on 16/2/3.
*/
public class CameraModelImpl implements ICameraModel {
private static final String TAG = CameraModelImpl.class.getSimpleName();
private Camera mCamera;
private static final int STATE_CAMERA_CLOSE = 0;
private static final int STATE_CAMERA_OPEN = 1;
private static final int STATE_CAMERA_PREVIEW = 2;
private static final int STATE_CAMERA_CAPTURE = 3;
private int mCameraState = STATE_CAMERA_CLOSE;
private CameraSettingModel mCameraSettingModel;
private CameraFocusModel mCameraFocusModel;
private PreviewModel mPreviewModel;
private CaptureModel mCaptureModel;
private PicturesPreviewCallback mPicturesPreviewCallback;
@Singleton
@Inject
public CameraModelImpl() {
}
@Override
public void openCamera(String id, OnCameraOpenedCallback callback, int orientation, Size pictureSize) {
if (mCameraState != STATE_CAMERA_CLOSE) {
return;
}
if (callback == null) {
throw new IllegalArgumentException("");
}
if (mCameraState == STATE_CAMERA_CLOSE && mCamera == null) {
int cameraId = 0;
try {
cameraId = Integer.parseInt(id);
} catch (Exception e) {
//String转int失败,id不是数字
}
mCamera = Camera.open(cameraId);
mCamera.setDisplayOrientation(orientation);
mCameraState = STATE_CAMERA_OPEN;
mPreviewModel = new PreviewModel();
} else {
printLog("openCamera");
}
mCameraSettingModel = new CameraSettingModel(mCamera);
if (pictureSize == null) {
List<Size> list = mCameraSettingModel.getSupportPictureSizes();
Collections.sort(list, new Comparator<Size>() {
@Override
public int compare(Size lhs, Size rhs) {
return -(rhs.getWidth() * rhs.getHeight() - lhs.getWidth() * lhs.getHeight());
}
});
pictureSize = list.get(list.size() - 1);
}
mCameraSettingModel.setPictureSize(pictureSize.getWidth(), pictureSize.getHeight());
callback.onOpen(mPreviewModel, mCameraSettingModel);
}
public class PreviewModel implements IPreviewModel {
@Override
public void startPreview(AutoFitPreviewView.PreviewSurface previewSurface,
OnCameraPreviewCallback callback, Size previewSize) {
if (callback == null) {
throw new IllegalArgumentException("");
}
if (mCameraState == STATE_CAMERA_OPEN && mCamera != null) {
try {
mCameraSettingModel.setPreviewSize(previewSize.getWidth(), previewSize.getHeight());
if (previewSurface.getSurfaceHolder() != null) {
mCamera.setPreviewDisplay(previewSurface.getSurfaceHolder());
} else {
mCamera.setPreviewTexture(previewSurface.getSurfaceTexture());
}
} catch (IOException e) {
e.printStackTrace();
callback.onPreviewError();
return;
}
mCamera.startPreview();
mCaptureModel = new CaptureModel();
mCameraState = STATE_CAMERA_PREVIEW;
} else {
printLog("startPreview");
}
mCameraFocusModel = new CameraFocusModel(mCamera, previewSize.getWidth(), previewSize.getHeight());
callback.onPreview(mCaptureModel, mCameraFocusModel);
}
@Override
public void continuePreview() {
mCamera.startPreview();
mCameraState = STATE_CAMERA_PREVIEW;
}
@Override
public void stopPreview() {
if (mCameraState == STATE_CAMERA_PREVIEW && mCamera != null) {
mCamera.stopPreview();
mCameraState = STATE_CAMERA_OPEN;
mCameraFocusModel = null;
} else {
printLog("stopPreview");
}
}
@Override
public boolean isPreview() {
return mCameraState == STATE_CAMERA_PREVIEW;
}
}
public class CaptureModel implements ICaptureModel {
@Override
public long capture(PictureReturnCallback pictureReturnCallback) {
long time = 0l;
if (mCameraFocusModel != null && mCameraFocusModel.getFocusState() != ICameraFocus.FOCUS_STATE_FOCUSING
&& mCameraState == STATE_CAMERA_PREVIEW && pictureReturnCallback != null) {
time = System.currentTimeMillis();
try {
// mCamera.takePicture(sound ? new SoundCallBack() : null, null, new PictureCallBack(time, mCategoryId, ratio, isMirror));
mCamera.takePicture(null, null, new PictureCallBack(time, pictureReturnCallback));
mCameraState = STATE_CAMERA_CAPTURE;
} catch (Exception e) {
pictureReturnCallback.onPictureTaken(false, null, 0l);
}
} else {
YLog.i(TAG, "capture focusState--->" + mCameraFocusModel.getFocusState() + " CameraState--->" + mCameraState);
}
return time;
}
@Override
public void startStillCapture(StillPictureReturnCallback stillPictureReturnCallback) {
if (mCameraFocusModel != null && mCameraFocusModel.getFocusState() != ICameraFocus.FOCUS_STATE_FOCUSING
&& mCameraState == STATE_CAMERA_PREVIEW) {
if (mPicturesPreviewCallback == null) {
mPicturesPreviewCallback = new PicturesPreviewCallback(stillPictureReturnCallback);
} else {
if (mPicturesPreviewCallback.stillPictureReturnCallback != stillPictureReturnCallback) {
mPicturesPreviewCallback = null;
mPicturesPreviewCallback = new PicturesPreviewCallback(stillPictureReturnCallback);
}
}
mCamera.setPreviewCallback(mPicturesPreviewCallback);
} else {
YLog.i(TAG, "capture focusState--->" + mCameraFocusModel.getFocusState() + " CameraState--->" + mCameraState);
}
}
@Override
public void stopStillCapture() {
mCamera.setPreviewCallback(null);
mPicturesPreviewCallback = null;
}
}
private class PicturesPreviewCallback implements Camera.PreviewCallback {
private ICaptureModel.StillPictureReturnCallback stillPictureReturnCallback;
public PicturesPreviewCallback(ICaptureModel.StillPictureReturnCallback stillPictureReturnCallback) {
this.stillPictureReturnCallback = stillPictureReturnCallback;
}
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
if (stillPictureReturnCallback != null) {
stillPictureReturnCallback.onStillPictureTaken(ImageFormat.NV21, data, System.currentTimeMillis(),
mCameraSettingModel.getPreviewSize().getWidth(), mCameraSettingModel.getPreviewSize().getHeight());
}
}
}
@Override
public void closeCamera() {
if (mCameraState == STATE_CAMERA_OPEN && mCamera != null) {
mCamera.release();
mCamera = null;
mCameraSettingModel = null;
mCameraState = STATE_CAMERA_CLOSE;
} else {
printLog("closeCamera");
}
}
@Override
public boolean isOpen() {
return mCameraState == STATE_CAMERA_OPEN;
}
@Override
public int getCameraNumber(Context context) {
return Camera.getNumberOfCameras();
}
/**
* 创建jpeg图片回调数据对象
*/
private class PictureCallBack implements Camera.PictureCallback {
private long time;
private ICaptureModel.PictureReturnCallback pictureReturnCallback;
public PictureCallBack(long time, ICaptureModel.PictureReturnCallback pictureReturnCallback) {
this.time = time;
this.pictureReturnCallback = pictureReturnCallback;
}
@Override
public void onPictureTaken(byte[] data, Camera camera) {
if (pictureReturnCallback != null) {
pictureReturnCallback.onPictureTaken(true, data, time);
}
// //这里经常崩溃,做个延时处理
// new Handler().postDelayed(new Runnable() {
// @Override
// public void run() {
// reStartPreview();
// }
// }, 300);
}
}
private class SoundCallBack implements Camera.ShutterCallback {
@Override
public void onShutter() {
// try {
// AudioManager meng = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
// int volume = meng.getStreamVolume(AudioManager.STREAM_NOTIFICATION);
// if (volume != 0) {
// if (mShootSound == null) {
// mShootSound = MediaPlayer.create(mContext, Uri.parse("file:///system/media/audio/ui/camera_click.ogg"));
// }
// if (mShootSound != null) {
// mShootSound.start();
// }
// }
// } catch (Exception e) {
// e.getStackTrace();
// }
}
}
private void printLog(String method) {
StringBuilder sb = new StringBuilder(method + " ");
switch (mCameraState) {
case STATE_CAMERA_OPEN:
sb.append("STATE_CAMERA_OPEN");
break;
case STATE_CAMERA_PREVIEW:
sb.append("STATE_CAMERA_PREVIEW");
break;
case STATE_CAMERA_CLOSE:
sb.append("STATE_CAMERA_CLOSE");
break;
case STATE_CAMERA_CAPTURE:
sb.append("STATE_CAMERA_CAPTURE");
break;
}
YLog.i(TAG, "State--->" + sb.toString() + " Camera == null --->" + (mCamera == null));
}
}
| 11,066 | 0.585499 | 0.583863 | 294 | 36.435375 | 30.714855 | 133 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.510204 | false | false |
12
|
17d0fa22ebf1f6618c1904af380d5ad39922fee6
| 5,403,068,907,188 |
564ef6d113875293c4cab8c4625824da2d786e78
|
/src/main/java/com/kaitait/email/documentation/EmailControllerDocumentation.java
|
814bde37266fb36f57b4b5b3f008037c36e96cea
|
[] |
no_license
|
spik3r/email
|
https://github.com/spik3r/email
|
345368f7e57853cb72f8788ff771ae673ad3b273
|
3efe95ebbfd124a27421d67df04ead0d491c5a01
|
refs/heads/master
| 2020-06-07T00:31:25.128000 | 2019-06-23T15:36:50 | 2019-06-23T15:36:50 | 192,885,008 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.kaitait.email.documentation;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import javax.mail.MessagingException;
public interface EmailControllerDocumentation {
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Ok"),
@ApiResponse(code = 400, message = "Threw Exception as expected"),
})
@ApiOperation("Dummy endpoint for controller advice")
@GetMapping({"/{shouldExplode}", "/"})
ResponseEntity<String> index(@PathVariable(required = false) final String shouldExplode);
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Ok"),
@ApiResponse(code = 400, message = "Bad Request"),
})
@ApiOperation("Endpoint to test sending emails to a dummy user")
@PostMapping("/mail")
ResponseEntity<String> sendMail() throws MessagingException;
}
|
UTF-8
|
Java
| 1,167 |
java
|
EmailControllerDocumentation.java
|
Java
|
[] | null |
[] |
package com.kaitait.email.documentation;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import javax.mail.MessagingException;
public interface EmailControllerDocumentation {
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Ok"),
@ApiResponse(code = 400, message = "Threw Exception as expected"),
})
@ApiOperation("Dummy endpoint for controller advice")
@GetMapping({"/{shouldExplode}", "/"})
ResponseEntity<String> index(@PathVariable(required = false) final String shouldExplode);
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Ok"),
@ApiResponse(code = 400, message = "Bad Request"),
})
@ApiOperation("Endpoint to test sending emails to a dummy user")
@PostMapping("/mail")
ResponseEntity<String> sendMail() throws MessagingException;
}
| 1,167 | 0.730934 | 0.720651 | 30 | 37.933334 | 25.955004 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false |
12
|
5adf2aff13ee5a041d1de2a0f7f71dc08c2e847e
| 5,274,219,898,360 |
bee88e7305de366597cb7fb18deb17ca1841865c
|
/app-mc/src/main/java/com/lsxy/app/mc/MainClass.java
|
37b330cfc87e31ea3c0e0e0953c955fc93b6960d
|
[] |
no_license
|
bellmit/lsxy-yunhuni-peer-internet
|
https://github.com/bellmit/lsxy-yunhuni-peer-internet
|
70a92f366be4a40ad07a1211c44f446cfe0c3959
|
b24380f581545c1838f222d7ab13a50aa9a89e13
|
refs/heads/master
| 2022-03-23T22:57:02.960000 | 2018-01-07T12:40:28 | 2018-01-07T12:40:28 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.lsxy.app.mc;
import com.lsxy.framework.FrameworkServiceConfig;
import com.lsxy.framework.api.FrameworkApiConfig;
import com.lsxy.framework.cache.FrameworkCacheConfig;
import com.lsxy.framework.monitor.FrameworkMonitorConfig;
import com.lsxy.framework.web.web.AbstractSpringBootWebStarter;
import com.lsxy.yunhuni.YunhuniServiceConfig;
import com.lsxy.yunhuni.api.YunhuniApiConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration;
import org.springframework.context.annotation.Import;
/**
* Created by tandy on 16/11/19.
*/
@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
@Import({FrameworkApiConfig.class,FrameworkServiceConfig.class,YunhuniApiConfig.class, YunhuniServiceConfig.class, FrameworkCacheConfig.class,
FrameworkMonitorConfig.class})
public class MainClass extends AbstractSpringBootWebStarter {
@Override
public String systemId() {
return systemId;
}
public static final String systemId = "app.mc";
static {
System.setProperty("systemId",systemId);
}
public static void main(String[] args) {
SpringApplication.run(MainClass.class, args);
}
}
|
UTF-8
|
Java
| 1,307 |
java
|
MainClass.java
|
Java
|
[
{
"context": "work.context.annotation.Import;\n\n/**\n * Created by tandy on 16/11/19.\n */\n@SpringBootApplication(exclude =",
"end": 674,
"score": 0.9995425343513489,
"start": 669,
"tag": "USERNAME",
"value": "tandy"
}
] | null |
[] |
package com.lsxy.app.mc;
import com.lsxy.framework.FrameworkServiceConfig;
import com.lsxy.framework.api.FrameworkApiConfig;
import com.lsxy.framework.cache.FrameworkCacheConfig;
import com.lsxy.framework.monitor.FrameworkMonitorConfig;
import com.lsxy.framework.web.web.AbstractSpringBootWebStarter;
import com.lsxy.yunhuni.YunhuniServiceConfig;
import com.lsxy.yunhuni.api.YunhuniApiConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration;
import org.springframework.context.annotation.Import;
/**
* Created by tandy on 16/11/19.
*/
@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
@Import({FrameworkApiConfig.class,FrameworkServiceConfig.class,YunhuniApiConfig.class, YunhuniServiceConfig.class, FrameworkCacheConfig.class,
FrameworkMonitorConfig.class})
public class MainClass extends AbstractSpringBootWebStarter {
@Override
public String systemId() {
return systemId;
}
public static final String systemId = "app.mc";
static {
System.setProperty("systemId",systemId);
}
public static void main(String[] args) {
SpringApplication.run(MainClass.class, args);
}
}
| 1,307 | 0.79648 | 0.79189 | 35 | 36.342857 | 30.157627 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.657143 | false | false |
12
|
14d125ac5ae103d294ba456699bb05a575113c41
| 27,187,143,036,670 |
57129c986f497a92636a867a87413d874b70093b
|
/app/src/main/java/com/example/ocs/Activity/ShowDetailActivity.java
|
48d8ab47674c2852ce26fa7d87d7411a31dfaa8c
|
[] |
no_license
|
Khenteb/OCS
|
https://github.com/Khenteb/OCS
|
716db385a9a2700c520f43e3394be4898f8f3b21
|
eee8921ed0994be698c22fcbd7c907d39b43c97a
|
refs/heads/master
| 2023-09-05T05:10:35.797000 | 2021-11-16T15:42:54 | 2021-11-16T15:42:54 | 428,519,785 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.ocs.Activity;
public class ShowDetailActivity {
}
|
UTF-8
|
Java
| 71 |
java
|
ShowDetailActivity.java
|
Java
|
[] | null |
[] |
package com.example.ocs.Activity;
public class ShowDetailActivity {
}
| 71 | 0.802817 | 0.802817 | 5 | 13.4 | 16.007498 | 33 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false |
12
|
668ebe3f6f43c5035a5862ef973a010317003201
| 11,828,340,001,618 |
d7e71e03eb4b1263d650da87ad80060dc2c75dcf
|
/src/test/java/com/projectdeveloper/app/ws/service/impl/UserServiceImplTest.java
|
039abbd2cfe42fbccc0e1bd81a9cd94e30dc0763
|
[] |
no_license
|
hugoooo/SpringAPI
|
https://github.com/hugoooo/SpringAPI
|
95f6bd0132be36ad2b5c1d5dd306405dc5dbbc4c
|
cb55af6ed273014c0a60579816025a7fb3ec5e74
|
refs/heads/master
| 2018-10-23T17:09:14.247000 | 2018-09-03T17:15:56 | 2018-09-03T17:15:56 | 144,354,477 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.projectdeveloper.app.ws.service.impl;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.modelmapper.ModelMapper;
import org.modelmapper.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import com.projectdeveloper.app.ws.io.entity.AddressEntity;
import com.projectdeveloper.app.ws.io.entity.UserEntity;
import com.projectdeveloper.app.ws.io.repositories.UserRepository;
import com.projectdeveloper.app.ws.shared.Utils;
import com.projectdeveloper.app.ws.shared.dto.AddressDto;
import com.projectdeveloper.app.ws.shared.dto.UserDto;
//I make at hand this import
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
class UserServiceImplTest {
@InjectMocks
UserServiceImpl useService;
@Mock
UserRepository userRepository;
@Mock
Utils utils;
@Mock
BCryptPasswordEncoder bcryptPasswordEncoder;
String userId = "aasodiasjdi";
String encryptedPassword = "12345678";
UserEntity userEntity = new UserEntity();
@BeforeEach
void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
userEntity.setId(1L);
userEntity.setFirstName("first");
userEntity.setLastName("last");
userEntity.setUserId("dasqw23s");
userEntity.setEncryptedPassword("12345678");
userEntity.setEmail("test@gmail.com");
userEntity.setEmailVerificationToken("s3d1a12s2s");
}
@Test
void testGetUser() {
when( userRepository.findByemail( anyString() ) ).thenReturn(userEntity);
UserDto userDto = useService.getUser("test@gmail.com");
assertNotNull(userDto);
assertEquals("first", userDto.getFirstName());
}
@Test
final void testGetUser_UsernameNotFoundException() {
when( userRepository.findByemail( anyString() ) ).thenReturn(null);
assertThrows(UsernameNotFoundException.class,
()-> {
useService.getUser("test@gmail.com");
}
);
}
@Test
final void testCreateUser() {
when(userRepository.findByemail(anyString())).thenReturn(null);
when(utils.generateAndressId(anyInt())).thenReturn(null);
when(utils.generateUserId(anyInt())).thenReturn(userId);
when(bcryptPasswordEncoder.encode(anyString())).thenReturn(encryptedPassword);
when(userRepository.save(any(UserEntity.class))).thenReturn(userEntity);
AddressDto addressDto = new AddressDto();
addressDto.setType("shipping");
List<AddressDto> addresses = new ArrayList<>();
addresses.add(addressDto);
UserDto userDto = new UserDto();
userDto.setAddresses(getAdressesDto());
userDto.setFirstName("first");
userDto.setLastName("last");
userDto.setEncryptedPassword("12345678");
userDto.setEmail("test@gmail.com");
UserDto storedUserDetails = useService.createUser(userDto);
assertNotNull(storedUserDetails);
assertEquals(userEntity.getFirstName(), storedUserDetails.getFirstName());
assertEquals(userEntity.getLastName(), storedUserDetails.getLastName());
assertNotNull(storedUserDetails.getUserId());
verify(utils,times(2)).generateAndressId(30);
verify(userRepository, times(1)).save(any(UserEntity.class));
}
private List<AddressDto> getAdressesDto() {
AddressDto addressshipping = new AddressDto();
addressshipping.setType("shipping");
addressshipping.setCity("Vancouver");
addressshipping.setCountry("Canada");
addressshipping.setPostalCode("4ML 7VL");
addressshipping.setStreetName("123 Street fourth");
AddressDto addressBilling = new AddressDto();
addressBilling.setType("billing");
addressBilling.setCity("Vancouver");
addressBilling.setCountry("Canada");
addressBilling.setPostalCode("4ML 7VL");
addressBilling.setStreetName("123 Street fourth");
List<AddressDto> addresssDto = new ArrayList<>();
addresssDto.add(addressshipping);
addresssDto.add(addressBilling);
return addresssDto;
}
private List<AddressEntity> getAddressesEntity(){
List<AddressDto> addresssDto = getAdressesDto();
Type listType = new TypeToken<List<AddressEntity>> () {}.getType();
return new ModelMapper().map(addresssDto,listType);
}
}
|
UTF-8
|
Java
| 4,604 |
java
|
UserServiceImplTest.java
|
Java
|
[
{
"context": "der bcryptPasswordEncoder;\n\t\n\t\n\tString userId = \"aasodiasjdi\";\n\tString encryptedPassword = \"12345678\";\n\tUse",
"end": 1413,
"score": 0.5848950743675232,
"start": 1406,
"tag": "USERNAME",
"value": "asodias"
},
{
"context": "rId = \"aasodiasjdi\";\n\tString encryptedPassword = \"12345678\";\n\tUserEntity userEntity = new UserEntity();\n\t\n\n\t",
"end": 1456,
"score": 0.9993973970413208,
"start": 1448,
"tag": "PASSWORD",
"value": "12345678"
},
{
"context": "d(\"dasqw23s\");\n\t\tuserEntity.setEncryptedPassword(\"12345678\");\n\t\tuserEntity.setEmail(\"test@gmail.com\");\n\t\tuse",
"end": 1765,
"score": 0.9993852972984314,
"start": 1757,
"tag": "PASSWORD",
"value": "12345678"
},
{
"context": "yptedPassword(\"12345678\");\n\t\tuserEntity.setEmail(\"test@gmail.com\");\n\t\tuserEntity.setEmailVerificationToken(\"s3d1a1",
"end": 1806,
"score": 0.9999246597290039,
"start": 1792,
"tag": "EMAIL",
"value": "test@gmail.com"
},
{
"context": "il.com\");\n\t\tuserEntity.setEmailVerificationToken(\"s3d1a12s2s\");\n\t\t\n\t}\n\t\n\n\n\t@Test\n\tvoid testGetUser() {\n\t\t\n\t\n\t\t",
"end": 1860,
"score": 0.9992538690567017,
"start": 1850,
"tag": "PASSWORD",
"value": "s3d1a12s2s"
},
{
"context": "tity);\n\t\t\n\t\tUserDto userDto = useService.getUser(\"test@gmail.com\");\n\t\tassertNotNull(userDto);\n\t\tassertEquals(\"firs",
"end": 2041,
"score": 0.9999251365661621,
"start": 2027,
"tag": "EMAIL",
"value": "test@gmail.com"
},
{
"context": "n.class,\n\t\t\t\t\n\t\t\t\t()-> {\n\t\t\t\t\tuseService.getUser(\"test@gmail.com\");\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t);\n\t\t\n\t}\n\t\n\t@Test\n\tfinal v",
"end": 2368,
"score": 0.9999250173568726,
"start": 2354,
"tag": "EMAIL",
"value": "test@gmail.com"
},
{
"context": "esses(getAdressesDto());\t\n\t\tuserDto.setFirstName(\"first\");\n\t\tuserDto.setLastName(\"last\");\n\t\tuserDto.setEn",
"end": 3062,
"score": 0.8487930297851562,
"start": 3057,
"tag": "NAME",
"value": "first"
},
{
"context": "Dto.setFirstName(\"first\");\n\t\tuserDto.setLastName(\"last\");\n\t\tuserDto.setEncryptedPassword(\"12345678\");\n\t\t",
"end": 3093,
"score": 0.9088162183761597,
"start": 3089,
"tag": "NAME",
"value": "last"
},
{
"context": "LastName(\"last\");\n\t\tuserDto.setEncryptedPassword(\"12345678\");\n\t\tuserDto.setEmail(\"test@gmail.com\");\n\t\t\n\t\tUse",
"end": 3137,
"score": 0.9994560480117798,
"start": 3129,
"tag": "PASSWORD",
"value": "12345678"
},
{
"context": "ncryptedPassword(\"12345678\");\n\t\tuserDto.setEmail(\"test@gmail.com\");\n\t\t\n\t\tUserDto storedUserDetails = useService.cr",
"end": 3175,
"score": 0.9999256134033203,
"start": 3161,
"tag": "EMAIL",
"value": "test@gmail.com"
}
] | null |
[] |
package com.projectdeveloper.app.ws.service.impl;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.modelmapper.ModelMapper;
import org.modelmapper.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import com.projectdeveloper.app.ws.io.entity.AddressEntity;
import com.projectdeveloper.app.ws.io.entity.UserEntity;
import com.projectdeveloper.app.ws.io.repositories.UserRepository;
import com.projectdeveloper.app.ws.shared.Utils;
import com.projectdeveloper.app.ws.shared.dto.AddressDto;
import com.projectdeveloper.app.ws.shared.dto.UserDto;
//I make at hand this import
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
class UserServiceImplTest {
@InjectMocks
UserServiceImpl useService;
@Mock
UserRepository userRepository;
@Mock
Utils utils;
@Mock
BCryptPasswordEncoder bcryptPasswordEncoder;
String userId = "aasodiasjdi";
String encryptedPassword = "<PASSWORD>";
UserEntity userEntity = new UserEntity();
@BeforeEach
void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
userEntity.setId(1L);
userEntity.setFirstName("first");
userEntity.setLastName("last");
userEntity.setUserId("dasqw23s");
userEntity.setEncryptedPassword("<PASSWORD>");
userEntity.setEmail("<EMAIL>");
userEntity.setEmailVerificationToken("<PASSWORD>");
}
@Test
void testGetUser() {
when( userRepository.findByemail( anyString() ) ).thenReturn(userEntity);
UserDto userDto = useService.getUser("<EMAIL>");
assertNotNull(userDto);
assertEquals("first", userDto.getFirstName());
}
@Test
final void testGetUser_UsernameNotFoundException() {
when( userRepository.findByemail( anyString() ) ).thenReturn(null);
assertThrows(UsernameNotFoundException.class,
()-> {
useService.getUser("<EMAIL>");
}
);
}
@Test
final void testCreateUser() {
when(userRepository.findByemail(anyString())).thenReturn(null);
when(utils.generateAndressId(anyInt())).thenReturn(null);
when(utils.generateUserId(anyInt())).thenReturn(userId);
when(bcryptPasswordEncoder.encode(anyString())).thenReturn(encryptedPassword);
when(userRepository.save(any(UserEntity.class))).thenReturn(userEntity);
AddressDto addressDto = new AddressDto();
addressDto.setType("shipping");
List<AddressDto> addresses = new ArrayList<>();
addresses.add(addressDto);
UserDto userDto = new UserDto();
userDto.setAddresses(getAdressesDto());
userDto.setFirstName("first");
userDto.setLastName("last");
userDto.setEncryptedPassword("<PASSWORD>");
userDto.setEmail("<EMAIL>");
UserDto storedUserDetails = useService.createUser(userDto);
assertNotNull(storedUserDetails);
assertEquals(userEntity.getFirstName(), storedUserDetails.getFirstName());
assertEquals(userEntity.getLastName(), storedUserDetails.getLastName());
assertNotNull(storedUserDetails.getUserId());
verify(utils,times(2)).generateAndressId(30);
verify(userRepository, times(1)).save(any(UserEntity.class));
}
private List<AddressDto> getAdressesDto() {
AddressDto addressshipping = new AddressDto();
addressshipping.setType("shipping");
addressshipping.setCity("Vancouver");
addressshipping.setCountry("Canada");
addressshipping.setPostalCode("4ML 7VL");
addressshipping.setStreetName("123 Street fourth");
AddressDto addressBilling = new AddressDto();
addressBilling.setType("billing");
addressBilling.setCity("Vancouver");
addressBilling.setCountry("Canada");
addressBilling.setPostalCode("4ML 7VL");
addressBilling.setStreetName("123 Street fourth");
List<AddressDto> addresssDto = new ArrayList<>();
addresssDto.add(addressshipping);
addresssDto.add(addressBilling);
return addresssDto;
}
private List<AddressEntity> getAddressesEntity(){
List<AddressDto> addresssDto = getAdressesDto();
Type listType = new TypeToken<List<AddressEntity>> () {}.getType();
return new ModelMapper().map(addresssDto,listType);
}
}
| 4,582 | 0.757385 | 0.747394 | 169 | 26.242603 | 23.567486 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.928994 | false | false |
12
|
661e15944669039c43e0be2ae31cf83253e1efe8
| 12,730,283,104,150 |
7202f4694f090275a07a9dc0e5dc863e930d793f
|
/sale-service/src/main/java/com/saleservice/domain/services/SaleService.java
|
f0423b03150dfaf4321393e38683ca1cedfb2bde
|
[] |
no_license
|
Ruan-fe/Empire-Microservices
|
https://github.com/Ruan-fe/Empire-Microservices
|
0d80540f99c15124b881124172ada6b27a5ff197
|
20eefc0793b27f53a94499370a9e2217105d2f8d
|
refs/heads/master
| 2023-04-06T20:36:49.254000 | 2021-04-02T22:19:09 | 2021-04-02T22:19:09 | 338,922,408 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.saleservice.domain.services;
import com.saleservice.configurations.exceptions.ProductException;
import com.saleservice.configurations.exceptions.ResourceNotFoundException;
import com.saleservice.configurations.exceptions.SaleException;
import com.saleservice.domain.entities.Product;
import com.saleservice.domain.entities.Sale;
import com.saleservice.domain.entities.User;
import com.saleservice.domain.feignclients.UserFeignClient;
import com.saleservice.domain.repositories.ProductRepository;
import com.saleservice.domain.repositories.SaleItemRepository;
import com.saleservice.domain.repositories.SaleRepository;
import com.saleservice.rest.models.requests.ProductSaleRequest;
import com.saleservice.rest.models.requests.SaleItemRequest;
import com.saleservice.rest.models.requests.SaleRequest;
import com.saleservice.rest.models.responses.SaleResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.List;
@Service
public class SaleService {
@Autowired
private SaleRepository saleRepository;
@Autowired
private ProductRepository productRepository;
@Autowired
private SaleItemRepository saleItemRepository;
@Autowired
private UserFeignClient userFeignClient;
@Transactional
public SaleResponse makeSale(List<ProductSaleRequest> productSaleRequest, String bearerToken) {
Long userId = searchAuthenticatedUser(bearerToken);
Double totalValue = calculateTotalValueAndVerifyIfHaveInStock(productSaleRequest);
Long saleId = insertInSale(totalValue, userId);
insertInSaleItemAndReduceStock(saleId, productSaleRequest);
SaleResponse saleResponse = SaleResponse.builder().total(totalValue).build();
return saleResponse;
}
private Long searchAuthenticatedUser(String bearerToken) {
Long userId = null;
try {
User user = userFeignClient.getAuthenticated(bearerToken);
userId = user.getId();
}
catch (Exception e){
throw new SaleException(e.getMessage());
}
return userId;
}
private Double calculateTotalValueAndVerifyIfHaveInStock(List<ProductSaleRequest> productSaleRequest) {
Double totalValue = 0.0;
for(ProductSaleRequest productSale: productSaleRequest){
Long productId = productSale.getProductId();
Long quantityProduct = productSale.getQuantityProduct();
Product product = productRepository.findById(productId).orElseThrow(()-> new ResourceNotFoundException("Product not found!"));
verifyIfHaveInStock(product, quantityProduct);
totalValue += product.getValue() * quantityProduct;
}
return totalValue;
}
private Long insertInSale(Double totalValue, Long userId) {
SaleRequest saleRequest = SaleRequest.builder().userId(userId).discount(0.0).subTotal(totalValue).total(totalValue).build();
Sale sale = saleRepository.save(saleRequest.convert());
Long saleId = sale.getId();
return saleId;
}
private void insertInSaleItemAndReduceStock(Long saleId, List<ProductSaleRequest> productSaleRequest) {
for(ProductSaleRequest productSale: productSaleRequest){
Long productId = productSale.getProductId();
Long quantityProduct = productSale.getQuantityProduct();
SaleItemRequest saleItemRequest = SaleItemRequest.builder().saleId(saleId).productId(productId).quantityProductsSold(quantityProduct).build();
Product product = productRepository.findById(productId).orElseThrow(()->new ResourceNotFoundException("Product not found!"));
Sale sale = saleRepository.findById(saleId).orElseThrow(()-> new ResourceNotFoundException("Sale not found!"));
saleItemRepository.save(saleItemRequest.convert(product,sale));
reduceStock(product,quantityProduct);
}
}
private void reduceStock(Product product, Long quantityProduct) {
Long stock = product.getQuantityStock() - quantityProduct;
product.setQuantityStock(stock);
productRepository.save(product);
}
private void verifyIfHaveInStock(Product product, Long quantityProduct){
Long stockProduct = product.getQuantityStock();
if(quantityProduct <= 0){
throw new ProductException("Quantity of " + product.getDescription() + " cannot be 0 or less than 0");
}
if(stockProduct <= 0 || stockProduct - quantityProduct < 0 ){
throw new ProductException("Product " + product.getDescription() + " stock is insufficient, have just " + product.getQuantityStock() + " in stock!");
}
}
}
|
UTF-8
|
Java
| 4,830 |
java
|
SaleService.java
|
Java
|
[] | null |
[] |
package com.saleservice.domain.services;
import com.saleservice.configurations.exceptions.ProductException;
import com.saleservice.configurations.exceptions.ResourceNotFoundException;
import com.saleservice.configurations.exceptions.SaleException;
import com.saleservice.domain.entities.Product;
import com.saleservice.domain.entities.Sale;
import com.saleservice.domain.entities.User;
import com.saleservice.domain.feignclients.UserFeignClient;
import com.saleservice.domain.repositories.ProductRepository;
import com.saleservice.domain.repositories.SaleItemRepository;
import com.saleservice.domain.repositories.SaleRepository;
import com.saleservice.rest.models.requests.ProductSaleRequest;
import com.saleservice.rest.models.requests.SaleItemRequest;
import com.saleservice.rest.models.requests.SaleRequest;
import com.saleservice.rest.models.responses.SaleResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.List;
@Service
public class SaleService {
@Autowired
private SaleRepository saleRepository;
@Autowired
private ProductRepository productRepository;
@Autowired
private SaleItemRepository saleItemRepository;
@Autowired
private UserFeignClient userFeignClient;
@Transactional
public SaleResponse makeSale(List<ProductSaleRequest> productSaleRequest, String bearerToken) {
Long userId = searchAuthenticatedUser(bearerToken);
Double totalValue = calculateTotalValueAndVerifyIfHaveInStock(productSaleRequest);
Long saleId = insertInSale(totalValue, userId);
insertInSaleItemAndReduceStock(saleId, productSaleRequest);
SaleResponse saleResponse = SaleResponse.builder().total(totalValue).build();
return saleResponse;
}
private Long searchAuthenticatedUser(String bearerToken) {
Long userId = null;
try {
User user = userFeignClient.getAuthenticated(bearerToken);
userId = user.getId();
}
catch (Exception e){
throw new SaleException(e.getMessage());
}
return userId;
}
private Double calculateTotalValueAndVerifyIfHaveInStock(List<ProductSaleRequest> productSaleRequest) {
Double totalValue = 0.0;
for(ProductSaleRequest productSale: productSaleRequest){
Long productId = productSale.getProductId();
Long quantityProduct = productSale.getQuantityProduct();
Product product = productRepository.findById(productId).orElseThrow(()-> new ResourceNotFoundException("Product not found!"));
verifyIfHaveInStock(product, quantityProduct);
totalValue += product.getValue() * quantityProduct;
}
return totalValue;
}
private Long insertInSale(Double totalValue, Long userId) {
SaleRequest saleRequest = SaleRequest.builder().userId(userId).discount(0.0).subTotal(totalValue).total(totalValue).build();
Sale sale = saleRepository.save(saleRequest.convert());
Long saleId = sale.getId();
return saleId;
}
private void insertInSaleItemAndReduceStock(Long saleId, List<ProductSaleRequest> productSaleRequest) {
for(ProductSaleRequest productSale: productSaleRequest){
Long productId = productSale.getProductId();
Long quantityProduct = productSale.getQuantityProduct();
SaleItemRequest saleItemRequest = SaleItemRequest.builder().saleId(saleId).productId(productId).quantityProductsSold(quantityProduct).build();
Product product = productRepository.findById(productId).orElseThrow(()->new ResourceNotFoundException("Product not found!"));
Sale sale = saleRepository.findById(saleId).orElseThrow(()-> new ResourceNotFoundException("Sale not found!"));
saleItemRepository.save(saleItemRequest.convert(product,sale));
reduceStock(product,quantityProduct);
}
}
private void reduceStock(Product product, Long quantityProduct) {
Long stock = product.getQuantityStock() - quantityProduct;
product.setQuantityStock(stock);
productRepository.save(product);
}
private void verifyIfHaveInStock(Product product, Long quantityProduct){
Long stockProduct = product.getQuantityStock();
if(quantityProduct <= 0){
throw new ProductException("Quantity of " + product.getDescription() + " cannot be 0 or less than 0");
}
if(stockProduct <= 0 || stockProduct - quantityProduct < 0 ){
throw new ProductException("Product " + product.getDescription() + " stock is insufficient, have just " + product.getQuantityStock() + " in stock!");
}
}
}
| 4,830 | 0.726915 | 0.725052 | 143 | 32.776222 | 37.509796 | 161 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.496504 | false | false |
12
|
ef1f3f9dec39ee53ed08aa89bce1c23ac3ecc9a4
| 27,857,157,914,319 |
4eb2e6c2bf28a0843f6828dd5ea7462852949968
|
/zc-user-center/src/main/java/com/carry/ZcUserApplication.java
|
d32e2f374dff5c05403737c321c1ba0e621982c7
|
[] |
no_license
|
wuwenshuai/zcuser
|
https://github.com/wuwenshuai/zcuser
|
ef081937cca2bb9c60b9e9c7e857abc9235f69c9
|
dd8d97ed1c0e81c28675f6ae203f1d721cc391d5
|
refs/heads/master
| 2020-05-17T01:23:47.054000 | 2019-04-30T08:06:32 | 2019-04-30T08:06:32 | 183,424,340 | 0 | 0 | null | false | 2019-04-30T08:06:33 | 2019-04-25T11:52:55 | 2019-04-29T09:49:40 | 2019-04-30T08:06:33 | 5,269 | 0 | 0 | 0 |
JavaScript
| false | false |
package com.carry;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import tk.mybatis.spring.annotation.MapperScan;
@SpringBootApplication
@MapperScan("com.carry.mapper") // 扫描mapper包
public class ZcUserApplication {
public static void main(String[] args) {
SpringApplication.run(ZcUserApplication.class,args);
}
}
|
UTF-8
|
Java
| 411 |
java
|
ZcUserApplication.java
|
Java
|
[] | null |
[] |
package com.carry;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import tk.mybatis.spring.annotation.MapperScan;
@SpringBootApplication
@MapperScan("com.carry.mapper") // 扫描mapper包
public class ZcUserApplication {
public static void main(String[] args) {
SpringApplication.run(ZcUserApplication.class,args);
}
}
| 411 | 0.792593 | 0.792593 | 14 | 27.928572 | 23.517363 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false |
12
|
34078ea905e52f4da968f7ef5642fb9fffc6983a
| 8,976,481,682,493 |
33c89008d147ed4149c4fb5ed2507dbca376926b
|
/org.confery.network/src/main/java/translator/TagTranslator.java
|
24f38605745606695632a3897db96bad64869a22
|
[] |
no_license
|
alexandrustoica/ISS-Project
|
https://github.com/alexandrustoica/ISS-Project
|
97dc135975abe8192422090c84f391619c60da6a
|
cdc96db1fb602680f70a534b25cf18b869b53dfc
|
refs/heads/master
| 2018-05-16T10:43:54.550000 | 2017-05-29T20:36:52 | 2017-05-29T20:36:52 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package translator;
import domain.TagEntity;
import transfarable.Tag;
/**
* @author Alexandru Stoica
* @version 1.0
*/
public class TagTranslator {
public static Tag translate(TagEntity tag) {
return new Tag(tag.getId(), tag.getWord());
}
public static TagEntity translate(Tag tag) {
return new TagEntity(tag.getId(), tag.getWord());
}
}
|
UTF-8
|
Java
| 379 |
java
|
TagTranslator.java
|
Java
|
[
{
"context": "agEntity;\nimport transfarable.Tag;\n\n/**\n * @author Alexandru Stoica\n * @version 1.0\n */\n\npublic class TagTranslator {",
"end": 103,
"score": 0.9998527765274048,
"start": 87,
"tag": "NAME",
"value": "Alexandru Stoica"
}
] | null |
[] |
package translator;
import domain.TagEntity;
import transfarable.Tag;
/**
* @author <NAME>
* @version 1.0
*/
public class TagTranslator {
public static Tag translate(TagEntity tag) {
return new Tag(tag.getId(), tag.getWord());
}
public static TagEntity translate(Tag tag) {
return new TagEntity(tag.getId(), tag.getWord());
}
}
| 369 | 0.662269 | 0.656992 | 21 | 17.047619 | 19.117373 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false |
12
|
a922293beb822c8abaeb55acf48370af22b07e3c
| 12,103,217,880,598 |
f28f4ce48de5d0610328abfb2b8867f9b6176ac0
|
/app/src/main/java/com/global/globalonline/activities/user/ForgotaPsswordActivity.java
|
cdacfd015d370d69a775f7cda2e6756e6de2c619
|
[] |
no_license
|
globalonlineAndroid/globalonline
|
https://github.com/globalonlineAndroid/globalonline
|
5b9d9307db6e38b1de097d1de43d5f6343165fbb
|
0e09440f7aef440e3653e271e6ca57cd1d2f0225
|
refs/heads/master
| 2021-01-20T17:55:01.479000 | 2017-09-18T15:28:11 | 2017-09-18T15:28:11 | 60,230,444 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.global.globalonline.activities.user;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.global.globalonline.R;
import com.global.globalonline.base.BaseActivity;
import com.global.globalonline.base.StaticBase;
import com.global.globalonline.bean.CodeBean;
import com.global.globalonline.bean.UserBean;
import com.global.globalonline.dao.TimeCount;
import com.global.globalonline.service.CallBackService;
import com.global.globalonline.service.GetRetrofitService;
import com.global.globalonline.service.RestService;
import com.global.globalonline.service.serviceImpl.RestServiceImpl;
import com.global.globalonline.service.user.UserService;
import com.global.globalonline.tools.GetCheckoutET;
import com.global.globalonline.tools.GetToastUtil;
import com.global.globalonline.tools.MapToParams;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import java.util.HashMap;
import java.util.Map;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
@EActivity(R.layout.activity_forgota_pssword)
public class ForgotaPsswordActivity extends BaseActivity {
@ViewById
EditText et_phone,et_yanzhengma,et_pwd,et_rePwd;
@ViewById
Button btn_tijiao;
@ViewById
TextView btn_send_code;
UserService userService;
Map<String, String> stringMap;
TimeCount time;
CodeBean codeBean;
@AfterViews
void init(){
userService = GetRetrofitService.getRestClient(UserService.class);
}
@Click({R.id.btn_send_code,R.id.btn_tijiao})
void click(View view){
switch (view.getId()){
case R.id.btn_send_code:
send_code();
break;
case R.id.btn_tijiao:
tijiao();
break;
}
}
public void send_code() {
String phone = et_phone.getText().toString();
boolean b = GetCheckoutET.checkout(getApplicationContext(),et_phone);
if(!b){
return;
}
String stype = "2";
stringMap = new HashMap<String, String>();
stringMap.put("mobile", phone);
stringMap.put("stype", stype);
Map<String,String> parsMap = MapToParams.getParsMap(stringMap);
Call<CodeBean> call = userService.send_authcode(parsMap);
call.enqueue(new Callback<CodeBean>() {
@Override
public void onResponse(Call<CodeBean> call, Response<CodeBean> response) {
codeBean = response.body();
if (codeBean.getErrorCode().equals("0")) {
String a = "";
time = new TimeCount(StaticBase.YANZHENGTIME, 1000,ForgotaPsswordActivity.this,btn_send_code);
time.start();
}else {
GetToastUtil.getToads(ForgotaPsswordActivity.this,codeBean.getErrorCode());
}
}
@Override
public void onFailure(Call<CodeBean> call, Throwable t) {
String a = "";
}
});
}
public void tijiao(){
boolean b = GetCheckoutET.checkout(ForgotaPsswordActivity.this,et_phone,et_yanzhengma,et_pwd,et_rePwd);
if(!b){
return;
}
if( codeBean == null){
GetToastUtil.getToads(getApplicationContext(),getResources().getString(R.string.act_base_please_send_code));
return;
}
String mobile= et_phone.getText().toString();
String codetype=codeBean.getCodetype();
String code=et_yanzhengma.getText().toString();
String newpwd=et_pwd.getText().toString();
String new2pwd=et_rePwd.getText().toString();
String pwdtype="1";//1是密码,3是交易密码
stringMap = new HashMap<String, String>();
stringMap.put("mobile",mobile);
stringMap.put("code",code);
stringMap.put("codetype",codetype);
stringMap.put("newpwd",newpwd);
stringMap.put("new2pwd",new2pwd);
stringMap.put("pwdtype",pwdtype);
Map<String,String> parsMap = MapToParams.getParsMap(stringMap);
Call<UserBean> call = userService.find_pwd(parsMap);
RestService restService = new RestServiceImpl();
restService.get(ForgotaPsswordActivity.this,"",call, new CallBackService() {
@Override
public <T> void onResponse(Call<T> call, Response<T> response) {
UserBean userBean = (UserBean) response.body();
if(userBean.getErrorCode().equals("0")){
Toast.makeText(getApplicationContext(),getResources().getString(R.string.act_base_update_successful),Toast.LENGTH_SHORT).show();
finish();
}else {
Toast.makeText(getApplicationContext(),codeBean.getMessage(),Toast.LENGTH_SHORT).show();
}
}
@Override
public <T> void onFailure(Call<T> call, Throwable t) {
String a = "";
}
});
}
}
|
UTF-8
|
Java
| 5,280 |
java
|
ForgotaPsswordActivity.java
|
Java
|
[] | null |
[] |
package com.global.globalonline.activities.user;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.global.globalonline.R;
import com.global.globalonline.base.BaseActivity;
import com.global.globalonline.base.StaticBase;
import com.global.globalonline.bean.CodeBean;
import com.global.globalonline.bean.UserBean;
import com.global.globalonline.dao.TimeCount;
import com.global.globalonline.service.CallBackService;
import com.global.globalonline.service.GetRetrofitService;
import com.global.globalonline.service.RestService;
import com.global.globalonline.service.serviceImpl.RestServiceImpl;
import com.global.globalonline.service.user.UserService;
import com.global.globalonline.tools.GetCheckoutET;
import com.global.globalonline.tools.GetToastUtil;
import com.global.globalonline.tools.MapToParams;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import java.util.HashMap;
import java.util.Map;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
@EActivity(R.layout.activity_forgota_pssword)
public class ForgotaPsswordActivity extends BaseActivity {
@ViewById
EditText et_phone,et_yanzhengma,et_pwd,et_rePwd;
@ViewById
Button btn_tijiao;
@ViewById
TextView btn_send_code;
UserService userService;
Map<String, String> stringMap;
TimeCount time;
CodeBean codeBean;
@AfterViews
void init(){
userService = GetRetrofitService.getRestClient(UserService.class);
}
@Click({R.id.btn_send_code,R.id.btn_tijiao})
void click(View view){
switch (view.getId()){
case R.id.btn_send_code:
send_code();
break;
case R.id.btn_tijiao:
tijiao();
break;
}
}
public void send_code() {
String phone = et_phone.getText().toString();
boolean b = GetCheckoutET.checkout(getApplicationContext(),et_phone);
if(!b){
return;
}
String stype = "2";
stringMap = new HashMap<String, String>();
stringMap.put("mobile", phone);
stringMap.put("stype", stype);
Map<String,String> parsMap = MapToParams.getParsMap(stringMap);
Call<CodeBean> call = userService.send_authcode(parsMap);
call.enqueue(new Callback<CodeBean>() {
@Override
public void onResponse(Call<CodeBean> call, Response<CodeBean> response) {
codeBean = response.body();
if (codeBean.getErrorCode().equals("0")) {
String a = "";
time = new TimeCount(StaticBase.YANZHENGTIME, 1000,ForgotaPsswordActivity.this,btn_send_code);
time.start();
}else {
GetToastUtil.getToads(ForgotaPsswordActivity.this,codeBean.getErrorCode());
}
}
@Override
public void onFailure(Call<CodeBean> call, Throwable t) {
String a = "";
}
});
}
public void tijiao(){
boolean b = GetCheckoutET.checkout(ForgotaPsswordActivity.this,et_phone,et_yanzhengma,et_pwd,et_rePwd);
if(!b){
return;
}
if( codeBean == null){
GetToastUtil.getToads(getApplicationContext(),getResources().getString(R.string.act_base_please_send_code));
return;
}
String mobile= et_phone.getText().toString();
String codetype=codeBean.getCodetype();
String code=et_yanzhengma.getText().toString();
String newpwd=et_pwd.getText().toString();
String new2pwd=et_rePwd.getText().toString();
String pwdtype="1";//1是密码,3是交易密码
stringMap = new HashMap<String, String>();
stringMap.put("mobile",mobile);
stringMap.put("code",code);
stringMap.put("codetype",codetype);
stringMap.put("newpwd",newpwd);
stringMap.put("new2pwd",new2pwd);
stringMap.put("pwdtype",pwdtype);
Map<String,String> parsMap = MapToParams.getParsMap(stringMap);
Call<UserBean> call = userService.find_pwd(parsMap);
RestService restService = new RestServiceImpl();
restService.get(ForgotaPsswordActivity.this,"",call, new CallBackService() {
@Override
public <T> void onResponse(Call<T> call, Response<T> response) {
UserBean userBean = (UserBean) response.body();
if(userBean.getErrorCode().equals("0")){
Toast.makeText(getApplicationContext(),getResources().getString(R.string.act_base_update_successful),Toast.LENGTH_SHORT).show();
finish();
}else {
Toast.makeText(getApplicationContext(),codeBean.getMessage(),Toast.LENGTH_SHORT).show();
}
}
@Override
public <T> void onFailure(Call<T> call, Throwable t) {
String a = "";
}
});
}
}
| 5,280 | 0.6374 | 0.63436 | 161 | 31.683229 | 27.794817 | 148 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.751553 | false | false |
12
|
cc01fcb6e629153af84c1fc4048ad5f0647b6cb7
| 28,398,323,793,558 |
d50d447875241a49e74a3de9cf38bf390d162175
|
/src/main/java/be/storefront/imicloud/domain/document/structure/StructureSection.java
|
51556fc9e18408148048cc8333fad60da6fe0909
|
[] |
no_license
|
Kalesberg/Spring-Angular-MS-Word-Extension
|
https://github.com/Kalesberg/Spring-Angular-MS-Word-Extension
|
f855359a1de0e90041886a0f479b226f12085613
|
b65c80e10d6756de54e1fff5c49448359f137f18
|
refs/heads/master
| 2020-03-20T23:02:45.713000 | 2017-10-11T09:53:23 | 2017-10-11T09:53:23 | 137,826,529 | 0 | 1 | null | false | 2020-09-18T16:06:57 | 2018-06-19T01:47:43 | 2018-06-19T02:12:30 | 2018-06-19T02:12:04 | 104,952 | 0 | 1 | 1 |
Java
| false | false |
package be.storefront.imicloud.domain.document.structure;
/**
* Created by wouter on 30/01/2017.
*/
public class StructureSection extends TreeNode{
public String getCode(){
return "section";
}
}
|
UTF-8
|
Java
| 214 |
java
|
StructureSection.java
|
Java
|
[
{
"context": "loud.domain.document.structure;\n\n/**\n * Created by wouter on 30/01/2017.\n */\npublic class StructureSection ",
"end": 83,
"score": 0.999284029006958,
"start": 77,
"tag": "USERNAME",
"value": "wouter"
}
] | null |
[] |
package be.storefront.imicloud.domain.document.structure;
/**
* Created by wouter on 30/01/2017.
*/
public class StructureSection extends TreeNode{
public String getCode(){
return "section";
}
}
| 214 | 0.696262 | 0.658879 | 10 | 20.4 | 19.935898 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false |
12
|
ca67e1907dc075647332d608599cf4d3c42bb804
| 25,297,357,410,692 |
9e1b924c1dd87594b31aef54db5dee16763e62ce
|
/src/com/keshav/sorting/No_of_triangs.java
|
a4f00a2981bfb3f008704e763054e8bcfeff433e
|
[] |
no_license
|
keshavagarwal1998/DataStructures-Basics
|
https://github.com/keshavagarwal1998/DataStructures-Basics
|
f92839d26a3b89ad097fdf83a62a9817fcb2db7e
|
c191eb75626947265b6dbd080f5393fd2fe8a2be
|
refs/heads/master
| 2022-11-06T02:32:46.342000 | 2020-06-18T21:14:59 | 2020-06-18T21:14:59 | 265,040,326 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.keshav.sorting;
import java.util.Arrays;
import java.util.Scanner;
class No_of_triangs
{
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- > 0)
{
int n = sc.nextInt();
int arr[] = new int[n];
for(int i = 0; i < n; i++)
arr[i] = sc.nextInt();
Count_possible_triangle mn = new Count_possible_triangle();
System.out.println(Count_possible_triangle.findNumberOfTriangles(arr, n));
}
}
}
class Count_possible_triangle
{
static long findNumberOfTriangles(int arr[], int n)
{
Arrays.sort(arr);
int count = 0;
for(int i = 0 ; i<n-2 ; i++){
int k = i+2;
int j = i+1;
while(j<n && k<n) {
if (k <= n && arr[i] + arr[j]>arr[k]) {
count++;
k++;
} else {
k++;
}
if (k >n-1 ) {
j++;
k = j + 1;
}
}
}
return count;
}
}
|
UTF-8
|
Java
| 1,208 |
java
|
No_of_triangs.java
|
Java
|
[] | null |
[] |
package com.keshav.sorting;
import java.util.Arrays;
import java.util.Scanner;
class No_of_triangs
{
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- > 0)
{
int n = sc.nextInt();
int arr[] = new int[n];
for(int i = 0; i < n; i++)
arr[i] = sc.nextInt();
Count_possible_triangle mn = new Count_possible_triangle();
System.out.println(Count_possible_triangle.findNumberOfTriangles(arr, n));
}
}
}
class Count_possible_triangle
{
static long findNumberOfTriangles(int arr[], int n)
{
Arrays.sort(arr);
int count = 0;
for(int i = 0 ; i<n-2 ; i++){
int k = i+2;
int j = i+1;
while(j<n && k<n) {
if (k <= n && arr[i] + arr[j]>arr[k]) {
count++;
k++;
} else {
k++;
}
if (k >n-1 ) {
j++;
k = j + 1;
}
}
}
return count;
}
}
| 1,208 | 0.40149 | 0.39404 | 54 | 21.388889 | 18.698799 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.481481 | false | false |
12
|
b54a966b1f23ca19b37ab863c69569e1674f256f
| 23,450,521,467,197 |
227c598fd38bb3a4ef1c0942af28603ff11617b3
|
/alura-camel/src/main/java/br/com/caelum/camel/mq/TratadorMensagemJms.java
|
d4bcc7c7a63c90fd1ceae5a081a0b5365b5959d5
|
[] |
no_license
|
ralvesper/alura-camel
|
https://github.com/ralvesper/alura-camel
|
c7d69cf9918fa06510fb26764ec40c83858af85d
|
18c1ee8ebdb64edd6e40095c50c4562910c19f10
|
refs/heads/master
| 2021-01-12T15:03:13.575000 | 2016-10-23T00:40:02 | 2016-10-23T00:40:02 | 71,673,330 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package br.com.caelum.camel.mq;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
public class TratadorMensagemJms implements MessageListener {
public void onMessage(Message jmsMessage) {
// código que processa a mensagem JMS
try {
System.out.println("TratadorMensagemJms working...");
System.out.println("JMSMessageID: "+jmsMessage.getJMSMessageID());
} catch (JMSException e) {
throw new RuntimeException(e);
}
}
}
|
UTF-8
|
Java
| 484 |
java
|
TratadorMensagemJms.java
|
Java
|
[] | null |
[] |
package br.com.caelum.camel.mq;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
public class TratadorMensagemJms implements MessageListener {
public void onMessage(Message jmsMessage) {
// código que processa a mensagem JMS
try {
System.out.println("TratadorMensagemJms working...");
System.out.println("JMSMessageID: "+jmsMessage.getJMSMessageID());
} catch (JMSException e) {
throw new RuntimeException(e);
}
}
}
| 484 | 0.749482 | 0.749482 | 19 | 24.421053 | 22.074791 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.473684 | false | false |
12
|
43bba58466746412783e6fbc8d09bcc9de457b43
| 20,856,361,196,808 |
a3e8d8b3d421348504f9e81c0fa94f4846e98669
|
/java/Mailbox/src/stef/view/MenuUtils.java
|
0262263c3798d65c27c32a9119ccecef60bd6a24
|
[] |
no_license
|
stevD9/MailBox
|
https://github.com/stevD9/MailBox
|
820528ea4d1c07b1c6507643d2f688dd20c0e031
|
ef4eaa5a2ea54c4b0b6879a5523015b9535241ca
|
refs/heads/master
| 2020-04-14T17:55:09.837000 | 2019-01-03T16:50:17 | 2019-01-03T16:50:17 | 163,999,208 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package stef.view;
import java.io.IOException;
import java.util.Scanner;
/**
*
* @author StevenDrea
*/
public class MenuUtils {
public static boolean requestConfirmation() {
Scanner sc = new Scanner(System.in);
System.out.println("\nPress 'c' to continue, or any other key to cancel:");
String choice = sc.nextLine();
if (choice.toLowerCase().equals("c")) {
return true;
} else {
return false;
}
}
public final static void clearConsole() {
try {
final String os = System.getProperty("os.name");
// System.out.println(os);
if (os.contains("Windows")) {
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
} else {
Runtime.getRuntime().exec("clear");
System.out.print("\033\143");
}
} catch (final IOException | InterruptedException e) {
}
}
}
|
UTF-8
|
Java
| 1,022 |
java
|
MenuUtils.java
|
Java
|
[
{
"context": "\r\nimport java.util.Scanner;\r\n\r\n/**\r\n *\r\n * @author StevenDrea\r\n */\r\npublic class MenuUtils {\r\n\r\n public static",
"end": 110,
"score": 0.9262898564338684,
"start": 100,
"tag": "NAME",
"value": "StevenDrea"
}
] | null |
[] |
package stef.view;
import java.io.IOException;
import java.util.Scanner;
/**
*
* @author StevenDrea
*/
public class MenuUtils {
public static boolean requestConfirmation() {
Scanner sc = new Scanner(System.in);
System.out.println("\nPress 'c' to continue, or any other key to cancel:");
String choice = sc.nextLine();
if (choice.toLowerCase().equals("c")) {
return true;
} else {
return false;
}
}
public final static void clearConsole() {
try {
final String os = System.getProperty("os.name");
// System.out.println(os);
if (os.contains("Windows")) {
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
} else {
Runtime.getRuntime().exec("clear");
System.out.print("\033\143");
}
} catch (final IOException | InterruptedException e) {
}
}
}
| 1,022 | 0.521526 | 0.515656 | 36 | 26.388889 | 23.156805 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.472222 | false | false |
12
|
cacf2ab88c01a25a45d86a869109c21ac57aa69a
| 15,350,213,147,120 |
4344d98c4c95b20be70fcd22fddd0238122418ad
|
/src/dependency_inversion_and_interface_segregation/main/java/Main.java
|
f2e322b6a9f293cc6f3bef6b402c63e6bdab0ffa
|
[
"MIT"
] |
permissive
|
ChillyWe/JavaOOP_AdvancedNov2017
|
https://github.com/ChillyWe/JavaOOP_AdvancedNov2017
|
4935a622c9f59a8c2eee99a66764e3849b753293
|
cdf0f1f8f8028d60e83e8dfed0de1178bd9d8a60
|
refs/heads/master
| 2021-03-30T20:26:03.114000 | 2018-03-11T14:42:07 | 2018-03-11T14:42:07 | 124,761,753 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package dependency_inversion_and_interface_segregation.main.java;
import contracts.BoatSimulatorController;
import controllers.BoatSimulatorControllerImpl;
import core.CommandHandlerImpl;
import database.BoatSimulatorDatabase;
import engines.Engine;
import contracts.CommandHandler;
import contracts.InputReader;
import contracts.OutputWriter;
import io.ConsoleInputReader;
import io.ConsoleOutputWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
InputReader reader = new ConsoleInputReader();
OutputWriter writer = new ConsoleOutputWriter();
BoatSimulatorDatabase database = new BoatSimulatorDatabase();
BoatSimulatorController controller = new BoatSimulatorControllerImpl(database);
CommandHandler commandHandler = new CommandHandlerImpl(controller);
Engine engine = new Engine(commandHandler, reader, writer);
engine.run();
}
}
|
UTF-8
|
Java
| 992 |
java
|
Main.java
|
Java
|
[] | null |
[] |
package dependency_inversion_and_interface_segregation.main.java;
import contracts.BoatSimulatorController;
import controllers.BoatSimulatorControllerImpl;
import core.CommandHandlerImpl;
import database.BoatSimulatorDatabase;
import engines.Engine;
import contracts.CommandHandler;
import contracts.InputReader;
import contracts.OutputWriter;
import io.ConsoleInputReader;
import io.ConsoleOutputWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
InputReader reader = new ConsoleInputReader();
OutputWriter writer = new ConsoleOutputWriter();
BoatSimulatorDatabase database = new BoatSimulatorDatabase();
BoatSimulatorController controller = new BoatSimulatorControllerImpl(database);
CommandHandler commandHandler = new CommandHandlerImpl(controller);
Engine engine = new Engine(commandHandler, reader, writer);
engine.run();
}
}
| 992 | 0.764113 | 0.764113 | 27 | 34.740742 | 25.051935 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.777778 | false | false |
12
|
deb7fa113e1ff72c8a14205a3197417a805d033c
| 2,035,814,519,780 |
10f90612d8cc3c16bac304c811d948255957920e
|
/com/github/blank01/safarigames/phases/PostPhase.java
|
a447f04806773a432faf08e52511e9705471f476
|
[] |
no_license
|
CrimsonUniform97/SafariGamesOld
|
https://github.com/CrimsonUniform97/SafariGamesOld
|
7761d7ae6aeb5e6432111f335c44a23652b4c819
|
62a996067948c8fdfd6ab7835243a748162c4c36
|
refs/heads/master
| 2021-01-24T02:46:14.037000 | 2017-06-06T20:14:25 | 2017-06-06T20:14:25 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.github.blank01.safarigames.phases;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.EnumChatFormatting;
import com.github.blank01.safarigames.SafariGames;
import com.github.blank01.safarigames.utils.MinecraftUtils;
import com.github.blank01.safarigames.utils.PixelmonUtils;
public class PostPhase extends SafariPhase{
public PostPhase() {
super(-1, EnumPhase.POST);
}
@Override
public void run(){
MinecraftServer.getServer().getCommandManager().executeCommand(MinecraftServer.getServer(), "/whitelist off");
MinecraftUtils.removePlayersToWhitelist();
MinecraftUtils.broadcast(EnumChatFormatting.LIGHT_PURPLE +"=============");
MinecraftUtils.broadcast(EnumChatFormatting.RED + "Safari Games Ended");
MinecraftUtils.broadcast(EnumChatFormatting.LIGHT_PURPLE +"=============");
MinecraftUtils.clearAllInventories();
MinecraftUtils.tpAll(SafariGames.instance.getWarpManager().getWarp("pokecenter"), "The Pokecenter");
PixelmonUtils.healAllTeams();
}
@Override
public void doSomething() {
}
@Override
protected void doSomthingEndPhase() {
// TODO Auto-generated method stub
}
}
|
UTF-8
|
Java
| 1,156 |
java
|
PostPhase.java
|
Java
|
[
{
"context": "package com.github.blank01.safarigames.phases;\n\nimport net.minecraft.server.",
"end": 26,
"score": 0.9987657070159912,
"start": 19,
"tag": "USERNAME",
"value": "blank01"
},
{
"context": "craft.util.EnumChatFormatting;\n\nimport com.github.blank01.safarigames.SafariGames;\nimport com.github.blank0",
"end": 165,
"score": 0.9988679885864258,
"start": 158,
"tag": "USERNAME",
"value": "blank01"
},
{
"context": "lank01.safarigames.SafariGames;\nimport com.github.blank01.safarigames.utils.MinecraftUtils;\nimport com.gith",
"end": 216,
"score": 0.9989290237426758,
"start": 209,
"tag": "USERNAME",
"value": "blank01"
},
{
"context": "farigames.utils.MinecraftUtils;\nimport com.github.blank01.safarigames.utils.PixelmonUtils;\n\npublic class Po",
"end": 276,
"score": 0.9987532496452332,
"start": 269,
"tag": "USERNAME",
"value": "blank01"
}
] | null |
[] |
package com.github.blank01.safarigames.phases;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.EnumChatFormatting;
import com.github.blank01.safarigames.SafariGames;
import com.github.blank01.safarigames.utils.MinecraftUtils;
import com.github.blank01.safarigames.utils.PixelmonUtils;
public class PostPhase extends SafariPhase{
public PostPhase() {
super(-1, EnumPhase.POST);
}
@Override
public void run(){
MinecraftServer.getServer().getCommandManager().executeCommand(MinecraftServer.getServer(), "/whitelist off");
MinecraftUtils.removePlayersToWhitelist();
MinecraftUtils.broadcast(EnumChatFormatting.LIGHT_PURPLE +"=============");
MinecraftUtils.broadcast(EnumChatFormatting.RED + "Safari Games Ended");
MinecraftUtils.broadcast(EnumChatFormatting.LIGHT_PURPLE +"=============");
MinecraftUtils.clearAllInventories();
MinecraftUtils.tpAll(SafariGames.instance.getWarpManager().getWarp("pokecenter"), "The Pokecenter");
PixelmonUtils.healAllTeams();
}
@Override
public void doSomething() {
}
@Override
protected void doSomthingEndPhase() {
// TODO Auto-generated method stub
}
}
| 1,156 | 0.767301 | 0.759516 | 40 | 27.9 | 30.112953 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.375 | false | false |
12
|
38e9111328157721c75fe06b557abb694be96abd
| 10,969,346,476,240 |
4edbe52a2eeb5544582bbe8e08e9caca1f492f5f
|
/agent/src/main/java/com/heliosapm/shorthand/instrumentor/shorthand/ShorthandJSONScript.java
|
bbbaf60516fe9c8384eb7559c27e36436bd31be3
|
[
"Apache-2.0"
] |
permissive
|
nickman/shorthand
|
https://github.com/nickman/shorthand
|
e5a54033c45b3141326a0c1db281c5bab025eef0
|
9d9303167abcb318c6c7b329469d253d514e4f94
|
refs/heads/master
| 2020-03-30T11:18:28.494000 | 2017-04-08T19:33:00 | 2017-04-08T19:33:00 | 12,180,982 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* Helios, OpenSource Monitoring
* Brought to you by the Helios Development Group
*
* Copyright 2007, Helios Development Group and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*
*/
package com.heliosapm.shorthand.instrumentor.shorthand;
import java.io.File;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.regex.Pattern;
import javax.management.ObjectName;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.heliosapm.shorthand.ShorthandProperties;
import com.heliosapm.shorthand.collectors.EnumCollectors;
import com.heliosapm.shorthand.collectors.ICollector;
import com.heliosapm.shorthand.instrumentor.shorthand.gson.GsonProvider;
import com.heliosapm.shorthand.util.URLHelper;
import com.heliosapm.shorthand.util.classload.MultiClassLoader;
import com.heliosapm.shorthand.util.jmx.JMXHelper;
/**
* <p>Title: ShorthandJSONScript</p>
* <p>Description: </p>
* <p>Company: Helios Development Group LLC</p>
* @author Whitehead (nwhitehead AT heliosdev DOT org)
* <p><code>com.heliosapm.shorthand.instrumentor.shorthand.ShorthandJSONScript</code></p>
* <pre>
<ClassName>[+] [(Method Attributes)] <MethodName>[<Signature>] [Invocation Options] <CollectorName>[<BitMask>|<CollectionNames>] <MetricFormat> DISABLED
* </pre>
*/
public class ShorthandJSONScript implements JsonDeserializer<ShorthandJSONScript> {
// ===============================================================================================
// JSON ser/deser Permanent Fields (i.e. not transient, for temp values)
// ===============================================================================================
/** The target class containing the methods to be instrumented. */
@SerializedName("tc") @Expose
protected String className;
/** The target method name to be instrumented. May be a regular expression */
@SerializedName("meth") @Expose
protected String methodName;
/** An optional expression that if provided filters the target methods by matching against the method signature using a regular expression */
@SerializedName("sig") @Expose
protected String methodSignature = ".*";
/** An optional bitmask of enum members in {@link MethodAttribute} that filters method by {@link Modifier} attributes. Defaults to {@link MethodAttribute#DEFAULT_METHOD_MASK} */
@SerializedName("mod") @Expose
protected int methodMod = MethodAttribute.DEFAULT_METHOD_MASK;
/** The enum collector simple class name (if the package has been declared in {@link ShorthandProperties#ENUM_COLLECTOR_PACKAGES_PROP} or the fully qualified name */
@SerializedName("col") @Expose
protected String collectorName;
/** The bitmask of the enabled metric members in the declared enum collector in {@link #collectorName} */
@SerializedName("bitmask") @Expose
protected int bitMask = -1;
/** An expression from which the metric name generated a runtime will be derived from */
@SerializedName("exp")
@Expose
protected String metricExpression;
/** Indicates if injected instrumentation should remain active when the method is called recursively. Defaults to false. */
@SerializedName("rec") @Expose
protected boolean allowRecursion = false;
/** Indicates if all instrumentation should be disabled until the intrumented method completes. Defaults to false. */
@SerializedName("dis") @Expose
protected boolean disableOnCall = false;
// ===============================================================================================
// Permanent Fields (i.e. not transient, for temp values)
// derrived from the deser values and inserted when serialized
// ===============================================================================================
/** Indicates that the name in {@link #className} is a type level annotation and tha target is any classes annotated as such */
protected boolean annotatedClass = false;
/** Indicates that the name in {@link #className} is an interface implying that the target classes are ones that implement this interface */
protected boolean iface = false;
/** Indicates that the target classes are one that inherrit from the class named in {@link #className} */
protected boolean inherritance = false;
/** Indicates that the name in {@link #methodName} is a method level annotation and the target is any method annotated as such */
protected boolean annotatedMethod;
/** The target classloader. Defaults to this class's classloader */
protected ClassLoader targetClassLoader = getClass().getClassLoader();
/** The enum collector class classloaders. Defaults to this class's classloader */
protected ClassLoader collectorClassLoader = getClass().getClassLoader();
// ===============================================================================================
// Transient Fields (i.e. temp values read in by Gson, but then discarded)
// ===============================================================================================
/** The names or ordinals of the enabled metric members in the declared enum collector in {@link #collectorName}. Will be parsed and converted into the bitmask */
@SerializedName("cmbrs")
@Expose(serialize=false)
protected String collectorMembers = null;
/** Alternate expression syntax to specify the {@link ShorthandJSONScript#methodMod} as comma separated names or ordinals of the members in {@link MethodAttribute} */
@SerializedName("mbrs")
@Expose(serialize=false)
protected String methodModMembers = null;
/** Instrumentation target class classloader expressions as comma separated URLs, ObjectNames and keywords */
@SerializedName("tcldr")
@Expose(serialize=false)
protected String targetClassLoaderExpressions = null;
/** Enum collector class classloader expressions as comma separated URLs, ObjectNames and keywords */
@SerializedName("ccldr")
@Expose(serialize=false)
protected String collectorClassLoaderExpressions = null;
/**
* Parses a shorthand json script and returns an array of script objects
* @param scriptText The json script
* @return an array of script objects
*/
public static ShorthandJSONScript[] parse(String scriptText) {
JsonElement element = new JsonParser().parse(scriptText);
if(element.isJsonArray()) {
return GsonProvider.getInstance().getGson().fromJson(scriptText, ShorthandJSONScript[].class);
}
return new ShorthandJSONScript[]{GsonProvider.getInstance().getGson().fromJson(scriptText, ShorthandJSONScript.class)};
}
/** Annotation prefix pattern */
private static final Pattern ANNOT = Pattern.compile("@");
/** Inherritance sufffix pattern */
private static final Pattern PLUS = Pattern.compile("\\+");
/**
* Executed after json deserialization to complete parsing and validate
* @param pre The pre-processed script object
* @param json The json fragment that was just parsed
* @return The validated and post-processed script object
* @throws ShorthandParseFailureException thrown on any validation errors
*/
protected ShorthandJSONScript postDeserialize(ShorthandJSONScript pre, String json) throws ShorthandParseFailureException {
// ======================================================================
// Extract the class name qualifiers
// ======================================================================
if(pre.className==null || pre.className.trim().isEmpty()) throw new ShorthandParseFailureException("Target Class Name was null or empty", json);
pre.className = pre.className.trim();
if(pre.className.startsWith("@")) {
pre.annotatedClass = true;
pre.className = ANNOT.matcher(pre.className).replaceFirst("");
}
if(pre.className.endsWith("+")) {
pre.inherritance = true;
pre.className = PLUS.matcher(pre.className).replaceFirst("");
}
// ======================================================================
// Test for target class classpath overrides
// ======================================================================
if(pre.targetClassLoaderExpressions!=null && !pre.targetClassLoaderExpressions.trim().isEmpty()) {
pre.targetClassLoader = gatherClassLoaders(false, pre.targetClassLoaderExpressions);
}
// ======================================================================
// Locate and validate target class
// ======================================================================
try {
Class.forName(pre.className, false, pre.targetClassLoader);
} catch (Exception ex) {
throw new ShorthandParseFailureException("Failed to load target class [" + pre.className + "]", json, ex);
}
// ======================================================================
// Test for collector class classpath overrides
// ======================================================================
if(pre.collectorClassLoaderExpressions!=null && !pre.collectorClassLoaderExpressions.trim().isEmpty()) {
pre.collectorClassLoader = gatherClassLoaders(false, pre.collectorClassLoaderExpressions);
}
// ======================================================================
// Clean the collector class
// ======================================================================
if(pre.collectorName==null || pre.collectorName.trim().isEmpty()) throw new ShorthandParseFailureException("Collector Class Name was null or empty", json);
pre.collectorName = pre.collectorName.trim();
// ======================================================================
// Locate and validate collector class
// ======================================================================
Class<ICollector<?>> collectorClazz = null;
try {
collectorClazz = resolveCollectorName(pre.collectorName, pre.targetClassLoader);
pre.collectorName = collectorClazz.getName();
} catch (Exception ex) {
throw new ShorthandParseFailureException("Failed to load collector class [" + pre.collectorName + "]", json, ex);
}
// ======================================================================
// Sets the metric bit mask. If the actual bitmask is -1,
// then the bitmask should be validated from the specified collectorMembers
// ======================================================================
if(pre.bitMask==-1) {
if(pre.collectorMembers==null || pre.collectorMembers.trim().isEmpty()) {
throw new ShorthandParseFailureException("Enum collector bitmask was -1 and no collector member names were defined", json);
}
Set<String> names = new HashSet<String>();
for(String s: pre.collectorMembers.trim().split(",")) {
if(s.trim().isEmpty()) continue;
names.add(EnumCollectors.getInstance().getMember(collectorClazz.getName(), s).name());
}
if(names.isEmpty()) {
throw new ShorthandParseFailureException("Enum collector bitmask was -1 and no collector member names were defined", json);
}
pre.bitMask = collectorClazz.getEnumConstants()[0].getBitMaskOf(names.toArray(new String[names.size()]));
pre.collectorMembers=null;
}
// ======================================================================
// Check that metricExpression is not null
// Any other validation we can do here ?
// ======================================================================
if(pre.metricExpression==null || pre.metricExpression.trim().isEmpty()) {
throw new ShorthandParseFailureException("The metric expression was null or empty", json);
}
return pre;
}
/**
* {@inheritDoc}
* @see com.google.gson.JsonDeserializer#deserialize(com.google.gson.JsonElement, java.lang.reflect.Type, com.google.gson.JsonDeserializationContext)
*/
@Override
public ShorthandJSONScript deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
ShorthandJSONScript pre = GsonProvider.getInstance().getNoSerGson().fromJson(json, ShorthandJSONScript.class);
return postDeserialize(pre, json.toString());
}
/**
* Expands the collector name from the passed simple name to the fully qualified class name
* @param collectorName Assumed to be the short name, but will test to see if the name by itself can be loaded
* @param classLoader The classloader to load from
* @return the collector class
*/
protected Class<ICollector<?>> resolveCollectorName(String collectorName, ClassLoader classLoader) {
try {
return (Class<ICollector<?>>) Class.forName(collectorName, false, classLoader);
} catch (ClassNotFoundException cnfx) {}
for(String packageName: ShorthandProperties.getEnumCollectorPackages()) {
try {
return (Class<ICollector<?>>) Class.forName(packageName + "." + collectorName, false, classLoader);
} catch (ClassNotFoundException cnfx) {}
}
throw new RuntimeException("Failed to find enum collector [" + collectorName + "] in any package");
//Class.forName(pre.collectorName, false, pre.targetClassLoader);
}
/**
* Gathers a multi-classloader from the individual class loader expressions in the comma separated expression passed
* @param strict If true, an exception will the thrown if any of the expressions fails
* @param classLoaderExprs The comma separated classloader expressions
* @return a classloader
*/
protected ClassLoader gatherClassLoaders(boolean strict, String classLoaderExprs) {
Set<ClassLoader> classLoaders = new LinkedHashSet<ClassLoader>();
for(String s: classLoaderExprs.split(",")) {
try {
ClassLoader cl = getClassLoader(strict, s);
if(cl!=null) classLoaders.add(cl);
} catch (Exception ex) {
if(strict) throw new RuntimeException("Failed to create classloader", ex);
}
}
if(!classLoaders.isEmpty()) {
return new MultiClassLoader(classLoaders);
}
return getClass().getClassLoader();
}
/**
* Interprets a classloader from the passed expression
* @param strict If true, an exception will the thrown if the expression fails, otherwise this class's classloader will be returned
* @param expression The expression to interpret
* @return A classloader
*/
protected ClassLoader getClassLoader(boolean strict, String expression) {
if(expression==null || expression.trim().isEmpty()) {
if(strict) throw new RuntimeException("The passed expression was null or empty");
return getClass().getClassLoader();
}
String _expr = expression.trim();
if(_expr.equalsIgnoreCase("SYSTEM")) return ClassLoader.getSystemClassLoader();
if(URLHelper.isValidURL(_expr)) {
URL url = URLHelper.toURL(_expr);
return new URLClassLoader(new URL[]{url});
}
if(JMXHelper.isObjectName(_expr)) {
ObjectName on = JMXHelper.objectName(_expr);
if(JMXHelper.getHeliosMBeanServer().isRegistered(on)) {
try {
if(JMXHelper.getHeliosMBeanServer().isInstanceOf(on, ClassLoader.class.getName())) {
return JMXHelper.getHeliosMBeanServer().getClassLoader(on);
}
return JMXHelper.getHeliosMBeanServer().getClassLoaderFor(on);
} catch (Exception ex) {
if(strict) throw new RuntimeException("Failed to get ClassLoader for ObjectName [" + on + "]", ex);
return getClass().getClassLoader();
}
}
if(strict) throw new RuntimeException("Specified ObjectName ClassLoader [" + on + "] was not registered");
return getClass().getClassLoader();
}
File cpFile = new File(_expr);
if(cpFile.canRead()) {
URL url = URLHelper.toURL(cpFile);
return new URLClassLoader(new URL[]{url});
}
if(strict) throw new RuntimeException("Failed to derive ClassLoader from expression [" + _expr + "]");
return getClass().getClassLoader();
}
public static void main(String[] args) {
log("Shorthand Script Test");
ShorthandJSONScript sd = new ShorthandJSONScript();
//com.theice.aop.icebyteman.test.classes.BaseSampleClass massiveCalc(int) [*] '$class/$method/$1'"
sd.className = "java.util.concurrent.ThreadPoolExecutor";
sd.methodName = "massiveCalc";
sd.methodSignature = "int";
sd.collectorName = "MethodInterceptor";
sd.bitMask = 4095;
sd.metricExpression="$class/$method/$1";
//String json = GsonProvider.getInstance().getPrettyPrinter().toJson(sd);
String json = GsonProvider.getInstance().getGson().toJson(sd);
log("JSON:\n%s", json);
// {\"tc\":\"com.heliosapm.shorthand.testclasses.BaseSampleClass\",\"meth\":\"massiveCalc\",\"sig\":\"int\",\"col\":\"MethodInterceptor\",\"bitmask\":4095,\"exp\":\"$class/$method/$1\",\"rec\":false,\"dis\":false}
ShorthandJSONScript[] scripts = parse(json);
log(Arrays.deepToString(scripts));
}
/**
* Creates a new ShorthandJSONScript
*/
public ShorthandJSONScript() {
}
/**
* {@inheritDoc}
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder b = new StringBuilder();
b.append("ShorthandJSONScript [");
b.append("\n\ttargetClass=");
if(annotatedClass) b.append("@");
b.append(className);
if(iface && inherritance) b.append("* ");
if(!iface && inherritance) b.append("+ ");
b.append("\n\tmethodName=").append(methodName);
if (methodSignature != null) {
b.append("\n\tmethodSignature=[");
b.append(methodSignature).append("]");
}
b.append("\n\tmethodMod=").append(methodMod); //FIXME: Decode to member names
b.append("\n\tannotatedMethod=").append(annotatedMethod);
b.append("\n\tcollectorName=").append(collectorName);
b.append("\n\tbitMask=").append(bitMask);
b.append("\n\tmetricExpression=[").append(metricExpression).append("]");
b.append("\n\tallowRecursion=").append(allowRecursion);
b.append("\n\tdisableOnCall=").append(disableOnCall);
b.append("\n]");
return b.toString();
}
/**
* Simple out formatted logger
* @param fmt The format of the message
* @param args The message arguments
*/
public static void log(String fmt, Object...args) {
System.out.println(String.format(fmt, args));
}
/**
* Simple err formatted logger
* @param fmt The format of the message
* @param args The message arguments
*/
public static void loge(String fmt, Object...args) {
System.err.println(String.format(fmt, args));
}
/**
* Simple err formatted logger
* @param fmt The format of the message
* @param t The throwable to print stack trace for
* @param args The message arguments
*/
public static void loge(String fmt, Throwable t, Object...args) {
System.err.println(String.format(fmt, args));
t.printStackTrace(System.err);
}
}
|
UTF-8
|
Java
| 19,646 |
java
|
ShorthandJSONScript.java
|
Java
|
[
{
"context": "mpany: Helios Development Group LLC</p>\n * @author Whitehead (nwhitehead AT heliosdev DOT org)\n * <p><code>com",
"end": 2286,
"score": 0.9842455387115479,
"start": 2277,
"tag": "USERNAME",
"value": "Whitehead"
}
] | null |
[] |
/**
* Helios, OpenSource Monitoring
* Brought to you by the Helios Development Group
*
* Copyright 2007, Helios Development Group and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*
*/
package com.heliosapm.shorthand.instrumentor.shorthand;
import java.io.File;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.regex.Pattern;
import javax.management.ObjectName;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.heliosapm.shorthand.ShorthandProperties;
import com.heliosapm.shorthand.collectors.EnumCollectors;
import com.heliosapm.shorthand.collectors.ICollector;
import com.heliosapm.shorthand.instrumentor.shorthand.gson.GsonProvider;
import com.heliosapm.shorthand.util.URLHelper;
import com.heliosapm.shorthand.util.classload.MultiClassLoader;
import com.heliosapm.shorthand.util.jmx.JMXHelper;
/**
* <p>Title: ShorthandJSONScript</p>
* <p>Description: </p>
* <p>Company: Helios Development Group LLC</p>
* @author Whitehead (nwhitehead AT heliosdev DOT org)
* <p><code>com.heliosapm.shorthand.instrumentor.shorthand.ShorthandJSONScript</code></p>
* <pre>
<ClassName>[+] [(Method Attributes)] <MethodName>[<Signature>] [Invocation Options] <CollectorName>[<BitMask>|<CollectionNames>] <MetricFormat> DISABLED
* </pre>
*/
public class ShorthandJSONScript implements JsonDeserializer<ShorthandJSONScript> {
// ===============================================================================================
// JSON ser/deser Permanent Fields (i.e. not transient, for temp values)
// ===============================================================================================
/** The target class containing the methods to be instrumented. */
@SerializedName("tc") @Expose
protected String className;
/** The target method name to be instrumented. May be a regular expression */
@SerializedName("meth") @Expose
protected String methodName;
/** An optional expression that if provided filters the target methods by matching against the method signature using a regular expression */
@SerializedName("sig") @Expose
protected String methodSignature = ".*";
/** An optional bitmask of enum members in {@link MethodAttribute} that filters method by {@link Modifier} attributes. Defaults to {@link MethodAttribute#DEFAULT_METHOD_MASK} */
@SerializedName("mod") @Expose
protected int methodMod = MethodAttribute.DEFAULT_METHOD_MASK;
/** The enum collector simple class name (if the package has been declared in {@link ShorthandProperties#ENUM_COLLECTOR_PACKAGES_PROP} or the fully qualified name */
@SerializedName("col") @Expose
protected String collectorName;
/** The bitmask of the enabled metric members in the declared enum collector in {@link #collectorName} */
@SerializedName("bitmask") @Expose
protected int bitMask = -1;
/** An expression from which the metric name generated a runtime will be derived from */
@SerializedName("exp")
@Expose
protected String metricExpression;
/** Indicates if injected instrumentation should remain active when the method is called recursively. Defaults to false. */
@SerializedName("rec") @Expose
protected boolean allowRecursion = false;
/** Indicates if all instrumentation should be disabled until the intrumented method completes. Defaults to false. */
@SerializedName("dis") @Expose
protected boolean disableOnCall = false;
// ===============================================================================================
// Permanent Fields (i.e. not transient, for temp values)
// derrived from the deser values and inserted when serialized
// ===============================================================================================
/** Indicates that the name in {@link #className} is a type level annotation and tha target is any classes annotated as such */
protected boolean annotatedClass = false;
/** Indicates that the name in {@link #className} is an interface implying that the target classes are ones that implement this interface */
protected boolean iface = false;
/** Indicates that the target classes are one that inherrit from the class named in {@link #className} */
protected boolean inherritance = false;
/** Indicates that the name in {@link #methodName} is a method level annotation and the target is any method annotated as such */
protected boolean annotatedMethod;
/** The target classloader. Defaults to this class's classloader */
protected ClassLoader targetClassLoader = getClass().getClassLoader();
/** The enum collector class classloaders. Defaults to this class's classloader */
protected ClassLoader collectorClassLoader = getClass().getClassLoader();
// ===============================================================================================
// Transient Fields (i.e. temp values read in by Gson, but then discarded)
// ===============================================================================================
/** The names or ordinals of the enabled metric members in the declared enum collector in {@link #collectorName}. Will be parsed and converted into the bitmask */
@SerializedName("cmbrs")
@Expose(serialize=false)
protected String collectorMembers = null;
/** Alternate expression syntax to specify the {@link ShorthandJSONScript#methodMod} as comma separated names or ordinals of the members in {@link MethodAttribute} */
@SerializedName("mbrs")
@Expose(serialize=false)
protected String methodModMembers = null;
/** Instrumentation target class classloader expressions as comma separated URLs, ObjectNames and keywords */
@SerializedName("tcldr")
@Expose(serialize=false)
protected String targetClassLoaderExpressions = null;
/** Enum collector class classloader expressions as comma separated URLs, ObjectNames and keywords */
@SerializedName("ccldr")
@Expose(serialize=false)
protected String collectorClassLoaderExpressions = null;
/**
* Parses a shorthand json script and returns an array of script objects
* @param scriptText The json script
* @return an array of script objects
*/
public static ShorthandJSONScript[] parse(String scriptText) {
JsonElement element = new JsonParser().parse(scriptText);
if(element.isJsonArray()) {
return GsonProvider.getInstance().getGson().fromJson(scriptText, ShorthandJSONScript[].class);
}
return new ShorthandJSONScript[]{GsonProvider.getInstance().getGson().fromJson(scriptText, ShorthandJSONScript.class)};
}
/** Annotation prefix pattern */
private static final Pattern ANNOT = Pattern.compile("@");
/** Inherritance sufffix pattern */
private static final Pattern PLUS = Pattern.compile("\\+");
/**
* Executed after json deserialization to complete parsing and validate
* @param pre The pre-processed script object
* @param json The json fragment that was just parsed
* @return The validated and post-processed script object
* @throws ShorthandParseFailureException thrown on any validation errors
*/
protected ShorthandJSONScript postDeserialize(ShorthandJSONScript pre, String json) throws ShorthandParseFailureException {
// ======================================================================
// Extract the class name qualifiers
// ======================================================================
if(pre.className==null || pre.className.trim().isEmpty()) throw new ShorthandParseFailureException("Target Class Name was null or empty", json);
pre.className = pre.className.trim();
if(pre.className.startsWith("@")) {
pre.annotatedClass = true;
pre.className = ANNOT.matcher(pre.className).replaceFirst("");
}
if(pre.className.endsWith("+")) {
pre.inherritance = true;
pre.className = PLUS.matcher(pre.className).replaceFirst("");
}
// ======================================================================
// Test for target class classpath overrides
// ======================================================================
if(pre.targetClassLoaderExpressions!=null && !pre.targetClassLoaderExpressions.trim().isEmpty()) {
pre.targetClassLoader = gatherClassLoaders(false, pre.targetClassLoaderExpressions);
}
// ======================================================================
// Locate and validate target class
// ======================================================================
try {
Class.forName(pre.className, false, pre.targetClassLoader);
} catch (Exception ex) {
throw new ShorthandParseFailureException("Failed to load target class [" + pre.className + "]", json, ex);
}
// ======================================================================
// Test for collector class classpath overrides
// ======================================================================
if(pre.collectorClassLoaderExpressions!=null && !pre.collectorClassLoaderExpressions.trim().isEmpty()) {
pre.collectorClassLoader = gatherClassLoaders(false, pre.collectorClassLoaderExpressions);
}
// ======================================================================
// Clean the collector class
// ======================================================================
if(pre.collectorName==null || pre.collectorName.trim().isEmpty()) throw new ShorthandParseFailureException("Collector Class Name was null or empty", json);
pre.collectorName = pre.collectorName.trim();
// ======================================================================
// Locate and validate collector class
// ======================================================================
Class<ICollector<?>> collectorClazz = null;
try {
collectorClazz = resolveCollectorName(pre.collectorName, pre.targetClassLoader);
pre.collectorName = collectorClazz.getName();
} catch (Exception ex) {
throw new ShorthandParseFailureException("Failed to load collector class [" + pre.collectorName + "]", json, ex);
}
// ======================================================================
// Sets the metric bit mask. If the actual bitmask is -1,
// then the bitmask should be validated from the specified collectorMembers
// ======================================================================
if(pre.bitMask==-1) {
if(pre.collectorMembers==null || pre.collectorMembers.trim().isEmpty()) {
throw new ShorthandParseFailureException("Enum collector bitmask was -1 and no collector member names were defined", json);
}
Set<String> names = new HashSet<String>();
for(String s: pre.collectorMembers.trim().split(",")) {
if(s.trim().isEmpty()) continue;
names.add(EnumCollectors.getInstance().getMember(collectorClazz.getName(), s).name());
}
if(names.isEmpty()) {
throw new ShorthandParseFailureException("Enum collector bitmask was -1 and no collector member names were defined", json);
}
pre.bitMask = collectorClazz.getEnumConstants()[0].getBitMaskOf(names.toArray(new String[names.size()]));
pre.collectorMembers=null;
}
// ======================================================================
// Check that metricExpression is not null
// Any other validation we can do here ?
// ======================================================================
if(pre.metricExpression==null || pre.metricExpression.trim().isEmpty()) {
throw new ShorthandParseFailureException("The metric expression was null or empty", json);
}
return pre;
}
/**
* {@inheritDoc}
* @see com.google.gson.JsonDeserializer#deserialize(com.google.gson.JsonElement, java.lang.reflect.Type, com.google.gson.JsonDeserializationContext)
*/
@Override
public ShorthandJSONScript deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
ShorthandJSONScript pre = GsonProvider.getInstance().getNoSerGson().fromJson(json, ShorthandJSONScript.class);
return postDeserialize(pre, json.toString());
}
/**
* Expands the collector name from the passed simple name to the fully qualified class name
* @param collectorName Assumed to be the short name, but will test to see if the name by itself can be loaded
* @param classLoader The classloader to load from
* @return the collector class
*/
protected Class<ICollector<?>> resolveCollectorName(String collectorName, ClassLoader classLoader) {
try {
return (Class<ICollector<?>>) Class.forName(collectorName, false, classLoader);
} catch (ClassNotFoundException cnfx) {}
for(String packageName: ShorthandProperties.getEnumCollectorPackages()) {
try {
return (Class<ICollector<?>>) Class.forName(packageName + "." + collectorName, false, classLoader);
} catch (ClassNotFoundException cnfx) {}
}
throw new RuntimeException("Failed to find enum collector [" + collectorName + "] in any package");
//Class.forName(pre.collectorName, false, pre.targetClassLoader);
}
/**
* Gathers a multi-classloader from the individual class loader expressions in the comma separated expression passed
* @param strict If true, an exception will the thrown if any of the expressions fails
* @param classLoaderExprs The comma separated classloader expressions
* @return a classloader
*/
protected ClassLoader gatherClassLoaders(boolean strict, String classLoaderExprs) {
Set<ClassLoader> classLoaders = new LinkedHashSet<ClassLoader>();
for(String s: classLoaderExprs.split(",")) {
try {
ClassLoader cl = getClassLoader(strict, s);
if(cl!=null) classLoaders.add(cl);
} catch (Exception ex) {
if(strict) throw new RuntimeException("Failed to create classloader", ex);
}
}
if(!classLoaders.isEmpty()) {
return new MultiClassLoader(classLoaders);
}
return getClass().getClassLoader();
}
/**
* Interprets a classloader from the passed expression
* @param strict If true, an exception will the thrown if the expression fails, otherwise this class's classloader will be returned
* @param expression The expression to interpret
* @return A classloader
*/
protected ClassLoader getClassLoader(boolean strict, String expression) {
if(expression==null || expression.trim().isEmpty()) {
if(strict) throw new RuntimeException("The passed expression was null or empty");
return getClass().getClassLoader();
}
String _expr = expression.trim();
if(_expr.equalsIgnoreCase("SYSTEM")) return ClassLoader.getSystemClassLoader();
if(URLHelper.isValidURL(_expr)) {
URL url = URLHelper.toURL(_expr);
return new URLClassLoader(new URL[]{url});
}
if(JMXHelper.isObjectName(_expr)) {
ObjectName on = JMXHelper.objectName(_expr);
if(JMXHelper.getHeliosMBeanServer().isRegistered(on)) {
try {
if(JMXHelper.getHeliosMBeanServer().isInstanceOf(on, ClassLoader.class.getName())) {
return JMXHelper.getHeliosMBeanServer().getClassLoader(on);
}
return JMXHelper.getHeliosMBeanServer().getClassLoaderFor(on);
} catch (Exception ex) {
if(strict) throw new RuntimeException("Failed to get ClassLoader for ObjectName [" + on + "]", ex);
return getClass().getClassLoader();
}
}
if(strict) throw new RuntimeException("Specified ObjectName ClassLoader [" + on + "] was not registered");
return getClass().getClassLoader();
}
File cpFile = new File(_expr);
if(cpFile.canRead()) {
URL url = URLHelper.toURL(cpFile);
return new URLClassLoader(new URL[]{url});
}
if(strict) throw new RuntimeException("Failed to derive ClassLoader from expression [" + _expr + "]");
return getClass().getClassLoader();
}
public static void main(String[] args) {
log("Shorthand Script Test");
ShorthandJSONScript sd = new ShorthandJSONScript();
//com.theice.aop.icebyteman.test.classes.BaseSampleClass massiveCalc(int) [*] '$class/$method/$1'"
sd.className = "java.util.concurrent.ThreadPoolExecutor";
sd.methodName = "massiveCalc";
sd.methodSignature = "int";
sd.collectorName = "MethodInterceptor";
sd.bitMask = 4095;
sd.metricExpression="$class/$method/$1";
//String json = GsonProvider.getInstance().getPrettyPrinter().toJson(sd);
String json = GsonProvider.getInstance().getGson().toJson(sd);
log("JSON:\n%s", json);
// {\"tc\":\"com.heliosapm.shorthand.testclasses.BaseSampleClass\",\"meth\":\"massiveCalc\",\"sig\":\"int\",\"col\":\"MethodInterceptor\",\"bitmask\":4095,\"exp\":\"$class/$method/$1\",\"rec\":false,\"dis\":false}
ShorthandJSONScript[] scripts = parse(json);
log(Arrays.deepToString(scripts));
}
/**
* Creates a new ShorthandJSONScript
*/
public ShorthandJSONScript() {
}
/**
* {@inheritDoc}
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder b = new StringBuilder();
b.append("ShorthandJSONScript [");
b.append("\n\ttargetClass=");
if(annotatedClass) b.append("@");
b.append(className);
if(iface && inherritance) b.append("* ");
if(!iface && inherritance) b.append("+ ");
b.append("\n\tmethodName=").append(methodName);
if (methodSignature != null) {
b.append("\n\tmethodSignature=[");
b.append(methodSignature).append("]");
}
b.append("\n\tmethodMod=").append(methodMod); //FIXME: Decode to member names
b.append("\n\tannotatedMethod=").append(annotatedMethod);
b.append("\n\tcollectorName=").append(collectorName);
b.append("\n\tbitMask=").append(bitMask);
b.append("\n\tmetricExpression=[").append(metricExpression).append("]");
b.append("\n\tallowRecursion=").append(allowRecursion);
b.append("\n\tdisableOnCall=").append(disableOnCall);
b.append("\n]");
return b.toString();
}
/**
* Simple out formatted logger
* @param fmt The format of the message
* @param args The message arguments
*/
public static void log(String fmt, Object...args) {
System.out.println(String.format(fmt, args));
}
/**
* Simple err formatted logger
* @param fmt The format of the message
* @param args The message arguments
*/
public static void loge(String fmt, Object...args) {
System.err.println(String.format(fmt, args));
}
/**
* Simple err formatted logger
* @param fmt The format of the message
* @param t The throwable to print stack trace for
* @param args The message arguments
*/
public static void loge(String fmt, Throwable t, Object...args) {
System.err.println(String.format(fmt, args));
t.printStackTrace(System.err);
}
}
| 19,646 | 0.669398 | 0.667668 | 454 | 42.273129 | 38.324955 | 215 | false | false | 0 | 0 | 0 | 0 | 96 | 0.086888 | 2.044053 | false | false |
12
|
1778d740e25b77398e171c4ae3f249218fdab856
| 27,041,114,137,626 |
a493eb8e1cb098774eacc2d9587f225a1dc96a8c
|
/leetcode/BFS/MinimumCostToMakeAtLeastOneValidPathInAGrid.java
|
268f0a4f663a7c3cc8491578f104834f3481cfb4
|
[] |
no_license
|
lampardchelsea/hello-world
|
https://github.com/lampardchelsea/hello-world
|
52ab8394a4cb20c3aff742f05baa75fdd77daf72
|
b4fa8f0de466778de99be5f2e5ddc38a6269dd41
|
refs/heads/master
| 2023-08-22T02:21:18.109000 | 2023-08-21T01:57:20 | 2023-08-21T01:57:20 | 67,059,187 | 6 | 2 | null | false | 2016-08-31T20:54:48 | 2016-08-31T17:33:13 | 2016-08-31T17:33:13 | 2016-08-31T20:54:47 | 0 | 0 | 0 | 0 | null | null | null |
/**
Refer to
https://leetcode.com/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid/
Given a m x n grid. Each cell of the grid has a sign pointing to the next cell you should visit
if you are currently in this cell. The sign of grid[i][j] can be:
1 which means go to the cell to the right. (i.e go from grid[i][j] to grid[i][j + 1])
2 which means go to the cell to the left. (i.e go from grid[i][j] to grid[i][j - 1])
3 which means go to the lower cell. (i.e go from grid[i][j] to grid[i + 1][j])
4 which means go to the upper cell. (i.e go from grid[i][j] to grid[i - 1][j])
Notice that there could be some invalid signs on the cells of the grid which points outside the grid.
You will initially start at the upper left cell (0,0). A valid path in the grid is a path which
starts from the upper left cell (0,0) and ends at the bottom-right cell (m - 1, n - 1) following
the signs on the grid. The valid path doesn't have to be the shortest.
You can modify the sign on a cell with cost = 1. You can modify the sign on a cell one time only.
Return the minimum cost to make the grid have at least one valid path.
Example 1:
Input: grid = [[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]]
Output: 3
Explanation: You will start at point (0, 0).
The path to (3, 3) is as follows. (0, 0) --> (0, 1) --> (0, 2) --> (0, 3) change the arrow to down with
cost = 1 --> (1, 3) --> (1, 2) --> (1, 1) --> (1, 0) change the arrow to down with cost = 1 --> (2, 0)
--> (2, 1) --> (2, 2) --> (2, 3) change the arrow to down with cost = 1 --> (3, 3)
The total cost = 3.
Example 2:
Input: grid = [[1,1,3],[3,2,2],[1,1,4]]
Output: 0
Explanation: You can follow the path from (0, 0) to (2, 2).
Example 3:
Input: grid = [[1,2],[4,3]]
Output: 1
Example 4:
Input: grid = [[2,2,2],[2,2,2]]
Output: 3
Example 5:
Input: grid = [[4]]
Output: 0
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 100
*/
// Solution 1: BFS + DFS (Similar thought as ShortestBridge.java)
// Refer to
// https://github.com/lampardchelsea/hello-world/blob/master/leetcode/BFS/ShortestBridge.java
// https://leetcode.com/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid/discuss/524886/JavaC%2B%2BPython-BFS-and-DFS
/**
Intuition
One observation is that, (not sure if it's obvious)
we can greedily explore the grid.
We will never detour the path to a node that we can already reach.
In the view of graph,
the fleche indicates a directed edge of weight = 0.
The distance between all neighbours are at most 1.
Now we want to find out the minimum distance between top-left and bottom-right.
Explanation
1.Find out all reachable nodes without changing anything.
2.Save all new visited nodes to a queue bfs.
3.Now iterate the queue
3.1 For each node, try changing it to all 3 other direction
3.2 Save the new reachable and not visited nodes to the queue.
3.3 repeat step 3
Complexity
Time O(NM)
Space O(NM)
*/
class Solution {
int INF = (int) 1e9;
// 1 -> go right, 2 -> go left, 3 -> go lower, 4 -> go upper
int[] dx = new int[] {0,0,1,-1};
int[] dy = new int[] {1,-1,0,0};
public int minCost(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int[][] dp = new int[m][n];
for(int i = 0; i < m; i++) {
Arrays.fill(dp[i], INF);
}
Queue<int[]> q = new LinkedList<int[]>();
int cost = 0;
// Use DFS to find out all reachable nodes without changing anything,
// including following the given fleche direction to move to next node
helper(grid, 0, 0, dp, cost, q);
// The distance between all neighbours are at most 1, use level order
// traverse to find cost for each reachable node
while(!q.isEmpty()) {
cost++;
int size = q.size();
for(int i = 0; i < size; i++) {
int[] cur = q.poll();
int x = cur[0];
int y = cur[1];
// Not follow fleche since we can change direction for each node
// for 1 time now, try all 4 directions for next move
for(int j = 0; j < 4; j++) {
helper(grid, x + dx[j], y + dy[j], dp, cost, q);
}
}
}
return dp[m - 1][n - 1];
}
private void helper(int[][] grid, int x, int y, int[][] dp, int cost, Queue<int[]> q) {
if(x >= 0 && x < grid.length && y >= 0 && y < grid[0].length && dp[x][y] == INF) {
dp[x][y] = cost;
// Save all new visited nodes to a queue
q.offer(new int[] {x, y});
// Find next direction index mapping with fleche directions
int nextDirIndex = grid[x][y] - 1;
int new_x = x + dx[nextDirIndex];
int new_y = y + dy[nextDirIndex];
helper(grid, new_x, new_y, dp, cost, q);
}
}
}
|
UTF-8
|
Java
| 4,885 |
java
|
MinimumCostToMakeAtLeastOneValidPathInAGrid.java
|
Java
|
[
{
"context": "estBridge.java)\n// Refer to\n// https://github.com/lampardchelsea/hello-world/blob/master/leetcode/BFS/ShortestBrid",
"end": 2024,
"score": 0.9997225999832153,
"start": 2010,
"tag": "USERNAME",
"value": "lampardchelsea"
}
] | null |
[] |
/**
Refer to
https://leetcode.com/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid/
Given a m x n grid. Each cell of the grid has a sign pointing to the next cell you should visit
if you are currently in this cell. The sign of grid[i][j] can be:
1 which means go to the cell to the right. (i.e go from grid[i][j] to grid[i][j + 1])
2 which means go to the cell to the left. (i.e go from grid[i][j] to grid[i][j - 1])
3 which means go to the lower cell. (i.e go from grid[i][j] to grid[i + 1][j])
4 which means go to the upper cell. (i.e go from grid[i][j] to grid[i - 1][j])
Notice that there could be some invalid signs on the cells of the grid which points outside the grid.
You will initially start at the upper left cell (0,0). A valid path in the grid is a path which
starts from the upper left cell (0,0) and ends at the bottom-right cell (m - 1, n - 1) following
the signs on the grid. The valid path doesn't have to be the shortest.
You can modify the sign on a cell with cost = 1. You can modify the sign on a cell one time only.
Return the minimum cost to make the grid have at least one valid path.
Example 1:
Input: grid = [[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]]
Output: 3
Explanation: You will start at point (0, 0).
The path to (3, 3) is as follows. (0, 0) --> (0, 1) --> (0, 2) --> (0, 3) change the arrow to down with
cost = 1 --> (1, 3) --> (1, 2) --> (1, 1) --> (1, 0) change the arrow to down with cost = 1 --> (2, 0)
--> (2, 1) --> (2, 2) --> (2, 3) change the arrow to down with cost = 1 --> (3, 3)
The total cost = 3.
Example 2:
Input: grid = [[1,1,3],[3,2,2],[1,1,4]]
Output: 0
Explanation: You can follow the path from (0, 0) to (2, 2).
Example 3:
Input: grid = [[1,2],[4,3]]
Output: 1
Example 4:
Input: grid = [[2,2,2],[2,2,2]]
Output: 3
Example 5:
Input: grid = [[4]]
Output: 0
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 100
*/
// Solution 1: BFS + DFS (Similar thought as ShortestBridge.java)
// Refer to
// https://github.com/lampardchelsea/hello-world/blob/master/leetcode/BFS/ShortestBridge.java
// https://leetcode.com/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid/discuss/524886/JavaC%2B%2BPython-BFS-and-DFS
/**
Intuition
One observation is that, (not sure if it's obvious)
we can greedily explore the grid.
We will never detour the path to a node that we can already reach.
In the view of graph,
the fleche indicates a directed edge of weight = 0.
The distance between all neighbours are at most 1.
Now we want to find out the minimum distance between top-left and bottom-right.
Explanation
1.Find out all reachable nodes without changing anything.
2.Save all new visited nodes to a queue bfs.
3.Now iterate the queue
3.1 For each node, try changing it to all 3 other direction
3.2 Save the new reachable and not visited nodes to the queue.
3.3 repeat step 3
Complexity
Time O(NM)
Space O(NM)
*/
class Solution {
int INF = (int) 1e9;
// 1 -> go right, 2 -> go left, 3 -> go lower, 4 -> go upper
int[] dx = new int[] {0,0,1,-1};
int[] dy = new int[] {1,-1,0,0};
public int minCost(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int[][] dp = new int[m][n];
for(int i = 0; i < m; i++) {
Arrays.fill(dp[i], INF);
}
Queue<int[]> q = new LinkedList<int[]>();
int cost = 0;
// Use DFS to find out all reachable nodes without changing anything,
// including following the given fleche direction to move to next node
helper(grid, 0, 0, dp, cost, q);
// The distance between all neighbours are at most 1, use level order
// traverse to find cost for each reachable node
while(!q.isEmpty()) {
cost++;
int size = q.size();
for(int i = 0; i < size; i++) {
int[] cur = q.poll();
int x = cur[0];
int y = cur[1];
// Not follow fleche since we can change direction for each node
// for 1 time now, try all 4 directions for next move
for(int j = 0; j < 4; j++) {
helper(grid, x + dx[j], y + dy[j], dp, cost, q);
}
}
}
return dp[m - 1][n - 1];
}
private void helper(int[][] grid, int x, int y, int[][] dp, int cost, Queue<int[]> q) {
if(x >= 0 && x < grid.length && y >= 0 && y < grid[0].length && dp[x][y] == INF) {
dp[x][y] = cost;
// Save all new visited nodes to a queue
q.offer(new int[] {x, y});
// Find next direction index mapping with fleche directions
int nextDirIndex = grid[x][y] - 1;
int new_x = x + dx[nextDirIndex];
int new_y = y + dy[nextDirIndex];
helper(grid, new_x, new_y, dp, cost, q);
}
}
}
| 4,885 | 0.596929 | 0.564585 | 127 | 37.464565 | 31.592085 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.929134 | false | false |
12
|
04ded6fc7738213ce97551578f80a51ae50fb7b2
| 27,041,114,137,275 |
9e51379675bb0e7f1eaf326c7c823b8160ab77e0
|
/Lesson6/src/Car.java
|
17030b27c8f048a29e72c960d3568f4822567aa3
|
[] |
no_license
|
domestos/LogusHomeWork
|
https://github.com/domestos/LogusHomeWork
|
01356cdca5b75f14250b1b23a8bb1a3b3b6063d5
|
bb81b212854d8d97a3223f4cd7a7bbc0a25e2620
|
refs/heads/master
| 2021-01-10T12:16:55.609000 | 2015-11-11T20:26:00 | 2015-11-11T20:26:00 | 45,189,590 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* Created by v.pelenskyi on 04.11.2015.
*/
public class Car {
private Wheel wheel;
private SteeringWheel steeringWheel;
private Body body;
public Car(Wheel wheel, SteeringWheel steeringWheel, Body body) {
this.wheel = wheel;
this.steeringWheel = steeringWheel;
this.body = body;
}
public Wheel getWheel() {
return wheel;
}
public void setWheel(Wheel wheel) {
this.wheel = wheel;
}
public SteeringWheel getSteeringWheel() {
return steeringWheel;
}
public void setSteeringWheel(SteeringWheel steeringWheel) {
this.steeringWheel = steeringWheel;
}
public Body getBody() {
return body;
}
public void setBody(Body body) {
this.body = body;
}
public void reduceWheel(){
wheel.setRadius(wheel.getRadius()/2);
}
public void changedStreeringWhellType(StreeringWheelType type){
getSteeringWheel().setType(type);
}
@Override
public String toString() {
return "Car{" +
"wheel=" + wheel +
", steeringWheel=" + steeringWheel +
", body=" + body +
'}';
}
}
|
UTF-8
|
Java
| 1,223 |
java
|
Car.java
|
Java
|
[
{
"context": "/**\n * Created by v.pelenskyi on 04.11.2015.\n */\npublic class Car {\n\n privat",
"end": 29,
"score": 0.9820892214775085,
"start": 18,
"tag": "NAME",
"value": "v.pelenskyi"
}
] | null |
[] |
/**
* Created by v.pelenskyi on 04.11.2015.
*/
public class Car {
private Wheel wheel;
private SteeringWheel steeringWheel;
private Body body;
public Car(Wheel wheel, SteeringWheel steeringWheel, Body body) {
this.wheel = wheel;
this.steeringWheel = steeringWheel;
this.body = body;
}
public Wheel getWheel() {
return wheel;
}
public void setWheel(Wheel wheel) {
this.wheel = wheel;
}
public SteeringWheel getSteeringWheel() {
return steeringWheel;
}
public void setSteeringWheel(SteeringWheel steeringWheel) {
this.steeringWheel = steeringWheel;
}
public Body getBody() {
return body;
}
public void setBody(Body body) {
this.body = body;
}
public void reduceWheel(){
wheel.setRadius(wheel.getRadius()/2);
}
public void changedStreeringWhellType(StreeringWheelType type){
getSteeringWheel().setType(type);
}
@Override
public String toString() {
return "Car{" +
"wheel=" + wheel +
", steeringWheel=" + steeringWheel +
", body=" + body +
'}';
}
}
| 1,223 | 0.575634 | 0.568275 | 66 | 17.530304 | 18.997784 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.287879 | false | false |
12
|
6cf26ecb6fd79800f3b922138dc3d2677c583132
| 3,049,426,803,107 |
0aa77f8809a6208a091dbd71ddb75bd3a47beaac
|
/sunnly-cache/src/main/java/wang/sunnly/cache/controller/CacheController.java
|
67004c99c047a2f7feb5eb99068d4e5f9b3d5167
|
[] |
no_license
|
sunnly/enable
|
https://github.com/sunnly/enable
|
6c013ed7aeb6c01ca8a7d43109e566f7d645fd16
|
8f6075059ea73a0d67b9f121578c1c9a44636456
|
refs/heads/master
| 2022-09-18T01:27:00.532000 | 2019-09-08T13:58:25 | 2019-09-08T13:58:25 | 207,119,335 | 0 | 0 | null | false | 2022-09-01T23:22:59 | 2019-09-08T13:48:05 | 2019-09-08T13:54:40 | 2022-09-01T23:22:57 | 726 | 0 | 0 | 13 |
CSS
| false | false |
package wang.sunnly.cache.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import wang.sunnly.cache.service.CacheService;
/**
* CacheController
*
* @author Sunnly
* @create 2019/7/8 9:57
*/
@RestController
@RequestMapping("cache")
public class CacheController {
@Autowired
private CacheService cacheService;
@GetMapping("/def/{username}/{password}")
public String def(@PathVariable("username") String username,
@PathVariable("password") String password){
return cacheService.def(username,password);
}
@GetMapping("/mer/{username}/{password}")
public String get(@PathVariable("username") String username,
@PathVariable("password") String password){
return cacheService.mer(username,password);
}
@GetMapping("/ehc/{username}/{password}")
public String ehc(@PathVariable("username") String username,
@PathVariable("password") String password){
return cacheService.ehc(username,password);
}
@GetMapping("/red/{username}/{password}")
public String red(@PathVariable("username") String username,
@PathVariable("password") String password){
return cacheService.red(username,password);
}
}
|
UTF-8
|
Java
| 1,599 |
java
|
CacheController.java
|
Java
|
[
{
"context": "acheService;\n\n/**\n * CacheController\n *\n * @author Sunnly\n * @create 2019/7/8 9:57\n */\n@RestController\n@Req",
"end": 499,
"score": 0.9995965361595154,
"start": 493,
"tag": "USERNAME",
"value": "Sunnly"
}
] | null |
[] |
package wang.sunnly.cache.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import wang.sunnly.cache.service.CacheService;
/**
* CacheController
*
* @author Sunnly
* @create 2019/7/8 9:57
*/
@RestController
@RequestMapping("cache")
public class CacheController {
@Autowired
private CacheService cacheService;
@GetMapping("/def/{username}/{password}")
public String def(@PathVariable("username") String username,
@PathVariable("password") String password){
return cacheService.def(username,password);
}
@GetMapping("/mer/{username}/{password}")
public String get(@PathVariable("username") String username,
@PathVariable("password") String password){
return cacheService.mer(username,password);
}
@GetMapping("/ehc/{username}/{password}")
public String ehc(@PathVariable("username") String username,
@PathVariable("password") String password){
return cacheService.ehc(username,password);
}
@GetMapping("/red/{username}/{password}")
public String red(@PathVariable("username") String username,
@PathVariable("password") String password){
return cacheService.red(username,password);
}
}
| 1,599 | 0.707317 | 0.701689 | 44 | 35.340908 | 24.747766 | 65 | true | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.477273 | false | false |
12
|
37e129926e90d53d8eb5de72cd54482fe5ac7666
| 8,400,956,052,107 |
4ef8088efa2587d1ebeb6888057cf390e8dd7b4d
|
/src/main/java/com/codedifferently/BasicFunction.java
|
fe3d5a40dc982f6d682042b38002cea12be990bc
|
[] |
no_license
|
esanvee/StayReadyLab02
|
https://github.com/esanvee/StayReadyLab02
|
224c1a61da0dba2561ca5fda618ddec2d49b5aac
|
ec693647e9ae9da238f66d7c2e61edfebf409657
|
refs/heads/master
| 2022-11-15T20:11:31.111000 | 2020-07-06T22:17:09 | 2020-07-06T22:17:09 | 275,469,630 | 0 | 0 | null | true | 2020-06-27T23:23:26 | 2020-06-27T23:23:25 | 2020-06-16T21:41:32 | 2020-06-27T22:33:59 | 7 | 0 | 0 | 0 | null | false | false |
package com.codedifferently;
public class BasicFunction {
public static double add(double num1, double num2) {
double result = num1 + num2;
return result;
}
public static double subtract(double num1, double num2) {
double result = num1 - num2;
return result;
}
public static double multiply(double num1, double num2) {
double result = num1 * num2;
return result;
}
public static double divide(double num1, double num2) {
double result = num1 / num2;
return result;
}
public static double square(double num) {
double result = num * num;
return result;
}
public static double exponent(double num1, double exp) {
double result = 0;
if (exp >= 0) {
result = Math.pow(num1, exp);
}else{
System.out.println("Cannot multiply by a power below zero.\n\n");
}
return result;
}
public static double sqrt(double num) {
double result = 0;
if (num >= 0) {
result = Math.sqrt(num);
}else{
System.out.println("Cannot calculate the square root of a negative.\n\n");
}
return result;
}
public static double invert(double num){
return num * -1;
}
}
|
UTF-8
|
Java
| 1,349 |
java
|
BasicFunction.java
|
Java
|
[] | null |
[] |
package com.codedifferently;
public class BasicFunction {
public static double add(double num1, double num2) {
double result = num1 + num2;
return result;
}
public static double subtract(double num1, double num2) {
double result = num1 - num2;
return result;
}
public static double multiply(double num1, double num2) {
double result = num1 * num2;
return result;
}
public static double divide(double num1, double num2) {
double result = num1 / num2;
return result;
}
public static double square(double num) {
double result = num * num;
return result;
}
public static double exponent(double num1, double exp) {
double result = 0;
if (exp >= 0) {
result = Math.pow(num1, exp);
}else{
System.out.println("Cannot multiply by a power below zero.\n\n");
}
return result;
}
public static double sqrt(double num) {
double result = 0;
if (num >= 0) {
result = Math.sqrt(num);
}else{
System.out.println("Cannot calculate the square root of a negative.\n\n");
}
return result;
}
public static double invert(double num){
return num * -1;
}
}
| 1,349 | 0.555226 | 0.538176 | 60 | 21.5 | 21.354548 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.433333 | false | false |
12
|
d09eba842ee16a071c67b3d0983fd66d4575edf4
| 11,974,368,858,047 |
c7842a764ab01801bc974e54cc39ec3d335b0d62
|
/src/no26/Main.java
|
7cc4d470ede329b6adf852120f532e0cc6dd807f
|
[] |
no_license
|
RYUSUKJONG/algorism
|
https://github.com/RYUSUKJONG/algorism
|
ccdcf885bc724811f8107ceca55278d7ab30825e
|
ff82660c5ef489b8908e59fc8f4178d89caf9411
|
refs/heads/master
| 2023-05-12T02:46:32.642000 | 2021-05-17T14:58:48 | 2021-05-17T14:58:48 | 366,966,161 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package no26;
public class Main {
public static void main(String[] args) {
int a = 734;
int b = 896;
int arrA[] = new int[3];
int arrB[] = new int[3];
do {
for (int i = arrA.length-1; i >=0 ; i--) {
arrA[i] = a%10;
a /=10;
}
}while (a>0);
do {
for (int i = arrB.length-1; i >=0 ; i--) {
arrB[i] = b%10;
b /=10;
}
}while (b>0);
int reA = 0 ;
int n1 = 1;
for (int i = 0; i <arrA.length ; i++) {
reA += arrA[i] * n1;
n1=n1*10;
}
int reB = 0 ;
int n2 = 1;
for (int i = 0; i <arrB.length ; i++) {
reB += arrB[i] * n2;
n2=n2*10;
}
System.out.println(reA);
System.out.println(reB);
if(reA > reB){
System.out.println(reA);
}
else if(reB > reA){
System.out.println(reB);
}
else{
System.out.println("같습니다");
}
}
};
|
UTF-8
|
Java
| 1,119 |
java
|
Main.java
|
Java
|
[] | null |
[] |
package no26;
public class Main {
public static void main(String[] args) {
int a = 734;
int b = 896;
int arrA[] = new int[3];
int arrB[] = new int[3];
do {
for (int i = arrA.length-1; i >=0 ; i--) {
arrA[i] = a%10;
a /=10;
}
}while (a>0);
do {
for (int i = arrB.length-1; i >=0 ; i--) {
arrB[i] = b%10;
b /=10;
}
}while (b>0);
int reA = 0 ;
int n1 = 1;
for (int i = 0; i <arrA.length ; i++) {
reA += arrA[i] * n1;
n1=n1*10;
}
int reB = 0 ;
int n2 = 1;
for (int i = 0; i <arrB.length ; i++) {
reB += arrB[i] * n2;
n2=n2*10;
}
System.out.println(reA);
System.out.println(reB);
if(reA > reB){
System.out.println(reA);
}
else if(reB > reA){
System.out.println(reB);
}
else{
System.out.println("같습니다");
}
}
};
| 1,119 | 0.358236 | 0.320432 | 55 | 19.218182 | 14.923674 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false |
12
|
4208d08d0329f236f2a4617120660cc76ee494d8
| 7,636,451,921,240 |
a00deca40e96284f55881150a6491a6d36382f4f
|
/java/com/example/healthfirst/MainActivity2.java
|
21ef3e9d681aac03e6c765efd990bfb7b967fbc4
|
[] |
no_license
|
saana23/Health-First-App
|
https://github.com/saana23/Health-First-App
|
7433044b4f30806ba8631da0c6ab96aae87e8ef2
|
8510231a4c5980f8eeaeff48797b7fd70ea856a0
|
refs/heads/main
| 2023-06-18T13:13:47.970000 | 2021-07-24T17:54:26 | 2021-07-24T17:54:26 | 389,163,687 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.healthfirst;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity2 extends AppCompatActivity
{
ListView lv;
Context context;
ArrayList progList;
MyListAdapter adapter;
static public boolean active = false;
public static Integer[] progImages=
{
R.drawable.anchovy1,
R.drawable.carp1,
R.drawable.chicken1,
R.drawable.clam1,
R.drawable.cod1,
R.drawable.crab1,
R.drawable.egg1,
R.drawable.flyingfish1,
R.drawable.galjoen1,
R.drawable.lobster1,
R.drawable.mackerel1,
R.drawable.marlin1,
R.drawable.mussel1,
R.drawable.mutton1,
R.drawable.pork1,
R.drawable.salmon1,
R.drawable.sardines1,
R.drawable.seaurchin1,
R.drawable.shrimp1,
R.drawable.squid1,
R.drawable.trout1,
R.drawable.tuna1,
R.drawable.turkey1,
R.drawable.whole1
};
public static String[] progNames=
{
"Anchovy fish",
"Carp fish",
"Chicken",
"Clam",
"Cod fish",
"Crab",
"Egg white",
"Flying fish",
"Galjoen fish",
"Lobster",
"Mackerel",
"Marlin fish",
"Mussel",
"Mutton",
"Pork",
"Salmon",
"Sardines",
"Sea urchin",
"Shrimp",
"Squid",
"Trout",
"Tuna",
"Turkey",
"Whole egg"
};
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.menu,menu);
MenuItem menuItem=menu.findItem(R.id.searchview);
SearchView searchView=(SearchView) menuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener()
{
@Override
public boolean onQueryTextSubmit(String query)
{
return false;
}
@Override
public boolean onQueryTextChange(String newText)
{
adapter.getFilter().filter(newText);
return true;
}
});
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item)
{
int id=item.getItemId();
if(id== R.id.searchview)
{
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onStart() {
super.onStart();
active = true;
}
@Override
protected void onStop() {
super.onStop();
active = false;
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); //enable full screen
List<FoodItems> foodItems = new ArrayList<>();
for(int i = 0 ; i < progNames.length; i++)
{
foodItems.add(new FoodItems(progNames[i],progImages[i]));
}
adapter=new MyListAdapter(this,foodItems);
lv=(ListView)findViewById(R.id.listview2);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
TextView foodname = (TextView)view.findViewById(R.id.FoodItemName);
Intent intent = new Intent(MainActivity2.this, MainActivity4.class);
intent.putExtra("foodname",foodname.getText().toString());
intent.putExtra("VegValue", true);
startActivity(intent);
}
});
}
}
|
UTF-8
|
Java
| 4,688 |
java
|
MainActivity2.java
|
Java
|
[] | null |
[] |
package com.example.healthfirst;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity2 extends AppCompatActivity
{
ListView lv;
Context context;
ArrayList progList;
MyListAdapter adapter;
static public boolean active = false;
public static Integer[] progImages=
{
R.drawable.anchovy1,
R.drawable.carp1,
R.drawable.chicken1,
R.drawable.clam1,
R.drawable.cod1,
R.drawable.crab1,
R.drawable.egg1,
R.drawable.flyingfish1,
R.drawable.galjoen1,
R.drawable.lobster1,
R.drawable.mackerel1,
R.drawable.marlin1,
R.drawable.mussel1,
R.drawable.mutton1,
R.drawable.pork1,
R.drawable.salmon1,
R.drawable.sardines1,
R.drawable.seaurchin1,
R.drawable.shrimp1,
R.drawable.squid1,
R.drawable.trout1,
R.drawable.tuna1,
R.drawable.turkey1,
R.drawable.whole1
};
public static String[] progNames=
{
"Anchovy fish",
"Carp fish",
"Chicken",
"Clam",
"Cod fish",
"Crab",
"Egg white",
"Flying fish",
"Galjoen fish",
"Lobster",
"Mackerel",
"Marlin fish",
"Mussel",
"Mutton",
"Pork",
"Salmon",
"Sardines",
"Sea urchin",
"Shrimp",
"Squid",
"Trout",
"Tuna",
"Turkey",
"Whole egg"
};
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.menu,menu);
MenuItem menuItem=menu.findItem(R.id.searchview);
SearchView searchView=(SearchView) menuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener()
{
@Override
public boolean onQueryTextSubmit(String query)
{
return false;
}
@Override
public boolean onQueryTextChange(String newText)
{
adapter.getFilter().filter(newText);
return true;
}
});
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item)
{
int id=item.getItemId();
if(id== R.id.searchview)
{
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onStart() {
super.onStart();
active = true;
}
@Override
protected void onStop() {
super.onStop();
active = false;
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); //enable full screen
List<FoodItems> foodItems = new ArrayList<>();
for(int i = 0 ; i < progNames.length; i++)
{
foodItems.add(new FoodItems(progNames[i],progImages[i]));
}
adapter=new MyListAdapter(this,foodItems);
lv=(ListView)findViewById(R.id.listview2);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
TextView foodname = (TextView)view.findViewById(R.id.FoodItemName);
Intent intent = new Intent(MainActivity2.this, MainActivity4.class);
intent.putExtra("foodname",foodname.getText().toString());
intent.putExtra("VegValue", true);
startActivity(intent);
}
});
}
}
| 4,688 | 0.547142 | 0.540742 | 167 | 26.083832 | 21.132719 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.658683 | false | false |
12
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.