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
552cc9307749a132b37e8f8d5dd96d187075d2b9
13,915,694,083,632
9be9cbc97f39f04677446ba643a9fc118df966e0
/app/src/main/java/bupt/com/travelandroid/Bean/response/PhotoInfo.java
73163cd9f7794b6c5f5a67be9f1ca0afb794db84
[]
no_license
SmallJson/TravelAndroid
https://github.com/SmallJson/TravelAndroid
1cf6497147c5413b74268e4963ebc6d959a95f69
7e99a9a417288dc0a707ea99429860e21b47a047
refs/heads/master
2020-03-17T23:20:14.631000
2019-06-14T02:39:14
2019-06-14T02:39:14
134,040,407
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package bupt.com.travelandroid.Bean.response; import java.util.List; import bupt.com.travelandroid.Bean.PlaceBean; import bupt.com.travelandroid.Bean.UserInfo; //封装相册信息的类 public class PhotoInfo { public UserInfo userInfo; public String time; public PlaceBean place; public UserInfo getUserInfo() { return userInfo; } public void setUserInfo(UserInfo userInfo) { this.userInfo = userInfo; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public PlaceBean getPlace() { return place; } public void setPlace(PlaceBean place) { this.place = place; } }
UTF-8
Java
734
java
PhotoInfo.java
Java
[]
null
[]
package bupt.com.travelandroid.Bean.response; import java.util.List; import bupt.com.travelandroid.Bean.PlaceBean; import bupt.com.travelandroid.Bean.UserInfo; //封装相册信息的类 public class PhotoInfo { public UserInfo userInfo; public String time; public PlaceBean place; public UserInfo getUserInfo() { return userInfo; } public void setUserInfo(UserInfo userInfo) { this.userInfo = userInfo; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public PlaceBean getPlace() { return place; } public void setPlace(PlaceBean place) { this.place = place; } }
734
0.64624
0.64624
43
15.697675
16.244549
48
false
false
0
0
0
0
0
0
0.302326
false
false
10
e2f093586626aa21a9f162ebb83cea66f67dffb5
7,344,394,112,178
f4f0dfbccebe2923d1fc77edc67d2c6caa1d0094
/exec/backend/SpringSera/src/main/java/com/ssafy/sera/Controller/Request/UserRequest.java
fb8b9c868f7c2c33997e74c1fb4a2ac3b66356f2
[]
no_license
jihyeong2/PJT-Sera
https://github.com/jihyeong2/PJT-Sera
7cbbaa3fc0468c8322b3d6e1f9a2befeb9ecd238
8529cfa3434aab3527f4a04cd8306dcda822cc2c
refs/heads/master
2023-05-22T21:58:25.326000
2021-06-08T13:57:46
2021-06-08T13:57:46
356,801,380
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ssafy.sera.Controller.Request; import com.ssafy.sera.Domain.Skin.SkinDto; import io.swagger.annotations.ApiModel; import lombok.Data; import javax.persistence.Column; @Data @ApiModel(value = "클라이언트 측에서 보내주는 User 객체 정보", description = "회원가입 시 사용된다.") public class UserRequest { private Long userId; private String userLoginId; private String userPassword; private String userNickname; private int userAge; private String userPhone; private String userGender; private SkinDto skinId; // private String skinId; // private String skinType; }
UTF-8
Java
641
java
UserRequest.java
Java
[]
null
[]
package com.ssafy.sera.Controller.Request; import com.ssafy.sera.Domain.Skin.SkinDto; import io.swagger.annotations.ApiModel; import lombok.Data; import javax.persistence.Column; @Data @ApiModel(value = "클라이언트 측에서 보내주는 User 객체 정보", description = "회원가입 시 사용된다.") public class UserRequest { private Long userId; private String userLoginId; private String userPassword; private String userNickname; private int userAge; private String userPhone; private String userGender; private SkinDto skinId; // private String skinId; // private String skinType; }
641
0.746193
0.746193
22
25.863636
17.202789
76
false
false
0
0
0
0
0
0
0.727273
false
false
10
799d8aaeecb3649de9756e7252f2217145d2fa7b
21,423,296,921,716
55fbf4f02f9d20544105ff596d569d979afa0eae
/BookApp/src/main/java/com/example/BookApp/model/dto/BookDTO.java
b1b9dbe3297d319abc926b3fbd5b690b981b7b08
[]
no_license
teabogatinoska/BookApp
https://github.com/teabogatinoska/BookApp
89a8d48c1454baa8c369237fb4c8ec7deb752fc5
e5833e03dcda3d72357d12ff5ff2c169d9a6fc77
refs/heads/master
2023-05-06T13:28:14.828000
2021-05-31T09:09:58
2021-05-31T09:09:58
372,431,160
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.BookApp.model.dto; import com.example.BookApp.model.Author; import lombok.Data; import javax.persistence.*; @Data public class BookDTO { private String bookTitle; private long ISBN; private int year; @ManyToOne private Author author; public BookDTO(String bookTitle, long ISBN, int year, Author author) { this.bookTitle = bookTitle; this.ISBN = ISBN; this.year = year; this.author = author; } }
UTF-8
Java
488
java
BookDTO.java
Java
[]
null
[]
package com.example.BookApp.model.dto; import com.example.BookApp.model.Author; import lombok.Data; import javax.persistence.*; @Data public class BookDTO { private String bookTitle; private long ISBN; private int year; @ManyToOne private Author author; public BookDTO(String bookTitle, long ISBN, int year, Author author) { this.bookTitle = bookTitle; this.ISBN = ISBN; this.year = year; this.author = author; } }
488
0.659836
0.659836
31
14.741936
17.378088
74
false
false
0
0
0
0
0
0
0.483871
false
false
10
a1504bc2c7efc3e575a58440203fb1187d5f5bd6
18,580,028,571,687
c38a9ac5ec816dfd7ca9bde83fa90681c6ffffa8
/src/main/java/fr/epsi/mspr/msprapi/entities/Pharmacy.java
e2e55ee0ef7215e47cbee471e4e56a934a2d2a35
[]
no_license
mspr-conception-epsi/back
https://github.com/mspr-conception-epsi/back
085568fef88993f1e0200c5c413d39085eb235fc
7ab52c0110e40fbce793faa15247dd8feed8df52
refs/heads/master
2020-05-17T07:17:10.022000
2019-10-02T22:43:25
2019-10-02T22:43:25
183,575,794
0
0
null
false
2019-10-02T22:57:03
2019-04-26T07:02:13
2019-10-02T22:43:31
2019-10-02T22:56:44
84
0
0
1
Java
false
false
package fr.epsi.mspr.msprapi.entities; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; @Entity public class Pharmacy { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; private String name; private String address; @Column(name="gps_lat") private float gpsLat; @Column(name="gps_long") private float gpsLong; @OneToMany(mappedBy="pharmacy") Set<Request> request; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public float getGpsLat() { return gpsLat; } public void setGpsLat(float gpsLat) { this.gpsLat = gpsLat; } public float getGpsLong() { return gpsLong; } public void setGpsLong(float gpsLong) { this.gpsLong = gpsLong; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Pharmacy [id=").append(id).append(", name=").append(name).append(", address=").append(address) .append(", gpsLat=").append(gpsLat).append(", gpsLong=").append(gpsLong).append("]"); return builder.toString(); } }
UTF-8
Java
1,520
java
Pharmacy.java
Java
[]
null
[]
package fr.epsi.mspr.msprapi.entities; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; @Entity public class Pharmacy { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; private String name; private String address; @Column(name="gps_lat") private float gpsLat; @Column(name="gps_long") private float gpsLong; @OneToMany(mappedBy="pharmacy") Set<Request> request; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public float getGpsLat() { return gpsLat; } public void setGpsLat(float gpsLat) { this.gpsLat = gpsLat; } public float getGpsLong() { return gpsLong; } public void setGpsLong(float gpsLong) { this.gpsLong = gpsLong; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Pharmacy [id=").append(id).append(", name=").append(name).append(", address=").append(address) .append(", gpsLat=").append(gpsLat).append(", gpsLong=").append(gpsLong).append("]"); return builder.toString(); } }
1,520
0.686842
0.686842
65
21.384615
19.727133
112
false
false
0
0
0
0
0
0
1.492308
false
false
10
7bac09e85f9c01e59ded9da8d7a2cd276d16501e
22,986,665,032,167
26379ac7fd13544b8233317888acdb56b68483ce
/배열/src/Ex5.java
dbbcb627d4b63acdae48818d7d63b6049619582f
[]
no_license
cjy2103/SummerjavaStud
https://github.com/cjy2103/SummerjavaStud
1890a86dbaced668995178dc80885e36a9964855
8605ab9d2e5616871d5b4061b118430aca6b5723
refs/heads/master
2020-06-13T13:05:26.780000
2019-09-24T12:58:15
2019-09-24T12:58:15
194,663,947
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Arrays; public class Ex5 { public static void main(String[] args) { int [] score = {40 ,60,70 ,80,100 ,35}; Arrays.sort(score); System.out.println(score[score.length-1]); System.out.println(score[0]); } }
UTF-8
Java
273
java
Ex5.java
Java
[]
null
[]
import java.util.Arrays; public class Ex5 { public static void main(String[] args) { int [] score = {40 ,60,70 ,80,100 ,35}; Arrays.sort(score); System.out.println(score[score.length-1]); System.out.println(score[0]); } }
273
0.567766
0.509158
10
25.299999
18.077887
50
false
false
0
0
0
0
0
0
1
false
false
10
5d5afac0747577042c57bfd77591630e9620e266
858,993,501,890
b2a087dca3c12cb79ee2055b247f5980bcdbad3d
/src/main/java/net/thiagomarinho/jkstest/commands/SignMessage.java
84b8ac83efc5e275cfee64ed5ed2f7f33dc67cdf
[]
no_license
thiagomarinho/jks-test
https://github.com/thiagomarinho/jks-test
57c21e76f9451d470763cf852e9fc8eea10b2297
71853e9fd762cd4c4dd2cbaa07622e1926729f5e
refs/heads/master
2020-04-13T02:35:01.832000
2018-12-23T16:25:05
2018-12-23T16:25:05
162,906,298
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.thiagomarinho.jkstest.commands; import com.beust.jcommander.Parameter; import net.thiagomarinho.jkstest.Utils; public class SignMessage extends DefaultCommandWithKeystore { @Parameter(names = {"--algorithm"}) private String signatureAlgorithm = "SHA256withRSA"; @Parameter(names = {"-m", "--message"}) private String message = Utils.DEFAULT_MESSAGE; @Parameter(names = {"--output-file"}) private String outputFile = "message.txt"; @Parameter(names = {"--signature-file"}) private String signatureFile = "signature.txt"; @Parameter(names = {"--certificate-file"}) private String certificateFile = "certificate.txt"; @Override public void runCommand() { String signatureForMessage = keyStoreHandler().signMessage(message, signatureAlgorithm); writeFile(outputFile, message); writeFile(signatureFile, signatureForMessage); writeFile(certificateFile, keyStoreHandler().certificateContent()); } }
UTF-8
Java
999
java
SignMessage.java
Java
[]
null
[]
package net.thiagomarinho.jkstest.commands; import com.beust.jcommander.Parameter; import net.thiagomarinho.jkstest.Utils; public class SignMessage extends DefaultCommandWithKeystore { @Parameter(names = {"--algorithm"}) private String signatureAlgorithm = "SHA256withRSA"; @Parameter(names = {"-m", "--message"}) private String message = Utils.DEFAULT_MESSAGE; @Parameter(names = {"--output-file"}) private String outputFile = "message.txt"; @Parameter(names = {"--signature-file"}) private String signatureFile = "signature.txt"; @Parameter(names = {"--certificate-file"}) private String certificateFile = "certificate.txt"; @Override public void runCommand() { String signatureForMessage = keyStoreHandler().signMessage(message, signatureAlgorithm); writeFile(outputFile, message); writeFile(signatureFile, signatureForMessage); writeFile(certificateFile, keyStoreHandler().certificateContent()); } }
999
0.70971
0.706707
33
29.272728
26.521887
96
false
false
0
0
0
0
0
0
0.515152
false
false
10
b8002cac98598a6f4f691f7ab579cc104f2de657
32,143,535,304,088
b63196153e5c74fc794bcaa79ff4d0be2c9d950b
/src/main/java/com/github/datalking/aop/aspectj/MetadataAwareAspectInstanceFactory.java
672fafeba8447ebcabb4cc5ef968170719fe349d
[ "MIT" ]
permissive
datalking/play-mvc
https://github.com/datalking/play-mvc
53004f7319ee42e9252f8decb7f096fed3489652
35e3f4900fae4690e397d915564d3ca034b26ebb
refs/heads/master
2021-05-26T04:45:11.656000
2020-12-06T13:10:21
2020-12-06T13:10:21
127,446,313
0
1
MIT
false
2020-12-06T10:15:00
2018-03-30T15:55:59
2020-12-06T10:13:34
2020-12-06T10:14:42
5,541
0
1
0
JavaScript
false
false
package com.github.datalking.aop.aspectj; /** * @author yaoo on 4/19/18 */ public interface MetadataAwareAspectInstanceFactory extends AspectInstanceFactory { AspectMetadata getAspectMetadata(); //Object getAspectCreationMutex(); }
UTF-8
Java
247
java
MetadataAwareAspectInstanceFactory.java
Java
[ { "context": " com.github.datalking.aop.aspectj;\n\n/**\n * @author yaoo on 4/19/18\n */\npublic interface MetadataAwareAspe", "end": 62, "score": 0.9996347427368164, "start": 58, "tag": "USERNAME", "value": "yaoo" } ]
null
[]
package com.github.datalking.aop.aspectj; /** * @author yaoo on 4/19/18 */ public interface MetadataAwareAspectInstanceFactory extends AspectInstanceFactory { AspectMetadata getAspectMetadata(); //Object getAspectCreationMutex(); }
247
0.761134
0.740891
13
18
24.834839
83
false
false
0
0
0
0
0
0
0.230769
false
false
10
793277a1be452aaa6637aa56f4d4b1b0307cba0e
26,585,847,571,446
660e139843d71c9252ed8d39e2a7fd9522ca2811
/plugin_dev/src/com/google/idea/blaze/plugin/run/BlazeIntellijPluginConfiguration.java
3905817b0c92ef14d7fc3af2ab4b4a06e20c149f
[ "Apache-2.0" ]
permissive
wix-playground/intellij
https://github.com/wix-playground/intellij
aa48c19b1947cd134b834704be5f84199ca58dbd
33e4707514788bc66bf8e58a67d1b178af4cec2a
refs/heads/wix-master
2023-09-03T01:09:45.650000
2023-08-28T10:48:04
2023-08-28T10:48:04
147,094,500
10
7
Apache-2.0
true
2023-08-28T10:48:06
2018-09-02T14:52:00
2022-06-06T08:39:57
2023-08-28T10:48:05
165,127
9
3
3
Java
false
false
/* * Copyright 2016 The Bazel Authors. All rights reserved. * * 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.google.idea.blaze.plugin.run; import static com.google.common.collect.ImmutableSet.toImmutableSet; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Ordering; import com.google.idea.blaze.base.dependencies.TargetInfo; import com.google.idea.blaze.base.model.BlazeProjectData; import com.google.idea.blaze.base.model.primitives.Label; import com.google.idea.blaze.base.model.primitives.TargetExpression; import com.google.idea.blaze.base.run.BlazeConfigurationNameBuilder; import com.google.idea.blaze.base.run.BlazeRunConfiguration; import com.google.idea.blaze.base.run.state.RunConfigurationFlagsState; import com.google.idea.blaze.base.run.state.RunConfigurationStateEditor; import com.google.idea.blaze.base.run.targetfinder.TargetFinder; import com.google.idea.blaze.base.settings.Blaze; import com.google.idea.blaze.base.sync.data.BlazeProjectDataManager; import com.google.idea.blaze.base.ui.UiUtil; import com.google.idea.blaze.plugin.IntellijPluginRule; import com.google.idea.blaze.plugin.run.BlazeIntellijPluginDeployer.DeployedPluginInfo; import com.intellij.execution.ExecutionException; import com.intellij.execution.Executor; import com.intellij.execution.configurations.ConfigurationFactory; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.configurations.JavaCommandLineState; import com.intellij.execution.configurations.JavaParameters; import com.intellij.execution.configurations.LocatableConfigurationBase; import com.intellij.execution.configurations.LogFileOptions; import com.intellij.execution.configurations.ModuleRunConfiguration; import com.intellij.execution.configurations.ParametersList; import com.intellij.execution.configurations.RunProfileState; import com.intellij.execution.configurations.RuntimeConfigurationError; import com.intellij.execution.configurations.RuntimeConfigurationException; import com.intellij.execution.process.OSProcessHandler; import com.intellij.execution.process.ProcessAdapter; import com.intellij.execution.process.ProcessEvent; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.openapi.module.Module; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.options.SettingsEditor; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.ProjectJdkTable; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.roots.ui.configuration.JdkComboBox; import com.intellij.openapi.roots.ui.configuration.projectRoot.ProjectSdksModel; import com.intellij.openapi.ui.ComboBox; import com.intellij.openapi.ui.LabeledComponent; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.WriteExternalException; import com.intellij.ui.RawCommandLineEditor; import com.intellij.ui.SimpleListCellRenderer; import com.intellij.ui.components.JBCheckBox; import com.intellij.util.PlatformUtils; import com.intellij.util.execution.ParametersListUtil; import java.awt.BorderLayout; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Set; import javax.annotation.Nullable; import javax.swing.DefaultComboBoxModel; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JList; import org.jdom.Element; /** * A run configuration that builds a plugin jar via blaze, copies it to the SDK sandbox, then runs * IJ with the plugin loaded. */ public class BlazeIntellijPluginConfiguration extends LocatableConfigurationBase<Object> implements BlazeRunConfiguration, ModuleRunConfiguration { private static final String TARGET_TAG = "blaze-target"; private static final String USER_BLAZE_FLAG_TAG = "blaze-user-flag"; private static final String USER_EXE_FLAG_TAG = "blaze-user-exe-flag"; private static final String SDK_ATTR = "blaze-plugin-sdk"; private static final String VM_PARAMS_ATTR = "blaze-vm-params"; private static final String PROGRAM_PARAMS_ATTR = "blaze-program-params"; private static final String KEEP_IN_SYNC_TAG = "keep-in-sync"; private final String buildSystem; @Nullable private volatile Label target; private RunConfigurationFlagsState blazeFlags; private RunConfigurationFlagsState exeFlags; @Nullable private Sdk pluginSdk; @Nullable String vmParameters; @Nullable private String programParameters; // for keeping imported configurations in sync with their source XML @Nullable private Boolean keepInSync = null; public BlazeIntellijPluginConfiguration( Project project, ConfigurationFactory factory, String name, @Nullable Label initialTarget) { super(project, factory, name); this.buildSystem = Blaze.buildSystemName(project); Sdk projectSdk = ProjectRootManager.getInstance(project).getProjectSdk(); if (IdeaJdkHelper.isIdeaJdk(projectSdk)) { pluginSdk = projectSdk; } target = initialTarget; blazeFlags = new RunConfigurationFlagsState(USER_BLAZE_FLAG_TAG, buildSystem + " flags:"); exeFlags = new RunConfigurationFlagsState(USER_EXE_FLAG_TAG, "Executable flags:"); } @Override public void setKeepInSync(@Nullable Boolean keepInSync) { this.keepInSync = keepInSync; } @Override @Nullable public Boolean getKeepInSync() { return keepInSync; } @Override public ImmutableList<Label> getTargets() { Label target = this.target; return target == null ? ImmutableList.of() : ImmutableList.of(target); } public void setTarget(Label target) { this.target = target; } public void setPluginSdk(Sdk sdk) { if (IdeaJdkHelper.isIdeaJdk(sdk)) { pluginSdk = sdk; } } @Override public ArrayList<LogFileOptions> getAllLogFiles() { ArrayList<LogFileOptions> result = new ArrayList<>(); if (pluginSdk == null) { return result; } String sandboxHome = IdeaJdkHelper.getSandboxHome(pluginSdk); String logFile = Paths.get(sandboxHome, "system", "log", "idea.log").toString(); LogFileOptions logFileOptions = new LogFileOptions("idea.log", logFile, true, true, true); result.add(logFileOptions); return result; } /** * Plugin jar has been previously created via blaze build. This method: - copies jar to sandbox * environment - cracks open jar and finds plugin.xml (with ID, etc., needed for JVM args) - sets * up the SDK, etc. (use project SDK?) - sets up the JVM, and returns a JavaCommandLineState */ @Nullable @Override public RunProfileState getState(Executor executor, ExecutionEnvironment env) throws ExecutionException { final Sdk ideaJdk = pluginSdk; if (!IdeaJdkHelper.isIdeaJdk(ideaJdk)) { throw new ExecutionException("Choose an IntelliJ Platform Plugin SDK"); } String sandboxHome = IdeaJdkHelper.getSandboxHome(ideaJdk); if (sandboxHome == null) { throw new ExecutionException("No sandbox specified for IntelliJ Platform Plugin SDK"); } try { sandboxHome = new File(sandboxHome).getCanonicalPath(); } catch (IOException e) { throw new ExecutionException("No sandbox specified for IntelliJ Platform Plugin SDK", e); } String buildNumber = IdeaJdkHelper.getBuildNumber(ideaJdk); final BlazeIntellijPluginDeployer deployer = new BlazeIntellijPluginDeployer(sandboxHome); env.putUserData(BlazeIntellijPluginDeployer.USER_DATA_KEY, deployer); // copy license from running instance of idea IdeaJdkHelper.copyIDEALicense(sandboxHome); return new JavaCommandLineState(env) { @Override protected JavaParameters createJavaParameters() throws ExecutionException { DeployedPluginInfo deployedPluginInfo = deployer.deployNonBlocking(buildSystem); final JavaParameters params = new JavaParameters(); ParametersList vm = params.getVMParametersList(); fillParameterList(vm, vmParameters); fillParameterList(params.getProgramParametersList(), programParameters); IntellijWithPluginClasspathHelper.addRequiredVmParams( params, ideaJdk, deployedPluginInfo.javaAgents); if (!vm.hasProperty(PlatformUtils.PLATFORM_PREFIX_KEY) && buildNumber != null) { String prefix = IdeaJdkHelper.getPlatformPrefix(buildNumber); if (prefix != null) { vm.defineProperty(PlatformUtils.PLATFORM_PREFIX_KEY, prefix); } } return params; } /** https://youtrack.jetbrains.com/issue/IDEA-201733 */ @Override protected GeneralCommandLine createCommandLine() throws ExecutionException { GeneralCommandLine commandLine = super.createCommandLine(); for (String jreName : new String[] {"jbr", "jre64", "jre"}) { File bundledJre = new File(ideaJdk.getHomePath(), jreName); if (bundledJre.isDirectory()) { File bundledJava = new File(bundledJre, "bin/java"); if (bundledJava.canExecute()) { commandLine.setExePath(bundledJava.getAbsolutePath()); break; } } } return commandLine; } @Override protected OSProcessHandler startProcess() throws ExecutionException { deployer.blockUntilDeployComplete(); final OSProcessHandler handler = super.startProcess(); handler.addProcessListener( new ProcessAdapter() { @Override public void processTerminated(ProcessEvent event) { deployer.deleteDeployment(); } }); return handler; } }; } private static void fillParameterList(ParametersList list, @Nullable String parameters) { if (parameters == null) { return; } list.addAll(ParametersListUtil.parse(parameters, /* keepQuotes= */ false)); } @Override public Module[] getModules() { return Module.EMPTY_ARRAY; } @Override public void checkConfiguration() throws RuntimeConfigurationException { super.checkConfiguration(); Label label = target; if (label == null) { throw new RuntimeConfigurationError("Select a target to run"); } TargetInfo target = TargetFinder.findTargetInfo(getProject(), label); if (target == null) { throw new RuntimeConfigurationError("The selected target does not exist."); } if (!IntellijPluginRule.isPluginTarget(target)) { throw new RuntimeConfigurationError("The selected target is not an intellij_plugin"); } if (!IdeaJdkHelper.isIdeaJdk(pluginSdk)) { throw new RuntimeConfigurationError("Select an IntelliJ Platform Plugin SDK"); } } @Override public void readExternal(Element element) throws InvalidDataException { super.readExternal(element); // Target is persisted as a tag to permit multiple targets in the future. Element targetElement = element.getChild(TARGET_TAG); if (targetElement != null && !Strings.isNullOrEmpty(targetElement.getTextTrim())) { target = (Label) TargetExpression.fromStringSafe(targetElement.getTextTrim()); } else { target = null; } blazeFlags.readExternal(element); exeFlags.readExternal(element); String sdkName = element.getAttributeValue(SDK_ATTR); if (!Strings.isNullOrEmpty(sdkName)) { pluginSdk = ProjectJdkTable.getInstance().findJdk(sdkName); } vmParameters = Strings.emptyToNull(element.getAttributeValue(VM_PARAMS_ATTR)); programParameters = Strings.emptyToNull(element.getAttributeValue(PROGRAM_PARAMS_ATTR)); String keepInSyncString = element.getAttributeValue(KEEP_IN_SYNC_TAG); keepInSync = keepInSyncString != null ? Boolean.parseBoolean(keepInSyncString) : null; } @Override public void writeExternal(Element element) throws WriteExternalException { super.writeExternal(element); if (target != null) { // Target is persisted as a tag to permit multiple targets in the future. Element targetElement = new Element(TARGET_TAG); targetElement.setText(target.toString()); element.addContent(targetElement); } blazeFlags.writeExternal(element); exeFlags.writeExternal(element); if (pluginSdk != null) { element.setAttribute(SDK_ATTR, pluginSdk.getName()); } if (vmParameters != null) { element.setAttribute(VM_PARAMS_ATTR, vmParameters); } if (programParameters != null) { element.setAttribute(PROGRAM_PARAMS_ATTR, programParameters); } if (keepInSync != null) { element.setAttribute(KEEP_IN_SYNC_TAG, Boolean.toString(keepInSync)); } } @Override public BlazeIntellijPluginConfiguration clone() { final BlazeIntellijPluginConfiguration configuration = (BlazeIntellijPluginConfiguration) super.clone(); configuration.target = target; configuration.blazeFlags = blazeFlags.copy(); configuration.exeFlags = exeFlags.copy(); configuration.pluginSdk = pluginSdk; configuration.vmParameters = vmParameters; configuration.programParameters = programParameters; configuration.keepInSync = keepInSync; return configuration; } RunConfigurationFlagsState getBlazeFlagsState() { return blazeFlags; } RunConfigurationFlagsState getExeFlagsState() { return exeFlags; } @Override public BlazeIntellijPluginConfigurationSettingsEditor getConfigurationEditor() { Project project = getProject(); return new BlazeIntellijPluginConfigurationSettingsEditor( findPluginTargets(project), blazeFlags.getEditor(project), exeFlags.getEditor(project)); } private static Set<Label> findPluginTargets(Project project) { BlazeProjectData projectData = BlazeProjectDataManager.getInstance(project).getBlazeProjectData(); if (projectData == null) { return ImmutableSet.of(); } return projectData.targets().stream() .filter(IntellijPluginRule::isPluginTarget) .map(info -> info.label) .collect(toImmutableSet()); } @Override @Nullable public String suggestedName() { Label target = this.target; if (target == null) { return null; } return new BlazeConfigurationNameBuilder() .setBuildSystemName(getProject()) .setCommandName("build") .setTargetString(target) .build(); } @VisibleForTesting static class BlazeIntellijPluginConfigurationSettingsEditor extends SettingsEditor<BlazeIntellijPluginConfiguration> { private final ComboBox<Label> targetCombo; private final RunConfigurationStateEditor blazeFlagsEditor; private final RunConfigurationStateEditor exeFlagsEditor; private final JdkComboBox sdkCombo; private final LabeledComponent<RawCommandLineEditor> vmParameters = new LabeledComponent<>(); private final LabeledComponent<RawCommandLineEditor> programParameters = new LabeledComponent<>(); private final JBCheckBox keepInSyncCheckBox; public BlazeIntellijPluginConfigurationSettingsEditor( Iterable<Label> javaLabels, RunConfigurationStateEditor blazeFlagsEditor, RunConfigurationStateEditor exeFlagsEditor) { targetCombo = new ComboBox<>( new DefaultComboBoxModel<>( Ordering.usingToString().sortedCopy(javaLabels).toArray(new Label[0]))); targetCombo.setRenderer( new SimpleListCellRenderer<Label>() { @Override public void customize( JList<? extends Label> list, @Nullable Label value, int index, boolean selected, boolean hasFocus) { setText(value == null ? null : value.toString()); } }); this.blazeFlagsEditor = blazeFlagsEditor; this.exeFlagsEditor = exeFlagsEditor; ProjectSdksModel sdksModel = new ProjectSdksModel(); sdksModel.reset(null); sdkCombo = new JdkComboBox(sdksModel, IdeaJdkHelper::isIdeaJdkType); keepInSyncCheckBox = new JBCheckBox("Keep in sync with source XML"); keepInSyncCheckBox.addItemListener(e -> updateEnabledStatus()); } private void updateEnabledStatus() { setEnabled(!keepInSyncCheckBox.isVisible() || !keepInSyncCheckBox.isSelected()); } private void setEnabled(boolean enabled) { targetCombo.setEnabled(enabled); sdkCombo.setEnabled(enabled); vmParameters.getComponent().setEnabled(enabled); programParameters.getComponent().setEnabled(enabled); blazeFlagsEditor.setComponentEnabled(enabled); exeFlagsEditor.setComponentEnabled(enabled); } @Nullable private static Sdk getProjectJdk(@Nullable Sdk possibleClone) { return possibleClone == null ? null : ProjectJdkTable.getInstance().findJdk(possibleClone.getName()); } @VisibleForTesting @Override public void resetEditorFrom(BlazeIntellijPluginConfiguration s) { targetCombo.setSelectedItem(s.target); blazeFlagsEditor.resetEditorFrom(s.blazeFlags); exeFlagsEditor.resetEditorFrom(s.exeFlags); if (s.pluginSdk != null) { sdkCombo.setSelectedJdk(s.pluginSdk); } else { s.pluginSdk = getProjectJdk(sdkCombo.getSelectedJdk()); } if (s.vmParameters != null) { vmParameters.getComponent().setText(s.vmParameters); } if (s.programParameters != null) { programParameters.getComponent().setText(s.programParameters); } keepInSyncCheckBox.setVisible(s.keepInSync != null); if (s.keepInSync != null) { keepInSyncCheckBox.setSelected(s.keepInSync); } } @VisibleForTesting @Override public void applyEditorTo(BlazeIntellijPluginConfiguration s) throws ConfigurationException { try { s.target = (Label) targetCombo.getSelectedItem(); } catch (ClassCastException e) { throw new ConfigurationException("Invalid label specified."); } blazeFlagsEditor.applyEditorTo(s.blazeFlags); exeFlagsEditor.applyEditorTo(s.exeFlags); s.pluginSdk = getProjectJdk(sdkCombo.getSelectedJdk()); s.vmParameters = vmParameters.getComponent().getText(); s.programParameters = programParameters.getComponent().getText(); s.keepInSync = keepInSyncCheckBox.isVisible() ? keepInSyncCheckBox.isSelected() : null; } @Override protected JComponent createEditor() { vmParameters.setText("VM options:"); vmParameters.setComponent(new RawCommandLineEditor()); vmParameters.getComponent().setDialogCaption(vmParameters.getRawText()); vmParameters.setLabelLocation(BorderLayout.WEST); programParameters.setText("Program arguments"); programParameters.setComponent(new RawCommandLineEditor()); programParameters.getComponent().setDialogCaption(programParameters.getRawText()); programParameters.setLabelLocation(BorderLayout.WEST); return UiUtil.createBox( new JLabel("Target:"), targetCombo, new JLabel("Plugin SDK"), sdkCombo, vmParameters.getLabel(), vmParameters.getComponent(), programParameters.getLabel(), programParameters.getComponent(), blazeFlagsEditor.createComponent(), exeFlagsEditor.createComponent(), keepInSyncCheckBox); } } }
UTF-8
Java
20,161
java
BlazeIntellijPluginConfiguration.java
Java
[]
null
[]
/* * Copyright 2016 The Bazel Authors. All rights reserved. * * 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.google.idea.blaze.plugin.run; import static com.google.common.collect.ImmutableSet.toImmutableSet; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Ordering; import com.google.idea.blaze.base.dependencies.TargetInfo; import com.google.idea.blaze.base.model.BlazeProjectData; import com.google.idea.blaze.base.model.primitives.Label; import com.google.idea.blaze.base.model.primitives.TargetExpression; import com.google.idea.blaze.base.run.BlazeConfigurationNameBuilder; import com.google.idea.blaze.base.run.BlazeRunConfiguration; import com.google.idea.blaze.base.run.state.RunConfigurationFlagsState; import com.google.idea.blaze.base.run.state.RunConfigurationStateEditor; import com.google.idea.blaze.base.run.targetfinder.TargetFinder; import com.google.idea.blaze.base.settings.Blaze; import com.google.idea.blaze.base.sync.data.BlazeProjectDataManager; import com.google.idea.blaze.base.ui.UiUtil; import com.google.idea.blaze.plugin.IntellijPluginRule; import com.google.idea.blaze.plugin.run.BlazeIntellijPluginDeployer.DeployedPluginInfo; import com.intellij.execution.ExecutionException; import com.intellij.execution.Executor; import com.intellij.execution.configurations.ConfigurationFactory; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.configurations.JavaCommandLineState; import com.intellij.execution.configurations.JavaParameters; import com.intellij.execution.configurations.LocatableConfigurationBase; import com.intellij.execution.configurations.LogFileOptions; import com.intellij.execution.configurations.ModuleRunConfiguration; import com.intellij.execution.configurations.ParametersList; import com.intellij.execution.configurations.RunProfileState; import com.intellij.execution.configurations.RuntimeConfigurationError; import com.intellij.execution.configurations.RuntimeConfigurationException; import com.intellij.execution.process.OSProcessHandler; import com.intellij.execution.process.ProcessAdapter; import com.intellij.execution.process.ProcessEvent; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.openapi.module.Module; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.options.SettingsEditor; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.ProjectJdkTable; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.roots.ui.configuration.JdkComboBox; import com.intellij.openapi.roots.ui.configuration.projectRoot.ProjectSdksModel; import com.intellij.openapi.ui.ComboBox; import com.intellij.openapi.ui.LabeledComponent; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.WriteExternalException; import com.intellij.ui.RawCommandLineEditor; import com.intellij.ui.SimpleListCellRenderer; import com.intellij.ui.components.JBCheckBox; import com.intellij.util.PlatformUtils; import com.intellij.util.execution.ParametersListUtil; import java.awt.BorderLayout; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Set; import javax.annotation.Nullable; import javax.swing.DefaultComboBoxModel; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JList; import org.jdom.Element; /** * A run configuration that builds a plugin jar via blaze, copies it to the SDK sandbox, then runs * IJ with the plugin loaded. */ public class BlazeIntellijPluginConfiguration extends LocatableConfigurationBase<Object> implements BlazeRunConfiguration, ModuleRunConfiguration { private static final String TARGET_TAG = "blaze-target"; private static final String USER_BLAZE_FLAG_TAG = "blaze-user-flag"; private static final String USER_EXE_FLAG_TAG = "blaze-user-exe-flag"; private static final String SDK_ATTR = "blaze-plugin-sdk"; private static final String VM_PARAMS_ATTR = "blaze-vm-params"; private static final String PROGRAM_PARAMS_ATTR = "blaze-program-params"; private static final String KEEP_IN_SYNC_TAG = "keep-in-sync"; private final String buildSystem; @Nullable private volatile Label target; private RunConfigurationFlagsState blazeFlags; private RunConfigurationFlagsState exeFlags; @Nullable private Sdk pluginSdk; @Nullable String vmParameters; @Nullable private String programParameters; // for keeping imported configurations in sync with their source XML @Nullable private Boolean keepInSync = null; public BlazeIntellijPluginConfiguration( Project project, ConfigurationFactory factory, String name, @Nullable Label initialTarget) { super(project, factory, name); this.buildSystem = Blaze.buildSystemName(project); Sdk projectSdk = ProjectRootManager.getInstance(project).getProjectSdk(); if (IdeaJdkHelper.isIdeaJdk(projectSdk)) { pluginSdk = projectSdk; } target = initialTarget; blazeFlags = new RunConfigurationFlagsState(USER_BLAZE_FLAG_TAG, buildSystem + " flags:"); exeFlags = new RunConfigurationFlagsState(USER_EXE_FLAG_TAG, "Executable flags:"); } @Override public void setKeepInSync(@Nullable Boolean keepInSync) { this.keepInSync = keepInSync; } @Override @Nullable public Boolean getKeepInSync() { return keepInSync; } @Override public ImmutableList<Label> getTargets() { Label target = this.target; return target == null ? ImmutableList.of() : ImmutableList.of(target); } public void setTarget(Label target) { this.target = target; } public void setPluginSdk(Sdk sdk) { if (IdeaJdkHelper.isIdeaJdk(sdk)) { pluginSdk = sdk; } } @Override public ArrayList<LogFileOptions> getAllLogFiles() { ArrayList<LogFileOptions> result = new ArrayList<>(); if (pluginSdk == null) { return result; } String sandboxHome = IdeaJdkHelper.getSandboxHome(pluginSdk); String logFile = Paths.get(sandboxHome, "system", "log", "idea.log").toString(); LogFileOptions logFileOptions = new LogFileOptions("idea.log", logFile, true, true, true); result.add(logFileOptions); return result; } /** * Plugin jar has been previously created via blaze build. This method: - copies jar to sandbox * environment - cracks open jar and finds plugin.xml (with ID, etc., needed for JVM args) - sets * up the SDK, etc. (use project SDK?) - sets up the JVM, and returns a JavaCommandLineState */ @Nullable @Override public RunProfileState getState(Executor executor, ExecutionEnvironment env) throws ExecutionException { final Sdk ideaJdk = pluginSdk; if (!IdeaJdkHelper.isIdeaJdk(ideaJdk)) { throw new ExecutionException("Choose an IntelliJ Platform Plugin SDK"); } String sandboxHome = IdeaJdkHelper.getSandboxHome(ideaJdk); if (sandboxHome == null) { throw new ExecutionException("No sandbox specified for IntelliJ Platform Plugin SDK"); } try { sandboxHome = new File(sandboxHome).getCanonicalPath(); } catch (IOException e) { throw new ExecutionException("No sandbox specified for IntelliJ Platform Plugin SDK", e); } String buildNumber = IdeaJdkHelper.getBuildNumber(ideaJdk); final BlazeIntellijPluginDeployer deployer = new BlazeIntellijPluginDeployer(sandboxHome); env.putUserData(BlazeIntellijPluginDeployer.USER_DATA_KEY, deployer); // copy license from running instance of idea IdeaJdkHelper.copyIDEALicense(sandboxHome); return new JavaCommandLineState(env) { @Override protected JavaParameters createJavaParameters() throws ExecutionException { DeployedPluginInfo deployedPluginInfo = deployer.deployNonBlocking(buildSystem); final JavaParameters params = new JavaParameters(); ParametersList vm = params.getVMParametersList(); fillParameterList(vm, vmParameters); fillParameterList(params.getProgramParametersList(), programParameters); IntellijWithPluginClasspathHelper.addRequiredVmParams( params, ideaJdk, deployedPluginInfo.javaAgents); if (!vm.hasProperty(PlatformUtils.PLATFORM_PREFIX_KEY) && buildNumber != null) { String prefix = IdeaJdkHelper.getPlatformPrefix(buildNumber); if (prefix != null) { vm.defineProperty(PlatformUtils.PLATFORM_PREFIX_KEY, prefix); } } return params; } /** https://youtrack.jetbrains.com/issue/IDEA-201733 */ @Override protected GeneralCommandLine createCommandLine() throws ExecutionException { GeneralCommandLine commandLine = super.createCommandLine(); for (String jreName : new String[] {"jbr", "jre64", "jre"}) { File bundledJre = new File(ideaJdk.getHomePath(), jreName); if (bundledJre.isDirectory()) { File bundledJava = new File(bundledJre, "bin/java"); if (bundledJava.canExecute()) { commandLine.setExePath(bundledJava.getAbsolutePath()); break; } } } return commandLine; } @Override protected OSProcessHandler startProcess() throws ExecutionException { deployer.blockUntilDeployComplete(); final OSProcessHandler handler = super.startProcess(); handler.addProcessListener( new ProcessAdapter() { @Override public void processTerminated(ProcessEvent event) { deployer.deleteDeployment(); } }); return handler; } }; } private static void fillParameterList(ParametersList list, @Nullable String parameters) { if (parameters == null) { return; } list.addAll(ParametersListUtil.parse(parameters, /* keepQuotes= */ false)); } @Override public Module[] getModules() { return Module.EMPTY_ARRAY; } @Override public void checkConfiguration() throws RuntimeConfigurationException { super.checkConfiguration(); Label label = target; if (label == null) { throw new RuntimeConfigurationError("Select a target to run"); } TargetInfo target = TargetFinder.findTargetInfo(getProject(), label); if (target == null) { throw new RuntimeConfigurationError("The selected target does not exist."); } if (!IntellijPluginRule.isPluginTarget(target)) { throw new RuntimeConfigurationError("The selected target is not an intellij_plugin"); } if (!IdeaJdkHelper.isIdeaJdk(pluginSdk)) { throw new RuntimeConfigurationError("Select an IntelliJ Platform Plugin SDK"); } } @Override public void readExternal(Element element) throws InvalidDataException { super.readExternal(element); // Target is persisted as a tag to permit multiple targets in the future. Element targetElement = element.getChild(TARGET_TAG); if (targetElement != null && !Strings.isNullOrEmpty(targetElement.getTextTrim())) { target = (Label) TargetExpression.fromStringSafe(targetElement.getTextTrim()); } else { target = null; } blazeFlags.readExternal(element); exeFlags.readExternal(element); String sdkName = element.getAttributeValue(SDK_ATTR); if (!Strings.isNullOrEmpty(sdkName)) { pluginSdk = ProjectJdkTable.getInstance().findJdk(sdkName); } vmParameters = Strings.emptyToNull(element.getAttributeValue(VM_PARAMS_ATTR)); programParameters = Strings.emptyToNull(element.getAttributeValue(PROGRAM_PARAMS_ATTR)); String keepInSyncString = element.getAttributeValue(KEEP_IN_SYNC_TAG); keepInSync = keepInSyncString != null ? Boolean.parseBoolean(keepInSyncString) : null; } @Override public void writeExternal(Element element) throws WriteExternalException { super.writeExternal(element); if (target != null) { // Target is persisted as a tag to permit multiple targets in the future. Element targetElement = new Element(TARGET_TAG); targetElement.setText(target.toString()); element.addContent(targetElement); } blazeFlags.writeExternal(element); exeFlags.writeExternal(element); if (pluginSdk != null) { element.setAttribute(SDK_ATTR, pluginSdk.getName()); } if (vmParameters != null) { element.setAttribute(VM_PARAMS_ATTR, vmParameters); } if (programParameters != null) { element.setAttribute(PROGRAM_PARAMS_ATTR, programParameters); } if (keepInSync != null) { element.setAttribute(KEEP_IN_SYNC_TAG, Boolean.toString(keepInSync)); } } @Override public BlazeIntellijPluginConfiguration clone() { final BlazeIntellijPluginConfiguration configuration = (BlazeIntellijPluginConfiguration) super.clone(); configuration.target = target; configuration.blazeFlags = blazeFlags.copy(); configuration.exeFlags = exeFlags.copy(); configuration.pluginSdk = pluginSdk; configuration.vmParameters = vmParameters; configuration.programParameters = programParameters; configuration.keepInSync = keepInSync; return configuration; } RunConfigurationFlagsState getBlazeFlagsState() { return blazeFlags; } RunConfigurationFlagsState getExeFlagsState() { return exeFlags; } @Override public BlazeIntellijPluginConfigurationSettingsEditor getConfigurationEditor() { Project project = getProject(); return new BlazeIntellijPluginConfigurationSettingsEditor( findPluginTargets(project), blazeFlags.getEditor(project), exeFlags.getEditor(project)); } private static Set<Label> findPluginTargets(Project project) { BlazeProjectData projectData = BlazeProjectDataManager.getInstance(project).getBlazeProjectData(); if (projectData == null) { return ImmutableSet.of(); } return projectData.targets().stream() .filter(IntellijPluginRule::isPluginTarget) .map(info -> info.label) .collect(toImmutableSet()); } @Override @Nullable public String suggestedName() { Label target = this.target; if (target == null) { return null; } return new BlazeConfigurationNameBuilder() .setBuildSystemName(getProject()) .setCommandName("build") .setTargetString(target) .build(); } @VisibleForTesting static class BlazeIntellijPluginConfigurationSettingsEditor extends SettingsEditor<BlazeIntellijPluginConfiguration> { private final ComboBox<Label> targetCombo; private final RunConfigurationStateEditor blazeFlagsEditor; private final RunConfigurationStateEditor exeFlagsEditor; private final JdkComboBox sdkCombo; private final LabeledComponent<RawCommandLineEditor> vmParameters = new LabeledComponent<>(); private final LabeledComponent<RawCommandLineEditor> programParameters = new LabeledComponent<>(); private final JBCheckBox keepInSyncCheckBox; public BlazeIntellijPluginConfigurationSettingsEditor( Iterable<Label> javaLabels, RunConfigurationStateEditor blazeFlagsEditor, RunConfigurationStateEditor exeFlagsEditor) { targetCombo = new ComboBox<>( new DefaultComboBoxModel<>( Ordering.usingToString().sortedCopy(javaLabels).toArray(new Label[0]))); targetCombo.setRenderer( new SimpleListCellRenderer<Label>() { @Override public void customize( JList<? extends Label> list, @Nullable Label value, int index, boolean selected, boolean hasFocus) { setText(value == null ? null : value.toString()); } }); this.blazeFlagsEditor = blazeFlagsEditor; this.exeFlagsEditor = exeFlagsEditor; ProjectSdksModel sdksModel = new ProjectSdksModel(); sdksModel.reset(null); sdkCombo = new JdkComboBox(sdksModel, IdeaJdkHelper::isIdeaJdkType); keepInSyncCheckBox = new JBCheckBox("Keep in sync with source XML"); keepInSyncCheckBox.addItemListener(e -> updateEnabledStatus()); } private void updateEnabledStatus() { setEnabled(!keepInSyncCheckBox.isVisible() || !keepInSyncCheckBox.isSelected()); } private void setEnabled(boolean enabled) { targetCombo.setEnabled(enabled); sdkCombo.setEnabled(enabled); vmParameters.getComponent().setEnabled(enabled); programParameters.getComponent().setEnabled(enabled); blazeFlagsEditor.setComponentEnabled(enabled); exeFlagsEditor.setComponentEnabled(enabled); } @Nullable private static Sdk getProjectJdk(@Nullable Sdk possibleClone) { return possibleClone == null ? null : ProjectJdkTable.getInstance().findJdk(possibleClone.getName()); } @VisibleForTesting @Override public void resetEditorFrom(BlazeIntellijPluginConfiguration s) { targetCombo.setSelectedItem(s.target); blazeFlagsEditor.resetEditorFrom(s.blazeFlags); exeFlagsEditor.resetEditorFrom(s.exeFlags); if (s.pluginSdk != null) { sdkCombo.setSelectedJdk(s.pluginSdk); } else { s.pluginSdk = getProjectJdk(sdkCombo.getSelectedJdk()); } if (s.vmParameters != null) { vmParameters.getComponent().setText(s.vmParameters); } if (s.programParameters != null) { programParameters.getComponent().setText(s.programParameters); } keepInSyncCheckBox.setVisible(s.keepInSync != null); if (s.keepInSync != null) { keepInSyncCheckBox.setSelected(s.keepInSync); } } @VisibleForTesting @Override public void applyEditorTo(BlazeIntellijPluginConfiguration s) throws ConfigurationException { try { s.target = (Label) targetCombo.getSelectedItem(); } catch (ClassCastException e) { throw new ConfigurationException("Invalid label specified."); } blazeFlagsEditor.applyEditorTo(s.blazeFlags); exeFlagsEditor.applyEditorTo(s.exeFlags); s.pluginSdk = getProjectJdk(sdkCombo.getSelectedJdk()); s.vmParameters = vmParameters.getComponent().getText(); s.programParameters = programParameters.getComponent().getText(); s.keepInSync = keepInSyncCheckBox.isVisible() ? keepInSyncCheckBox.isSelected() : null; } @Override protected JComponent createEditor() { vmParameters.setText("VM options:"); vmParameters.setComponent(new RawCommandLineEditor()); vmParameters.getComponent().setDialogCaption(vmParameters.getRawText()); vmParameters.setLabelLocation(BorderLayout.WEST); programParameters.setText("Program arguments"); programParameters.setComponent(new RawCommandLineEditor()); programParameters.getComponent().setDialogCaption(programParameters.getRawText()); programParameters.setLabelLocation(BorderLayout.WEST); return UiUtil.createBox( new JLabel("Target:"), targetCombo, new JLabel("Plugin SDK"), sdkCombo, vmParameters.getLabel(), vmParameters.getComponent(), programParameters.getLabel(), programParameters.getComponent(), blazeFlagsEditor.createComponent(), exeFlagsEditor.createComponent(), keepInSyncCheckBox); } } }
20,161
0.729031
0.728188
517
37.996132
27.437778
99
false
false
0
0
0
0
0
0
0.584139
false
false
10
188ca7c7a3c2ee8292d674c40fcbabc1636151aa
22,694,607,238,537
d141dacd975531fa1580ecba196f69cd5802b0b7
/CS-136 (Java)/CS-136 Homework/Project_8/src/package_8/TwoDimArrayClass.java
0efe600c87c5ea157e23359e098a2274154a57ce
[]
no_license
SirRyan123/Class-Assignments
https://github.com/SirRyan123/Class-Assignments
7a27eaa9ce5af1a47db407c779098a76560f6249
36e076337981c16c778df76e88bf0e825b5834e3
refs/heads/master
2020-07-25T17:04:19.301000
2020-05-04T00:14:27
2020-05-04T00:14:27
208,364,691
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package package_8; public class TwoDimArrayClass { private static final int DEFAULT_MAX_CAPACITY = 100; private static final int DEFAULT_MIN_CAPACITY = 3; public static final int FAILED_ACCESS = -999999; private int[][] localTD_Array; private int rowCapacity; private int colCapacity; private int maxCapacity; public TwoDimArrayClass() { rowCapacity = DEFAULT_MIN_CAPACITY; colCapacity = DEFAULT_MIN_CAPACITY; maxCapacity = DEFAULT_MAX_CAPACITY; this.localTD_Array = new int[rowCapacity][colCapacity]; } public TwoDimArrayClass(int rowCap, int colCap, int maxCap) { if (rowCap < DEFAULT_MIN_CAPACITY) { rowCapacity = DEFAULT_MIN_CAPACITY; } else { rowCapacity = rowCap; } if (colCap < DEFAULT_MIN_CAPACITY) { colCapacity = DEFAULT_MIN_CAPACITY; } else { colCapacity = colCap; } if(maxCap > rowCap && maxCap > colCap && maxCap > DEFAULT_MAX_CAPACITY) { maxCapacity = maxCap; } else if (rowCap > DEFAULT_MAX_CAPACITY && rowCap >= colCap) { maxCapacity = rowCap; } else if (colCap > DEFAULT_MAX_CAPACITY && colCap >= rowCap) { maxCapacity = colCap; } else { maxCapacity = DEFAULT_MAX_CAPACITY; } localTD_Array = new int[rowCapacity][colCapacity]; } public TwoDimArrayClass(TwoDimArrayClass copied) { int row, column; this.maxCapacity = copied.maxCapacity; this.rowCapacity = copied.rowCapacity; this.colCapacity = copied.colCapacity; this.localTD_Array = new int[rowCapacity][colCapacity]; for (row = 0; row < rowCapacity; row++) { for (column = 0; column < colCapacity; column++) { localTD_Array[row][column] = copied.localTD_Array[row][column]; } } } public int accessItemAt(int rowAccessIndex, int colAccessIndex) { if(rowAccessIndex >= 0 && rowAccessIndex < maxCapacity) { return localTD_Array[rowAccessIndex][colAccessIndex]; } else { return FAILED_ACCESS; } } public boolean arrayIndicesWithinMaxBounds(int testedRowIndex, int testedColIndex) { if (testedRowIndex < maxCapacity && testedColIndex < maxCapacity) { return true; } return false; } public void dumpTwoDimArray() { int rowIndex, colIndex, endOfCol = 1; System.out.println("\nTwoDimArrayClass Array Dump:"); for (rowIndex = 0; rowIndex < rowCapacity; rowIndex++) { for (colIndex = 0; colIndex < colCapacity; colIndex++) { if (localTD_Array[rowIndex][colIndex] > 0) { if (colIndex == colCapacity - endOfCol) { System.out.format("% 5d%s", localTD_Array[rowIndex][colIndex], ""); } else { System.out.format("% 5d%s", localTD_Array[rowIndex][colIndex], ", "); } } } System.out.println(); } System.out.println('\n'); } public int getCurrentColCapacity() { return colCapacity; } public int getCurrentRowCapacity() { return rowCapacity; } public void resize(int newRowCapacity, int newColCapacity) { int row, column; int[][] newArray = new int[newRowCapacity][newColCapacity]; for (row = 0; row < rowCapacity; row++) { for (column = 0; column < colCapacity; column++) { newArray[row][column] = localTD_Array[row][column]; } } localTD_Array = newArray; } public boolean setItemAt(int rowIndexToSet, int colIndexToSet, int newValue) { if (rowIndexToSet > maxCapacity || colIndexToSet > maxCapacity) { return false; } else { if (rowIndexToSet >= rowCapacity && rowIndexToSet <= maxCapacity) { resize(rowIndexToSet + 1, colCapacity); } else if (colIndexToSet >= colCapacity && colIndexToSet <= maxCapacity) { resize(rowCapacity, colIndexToSet + 1); } localTD_Array[rowIndexToSet][colIndexToSet] = newValue; return true; } } }
UTF-8
Java
3,993
java
TwoDimArrayClass.java
Java
[]
null
[]
package package_8; public class TwoDimArrayClass { private static final int DEFAULT_MAX_CAPACITY = 100; private static final int DEFAULT_MIN_CAPACITY = 3; public static final int FAILED_ACCESS = -999999; private int[][] localTD_Array; private int rowCapacity; private int colCapacity; private int maxCapacity; public TwoDimArrayClass() { rowCapacity = DEFAULT_MIN_CAPACITY; colCapacity = DEFAULT_MIN_CAPACITY; maxCapacity = DEFAULT_MAX_CAPACITY; this.localTD_Array = new int[rowCapacity][colCapacity]; } public TwoDimArrayClass(int rowCap, int colCap, int maxCap) { if (rowCap < DEFAULT_MIN_CAPACITY) { rowCapacity = DEFAULT_MIN_CAPACITY; } else { rowCapacity = rowCap; } if (colCap < DEFAULT_MIN_CAPACITY) { colCapacity = DEFAULT_MIN_CAPACITY; } else { colCapacity = colCap; } if(maxCap > rowCap && maxCap > colCap && maxCap > DEFAULT_MAX_CAPACITY) { maxCapacity = maxCap; } else if (rowCap > DEFAULT_MAX_CAPACITY && rowCap >= colCap) { maxCapacity = rowCap; } else if (colCap > DEFAULT_MAX_CAPACITY && colCap >= rowCap) { maxCapacity = colCap; } else { maxCapacity = DEFAULT_MAX_CAPACITY; } localTD_Array = new int[rowCapacity][colCapacity]; } public TwoDimArrayClass(TwoDimArrayClass copied) { int row, column; this.maxCapacity = copied.maxCapacity; this.rowCapacity = copied.rowCapacity; this.colCapacity = copied.colCapacity; this.localTD_Array = new int[rowCapacity][colCapacity]; for (row = 0; row < rowCapacity; row++) { for (column = 0; column < colCapacity; column++) { localTD_Array[row][column] = copied.localTD_Array[row][column]; } } } public int accessItemAt(int rowAccessIndex, int colAccessIndex) { if(rowAccessIndex >= 0 && rowAccessIndex < maxCapacity) { return localTD_Array[rowAccessIndex][colAccessIndex]; } else { return FAILED_ACCESS; } } public boolean arrayIndicesWithinMaxBounds(int testedRowIndex, int testedColIndex) { if (testedRowIndex < maxCapacity && testedColIndex < maxCapacity) { return true; } return false; } public void dumpTwoDimArray() { int rowIndex, colIndex, endOfCol = 1; System.out.println("\nTwoDimArrayClass Array Dump:"); for (rowIndex = 0; rowIndex < rowCapacity; rowIndex++) { for (colIndex = 0; colIndex < colCapacity; colIndex++) { if (localTD_Array[rowIndex][colIndex] > 0) { if (colIndex == colCapacity - endOfCol) { System.out.format("% 5d%s", localTD_Array[rowIndex][colIndex], ""); } else { System.out.format("% 5d%s", localTD_Array[rowIndex][colIndex], ", "); } } } System.out.println(); } System.out.println('\n'); } public int getCurrentColCapacity() { return colCapacity; } public int getCurrentRowCapacity() { return rowCapacity; } public void resize(int newRowCapacity, int newColCapacity) { int row, column; int[][] newArray = new int[newRowCapacity][newColCapacity]; for (row = 0; row < rowCapacity; row++) { for (column = 0; column < colCapacity; column++) { newArray[row][column] = localTD_Array[row][column]; } } localTD_Array = newArray; } public boolean setItemAt(int rowIndexToSet, int colIndexToSet, int newValue) { if (rowIndexToSet > maxCapacity || colIndexToSet > maxCapacity) { return false; } else { if (rowIndexToSet >= rowCapacity && rowIndexToSet <= maxCapacity) { resize(rowIndexToSet + 1, colCapacity); } else if (colIndexToSet >= colCapacity && colIndexToSet <= maxCapacity) { resize(rowCapacity, colIndexToSet + 1); } localTD_Array[rowIndexToSet][colIndexToSet] = newValue; return true; } } }
3,993
0.626597
0.620586
191
19.90576
21.028814
73
false
false
0
0
0
0
0
0
2.47644
false
false
10
f4092659bee8a845c052eba07af6a1ae0d20f90d
21,620,865,401,864
07e88749d44037ee61e9af8e1958e3aaa6098a17
/ecommerce_2016_1610889/src/ecommerce_2016_1610889/session/CookieMode.java
ed10d6d39fcf284b39fb2d8a8df9e6fd66d8094a
[]
no_license
addosso/University---Ecommerce-Project
https://github.com/addosso/University---Ecommerce-Project
7d984be40cd92d1b878aedfe0f464ad0748762e1
cfd62814fc3723efeec553a0a9d50f3d39051677
refs/heads/master
2021-09-18T15:39:26.053000
2018-07-16T18:07:50
2018-07-16T18:07:50
59,109,864
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ecommerce_2016_1610889.session; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Servlet Filter implementation class CookieMode */ public class CookieMode implements Filter { private boolean cookieModeStrict; private boolean one; private String dono = ""; /** * Default constructor. */ public CookieMode() { // TODO Auto-generated constructor stub } /** * @see Filter#destroy() */ public void destroy() { // TODO Auto-generated method stub } /** * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub // place your code here final HttpServletRequest req = (HttpServletRequest)request; final HttpServletResponse res = (HttpServletResponse)response; HttpSession session = req.getSession(); if(cookieModeStrict){ if(req.getCookies() == null){ Cookie strictMode = new Cookie("strictMode", "true"); res.addCookie(strictMode); res.sendError(401, "Abilita i cookie per utilizzare il sito"); return; } } if(req.getRequestURI().contains("cookie")){ Cookie strictMode = new Cookie("strictMode", "true"); res.addCookie(strictMode); cookieModeStrict = true; res.sendRedirect("/ecommerce_2016_1610889/"); return; } chain.doFilter(request, response); } /** * @see Filter#init(FilterConfig) */ public void init(FilterConfig fConfig) throws ServletException { // TODO Auto-generated method stub } }
UTF-8
Java
2,064
java
CookieMode.java
Java
[]
null
[]
package ecommerce_2016_1610889.session; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Servlet Filter implementation class CookieMode */ public class CookieMode implements Filter { private boolean cookieModeStrict; private boolean one; private String dono = ""; /** * Default constructor. */ public CookieMode() { // TODO Auto-generated constructor stub } /** * @see Filter#destroy() */ public void destroy() { // TODO Auto-generated method stub } /** * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub // place your code here final HttpServletRequest req = (HttpServletRequest)request; final HttpServletResponse res = (HttpServletResponse)response; HttpSession session = req.getSession(); if(cookieModeStrict){ if(req.getCookies() == null){ Cookie strictMode = new Cookie("strictMode", "true"); res.addCookie(strictMode); res.sendError(401, "Abilita i cookie per utilizzare il sito"); return; } } if(req.getRequestURI().contains("cookie")){ Cookie strictMode = new Cookie("strictMode", "true"); res.addCookie(strictMode); cookieModeStrict = true; res.sendRedirect("/ecommerce_2016_1610889/"); return; } chain.doFilter(request, response); } /** * @see Filter#init(FilterConfig) */ public void init(FilterConfig fConfig) throws ServletException { // TODO Auto-generated method stub } }
2,064
0.737888
0.725775
77
25.805195
23.479773
129
false
false
0
0
0
0
0
0
1.584416
false
false
10
ed0e99f9df02d6d732f34666be97b652eb8bb4d5
23,450,521,482,522
7d955ac0a5a9c45a7d91cfe67972350d2ab7fa7a
/SSMShop2/src/com/ujiuye/controller/CartController.java
61a9b127e38c4d0a56b03e302d9bc179d6f71b4b
[]
no_license
whistle1997/FirstTest
https://github.com/whistle1997/FirstTest
d3a7b219f9c1cd3cebc17ef526c40102f5af379c
4c3e624aa5036c6c54c0ba19de228ba81645dad4
refs/heads/master
2020-04-09T16:26:34.272000
2018-12-05T03:39:12
2018-12-05T03:39:12
160,453,463
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ujiuye.controller; import java.util.Arrays; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.ujiuye.bean.Cart; import com.ujiuye.bean.Cartitem; import com.ujiuye.bean.Product; import com.ujiuye.bean.User; import com.ujiuye.service.CartService; import com.ujiuye.service.ProductService; @Controller @RequestMapping("/cart") public class CartController { @Resource private CartService cartService; private ProductService productService; @RequestMapping("addCartitem") public String addCartitem(Cartitem ci , double price , HttpSession session) { User user = (User)session.getAttribute("activeuser"); if(user == null) { return "redirect:/login.jsp"; } Cart car = cartService.getOneCarByUid(user.getUid()); double subtotal = ci.getCount()*price; ci.setSubtotal(subtotal); ci.setCid(car.getCid()); cartService.addCartitem(ci); return "redirect:/index.jsp"; } @RequestMapping("showCart") public String showCart(HttpSession session) { User user = (User)session.getAttribute("activeuser"); if(user == null) { return "redirect:/login.jsp"; } Cart car = cartService.getOneCarByUid(user.getUid()); session.setAttribute("cart", car); return "redirect:/cart.jsp"; } @RequestMapping("deleteCart") public String deleteCart(Integer[] ids) { System.out.println(ids); boolean flag = cartService.deleteCaritem(ids); if(flag) { return "redirect:showCart"; } return "redirect:/index.jsp"; } @RequestMapping("deleteOne") public String deleteOne(int id) { boolean flag = cartService.deleteOne(id); if(flag) { return "redirect:showCart"; } return "redirect:/index.jsp"; } }
UTF-8
Java
1,834
java
CartController.java
Java
[]
null
[]
package com.ujiuye.controller; import java.util.Arrays; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.ujiuye.bean.Cart; import com.ujiuye.bean.Cartitem; import com.ujiuye.bean.Product; import com.ujiuye.bean.User; import com.ujiuye.service.CartService; import com.ujiuye.service.ProductService; @Controller @RequestMapping("/cart") public class CartController { @Resource private CartService cartService; private ProductService productService; @RequestMapping("addCartitem") public String addCartitem(Cartitem ci , double price , HttpSession session) { User user = (User)session.getAttribute("activeuser"); if(user == null) { return "redirect:/login.jsp"; } Cart car = cartService.getOneCarByUid(user.getUid()); double subtotal = ci.getCount()*price; ci.setSubtotal(subtotal); ci.setCid(car.getCid()); cartService.addCartitem(ci); return "redirect:/index.jsp"; } @RequestMapping("showCart") public String showCart(HttpSession session) { User user = (User)session.getAttribute("activeuser"); if(user == null) { return "redirect:/login.jsp"; } Cart car = cartService.getOneCarByUid(user.getUid()); session.setAttribute("cart", car); return "redirect:/cart.jsp"; } @RequestMapping("deleteCart") public String deleteCart(Integer[] ids) { System.out.println(ids); boolean flag = cartService.deleteCaritem(ids); if(flag) { return "redirect:showCart"; } return "redirect:/index.jsp"; } @RequestMapping("deleteOne") public String deleteOne(int id) { boolean flag = cartService.deleteOne(id); if(flag) { return "redirect:showCart"; } return "redirect:/index.jsp"; } }
1,834
0.736096
0.736096
74
23.783783
18.501476
78
false
false
0
0
0
0
0
0
1.689189
false
false
10
34e2f1519607e6e58ae472e116e4dec4b978c39a
13,039,520,764,638
9c0d7e84e99bea9d8e0db5ebc40b3de153198fa1
/DataProcessingDSLPart1/ASEProject-Metamodel/src/pipelineproject/impl/PipelineprojectFactoryImpl.java
c6187db2beec9050f80666124db5f35aa09e679c
[]
no_license
FrancescoPinto/DataProcessingDSL
https://github.com/FrancescoPinto/DataProcessingDSL
ea36221638d15c69948abe3386bc73a7ae899e3f
eff66e28aa1e575f0817332c6281506582704d20
refs/heads/master
2022-04-24T09:59:55.097000
2020-04-20T18:57:30
2020-04-20T18:57:30
257,376,186
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** */ package pipelineproject.impl; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EDataType; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.impl.EFactoryImpl; import org.eclipse.emf.ecore.plugin.EcorePlugin; import pipelineproject.*; /** * <!-- begin-user-doc --> * An implementation of the model <b>Factory</b>. * <!-- end-user-doc --> * @generated */ public class PipelineprojectFactoryImpl extends EFactoryImpl implements PipelineprojectFactory { /** * Creates the default factory implementation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static PipelineprojectFactory init() { try { PipelineprojectFactory thePipelineprojectFactory = (PipelineprojectFactory)EPackage.Registry.INSTANCE.getEFactory(PipelineprojectPackage.eNS_URI); if (thePipelineprojectFactory != null) { return thePipelineprojectFactory; } } catch (Exception exception) { EcorePlugin.INSTANCE.log(exception); } return new PipelineprojectFactoryImpl(); } /** * Creates an instance of the factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public PipelineprojectFactoryImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EObject create(EClass eClass) { switch (eClass.getClassifierID()) { case PipelineprojectPackage.PIPELINE: return createPipeline(); case PipelineprojectPackage.DATA_FLOW: return createDataFlow(); case PipelineprojectPackage.DATA_COLLECTION: return createDataCollection(); case PipelineprojectPackage.DATA_INTEGRATION: return createDataIntegration(); case PipelineprojectPackage.EXPORT: return createExport(); case PipelineprojectPackage.INPUT_SOURCE_DECLARATION: return createInputSourceDeclaration(); case PipelineprojectPackage.OUTPUT_FILE: return createOutputFile(); case PipelineprojectPackage.NULL_VALUES_REMOVAL: return createNullValuesRemoval(); case PipelineprojectPackage.CUSTOM_CLEANING: return createCustomCleaning(); case PipelineprojectPackage.SCHEMA: return createSchema(); case PipelineprojectPackage.JOIN_ATTRIBUTES_LIST: return createJoinAttributesList(); case PipelineprojectPackage.RUNTIME_INFO: return createRuntimeInfo(); case PipelineprojectPackage.CHANGE_DATA_FORMAT: return createChangeDataFormat(); case PipelineprojectPackage.KNN: return createKNN(); case PipelineprojectPackage.SVM: return createSVM(); case PipelineprojectPackage.KMEANS: return createKMeans(); case PipelineprojectPackage.AGGLOMERATIVE: return createAgglomerative(); case PipelineprojectPackage.DBSCAN: return createDBSCAN(); case PipelineprojectPackage.JARVIS_PATRICK: return createJarvisPatrick(); case PipelineprojectPackage.LINEAR_REGRESSION: return createLinearRegression(); case PipelineprojectPackage.RIDGE: return createRidge(); case PipelineprojectPackage.LASSO: return createLasso(); case PipelineprojectPackage.MEAN: return createMean(); case PipelineprojectPackage.MEDIAN: return createMedian(); case PipelineprojectPackage.VARIANCE: return createVariance(); case PipelineprojectPackage.NOT_CLAUSE: return createNotClause(); case PipelineprojectPackage.AND_CLAUSE: return createAndClause(); case PipelineprojectPackage.OR_CLAUSE: return createOrClause(); case PipelineprojectPackage.LT_CLAUSE: return createLtClause(); case PipelineprojectPackage.GT_CLAUSE: return createGtClause(); case PipelineprojectPackage.EQ_CLAUSE: return createEqClause(); case PipelineprojectPackage.LE_CLAUSE: return createLeClause(); case PipelineprojectPackage.GE_CLAUSE: return createGeClause(); case PipelineprojectPackage.CONTAINS_CLAUSE: return createContainsClause(); case PipelineprojectPackage.QUERY_PARAM: return createQueryParam(); case PipelineprojectPackage.CUSTOM_PARAM: return createCustomParam(); case PipelineprojectPackage.PRIMARY_KEY: return createPrimaryKey(); case PipelineprojectPackage.ATTRIBUTE: return createAttribute(); case PipelineprojectPackage.LOGISTIC_REGRESSION: return createLogisticRegression(); case PipelineprojectPackage.SKEWNESS: return createSkewness(); case PipelineprojectPackage.SCATTER_PLOT: return createScatterPlot(); case PipelineprojectPackage.LABELED_SCATTER_PLOT: return createLabeledScatterPlot(); case PipelineprojectPackage.HISTOGRAM: return createHistogram(); case PipelineprojectPackage.PIE_PLOT: return createPiePlot(); case PipelineprojectPackage.PROJECT_ON_ATTRIBUTES: return createProjectOnAttributes(); default: throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier"); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object createFromString(EDataType eDataType, String initialValue) { switch (eDataType.getClassifierID()) { case PipelineprojectPackage.FORMAT: return createFormatFromString(eDataType, initialValue); case PipelineprojectPackage.TYPE: return createTypeFromString(eDataType, initialValue); case PipelineprojectPackage.NUL_VALUES_POLICY: return createNulValuesPolicyFromString(eDataType, initialValue); case PipelineprojectPackage.KERNEL_FUNCTION: return createKernelFunctionFromString(eDataType, initialValue); case PipelineprojectPackage.INTER_CLUSTER_SIMILARITY: return createInterClusterSimilarityFromString(eDataType, initialValue); case PipelineprojectPackage.SOURCE_TYPE: return createSourceTypeFromString(eDataType, initialValue); default: throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier"); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String convertToString(EDataType eDataType, Object instanceValue) { switch (eDataType.getClassifierID()) { case PipelineprojectPackage.FORMAT: return convertFormatToString(eDataType, instanceValue); case PipelineprojectPackage.TYPE: return convertTypeToString(eDataType, instanceValue); case PipelineprojectPackage.NUL_VALUES_POLICY: return convertNulValuesPolicyToString(eDataType, instanceValue); case PipelineprojectPackage.KERNEL_FUNCTION: return convertKernelFunctionToString(eDataType, instanceValue); case PipelineprojectPackage.INTER_CLUSTER_SIMILARITY: return convertInterClusterSimilarityToString(eDataType, instanceValue); case PipelineprojectPackage.SOURCE_TYPE: return convertSourceTypeToString(eDataType, instanceValue); default: throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier"); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Pipeline createPipeline() { PipelineImpl pipeline = new PipelineImpl(); return pipeline; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public DataFlow createDataFlow() { DataFlowImpl dataFlow = new DataFlowImpl(); return dataFlow; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public DataCollection createDataCollection() { DataCollectionImpl dataCollection = new DataCollectionImpl(); return dataCollection; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public DataIntegration createDataIntegration() { DataIntegrationImpl dataIntegration = new DataIntegrationImpl(); return dataIntegration; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Export createExport() { ExportImpl export = new ExportImpl(); return export; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public InputSourceDeclaration createInputSourceDeclaration() { InputSourceDeclarationImpl inputSourceDeclaration = new InputSourceDeclarationImpl(); return inputSourceDeclaration; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public OutputFile createOutputFile() { OutputFileImpl outputFile = new OutputFileImpl(); return outputFile; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NullValuesRemoval createNullValuesRemoval() { NullValuesRemovalImpl nullValuesRemoval = new NullValuesRemovalImpl(); return nullValuesRemoval; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public CustomCleaning createCustomCleaning() { CustomCleaningImpl customCleaning = new CustomCleaningImpl(); return customCleaning; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Schema createSchema() { SchemaImpl schema = new SchemaImpl(); return schema; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public JoinAttributesList createJoinAttributesList() { JoinAttributesListImpl joinAttributesList = new JoinAttributesListImpl(); return joinAttributesList; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public RuntimeInfo createRuntimeInfo() { RuntimeInfoImpl runtimeInfo = new RuntimeInfoImpl(); return runtimeInfo; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ChangeDataFormat createChangeDataFormat() { ChangeDataFormatImpl changeDataFormat = new ChangeDataFormatImpl(); return changeDataFormat; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public KNN createKNN() { KNNImpl knn = new KNNImpl(); return knn; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public SVM createSVM() { SVMImpl svm = new SVMImpl(); return svm; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public KMeans createKMeans() { KMeansImpl kMeans = new KMeansImpl(); return kMeans; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Agglomerative createAgglomerative() { AgglomerativeImpl agglomerative = new AgglomerativeImpl(); return agglomerative; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public DBSCAN createDBSCAN() { DBSCANImpl dbscan = new DBSCANImpl(); return dbscan; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public JarvisPatrick createJarvisPatrick() { JarvisPatrickImpl jarvisPatrick = new JarvisPatrickImpl(); return jarvisPatrick; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public LinearRegression createLinearRegression() { LinearRegressionImpl linearRegression = new LinearRegressionImpl(); return linearRegression; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Ridge createRidge() { RidgeImpl ridge = new RidgeImpl(); return ridge; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Lasso createLasso() { LassoImpl lasso = new LassoImpl(); return lasso; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Mean createMean() { MeanImpl mean = new MeanImpl(); return mean; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Median createMedian() { MedianImpl median = new MedianImpl(); return median; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Variance createVariance() { VarianceImpl variance = new VarianceImpl(); return variance; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotClause createNotClause() { NotClauseImpl notClause = new NotClauseImpl(); return notClause; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public AndClause createAndClause() { AndClauseImpl andClause = new AndClauseImpl(); return andClause; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public OrClause createOrClause() { OrClauseImpl orClause = new OrClauseImpl(); return orClause; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public LtClause createLtClause() { LtClauseImpl ltClause = new LtClauseImpl(); return ltClause; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public GtClause createGtClause() { GtClauseImpl gtClause = new GtClauseImpl(); return gtClause; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EqClause createEqClause() { EqClauseImpl eqClause = new EqClauseImpl(); return eqClause; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public LeClause createLeClause() { LeClauseImpl leClause = new LeClauseImpl(); return leClause; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public GeClause createGeClause() { GeClauseImpl geClause = new GeClauseImpl(); return geClause; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ContainsClause createContainsClause() { ContainsClauseImpl containsClause = new ContainsClauseImpl(); return containsClause; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public QueryParam createQueryParam() { QueryParamImpl queryParam = new QueryParamImpl(); return queryParam; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public CustomParam createCustomParam() { CustomParamImpl customParam = new CustomParamImpl(); return customParam; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public PrimaryKey createPrimaryKey() { PrimaryKeyImpl primaryKey = new PrimaryKeyImpl(); return primaryKey; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Attribute createAttribute() { AttributeImpl attribute = new AttributeImpl(); return attribute; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public LogisticRegression createLogisticRegression() { LogisticRegressionImpl logisticRegression = new LogisticRegressionImpl(); return logisticRegression; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Skewness createSkewness() { SkewnessImpl skewness = new SkewnessImpl(); return skewness; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ScatterPlot createScatterPlot() { ScatterPlotImpl scatterPlot = new ScatterPlotImpl(); return scatterPlot; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public LabeledScatterPlot createLabeledScatterPlot() { LabeledScatterPlotImpl labeledScatterPlot = new LabeledScatterPlotImpl(); return labeledScatterPlot; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Histogram createHistogram() { HistogramImpl histogram = new HistogramImpl(); return histogram; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public PiePlot createPiePlot() { PiePlotImpl piePlot = new PiePlotImpl(); return piePlot; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ProjectOnAttributes createProjectOnAttributes() { ProjectOnAttributesImpl projectOnAttributes = new ProjectOnAttributesImpl(); return projectOnAttributes; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Format createFormatFromString(EDataType eDataType, String initialValue) { Format result = Format.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'"); return result; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String convertFormatToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Type createTypeFromString(EDataType eDataType, String initialValue) { Type result = Type.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'"); return result; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String convertTypeToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NulValuesPolicy createNulValuesPolicyFromString(EDataType eDataType, String initialValue) { NulValuesPolicy result = NulValuesPolicy.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'"); return result; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String convertNulValuesPolicyToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public KernelFunction createKernelFunctionFromString(EDataType eDataType, String initialValue) { KernelFunction result = KernelFunction.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'"); return result; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String convertKernelFunctionToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public InterClusterSimilarity createInterClusterSimilarityFromString(EDataType eDataType, String initialValue) { InterClusterSimilarity result = InterClusterSimilarity.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'"); return result; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String convertInterClusterSimilarityToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public SourceType createSourceTypeFromString(EDataType eDataType, String initialValue) { SourceType result = SourceType.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'"); return result; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String convertSourceTypeToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public PipelineprojectPackage getPipelineprojectPackage() { return (PipelineprojectPackage)getEPackage(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @deprecated * @generated */ @Deprecated public static PipelineprojectPackage getPackage() { return PipelineprojectPackage.eINSTANCE; } } //PipelineprojectFactoryImpl
UTF-8
Java
20,697
java
PipelineprojectFactoryImpl.java
Java
[]
null
[]
/** */ package pipelineproject.impl; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EDataType; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.impl.EFactoryImpl; import org.eclipse.emf.ecore.plugin.EcorePlugin; import pipelineproject.*; /** * <!-- begin-user-doc --> * An implementation of the model <b>Factory</b>. * <!-- end-user-doc --> * @generated */ public class PipelineprojectFactoryImpl extends EFactoryImpl implements PipelineprojectFactory { /** * Creates the default factory implementation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static PipelineprojectFactory init() { try { PipelineprojectFactory thePipelineprojectFactory = (PipelineprojectFactory)EPackage.Registry.INSTANCE.getEFactory(PipelineprojectPackage.eNS_URI); if (thePipelineprojectFactory != null) { return thePipelineprojectFactory; } } catch (Exception exception) { EcorePlugin.INSTANCE.log(exception); } return new PipelineprojectFactoryImpl(); } /** * Creates an instance of the factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public PipelineprojectFactoryImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EObject create(EClass eClass) { switch (eClass.getClassifierID()) { case PipelineprojectPackage.PIPELINE: return createPipeline(); case PipelineprojectPackage.DATA_FLOW: return createDataFlow(); case PipelineprojectPackage.DATA_COLLECTION: return createDataCollection(); case PipelineprojectPackage.DATA_INTEGRATION: return createDataIntegration(); case PipelineprojectPackage.EXPORT: return createExport(); case PipelineprojectPackage.INPUT_SOURCE_DECLARATION: return createInputSourceDeclaration(); case PipelineprojectPackage.OUTPUT_FILE: return createOutputFile(); case PipelineprojectPackage.NULL_VALUES_REMOVAL: return createNullValuesRemoval(); case PipelineprojectPackage.CUSTOM_CLEANING: return createCustomCleaning(); case PipelineprojectPackage.SCHEMA: return createSchema(); case PipelineprojectPackage.JOIN_ATTRIBUTES_LIST: return createJoinAttributesList(); case PipelineprojectPackage.RUNTIME_INFO: return createRuntimeInfo(); case PipelineprojectPackage.CHANGE_DATA_FORMAT: return createChangeDataFormat(); case PipelineprojectPackage.KNN: return createKNN(); case PipelineprojectPackage.SVM: return createSVM(); case PipelineprojectPackage.KMEANS: return createKMeans(); case PipelineprojectPackage.AGGLOMERATIVE: return createAgglomerative(); case PipelineprojectPackage.DBSCAN: return createDBSCAN(); case PipelineprojectPackage.JARVIS_PATRICK: return createJarvisPatrick(); case PipelineprojectPackage.LINEAR_REGRESSION: return createLinearRegression(); case PipelineprojectPackage.RIDGE: return createRidge(); case PipelineprojectPackage.LASSO: return createLasso(); case PipelineprojectPackage.MEAN: return createMean(); case PipelineprojectPackage.MEDIAN: return createMedian(); case PipelineprojectPackage.VARIANCE: return createVariance(); case PipelineprojectPackage.NOT_CLAUSE: return createNotClause(); case PipelineprojectPackage.AND_CLAUSE: return createAndClause(); case PipelineprojectPackage.OR_CLAUSE: return createOrClause(); case PipelineprojectPackage.LT_CLAUSE: return createLtClause(); case PipelineprojectPackage.GT_CLAUSE: return createGtClause(); case PipelineprojectPackage.EQ_CLAUSE: return createEqClause(); case PipelineprojectPackage.LE_CLAUSE: return createLeClause(); case PipelineprojectPackage.GE_CLAUSE: return createGeClause(); case PipelineprojectPackage.CONTAINS_CLAUSE: return createContainsClause(); case PipelineprojectPackage.QUERY_PARAM: return createQueryParam(); case PipelineprojectPackage.CUSTOM_PARAM: return createCustomParam(); case PipelineprojectPackage.PRIMARY_KEY: return createPrimaryKey(); case PipelineprojectPackage.ATTRIBUTE: return createAttribute(); case PipelineprojectPackage.LOGISTIC_REGRESSION: return createLogisticRegression(); case PipelineprojectPackage.SKEWNESS: return createSkewness(); case PipelineprojectPackage.SCATTER_PLOT: return createScatterPlot(); case PipelineprojectPackage.LABELED_SCATTER_PLOT: return createLabeledScatterPlot(); case PipelineprojectPackage.HISTOGRAM: return createHistogram(); case PipelineprojectPackage.PIE_PLOT: return createPiePlot(); case PipelineprojectPackage.PROJECT_ON_ATTRIBUTES: return createProjectOnAttributes(); default: throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier"); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object createFromString(EDataType eDataType, String initialValue) { switch (eDataType.getClassifierID()) { case PipelineprojectPackage.FORMAT: return createFormatFromString(eDataType, initialValue); case PipelineprojectPackage.TYPE: return createTypeFromString(eDataType, initialValue); case PipelineprojectPackage.NUL_VALUES_POLICY: return createNulValuesPolicyFromString(eDataType, initialValue); case PipelineprojectPackage.KERNEL_FUNCTION: return createKernelFunctionFromString(eDataType, initialValue); case PipelineprojectPackage.INTER_CLUSTER_SIMILARITY: return createInterClusterSimilarityFromString(eDataType, initialValue); case PipelineprojectPackage.SOURCE_TYPE: return createSourceTypeFromString(eDataType, initialValue); default: throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier"); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String convertToString(EDataType eDataType, Object instanceValue) { switch (eDataType.getClassifierID()) { case PipelineprojectPackage.FORMAT: return convertFormatToString(eDataType, instanceValue); case PipelineprojectPackage.TYPE: return convertTypeToString(eDataType, instanceValue); case PipelineprojectPackage.NUL_VALUES_POLICY: return convertNulValuesPolicyToString(eDataType, instanceValue); case PipelineprojectPackage.KERNEL_FUNCTION: return convertKernelFunctionToString(eDataType, instanceValue); case PipelineprojectPackage.INTER_CLUSTER_SIMILARITY: return convertInterClusterSimilarityToString(eDataType, instanceValue); case PipelineprojectPackage.SOURCE_TYPE: return convertSourceTypeToString(eDataType, instanceValue); default: throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier"); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Pipeline createPipeline() { PipelineImpl pipeline = new PipelineImpl(); return pipeline; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public DataFlow createDataFlow() { DataFlowImpl dataFlow = new DataFlowImpl(); return dataFlow; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public DataCollection createDataCollection() { DataCollectionImpl dataCollection = new DataCollectionImpl(); return dataCollection; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public DataIntegration createDataIntegration() { DataIntegrationImpl dataIntegration = new DataIntegrationImpl(); return dataIntegration; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Export createExport() { ExportImpl export = new ExportImpl(); return export; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public InputSourceDeclaration createInputSourceDeclaration() { InputSourceDeclarationImpl inputSourceDeclaration = new InputSourceDeclarationImpl(); return inputSourceDeclaration; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public OutputFile createOutputFile() { OutputFileImpl outputFile = new OutputFileImpl(); return outputFile; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NullValuesRemoval createNullValuesRemoval() { NullValuesRemovalImpl nullValuesRemoval = new NullValuesRemovalImpl(); return nullValuesRemoval; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public CustomCleaning createCustomCleaning() { CustomCleaningImpl customCleaning = new CustomCleaningImpl(); return customCleaning; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Schema createSchema() { SchemaImpl schema = new SchemaImpl(); return schema; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public JoinAttributesList createJoinAttributesList() { JoinAttributesListImpl joinAttributesList = new JoinAttributesListImpl(); return joinAttributesList; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public RuntimeInfo createRuntimeInfo() { RuntimeInfoImpl runtimeInfo = new RuntimeInfoImpl(); return runtimeInfo; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ChangeDataFormat createChangeDataFormat() { ChangeDataFormatImpl changeDataFormat = new ChangeDataFormatImpl(); return changeDataFormat; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public KNN createKNN() { KNNImpl knn = new KNNImpl(); return knn; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public SVM createSVM() { SVMImpl svm = new SVMImpl(); return svm; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public KMeans createKMeans() { KMeansImpl kMeans = new KMeansImpl(); return kMeans; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Agglomerative createAgglomerative() { AgglomerativeImpl agglomerative = new AgglomerativeImpl(); return agglomerative; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public DBSCAN createDBSCAN() { DBSCANImpl dbscan = new DBSCANImpl(); return dbscan; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public JarvisPatrick createJarvisPatrick() { JarvisPatrickImpl jarvisPatrick = new JarvisPatrickImpl(); return jarvisPatrick; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public LinearRegression createLinearRegression() { LinearRegressionImpl linearRegression = new LinearRegressionImpl(); return linearRegression; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Ridge createRidge() { RidgeImpl ridge = new RidgeImpl(); return ridge; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Lasso createLasso() { LassoImpl lasso = new LassoImpl(); return lasso; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Mean createMean() { MeanImpl mean = new MeanImpl(); return mean; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Median createMedian() { MedianImpl median = new MedianImpl(); return median; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Variance createVariance() { VarianceImpl variance = new VarianceImpl(); return variance; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotClause createNotClause() { NotClauseImpl notClause = new NotClauseImpl(); return notClause; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public AndClause createAndClause() { AndClauseImpl andClause = new AndClauseImpl(); return andClause; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public OrClause createOrClause() { OrClauseImpl orClause = new OrClauseImpl(); return orClause; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public LtClause createLtClause() { LtClauseImpl ltClause = new LtClauseImpl(); return ltClause; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public GtClause createGtClause() { GtClauseImpl gtClause = new GtClauseImpl(); return gtClause; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EqClause createEqClause() { EqClauseImpl eqClause = new EqClauseImpl(); return eqClause; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public LeClause createLeClause() { LeClauseImpl leClause = new LeClauseImpl(); return leClause; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public GeClause createGeClause() { GeClauseImpl geClause = new GeClauseImpl(); return geClause; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ContainsClause createContainsClause() { ContainsClauseImpl containsClause = new ContainsClauseImpl(); return containsClause; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public QueryParam createQueryParam() { QueryParamImpl queryParam = new QueryParamImpl(); return queryParam; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public CustomParam createCustomParam() { CustomParamImpl customParam = new CustomParamImpl(); return customParam; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public PrimaryKey createPrimaryKey() { PrimaryKeyImpl primaryKey = new PrimaryKeyImpl(); return primaryKey; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Attribute createAttribute() { AttributeImpl attribute = new AttributeImpl(); return attribute; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public LogisticRegression createLogisticRegression() { LogisticRegressionImpl logisticRegression = new LogisticRegressionImpl(); return logisticRegression; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Skewness createSkewness() { SkewnessImpl skewness = new SkewnessImpl(); return skewness; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ScatterPlot createScatterPlot() { ScatterPlotImpl scatterPlot = new ScatterPlotImpl(); return scatterPlot; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public LabeledScatterPlot createLabeledScatterPlot() { LabeledScatterPlotImpl labeledScatterPlot = new LabeledScatterPlotImpl(); return labeledScatterPlot; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Histogram createHistogram() { HistogramImpl histogram = new HistogramImpl(); return histogram; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public PiePlot createPiePlot() { PiePlotImpl piePlot = new PiePlotImpl(); return piePlot; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ProjectOnAttributes createProjectOnAttributes() { ProjectOnAttributesImpl projectOnAttributes = new ProjectOnAttributesImpl(); return projectOnAttributes; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Format createFormatFromString(EDataType eDataType, String initialValue) { Format result = Format.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'"); return result; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String convertFormatToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Type createTypeFromString(EDataType eDataType, String initialValue) { Type result = Type.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'"); return result; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String convertTypeToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NulValuesPolicy createNulValuesPolicyFromString(EDataType eDataType, String initialValue) { NulValuesPolicy result = NulValuesPolicy.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'"); return result; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String convertNulValuesPolicyToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public KernelFunction createKernelFunctionFromString(EDataType eDataType, String initialValue) { KernelFunction result = KernelFunction.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'"); return result; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String convertKernelFunctionToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public InterClusterSimilarity createInterClusterSimilarityFromString(EDataType eDataType, String initialValue) { InterClusterSimilarity result = InterClusterSimilarity.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'"); return result; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String convertInterClusterSimilarityToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public SourceType createSourceTypeFromString(EDataType eDataType, String initialValue) { SourceType result = SourceType.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'"); return result; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String convertSourceTypeToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public PipelineprojectPackage getPipelineprojectPackage() { return (PipelineprojectPackage)getEPackage(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @deprecated * @generated */ @Deprecated public static PipelineprojectPackage getPackage() { return PipelineprojectPackage.eINSTANCE; } } //PipelineprojectFactoryImpl
20,697
0.656424
0.656424
750
25.596001
26.961222
152
false
false
0
0
0
0
0
0
1.576
false
false
10
9fcfd602c8d36653dec9ecf007149ed4279d91f0
28,166,395,536,572
2163888d541a9c8671470445b35eb0f7346e3eaf
/sample/src/main/java/com/lapism/searchview/sample/view/RecyclerViewAdapter.java
82546f3a1a340ca9650d80e0d9bc5049f6fafc88
[ "Apache-2.0" ]
permissive
olxindonesia/SearchView
https://github.com/olxindonesia/SearchView
0d58dd431de421dac99ebcd0805f890e12d33bbe
3c49d3b2c2e4b3bc86e4b18b688c7a8a63b024a3
refs/heads/master
2018-01-06T08:19:42.778000
2017-02-03T10:45:36
2017-02-03T10:45:36
69,717,087
1
0
null
true
2017-02-03T10:45:47
2016-10-01T03:22:30
2016-10-01T03:22:32
2017-02-03T10:45:46
3,251
0
0
0
Java
null
null
package com.lapism.searchview.sample.view; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.lapism.searchview.sample.R; import java.util.List; public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> { private final List<String> mValues; public RecyclerViewAdapter(List<String> items) { //context.getTheme().resolveAttribute(R.attr.selectableItemBackground, mTypedValue, true); //TypedValue mTypedValue = new TypedValue(); //int mBackground = mTypedValue.resourceId; mValues = items; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_search, parent, false); //view.setBackgroundResource(mBackground); return new ViewHolder(view); } @Override public void onBindViewHolder(final ViewHolder holder, int position) { holder.mTextView.setText(mValues.get(position)); holder.mView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /*Context context = v.getContext(); Intent intent = news Intent(context, ExampleDetailActivity.class); intent.putExtra(ExampleDetailActivity.EXTRA_NAME, holder.mBoundString); context.startActivity(intent);*/ } }); //holder.mImageView.getContext()) //Cheeses2.getRandomCheeseDrawable } @Override public int getItemCount() { return mValues.size(); } static class ViewHolder extends RecyclerView.ViewHolder { final View mView; final TextView mTextView; ViewHolder(View view) { super(view); mView = view; mTextView = (TextView) view.findViewById(R.id.text); } @Override public String toString() { return super.toString() + " '" + mTextView.getText(); } } }
UTF-8
Java
2,194
java
RecyclerViewAdapter.java
Java
[]
null
[]
package com.lapism.searchview.sample.view; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.lapism.searchview.sample.R; import java.util.List; public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> { private final List<String> mValues; public RecyclerViewAdapter(List<String> items) { //context.getTheme().resolveAttribute(R.attr.selectableItemBackground, mTypedValue, true); //TypedValue mTypedValue = new TypedValue(); //int mBackground = mTypedValue.resourceId; mValues = items; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_search, parent, false); //view.setBackgroundResource(mBackground); return new ViewHolder(view); } @Override public void onBindViewHolder(final ViewHolder holder, int position) { holder.mTextView.setText(mValues.get(position)); holder.mView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /*Context context = v.getContext(); Intent intent = news Intent(context, ExampleDetailActivity.class); intent.putExtra(ExampleDetailActivity.EXTRA_NAME, holder.mBoundString); context.startActivity(intent);*/ } }); //holder.mImageView.getContext()) //Cheeses2.getRandomCheeseDrawable } @Override public int getItemCount() { return mValues.size(); } static class ViewHolder extends RecyclerView.ViewHolder { final View mView; final TextView mTextView; ViewHolder(View view) { super(view); mView = view; mTextView = (TextView) view.findViewById(R.id.text); } @Override public String toString() { return super.toString() + " '" + mTextView.getText(); } } }
2,194
0.652689
0.651778
71
29.915493
28.253754
111
false
false
0
0
0
0
0
0
0.521127
false
false
10
c97fba1b4485510a302c54202412b1dbb45e7a18
14,302,241,099,651
cbe15d23f2ab195192f1f526d9aa8157b0a162ea
/src/main/java/com/cg/tms/service/BookingServiceImpl.java
dafc8623d6c999cb222ce509f67027eba82cc426
[]
no_license
Niranjan-codes/Sprint
https://github.com/Niranjan-codes/Sprint
8d7422e9f8db8ba42bc17d1c9bb38ced2ddc9e2c
f0f8599aa00160a34a58a6abc7617646e745a0e1
refs/heads/master
2023-03-30T13:34:09.095000
2021-03-27T12:18:20
2021-03-27T12:18:20
352,064,889
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cg.tms.service; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cg.tms.entities.Booking; import com.cg.tms.exceptions.BookingNotFoundException; import com.cg.tms.exceptions.InvalidBookingException; import com.cg.tms.exceptions.InvalidIdException; import com.cg.tms.repository.IBookingRepository; @Service public class BookingServiceImpl implements IBookingService { @Autowired private IBookingRepository repo; @Override public Booking makeBooking(Booking booking) { validateUserId(booking.getUserId()); validateBookingType(booking.getBookingType()); validateBookingTitle(booking.getBookingTitle()); Booking saved=repo.save(booking); return saved; } @Override public Booking cancelBooking(int bookingId) throws BookingNotFoundException { return null; } @Override public Booking viewBooking(int bookingId) throws BookingNotFoundException { Optional<Booking> optional = repo.findById(bookingId); if(!optional.isPresent()) { throw new BookingNotFoundException("Booking not found"); } return optional.get(); } @Override public List<Booking> viewAllBookings() { return null; } void validateUserId(int id) { if (id < 0) { throw new InvalidIdException("ID cannot be negative"); } } void validateBookingType(String type) { if (type == null || type.isEmpty() || type.trim().isEmpty()) { throw new InvalidBookingException("Check Booking type"); } } void validateBookingTitle(String title) { if (title == null || title.isEmpty() || title.trim().isEmpty()) { throw new InvalidBookingException("Check Booking title"); } } }
UTF-8
Java
1,725
java
BookingServiceImpl.java
Java
[]
null
[]
package com.cg.tms.service; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cg.tms.entities.Booking; import com.cg.tms.exceptions.BookingNotFoundException; import com.cg.tms.exceptions.InvalidBookingException; import com.cg.tms.exceptions.InvalidIdException; import com.cg.tms.repository.IBookingRepository; @Service public class BookingServiceImpl implements IBookingService { @Autowired private IBookingRepository repo; @Override public Booking makeBooking(Booking booking) { validateUserId(booking.getUserId()); validateBookingType(booking.getBookingType()); validateBookingTitle(booking.getBookingTitle()); Booking saved=repo.save(booking); return saved; } @Override public Booking cancelBooking(int bookingId) throws BookingNotFoundException { return null; } @Override public Booking viewBooking(int bookingId) throws BookingNotFoundException { Optional<Booking> optional = repo.findById(bookingId); if(!optional.isPresent()) { throw new BookingNotFoundException("Booking not found"); } return optional.get(); } @Override public List<Booking> viewAllBookings() { return null; } void validateUserId(int id) { if (id < 0) { throw new InvalidIdException("ID cannot be negative"); } } void validateBookingType(String type) { if (type == null || type.isEmpty() || type.trim().isEmpty()) { throw new InvalidBookingException("Check Booking type"); } } void validateBookingTitle(String title) { if (title == null || title.isEmpty() || title.trim().isEmpty()) { throw new InvalidBookingException("Check Booking title"); } } }
1,725
0.758261
0.757681
67
24.746269
24.096413
78
false
false
0
0
0
0
0
0
1.477612
false
false
10
faaa639115ee5d11e09ee285984f6b0be9f9ea41
14,302,241,100,597
80403ec5838e300c53fcb96aeb84d409bdce1c0c
/server/modules/study/src/org/labkey/study/pipeline/StandaloneSpecimenTask.java
b68a10d6ddbf3b27c3b7dbb131d7b93d95f44204
[]
no_license
scchess/LabKey
https://github.com/scchess/LabKey
7e073656ea494026b0020ad7f9d9179f03d87b41
ce5f7a903c78c0d480002f738bccdbef97d6aeb9
refs/heads/master
2021-09-17T10:49:48.147000
2018-03-22T13:01:41
2018-03-22T13:01:41
126,447,224
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (c) 2009-2014 LabKey Corporation * * 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.labkey.study.pipeline; import org.labkey.api.pipeline.PipelineJob; /* * User: adam * Date: Sep 1, 2009 * Time: 4:37:31 PM */ // This task is used to import specimen archives directly via the pipeline ui. SpecimenBatch is the associated pipeline job. public class StandaloneSpecimenTask extends AbstractSpecimenTask<StandaloneSpecimenTask.Factory> { private StandaloneSpecimenTask(Factory factory, PipelineJob job) { super(factory, job); } public static class Factory extends AbstractSpecimenTaskFactory<Factory> { public Factory() { super(StandaloneSpecimenTask.class); } public PipelineJob.Task createTask(PipelineJob job) { return new StandaloneSpecimenTask(this, job); } } }
UTF-8
Java
1,459
java
StandaloneSpecimenTask.java
Java
[ { "context": "rg.labkey.api.pipeline.PipelineJob;\r\n\r\n/*\r\n* User: adam\r\n* Date: Sep 1, 2009\r\n* Time: 4:37:31 PM\r\n*/\r\n\r\n/", "end": 729, "score": 0.9991253614425659, "start": 725, "tag": "USERNAME", "value": "adam" } ]
null
[]
/* * Copyright (c) 2009-2014 LabKey Corporation * * 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.labkey.study.pipeline; import org.labkey.api.pipeline.PipelineJob; /* * User: adam * Date: Sep 1, 2009 * Time: 4:37:31 PM */ // This task is used to import specimen archives directly via the pipeline ui. SpecimenBatch is the associated pipeline job. public class StandaloneSpecimenTask extends AbstractSpecimenTask<StandaloneSpecimenTask.Factory> { private StandaloneSpecimenTask(Factory factory, PipelineJob job) { super(factory, job); } public static class Factory extends AbstractSpecimenTaskFactory<Factory> { public Factory() { super(StandaloneSpecimenTask.class); } public PipelineJob.Task createTask(PipelineJob job) { return new StandaloneSpecimenTask(this, job); } } }
1,459
0.687457
0.672378
47
29.042553
31.439884
125
false
false
0
0
0
0
0
0
0.297872
false
false
10
82285a97a69f1db009a53210f48c66810247de19
33,071,248,228,453
c57b9b22fff574127b2c65034d29e3e2722e6df3
/src/main/java/org/me/app/factory/abstact/HardDisk.java
0e5be93242203eef6d3eb1a6d86aeeacdce0b408
[]
no_license
longwu/design-pattern
https://github.com/longwu/design-pattern
d32ecc0ad1d4a42fdb27bbaa8039230092c83e68
4b4747547a36ad43c93cf1ea2f3fe29f3ca271ed
refs/heads/master
2020-04-15T06:32:06.283000
2019-01-07T17:20:14
2019-01-07T17:20:14
164,464,121
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.me.app.factory.abstact; public interface HardDisk { public void save(); }
UTF-8
Java
94
java
HardDisk.java
Java
[]
null
[]
package org.me.app.factory.abstact; public interface HardDisk { public void save(); }
94
0.702128
0.702128
5
17.799999
14.469277
35
false
false
0
0
0
0
0
0
0.4
false
false
10
1b083a926abff84cd412b1ca7d639ad55aaddb44
3,633,542,342,759
e6dc399cc717e39488f2ca9b7c9f15bd64dd1057
/src/ir/viratech/pond_ms/model/time_series/logic/TimeSeriesDateValuePairMgr.java
2acd99f7eca3aa54fe2af7fabf1aba0c196ad227
[]
no_license
amirhoseinkh91/pondms
https://github.com/amirhoseinkh91/pondms
1ed5cccc43bcdaefaa61f831060f92b3f9913c78
7950ca88dd4f6061f58c0f6d5b6dd1fc25ce28cb
refs/heads/master
2020-06-20T06:25:54.257000
2019-07-16T12:18:42
2019-07-16T12:18:42
197,024,235
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ir.viratech.pond_ms.model.time_series.logic; import ir.viratech.commons.persistence.base.BaseAbstractEntityDAO; import ir.viratech.pond_ms.model.time_series.RootCategory; import ir.viratech.pond_ms.model.time_series.base.BaseRootCategoryMgr; import ir.viratech.pond_ms.model.time_series.base.BaseTimeSeriesDateValuePairMgr; import ir.viratech.pond_ms.model.time_series.dao.RootCategoryDAO; /** * Mgr class for entity "ir.viratech.pond_ms.model.time_series.TimeSeriesDateValuePair". */ public class TimeSeriesDateValuePairMgr extends BaseTimeSeriesDateValuePairMgr { public void addTimeSeriesToPond(RootCategory newCategory) { BaseAbstractEntityDAO.closeCurrentThreadSessions(); BaseAbstractEntityDAO.touchSession(); RootCategory root = RootCategoryDAO.getInstance() .getByGroupUidAndPondUid(newCategory.getGroup().getExtuid(), newCategory.getPond().getExtuid()); if(root == null) RootCategoryMgr.getInstance().add(newCategory); else { BaseRootCategoryMgr rootCategoryMgr = BaseRootCategoryMgr.getInstance(); rootCategoryMgr.delete(root); RootCategoryMgr.getInstance().add(newCategory); } } public void addTimeSeriesToGISVectorObject(RootCategory newCategory) { BaseAbstractEntityDAO.closeCurrentThreadSessions(); BaseAbstractEntityDAO.touchSession(); RootCategory root = RootCategoryDAO.getInstance() .getByGroupUidAndObjectUid(newCategory.getGroup().getExtuid(), newCategory.getGISVectorObject().getExtuid()); if(root == null) RootCategoryMgr.getInstance().add(newCategory); else { BaseRootCategoryMgr rootCategoryMgr = BaseRootCategoryMgr.getInstance(); rootCategoryMgr.delete(root); RootCategoryMgr.getInstance().add(newCategory); } } }
UTF-8
Java
1,752
java
TimeSeriesDateValuePairMgr.java
Java
[]
null
[]
package ir.viratech.pond_ms.model.time_series.logic; import ir.viratech.commons.persistence.base.BaseAbstractEntityDAO; import ir.viratech.pond_ms.model.time_series.RootCategory; import ir.viratech.pond_ms.model.time_series.base.BaseRootCategoryMgr; import ir.viratech.pond_ms.model.time_series.base.BaseTimeSeriesDateValuePairMgr; import ir.viratech.pond_ms.model.time_series.dao.RootCategoryDAO; /** * Mgr class for entity "ir.viratech.pond_ms.model.time_series.TimeSeriesDateValuePair". */ public class TimeSeriesDateValuePairMgr extends BaseTimeSeriesDateValuePairMgr { public void addTimeSeriesToPond(RootCategory newCategory) { BaseAbstractEntityDAO.closeCurrentThreadSessions(); BaseAbstractEntityDAO.touchSession(); RootCategory root = RootCategoryDAO.getInstance() .getByGroupUidAndPondUid(newCategory.getGroup().getExtuid(), newCategory.getPond().getExtuid()); if(root == null) RootCategoryMgr.getInstance().add(newCategory); else { BaseRootCategoryMgr rootCategoryMgr = BaseRootCategoryMgr.getInstance(); rootCategoryMgr.delete(root); RootCategoryMgr.getInstance().add(newCategory); } } public void addTimeSeriesToGISVectorObject(RootCategory newCategory) { BaseAbstractEntityDAO.closeCurrentThreadSessions(); BaseAbstractEntityDAO.touchSession(); RootCategory root = RootCategoryDAO.getInstance() .getByGroupUidAndObjectUid(newCategory.getGroup().getExtuid(), newCategory.getGISVectorObject().getExtuid()); if(root == null) RootCategoryMgr.getInstance().add(newCategory); else { BaseRootCategoryMgr rootCategoryMgr = BaseRootCategoryMgr.getInstance(); rootCategoryMgr.delete(root); RootCategoryMgr.getInstance().add(newCategory); } } }
1,752
0.785388
0.785388
55
30.872726
29.166018
88
false
false
0
0
0
0
0
0
2.054545
false
false
10
f9bde08507a8c45cf34d92ae596e0c8857b8b938
22,170,621,197,136
e7deda1e83083c94cfa1dcae4eb691897f77093d
/src/main/java/com/topsci/qh/webmanagement/Business/Normal/ORGANIZATIONBZREGController.java
4166681dd8a7d3d299092a0376b7eac203499c5a
[]
no_license
dingwei92/exchange-web
https://github.com/dingwei92/exchange-web
fd83f3a05118e5a95b977e3ec083cd35c5dc7115
16ab0bbc6728e394adcf7097e52016996cd8a508
refs/heads/master
2022-12-02T17:06:25.426000
2020-08-14T05:57:30
2020-08-14T05:57:32
287,455,438
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.topsci.qh.webmanagement.Business.Normal; import com.topsci.qh.webmanagement.Service.Normal.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.annotation.Resource; /** * 机构管理 * @author Administrator * */ @Controller @RequestMapping("/orgReg") public class ORGANIZATIONBZREGController { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Resource private ORGANIZATIONBZREGService orgRegService; @Resource private RoleService roleService; @Autowired private OrganizationService orgService; @Resource private DZXZQYBZService xzqyService; @Resource private CV0810001Service cv08001Service; @Resource private GBT12402Service gbt12402Service; @Autowired private OrganizationService standardOrgService; /*@Override @RequestMapping("/list.do") public ModelAndView list(HttpServletRequest request, PageInfo pageInfo) { ModelAndView model = new ModelAndView("/Normal/ORGANIZATIONBZREG/list"); pageInfo = getPageInfo(request, pageInfo); String keyWords = request.getParameter("search"); List<ORGANIZATIONBZREG> regs = orgRegService.findPageList(pageInfo,keyWords); model.addObject("pageinfo", pageInfo); model.addObject("orgs", regs); return model; } @RequestMapping("/review.do") @ResponseBody public Map<String,Object> review(HttpServletRequest request,RedirectAttributes attr) { Map<String,Object> result = new HashMap<>(); //判断当前登录用户是否属于管理员角色 有此角色才可以审核 String userUUId = sessionManager.getSessionAttr(request, Constants.USERID); String roleUUId = roleService.getUserRole(userUUId); if(null == roleUUId || !Constants.REVIEW_ROLE_UUID.equalsIgnoreCase(roleUUId) ) { result.put("ret", 500); result.put("msg", "您当前登录的用户没有审批权限"); return result; } attr.addAttribute(Constants.CURRENT_PAGE,request.getParameter(Constants.CURRENT_PAGE)); try { String indexId = request.getParameter("indexId"); String status = request.getParameter("status"); ORGANIZATIONBZREG orgReg = orgRegService.getById(Long.valueOf(indexId)); ORGANIZATIONBZREG parent = orgRegService.getById(Long.valueOf(orgReg.getParent().getOrgId())); if(parent == null) { Organizationbz standardParent = standardOrgService.findByOrgId(orgReg.getParent().getOrgId()); if(standardParent == null) { result.put("ret", 500); result.put("msg", "您选择的父级机构无效,请重新选择!"); return result; } } orgRegService.reviewOrgReg(indexId, status); //审批通过时向主表插入数据 if("1".equals(status)) { orgRegService.saveORGANIZATIONBZ(orgReg); } result.put("ret", 0); result.put("msg", "审核完成"); } catch (Exception e) { e.printStackTrace(); logger.error("机构审批异常.."); } return result; } @RequestMapping("/edit.do") @Override public ModelAndView edit(HttpServletRequest request) { ModelAndView model = new ModelAndView("/Normal/ORGANIZATIONBZREG/edit"); String indexId = request.getParameter("indexId"); //查询所有机构 用作表单页面的上级机构下拉框 List<Organizationbz> orgList = orgService.findAll(); model.addObject("orgs",orgList); //查询行政区域 List<DZXZQYBZ> xzqyList = xzqyService.findListByCondition(null); //机构类型 List<CV0810001> cv0810001s = cv08001Service.findAll(); model.addObject("orgTypes",cv0810001s); //经济类型 List<GBT12402> gbt12402s = gbt12402Service.findAll(); model.addObject("ecoTypes", gbt12402s); //医疗机构类别 List<HospitalsType> hospticalTypes = hospticalTypeService.findAll(); model.addObject("hospticalTypes",hospticalTypes); //所属县 level=4 List<DZXZQYBZ> countryList = xzqyList.stream().filter(c -> { if ("4".equals(c.getDj())) return true; return false; }).collect(Collectors.toList()); model.addObject("countryList",countryList); //所属镇 level=5 List<DZXZQYBZ> townList = xzqyList.stream().filter(c -> { if ("5".equals(c.getDj())) return true; return false; }).collect(Collectors.toList()); model.addObject("townList",townList); //所属村 level=6 List<DZXZQYBZ> villageList = xzqyList.stream().filter(c -> { if ("6".equals(c.getDj())) return true; return false; }).collect(Collectors.toList()); model.addObject("villageList",villageList); if(StringUtils.isNotBlank(indexId)) { model.addObject("title", "修改机构"); model.addObject("orgReg", orgRegService.getById(Long.valueOf(indexId))); }else { model.addObject("title", "添加机构"); } return model; } @RequestMapping("/saveOrUpdate.do") @ResponseBody public Map<String,Object> saveOrUpdate(HttpServletRequest request,ORGANIZATIONBZREG orgReg,RedirectAttributes attr) { Map<String,Object> result = new HashMap<>(); try { orgRegService.saveOrUpdate(orgReg); result.put("ret", 0); result.put("msg", "操作成功"); }catch(Exception e) { result.put("ret", 500); result.put("msg", "操作失败"); e.printStackTrace(); logger.error("添加,修改机构信息时出现异常"); } return result; }*/ }
UTF-8
Java
5,400
java
ORGANIZATIONBZREGController.java
Java
[ { "context": "x.annotation.Resource;\n\n/**\n * 机构管理\n * @author Administrator\n *\n */\n@Controller\n@RequestMapping(\"/orgReg\")\npub", "end": 416, "score": 0.5492836236953735, "start": 403, "tag": "USERNAME", "value": "Administrator" } ]
null
[]
package com.topsci.qh.webmanagement.Business.Normal; import com.topsci.qh.webmanagement.Service.Normal.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.annotation.Resource; /** * 机构管理 * @author Administrator * */ @Controller @RequestMapping("/orgReg") public class ORGANIZATIONBZREGController { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Resource private ORGANIZATIONBZREGService orgRegService; @Resource private RoleService roleService; @Autowired private OrganizationService orgService; @Resource private DZXZQYBZService xzqyService; @Resource private CV0810001Service cv08001Service; @Resource private GBT12402Service gbt12402Service; @Autowired private OrganizationService standardOrgService; /*@Override @RequestMapping("/list.do") public ModelAndView list(HttpServletRequest request, PageInfo pageInfo) { ModelAndView model = new ModelAndView("/Normal/ORGANIZATIONBZREG/list"); pageInfo = getPageInfo(request, pageInfo); String keyWords = request.getParameter("search"); List<ORGANIZATIONBZREG> regs = orgRegService.findPageList(pageInfo,keyWords); model.addObject("pageinfo", pageInfo); model.addObject("orgs", regs); return model; } @RequestMapping("/review.do") @ResponseBody public Map<String,Object> review(HttpServletRequest request,RedirectAttributes attr) { Map<String,Object> result = new HashMap<>(); //判断当前登录用户是否属于管理员角色 有此角色才可以审核 String userUUId = sessionManager.getSessionAttr(request, Constants.USERID); String roleUUId = roleService.getUserRole(userUUId); if(null == roleUUId || !Constants.REVIEW_ROLE_UUID.equalsIgnoreCase(roleUUId) ) { result.put("ret", 500); result.put("msg", "您当前登录的用户没有审批权限"); return result; } attr.addAttribute(Constants.CURRENT_PAGE,request.getParameter(Constants.CURRENT_PAGE)); try { String indexId = request.getParameter("indexId"); String status = request.getParameter("status"); ORGANIZATIONBZREG orgReg = orgRegService.getById(Long.valueOf(indexId)); ORGANIZATIONBZREG parent = orgRegService.getById(Long.valueOf(orgReg.getParent().getOrgId())); if(parent == null) { Organizationbz standardParent = standardOrgService.findByOrgId(orgReg.getParent().getOrgId()); if(standardParent == null) { result.put("ret", 500); result.put("msg", "您选择的父级机构无效,请重新选择!"); return result; } } orgRegService.reviewOrgReg(indexId, status); //审批通过时向主表插入数据 if("1".equals(status)) { orgRegService.saveORGANIZATIONBZ(orgReg); } result.put("ret", 0); result.put("msg", "审核完成"); } catch (Exception e) { e.printStackTrace(); logger.error("机构审批异常.."); } return result; } @RequestMapping("/edit.do") @Override public ModelAndView edit(HttpServletRequest request) { ModelAndView model = new ModelAndView("/Normal/ORGANIZATIONBZREG/edit"); String indexId = request.getParameter("indexId"); //查询所有机构 用作表单页面的上级机构下拉框 List<Organizationbz> orgList = orgService.findAll(); model.addObject("orgs",orgList); //查询行政区域 List<DZXZQYBZ> xzqyList = xzqyService.findListByCondition(null); //机构类型 List<CV0810001> cv0810001s = cv08001Service.findAll(); model.addObject("orgTypes",cv0810001s); //经济类型 List<GBT12402> gbt12402s = gbt12402Service.findAll(); model.addObject("ecoTypes", gbt12402s); //医疗机构类别 List<HospitalsType> hospticalTypes = hospticalTypeService.findAll(); model.addObject("hospticalTypes",hospticalTypes); //所属县 level=4 List<DZXZQYBZ> countryList = xzqyList.stream().filter(c -> { if ("4".equals(c.getDj())) return true; return false; }).collect(Collectors.toList()); model.addObject("countryList",countryList); //所属镇 level=5 List<DZXZQYBZ> townList = xzqyList.stream().filter(c -> { if ("5".equals(c.getDj())) return true; return false; }).collect(Collectors.toList()); model.addObject("townList",townList); //所属村 level=6 List<DZXZQYBZ> villageList = xzqyList.stream().filter(c -> { if ("6".equals(c.getDj())) return true; return false; }).collect(Collectors.toList()); model.addObject("villageList",villageList); if(StringUtils.isNotBlank(indexId)) { model.addObject("title", "修改机构"); model.addObject("orgReg", orgRegService.getById(Long.valueOf(indexId))); }else { model.addObject("title", "添加机构"); } return model; } @RequestMapping("/saveOrUpdate.do") @ResponseBody public Map<String,Object> saveOrUpdate(HttpServletRequest request,ORGANIZATIONBZREG orgReg,RedirectAttributes attr) { Map<String,Object> result = new HashMap<>(); try { orgRegService.saveOrUpdate(orgReg); result.put("ret", 0); result.put("msg", "操作成功"); }catch(Exception e) { result.put("ret", 500); result.put("msg", "操作失败"); e.printStackTrace(); logger.error("添加,修改机构信息时出现异常"); } return result; }*/ }
5,400
0.722353
0.705037
176
27.875
24.71603
118
false
false
0
0
0
0
0
0
2.505682
false
false
10
ebe042c09fa0ce908af28ae659fdfdb9ef4ad8b0
7,078,106,113,679
0a06cb0c464e68470edb29a07a93887ccace8a69
/LeetCodeSolutions/src/easy/PowerOfTwo.java
fc0d36299985d8d71a45753944a56771b266f874
[]
no_license
gzwongkk/LeetCode
https://github.com/gzwongkk/LeetCode
33859fe9b3429ad50d0943b2aee66d0d3c270138
91977f47ebd03605357c2eb0b9c26d25b6f136f6
refs/heads/master
2020-12-09T09:02:28.764000
2017-09-01T10:05:33
2017-09-01T10:05:33
38,517,922
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package easy; public class PowerOfTwo { /** * Given an integer, write a function to determine if it is a power of two. **/ public static void main(String[] args) { int input = 2048; System.out.println(isPowerOfTwo(input)); } /* * Bitwise operation can be tricky. Since an integer being power of two must have only * one 1 in its binary representation(2^0 = 1), n & n-1 can easily check this condition. */ public static boolean isPowerOfTwo(int n){ return n > 0 && (n&(n-1)) == 0; } }
UTF-8
Java
531
java
PowerOfTwo.java
Java
[]
null
[]
package easy; public class PowerOfTwo { /** * Given an integer, write a function to determine if it is a power of two. **/ public static void main(String[] args) { int input = 2048; System.out.println(isPowerOfTwo(input)); } /* * Bitwise operation can be tricky. Since an integer being power of two must have only * one 1 in its binary representation(2^0 = 1), n & n-1 can easily check this condition. */ public static boolean isPowerOfTwo(int n){ return n > 0 && (n&(n-1)) == 0; } }
531
0.640301
0.617702
21
23.285715
28.861151
89
false
false
0
0
0
0
0
0
1.095238
false
false
10
4075d80338220a9c8573b8cee2e6680ab00b9ddd
31,868,657,347,086
21d493388b0e3526bcffad2d7f150cc20b7be8c5
/app/src/main/java/com/andela/checkpoint/onestep/fragments/LocationListFragment.java
9d36074a801415e3c3569dca6f30172eb37309fd
[]
no_license
jugba/checkpoint-4
https://github.com/jugba/checkpoint-4
56ab3c705562b434442af58bcee683c9d2f9718e
e8a973fe5e61c1f4b4e4d2303c403f9862bce3ae
refs/heads/master
2021-05-30T20:44:23.763000
2015-11-11T16:27:20
2015-11-11T16:27:20
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.andela.checkpoint.onestep.fragments; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.andela.checkpoint.onestep.R; import com.andela.checkpoint.onestep.ui_helpers.recyclerView.ViewPagerAdapter; import java.util.ArrayList; import java.util.List; public class LocationListFragment extends Fragment { private final String LOGS_BY_DAY = "Logs By Day"; private final String LOGS_BY_LOCATION = "Logs By Location"; private ViewPager mViewPager; private TabLayout mTabLayout; public LocationListFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_location_list, container, false); mViewPager = (ViewPager) view.findViewById(R.id.viewpager); setupViewPager(mViewPager); mTabLayout = (TabLayout) view.findViewById(R.id.slidingTab); mTabLayout.setupWithViewPager(mViewPager); return view; } private void setupViewPager(ViewPager viewPager) { ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager()); adapter.addFragment(new LocationByDateFragment(), LOGS_BY_DAY); adapter.addFragment(new LocationByLocationFragment(), LOGS_BY_LOCATION); viewPager.setAdapter(adapter); } }
UTF-8
Java
1,852
java
LocationListFragment.java
Java
[]
null
[]
package com.andela.checkpoint.onestep.fragments; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.andela.checkpoint.onestep.R; import com.andela.checkpoint.onestep.ui_helpers.recyclerView.ViewPagerAdapter; import java.util.ArrayList; import java.util.List; public class LocationListFragment extends Fragment { private final String LOGS_BY_DAY = "Logs By Day"; private final String LOGS_BY_LOCATION = "Logs By Location"; private ViewPager mViewPager; private TabLayout mTabLayout; public LocationListFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_location_list, container, false); mViewPager = (ViewPager) view.findViewById(R.id.viewpager); setupViewPager(mViewPager); mTabLayout = (TabLayout) view.findViewById(R.id.slidingTab); mTabLayout.setupWithViewPager(mViewPager); return view; } private void setupViewPager(ViewPager viewPager) { ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager()); adapter.addFragment(new LocationByDateFragment(), LOGS_BY_DAY); adapter.addFragment(new LocationByLocationFragment(), LOGS_BY_LOCATION); viewPager.setAdapter(adapter); } }
1,852
0.738121
0.735961
58
30.931034
26.732946
88
false
false
0
0
0
0
0
0
0.603448
false
false
10
7ed293ede010643b60442c845093e05fa3980f10
30,700,426,258,585
93bc924502da1cf43dece04a3a96ab75ce9ede78
/src/backjun/N11004.java
56fe823529ecebcd79726c2a85248fc771135f75
[]
no_license
guswns1659/Java-Algorithm
https://github.com/guswns1659/Java-Algorithm
fb9825cb8042336f1fc1bc8f95e0b8c511470161
965a2f4ef3f6077c1f6ed86f6ae14513b034cb96
refs/heads/master
2020-12-31T22:27:36.727000
2020-11-02T08:44:36
2020-11-02T08:44:36
239,054,091
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package backjun; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.StringTokenizer; public class N11004 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer stringTokenizer = new StringTokenizer(br.readLine()); int n = Integer.parseInt(stringTokenizer.nextToken()); int k = Integer.parseInt(stringTokenizer.nextToken()); List<Integer> data = new ArrayList<>(); stringTokenizer = new StringTokenizer(br.readLine()); for (int loop = 0; loop < n; loop++) { data.add(Integer.parseInt(stringTokenizer.nextToken())); } Collections.sort(data); System.out.println(data.get(k - 1)); } }
UTF-8
Java
925
java
N11004.java
Java
[]
null
[]
package backjun; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.StringTokenizer; public class N11004 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer stringTokenizer = new StringTokenizer(br.readLine()); int n = Integer.parseInt(stringTokenizer.nextToken()); int k = Integer.parseInt(stringTokenizer.nextToken()); List<Integer> data = new ArrayList<>(); stringTokenizer = new StringTokenizer(br.readLine()); for (int loop = 0; loop < n; loop++) { data.add(Integer.parseInt(stringTokenizer.nextToken())); } Collections.sort(data); System.out.println(data.get(k - 1)); } }
925
0.687568
0.68
30
29.833334
25.611303
81
false
false
0
0
0
0
0
0
0.633333
false
false
10
6373810fe5f41adb57cf740e68cdb9d38abb7c45
15,848,429,358,072
9c561db19855ede05afdd721660c3fabaf5bc294
/src/grozail/lab6/FuzzyUlComparator.java
b6e9257f2ed58ba6d9e141d96921d34450869553
[]
no_license
grozail/uni-labs-2016
https://github.com/grozail/uni-labs-2016
2810fe833adc8411af590deee5f3b8755a2af9eb
14adee13dc7632e3ed4cd33f061c2680053ee14f
refs/heads/master
2021-01-20T01:54:18.202000
2017-04-25T09:53:34
2017-04-25T09:53:34
89,344,350
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package grozail.lab6; import java.util.Comparator; import java.util.function.Function; /** * Created by grozail on 25.10.16. * */ public class FuzzyUlComparator implements Comparator<FuzzyNumber> { public int compare(FuzzyNumber o1, FuzzyNumber o2) { return o1.getUl() < o2.getUl() ? -1 : o1.getUl() > o2.getUl() ? 1 : 0; } public Comparator<FuzzyNumber> reversed() { return new Comparator<FuzzyNumber>() { public int compare(FuzzyNumber o1, FuzzyNumber o2) { return o1.getUl() < o2.getUl() ? 1 : o1.getUl() > o2.getUl() ? -1 : 0; } }; } public String toString() { return "Represents Comparator<FuzzyNumber> for sorting by UL field."; } }
UTF-8
Java
674
java
FuzzyUlComparator.java
Java
[ { "context": "rt java.util.function.Function;\n\n/**\n * Created by grozail on 25.10.16.\n *\n */\npublic class FuzzyUlComparato", "end": 114, "score": 0.9995473027229309, "start": 107, "tag": "USERNAME", "value": "grozail" } ]
null
[]
package grozail.lab6; import java.util.Comparator; import java.util.function.Function; /** * Created by grozail on 25.10.16. * */ public class FuzzyUlComparator implements Comparator<FuzzyNumber> { public int compare(FuzzyNumber o1, FuzzyNumber o2) { return o1.getUl() < o2.getUl() ? -1 : o1.getUl() > o2.getUl() ? 1 : 0; } public Comparator<FuzzyNumber> reversed() { return new Comparator<FuzzyNumber>() { public int compare(FuzzyNumber o1, FuzzyNumber o2) { return o1.getUl() < o2.getUl() ? 1 : o1.getUl() > o2.getUl() ? -1 : 0; } }; } public String toString() { return "Represents Comparator<FuzzyNumber> for sorting by UL field."; } }
674
0.67359
0.636499
30
21.466667
25.908472
74
false
false
0
0
0
0
0
0
1.1
false
false
10
6753ef3a9d1684943ff4ca54024a67a4853c7caf
5,059,471,514,484
1010e948ed26b85a8fb5c0af2d34f169f23e97e0
/tools/parser-lib/parser/src/main/java/org/onepf/appdf/parser/TopLevelTag.java
cdff4d543ff90052639a92adc88144d68d57139f
[]
no_license
kapoynako34/AppDF
https://github.com/kapoynako34/AppDF
68016a13d75943058d0d7eab361d0ee67e06612b
52f78656ee2911667a56eb4a1f32135e8c5a6c9b
refs/heads/master
2021-01-16T22:10:47.502000
2013-04-06T08:01:31
2013-04-06T08:01:31
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/******************************************************************************* * Copyright 2012 One Platform Foundation * * 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.onepf.appdf.parser; import org.onepf.appdf.model.ApkFilesInfo; import org.onepf.appdf.model.Application; import org.onepf.appdf.model.Availability; import org.onepf.appdf.model.Consent; import org.onepf.appdf.model.ContentDescription; import org.onepf.appdf.model.CustomerSupport; import org.onepf.appdf.model.PriceInfo; import org.onepf.appdf.model.Requirments; import org.onepf.appdf.parser.util.XmlUtil; import org.w3c.dom.Node; public enum TopLevelTag implements NodeParser<Application> { CATEGORIZATION { @Override public void parse(Node node, Application application) throws ParsingException { (new CategorizationParser()).parse(node, application); } }, DESCRIPTION { @Override public void parse(Node node, Application application) throws ParsingException { (new DescriptionParser(true)).parse(node, application); } }, DESCRIPTION_LOCALIZATION { @Override public void parse(Node node, Application application) throws ParsingException { (new DescriptionParser(false)).parse(node, application); } }, CONTENT_DESCRIPTION { @Override public void parse(Node node, Application element) throws ParsingException { ContentDescription contentDescription = new ContentDescription(); (new ContentDescriptionParser()).parse(node, contentDescription); element.setContentDescription(contentDescription); } }, AVAILABILITY { @Override public void parse(Node node, Application element) throws ParsingException { Availability availability = new Availability(); (new AvailabilityParser()).parse(node, availability); element.setAvalability(availability); } }, PRICE { @Override public void parse(Node node, Application element) throws ParsingException { PriceInfo priceInfo = new PriceInfo(); Node freeAttr = node.getAttributes().getNamedItem("free"); if (freeAttr == null) { throw new ParsingException( "Required attribute free is missing inside price tag"); } priceInfo .setFree("yes".equalsIgnoreCase(freeAttr.getTextContent())); (new PriceParser()).parse(node, priceInfo); element.setPriceInfo(priceInfo); } }, /** * Apk files with extensions currently not supported since it's gonna be * removed from spec */ APK_FILES { private final static String APK_FILE_TAG = "apk-file"; @Override public void parse(Node node, Application element) throws ParsingException { for (String fileName : XmlUtil .collectNodeValues(node, APK_FILE_TAG)) { ApkFilesInfo filesInfo = element.getFilesInfo(); if (filesInfo == null) { filesInfo = new ApkFilesInfo(); element.setFilesInfo(filesInfo); } ApkFilesInfo.ApkFile apkFile = new ApkFilesInfo.ApkFile(); apkFile.setFileName(fileName); filesInfo.addApkFile(apkFile); } } }, REQUIREMENTS { @Override public void parse(Node node, Application element) throws ParsingException { Requirments requirments = new Requirments(); (new RequirmentsParser()).parse(node, requirments); } }, TESTING_INSTRUCTIONS { @Override public void parse(Node node, Application element) throws ParsingException { element.setTestingInstructions(node.getTextContent()); } }, CONSENT { @Override public void parse(Node node, Application element) throws ParsingException { Consent consent = new Consent(); XmlUtil.mapChildsToBean(node, Consent.class, consent); element.setConsent(consent); } }, CUSTOMER_SUPPORT { @Override public void parse(Node node, Application element) throws ParsingException { CustomerSupport customerSupport = new CustomerSupport(); XmlUtil.mapChildsToBean(node, CustomerSupport.class, customerSupport); element.setCustomerSupport(customerSupport); } }, STORE_SPECIFIC{ public void parse(Node node, Application element) throws ParsingException { (new StoreSpecificParser()).parse(node, element); } } ; }
UTF-8
Java
5,770
java
TopLevelTag.java
Java
[]
null
[]
/******************************************************************************* * Copyright 2012 One Platform Foundation * * 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.onepf.appdf.parser; import org.onepf.appdf.model.ApkFilesInfo; import org.onepf.appdf.model.Application; import org.onepf.appdf.model.Availability; import org.onepf.appdf.model.Consent; import org.onepf.appdf.model.ContentDescription; import org.onepf.appdf.model.CustomerSupport; import org.onepf.appdf.model.PriceInfo; import org.onepf.appdf.model.Requirments; import org.onepf.appdf.parser.util.XmlUtil; import org.w3c.dom.Node; public enum TopLevelTag implements NodeParser<Application> { CATEGORIZATION { @Override public void parse(Node node, Application application) throws ParsingException { (new CategorizationParser()).parse(node, application); } }, DESCRIPTION { @Override public void parse(Node node, Application application) throws ParsingException { (new DescriptionParser(true)).parse(node, application); } }, DESCRIPTION_LOCALIZATION { @Override public void parse(Node node, Application application) throws ParsingException { (new DescriptionParser(false)).parse(node, application); } }, CONTENT_DESCRIPTION { @Override public void parse(Node node, Application element) throws ParsingException { ContentDescription contentDescription = new ContentDescription(); (new ContentDescriptionParser()).parse(node, contentDescription); element.setContentDescription(contentDescription); } }, AVAILABILITY { @Override public void parse(Node node, Application element) throws ParsingException { Availability availability = new Availability(); (new AvailabilityParser()).parse(node, availability); element.setAvalability(availability); } }, PRICE { @Override public void parse(Node node, Application element) throws ParsingException { PriceInfo priceInfo = new PriceInfo(); Node freeAttr = node.getAttributes().getNamedItem("free"); if (freeAttr == null) { throw new ParsingException( "Required attribute free is missing inside price tag"); } priceInfo .setFree("yes".equalsIgnoreCase(freeAttr.getTextContent())); (new PriceParser()).parse(node, priceInfo); element.setPriceInfo(priceInfo); } }, /** * Apk files with extensions currently not supported since it's gonna be * removed from spec */ APK_FILES { private final static String APK_FILE_TAG = "apk-file"; @Override public void parse(Node node, Application element) throws ParsingException { for (String fileName : XmlUtil .collectNodeValues(node, APK_FILE_TAG)) { ApkFilesInfo filesInfo = element.getFilesInfo(); if (filesInfo == null) { filesInfo = new ApkFilesInfo(); element.setFilesInfo(filesInfo); } ApkFilesInfo.ApkFile apkFile = new ApkFilesInfo.ApkFile(); apkFile.setFileName(fileName); filesInfo.addApkFile(apkFile); } } }, REQUIREMENTS { @Override public void parse(Node node, Application element) throws ParsingException { Requirments requirments = new Requirments(); (new RequirmentsParser()).parse(node, requirments); } }, TESTING_INSTRUCTIONS { @Override public void parse(Node node, Application element) throws ParsingException { element.setTestingInstructions(node.getTextContent()); } }, CONSENT { @Override public void parse(Node node, Application element) throws ParsingException { Consent consent = new Consent(); XmlUtil.mapChildsToBean(node, Consent.class, consent); element.setConsent(consent); } }, CUSTOMER_SUPPORT { @Override public void parse(Node node, Application element) throws ParsingException { CustomerSupport customerSupport = new CustomerSupport(); XmlUtil.mapChildsToBean(node, CustomerSupport.class, customerSupport); element.setCustomerSupport(customerSupport); } }, STORE_SPECIFIC{ public void parse(Node node, Application element) throws ParsingException { (new StoreSpecificParser()).parse(node, element); } } ; }
5,770
0.578683
0.577123
171
31.742689
25.741936
82
false
false
0
0
0
0
0
0
0.497076
false
false
10
205cc203cc71f66c0fb4a4b93389293873e85dbc
670,014,940,156
70801a482711746d7c9e5edeba9a91d2f5415f84
/app/src/main/java/com/hippo/nimingban/util/ResImageGetter.java
c56ded78a0d310df9b10e08bd90c3529a87c3c82
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "IJG", "Zlib", "BSD-3-Clause", "Libpng", "BSD-2-Clause", "MIT", "GPL-1.0-or-later", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
seven332/Nimingban
https://github.com/seven332/Nimingban
e38d076c7618b59e939bd7b6d15a82f5f90f377a
954d8a12235740665cc0376c36af960fe0502850
refs/heads/master
2022-08-21T14:04:19.954000
2022-02-25T10:27:59
2022-02-25T10:27:59
41,467,872
349
93
Apache-2.0
false
2019-03-25T05:50:01
2015-08-27T05:40:32
2019-03-25T03:53:56
2019-03-25T05:50:00
8,242
207
48
27
Java
false
null
/* * Copyright 2015 Hippo Seven * * 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.hippo.nimingban.util; import android.content.Context; import android.content.res.Resources; import android.graphics.drawable.Drawable; import com.hippo.text.Html; import com.hippo.yorozuya.StringUtils; public class ResImageGetter implements Html.ImageGetter { private static Resources sResources; public static void initialize(Context context) { sResources = context.getResources(); } @Override public Drawable getDrawable(String source) { if (StringUtils.isAllDigit(source)) { int resId = Integer.parseInt(source); Drawable d = sResources.getDrawable(resId); if (d != null) { d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); return d; } else { return null; } } else { return null; } } }
UTF-8
Java
1,495
java
ResImageGetter.java
Java
[ { "context": "/*\n * Copyright 2015 Hippo Seven\n *\n * Licensed under the Apache License, Version ", "end": 32, "score": 0.9998546838760376, "start": 21, "tag": "NAME", "value": "Hippo Seven" } ]
null
[]
/* * Copyright 2015 <NAME> * * 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.hippo.nimingban.util; import android.content.Context; import android.content.res.Resources; import android.graphics.drawable.Drawable; import com.hippo.text.Html; import com.hippo.yorozuya.StringUtils; public class ResImageGetter implements Html.ImageGetter { private static Resources sResources; public static void initialize(Context context) { sResources = context.getResources(); } @Override public Drawable getDrawable(String source) { if (StringUtils.isAllDigit(source)) { int resId = Integer.parseInt(source); Drawable d = sResources.getDrawable(resId); if (d != null) { d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); return d; } else { return null; } } else { return null; } } }
1,490
0.667559
0.66087
49
29.510204
24.494165
81
false
false
0
0
0
0
0
0
0.44898
false
false
10
2d87c63930caf436e7f59d0fa3c1b0e771ca6df2
15,144,054,724,643
4623b3eb1b7cc854f61acc5f4642e00edf682c7d
/dd-java-agent/src/main/java/datadog/trace/agent/TracingAgent.java
5ef759022938a28fdd5096b80fa1dfada3e99fb3
[ "Apache-2.0", "EPL-1.0", "LGPL-2.1-only", "MIT" ]
permissive
qudongfang/opentelemetry-auto-instr-java
https://github.com/qudongfang/opentelemetry-auto-instr-java
6fa8d0122ba13b4556171e5d674a395a6f0107f0
5ad3aeadd64a170b4515255641f73f916a8b6950
refs/heads/master
2020-08-13T06:37:17.303000
2019-11-20T08:11:48
2019-11-20T08:11:48
214,926,109
0
0
Apache-2.0
true
2019-10-14T01:58:43
2019-10-14T01:58:43
2019-10-14T01:58:25
2019-09-26T16:41:47
5
0
0
0
null
false
false
package datadog.trace.agent; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.lang.instrument.Instrumentation; import java.lang.management.ManagementFactory; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.CodeSource; import java.util.Arrays; import java.util.List; import java.util.jar.JarFile; import java.util.regex.Matcher; import java.util.regex.Pattern; /** Entry point for initializing the agent. */ public class TracingAgent { private static final String SIMPLE_LOGGER_SHOW_DATE_TIME_PROPERTY = "datadog.slf4j.simpleLogger.showDateTime"; private static final String SIMPLE_LOGGER_DATE_TIME_FORMAT_PROPERTY = "datadog.slf4j.simpleLogger.dateTimeFormat"; private static final String SIMPLE_LOGGER_DATE_TIME_FORMAT_DEFAULT = "'[dd.trace 'yyyy-MM-dd HH:mm:ss:SSS Z']'"; private static final String SIMPLE_LOGGER_DEFAULT_LOG_LEVEL_PROPERTY = "datadog.slf4j.simpleLogger.defaultLogLevel"; // fields must be managed under class lock private static ClassLoader AGENT_CLASSLOADER = null; public static void premain(final String agentArgs, final Instrumentation inst) throws Exception { agentmain(agentArgs, inst); } public static void agentmain(final String agentArgs, final Instrumentation inst) throws Exception { configureLogger(); final URL bootstrapURL = installBootstrapJar(inst); startDatadogAgent(inst, bootstrapURL); } private static synchronized void startDatadogAgent( final Instrumentation inst, final URL bootstrapURL) throws Exception { if (AGENT_CLASSLOADER == null) { final ClassLoader agentClassLoader = createDatadogClassLoader("agent-tooling-and-instrumentation.isolated", bootstrapURL); final ClassLoader contextLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(agentClassLoader); { // install agent final Class<?> agentInstallerClass = agentClassLoader.loadClass("datadog.trace.agent.tooling.AgentInstaller"); final Method agentInstallerMethod = agentInstallerClass.getMethod("installBytebuddyAgent", Instrumentation.class); agentInstallerMethod.invoke(null, inst); } { // install global tracer final Class<?> tracerInstallerClass = agentClassLoader.loadClass("datadog.trace.agent.tooling.TracerInstaller"); final Method tracerInstallerMethod = tracerInstallerClass.getMethod("installGlobalTracer"); tracerInstallerMethod.invoke(null); final Method logVersionInfoMethod = tracerInstallerClass.getMethod("logVersionInfo"); logVersionInfoMethod.invoke(null); } AGENT_CLASSLOADER = agentClassLoader; } finally { Thread.currentThread().setContextClassLoader(contextLoader); } } } private static void configureLogger() { setSystemPropertyDefault(SIMPLE_LOGGER_SHOW_DATE_TIME_PROPERTY, "true"); setSystemPropertyDefault( SIMPLE_LOGGER_DATE_TIME_FORMAT_PROPERTY, SIMPLE_LOGGER_DATE_TIME_FORMAT_DEFAULT); final boolean debugEnabled = isDebugMode(); if (debugEnabled) { setSystemPropertyDefault(SIMPLE_LOGGER_DEFAULT_LOG_LEVEL_PROPERTY, "DEBUG"); } } private static void setSystemPropertyDefault(final String property, final String value) { if (System.getProperty(property) == null) { System.setProperty(property, value); } } private static synchronized URL installBootstrapJar(final Instrumentation inst) throws IOException, URISyntaxException { URL bootstrapURL = null; // First try Code Source final CodeSource codeSource = TracingAgent.class.getProtectionDomain().getCodeSource(); if (codeSource != null) { bootstrapURL = codeSource.getLocation(); final File bootstrapFile = new File(bootstrapURL.toURI()); if (!bootstrapFile.isDirectory()) { inst.appendToBootstrapClassLoaderSearch(new JarFile(bootstrapFile)); return bootstrapURL; } } System.out.println("Could not get bootstrap jar from code source, using -javaagent arg"); // ManagementFactory indirectly references java.util.logging.LogManager // - On Oracle-based JDKs after 1.8 // - On IBM-based JDKs since at least 1.7 // This prevents custom log managers from working correctly // Use reflection to bypass the loading of the class final List<String> arguments = getVMArgumentsThroughReflection(); String agentArgument = null; for (final String arg : arguments) { if (arg.startsWith("-javaagent")) { if (agentArgument == null) { agentArgument = arg; } else { throw new RuntimeException( "Multiple javaagents specified and code source unavailable, not installing tracing agent"); } } } if (agentArgument == null) { throw new RuntimeException( "Could not find javaagent parameter and code source unavailable, not installing tracing agent"); } // argument is of the form -javaagent:/path/to/dd-java-agent.jar=optionalargumentstring final Matcher matcher = Pattern.compile("-javaagent:([^=]+).*").matcher(agentArgument); if (!matcher.matches()) { throw new RuntimeException("Unable to parse javaagent parameter: " + agentArgument); } bootstrapURL = new URL("file:" + matcher.group(1)); inst.appendToBootstrapClassLoaderSearch(new JarFile(new File(bootstrapURL.toURI()))); return bootstrapURL; } private static List<String> getVMArgumentsThroughReflection() { try { // Try Oracle-based final Class managementFactoryHelperClass = TracingAgent.class.getClassLoader().loadClass("sun.management.ManagementFactoryHelper"); final Class vmManagementClass = TracingAgent.class.getClassLoader().loadClass("sun.management.VMManagement"); Object vmManagement; try { vmManagement = managementFactoryHelperClass.getDeclaredMethod("getVMManagement").invoke(null); } catch (final NoSuchMethodException e) { // Older vm before getVMManagement() existed final Field field = managementFactoryHelperClass.getDeclaredField("jvm"); field.setAccessible(true); vmManagement = field.get(null); field.setAccessible(false); } return (List<String>) vmManagementClass.getMethod("getVmArguments").invoke(vmManagement); } catch (final ReflectiveOperationException e) { try { // Try IBM-based. final Class VMClass = TracingAgent.class.getClassLoader().loadClass("com.ibm.oti.vm.VM"); final String[] argArray = (String[]) VMClass.getMethod("getVMArgs").invoke(null); return Arrays.asList(argArray); } catch (final ReflectiveOperationException e1) { // Fallback to default System.out.println( "WARNING: Unable to get VM args through reflection. A custom java.util.logging.LogManager may not work correctly"); return ManagementFactory.getRuntimeMXBean().getInputArguments(); } } } /** * Create the datadog classloader. This must be called after the bootstrap jar has been appened to * the bootstrap classpath. * * @param innerJarFilename Filename of internal jar to use for the classpath of the datadog * classloader * @param bootstrapURL * @return Datadog Classloader */ private static ClassLoader createDatadogClassLoader( final String innerJarFilename, final URL bootstrapURL) throws Exception { final ClassLoader agentParent; if (isJavaBefore9()) { agentParent = null; // bootstrap } else { // platform classloader is parent of system in java 9+ agentParent = getPlatformClassLoader(); } final Class<?> loaderClass = ClassLoader.getSystemClassLoader().loadClass("datadog.trace.bootstrap.DatadogClassLoader"); final Constructor constructor = loaderClass.getDeclaredConstructor(URL.class, String.class, ClassLoader.class); return (ClassLoader) constructor.newInstance(bootstrapURL, innerJarFilename, agentParent); } private static ClassLoader getPlatformClassLoader() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { /* Must invoke ClassLoader.getPlatformClassLoader by reflection to remain compatible with java 7 + 8. */ final Method method = ClassLoader.class.getDeclaredMethod("getPlatformClassLoader"); return (ClassLoader) method.invoke(null); } /** * Determine if we should log in debug level according to dd.trace.debug * * @return true if we should */ private static boolean isDebugMode() { final String tracerDebugLevelSysprop = "dd.trace.debug"; final String tracerDebugLevelProp = System.getProperty(tracerDebugLevelSysprop); if (tracerDebugLevelProp != null) { return Boolean.parseBoolean(tracerDebugLevelProp); } final String tracerDebugLevelEnv = System.getenv(tracerDebugLevelSysprop.replace('.', '_').toUpperCase()); if (tracerDebugLevelEnv != null) { return Boolean.parseBoolean(tracerDebugLevelEnv); } return false; } private static boolean isJavaBefore9() { return System.getProperty("java.version").startsWith("1."); } /** * Main entry point. * * @param args command line agruments */ public static void main(final String... args) { try { System.out.println(getAgentVersion()); } catch (final Exception e) { System.out.println("Failed to parse agent version"); e.printStackTrace(); } } /** * Read version file out of the agent jar. * * @return Agent version */ public static String getAgentVersion() throws IOException { final StringBuilder sb = new StringBuilder(); try (final BufferedReader reader = new BufferedReader( new InputStreamReader( TracingAgent.class.getResourceAsStream("/dd-java-agent.version"), StandardCharsets.UTF_8))) { for (int c = reader.read(); c != -1; c = reader.read()) { sb.append((char) c); } } return sb.toString().trim(); } }
UTF-8
Java
10,563
java
TracingAgent.java
Java
[]
null
[]
package datadog.trace.agent; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.lang.instrument.Instrumentation; import java.lang.management.ManagementFactory; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.CodeSource; import java.util.Arrays; import java.util.List; import java.util.jar.JarFile; import java.util.regex.Matcher; import java.util.regex.Pattern; /** Entry point for initializing the agent. */ public class TracingAgent { private static final String SIMPLE_LOGGER_SHOW_DATE_TIME_PROPERTY = "datadog.slf4j.simpleLogger.showDateTime"; private static final String SIMPLE_LOGGER_DATE_TIME_FORMAT_PROPERTY = "datadog.slf4j.simpleLogger.dateTimeFormat"; private static final String SIMPLE_LOGGER_DATE_TIME_FORMAT_DEFAULT = "'[dd.trace 'yyyy-MM-dd HH:mm:ss:SSS Z']'"; private static final String SIMPLE_LOGGER_DEFAULT_LOG_LEVEL_PROPERTY = "datadog.slf4j.simpleLogger.defaultLogLevel"; // fields must be managed under class lock private static ClassLoader AGENT_CLASSLOADER = null; public static void premain(final String agentArgs, final Instrumentation inst) throws Exception { agentmain(agentArgs, inst); } public static void agentmain(final String agentArgs, final Instrumentation inst) throws Exception { configureLogger(); final URL bootstrapURL = installBootstrapJar(inst); startDatadogAgent(inst, bootstrapURL); } private static synchronized void startDatadogAgent( final Instrumentation inst, final URL bootstrapURL) throws Exception { if (AGENT_CLASSLOADER == null) { final ClassLoader agentClassLoader = createDatadogClassLoader("agent-tooling-and-instrumentation.isolated", bootstrapURL); final ClassLoader contextLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(agentClassLoader); { // install agent final Class<?> agentInstallerClass = agentClassLoader.loadClass("datadog.trace.agent.tooling.AgentInstaller"); final Method agentInstallerMethod = agentInstallerClass.getMethod("installBytebuddyAgent", Instrumentation.class); agentInstallerMethod.invoke(null, inst); } { // install global tracer final Class<?> tracerInstallerClass = agentClassLoader.loadClass("datadog.trace.agent.tooling.TracerInstaller"); final Method tracerInstallerMethod = tracerInstallerClass.getMethod("installGlobalTracer"); tracerInstallerMethod.invoke(null); final Method logVersionInfoMethod = tracerInstallerClass.getMethod("logVersionInfo"); logVersionInfoMethod.invoke(null); } AGENT_CLASSLOADER = agentClassLoader; } finally { Thread.currentThread().setContextClassLoader(contextLoader); } } } private static void configureLogger() { setSystemPropertyDefault(SIMPLE_LOGGER_SHOW_DATE_TIME_PROPERTY, "true"); setSystemPropertyDefault( SIMPLE_LOGGER_DATE_TIME_FORMAT_PROPERTY, SIMPLE_LOGGER_DATE_TIME_FORMAT_DEFAULT); final boolean debugEnabled = isDebugMode(); if (debugEnabled) { setSystemPropertyDefault(SIMPLE_LOGGER_DEFAULT_LOG_LEVEL_PROPERTY, "DEBUG"); } } private static void setSystemPropertyDefault(final String property, final String value) { if (System.getProperty(property) == null) { System.setProperty(property, value); } } private static synchronized URL installBootstrapJar(final Instrumentation inst) throws IOException, URISyntaxException { URL bootstrapURL = null; // First try Code Source final CodeSource codeSource = TracingAgent.class.getProtectionDomain().getCodeSource(); if (codeSource != null) { bootstrapURL = codeSource.getLocation(); final File bootstrapFile = new File(bootstrapURL.toURI()); if (!bootstrapFile.isDirectory()) { inst.appendToBootstrapClassLoaderSearch(new JarFile(bootstrapFile)); return bootstrapURL; } } System.out.println("Could not get bootstrap jar from code source, using -javaagent arg"); // ManagementFactory indirectly references java.util.logging.LogManager // - On Oracle-based JDKs after 1.8 // - On IBM-based JDKs since at least 1.7 // This prevents custom log managers from working correctly // Use reflection to bypass the loading of the class final List<String> arguments = getVMArgumentsThroughReflection(); String agentArgument = null; for (final String arg : arguments) { if (arg.startsWith("-javaagent")) { if (agentArgument == null) { agentArgument = arg; } else { throw new RuntimeException( "Multiple javaagents specified and code source unavailable, not installing tracing agent"); } } } if (agentArgument == null) { throw new RuntimeException( "Could not find javaagent parameter and code source unavailable, not installing tracing agent"); } // argument is of the form -javaagent:/path/to/dd-java-agent.jar=optionalargumentstring final Matcher matcher = Pattern.compile("-javaagent:([^=]+).*").matcher(agentArgument); if (!matcher.matches()) { throw new RuntimeException("Unable to parse javaagent parameter: " + agentArgument); } bootstrapURL = new URL("file:" + matcher.group(1)); inst.appendToBootstrapClassLoaderSearch(new JarFile(new File(bootstrapURL.toURI()))); return bootstrapURL; } private static List<String> getVMArgumentsThroughReflection() { try { // Try Oracle-based final Class managementFactoryHelperClass = TracingAgent.class.getClassLoader().loadClass("sun.management.ManagementFactoryHelper"); final Class vmManagementClass = TracingAgent.class.getClassLoader().loadClass("sun.management.VMManagement"); Object vmManagement; try { vmManagement = managementFactoryHelperClass.getDeclaredMethod("getVMManagement").invoke(null); } catch (final NoSuchMethodException e) { // Older vm before getVMManagement() existed final Field field = managementFactoryHelperClass.getDeclaredField("jvm"); field.setAccessible(true); vmManagement = field.get(null); field.setAccessible(false); } return (List<String>) vmManagementClass.getMethod("getVmArguments").invoke(vmManagement); } catch (final ReflectiveOperationException e) { try { // Try IBM-based. final Class VMClass = TracingAgent.class.getClassLoader().loadClass("com.ibm.oti.vm.VM"); final String[] argArray = (String[]) VMClass.getMethod("getVMArgs").invoke(null); return Arrays.asList(argArray); } catch (final ReflectiveOperationException e1) { // Fallback to default System.out.println( "WARNING: Unable to get VM args through reflection. A custom java.util.logging.LogManager may not work correctly"); return ManagementFactory.getRuntimeMXBean().getInputArguments(); } } } /** * Create the datadog classloader. This must be called after the bootstrap jar has been appened to * the bootstrap classpath. * * @param innerJarFilename Filename of internal jar to use for the classpath of the datadog * classloader * @param bootstrapURL * @return Datadog Classloader */ private static ClassLoader createDatadogClassLoader( final String innerJarFilename, final URL bootstrapURL) throws Exception { final ClassLoader agentParent; if (isJavaBefore9()) { agentParent = null; // bootstrap } else { // platform classloader is parent of system in java 9+ agentParent = getPlatformClassLoader(); } final Class<?> loaderClass = ClassLoader.getSystemClassLoader().loadClass("datadog.trace.bootstrap.DatadogClassLoader"); final Constructor constructor = loaderClass.getDeclaredConstructor(URL.class, String.class, ClassLoader.class); return (ClassLoader) constructor.newInstance(bootstrapURL, innerJarFilename, agentParent); } private static ClassLoader getPlatformClassLoader() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { /* Must invoke ClassLoader.getPlatformClassLoader by reflection to remain compatible with java 7 + 8. */ final Method method = ClassLoader.class.getDeclaredMethod("getPlatformClassLoader"); return (ClassLoader) method.invoke(null); } /** * Determine if we should log in debug level according to dd.trace.debug * * @return true if we should */ private static boolean isDebugMode() { final String tracerDebugLevelSysprop = "dd.trace.debug"; final String tracerDebugLevelProp = System.getProperty(tracerDebugLevelSysprop); if (tracerDebugLevelProp != null) { return Boolean.parseBoolean(tracerDebugLevelProp); } final String tracerDebugLevelEnv = System.getenv(tracerDebugLevelSysprop.replace('.', '_').toUpperCase()); if (tracerDebugLevelEnv != null) { return Boolean.parseBoolean(tracerDebugLevelEnv); } return false; } private static boolean isJavaBefore9() { return System.getProperty("java.version").startsWith("1."); } /** * Main entry point. * * @param args command line agruments */ public static void main(final String... args) { try { System.out.println(getAgentVersion()); } catch (final Exception e) { System.out.println("Failed to parse agent version"); e.printStackTrace(); } } /** * Read version file out of the agent jar. * * @return Agent version */ public static String getAgentVersion() throws IOException { final StringBuilder sb = new StringBuilder(); try (final BufferedReader reader = new BufferedReader( new InputStreamReader( TracingAgent.class.getResourceAsStream("/dd-java-agent.version"), StandardCharsets.UTF_8))) { for (int c = reader.read(); c != -1; c = reader.read()) { sb.append((char) c); } } return sb.toString().trim(); } }
10,563
0.701884
0.700275
292
35.174656
30.462311
128
false
false
0
0
0
0
0
0
0.434932
false
false
10
84fb5e086de92d45f012f7e47d5fe639bf590b67
9,964,324,143,439
48282d6985341ded6e382255cca06458b0260ceb
/JavaSurvey/src/view/ESurvey.java
2ef86aae7726a243a6dfd401152718f6efe84446
[]
no_license
JacobSharp/JavaSurvey
https://github.com/JacobSharp/JavaSurvey
beb7d6ec5c16de198817ccfae703f06c0beabe89
970b9022e660a1bbeac4790cc33dd172194b4ab3
refs/heads/master
2021-09-08T05:26:47.121000
2018-02-26T14:38:47
2018-02-26T14:38:47
119,379,518
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package view; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class ESurvey extends JDialog { private static final long serialVersionUID = 5232428732984733599L; private JLabel title = new JLabel("Erstelle dein eigenes Survey"); private JPanel buttonPanel = new JPanel(new GridLayout(0, 2)); private JButton back = new JButton("Zurück"); private JButton save = new JButton("Speichern"); private JTextField in = new JTextField("Hier deine Frage hinschreiben"); private JTextField ant = new JTextField("Hier die Antwort hinschreiben (Ja/Nein)"); private JPanel eingaben = new JPanel(); public ESurvey() { eingaben.setLayout(new BoxLayout(eingaben, BoxLayout.Y_AXIS)); setLayout(new BorderLayout()); title.setHorizontalAlignment(JLabel.CENTER); add(title, BorderLayout.NORTH); eingaben.add(in); eingaben.add(ant); add(eingaben, BorderLayout.CENTER); buttonPanel.add(back); buttonPanel.add(save); add(buttonPanel, BorderLayout.SOUTH); setSize(400, 400); back.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Erstellen launcher = new Erstellen(); launcher.setVisible(true); setVisible(false); } }); } public static void main(String[] args) { ESurvey launcher = new ESurvey(); launcher.setVisible(true); } }
UTF-8
Java
1,649
java
ESurvey.java
Java
[]
null
[]
package view; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class ESurvey extends JDialog { private static final long serialVersionUID = 5232428732984733599L; private JLabel title = new JLabel("Erstelle dein eigenes Survey"); private JPanel buttonPanel = new JPanel(new GridLayout(0, 2)); private JButton back = new JButton("Zurück"); private JButton save = new JButton("Speichern"); private JTextField in = new JTextField("Hier deine Frage hinschreiben"); private JTextField ant = new JTextField("Hier die Antwort hinschreiben (Ja/Nein)"); private JPanel eingaben = new JPanel(); public ESurvey() { eingaben.setLayout(new BoxLayout(eingaben, BoxLayout.Y_AXIS)); setLayout(new BorderLayout()); title.setHorizontalAlignment(JLabel.CENTER); add(title, BorderLayout.NORTH); eingaben.add(in); eingaben.add(ant); add(eingaben, BorderLayout.CENTER); buttonPanel.add(back); buttonPanel.add(save); add(buttonPanel, BorderLayout.SOUTH); setSize(400, 400); back.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Erstellen launcher = new Erstellen(); launcher.setVisible(true); setVisible(false); } }); } public static void main(String[] args) { ESurvey launcher = new ESurvey(); launcher.setVisible(true); } }
1,649
0.721481
0.705097
61
25.016394
21.724422
84
false
false
0
0
0
0
0
0
1.721311
false
false
10
458181b4717ea9bf2724dc0a77a80408437142d4
31,009,663,915,195
aa197d97ae71661bb8d1ce5558e554ff861defdd
/Project/src/project/DiemMonHoc.java
827b680dbe37300ce80f365e09c7b0e74b701194
[]
no_license
huynhvuonghihi/DoAn_Java_Nhom9
https://github.com/huynhvuonghihi/DoAn_Java_Nhom9
fc30b3f1b556954a5bf9e31835515ca791e996ae
7277d2f420316857afd0d603fab06bcdd7a42705
refs/heads/master
2020-09-29T10:57:00.678000
2019-12-10T04:36:35
2019-12-10T04:36:35
227,023,228
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 project; /** * * @author ASUS */ public class DiemMonHoc { private SinhVien sinhVien; private MonHoc monHoc; private String diem; public DiemMonHoc() { } public DiemMonHoc(SinhVien sinhVien, MonHoc monHoc, String Diem) { this.sinhVien = sinhVien; this.monHoc = monHoc; this.diem = Diem; } public SinhVien getSinhVien() { return sinhVien; } public void setSinhVien(SinhVien sinhVien) { this.sinhVien = sinhVien; } public MonHoc getMonHoc() { return monHoc; } public void setMonHoc(MonHoc monHoc) { this.monHoc = monHoc; } public String getDiem() { return diem; } public void setDiem(String Diem) { this.diem = Diem; } public String stringGhiFile(){ return sinhVien.getMaSV() + ":" + monHoc.getTenMon() + ":" + diem; } }
UTF-8
Java
1,093
java
DiemMonHoc.java
Java
[ { "context": "he editor.\n */\npackage project;\n\n/**\n *\n * @author ASUS\n */\npublic class DiemMonHoc {\n private SinhVie", "end": 225, "score": 0.9989091157913208, "start": 221, "tag": "USERNAME", "value": "ASUS" } ]
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 project; /** * * @author ASUS */ public class DiemMonHoc { private SinhVien sinhVien; private MonHoc monHoc; private String diem; public DiemMonHoc() { } public DiemMonHoc(SinhVien sinhVien, MonHoc monHoc, String Diem) { this.sinhVien = sinhVien; this.monHoc = monHoc; this.diem = Diem; } public SinhVien getSinhVien() { return sinhVien; } public void setSinhVien(SinhVien sinhVien) { this.sinhVien = sinhVien; } public MonHoc getMonHoc() { return monHoc; } public void setMonHoc(MonHoc monHoc) { this.monHoc = monHoc; } public String getDiem() { return diem; } public void setDiem(String Diem) { this.diem = Diem; } public String stringGhiFile(){ return sinhVien.getMaSV() + ":" + monHoc.getTenMon() + ":" + diem; } }
1,093
0.611162
0.611162
53
19.622641
20.096209
79
false
false
0
0
0
0
0
0
0.358491
false
false
10
76196414b2635da877b948a4c4f4f15731e5e978
23,175,643,588,382
ad4fd30bb8232bf996f39346ef2b84d77b9f6e6c
/src/org/rascalmpl/library/experiments/Compiler/RVM/Interpreter/java2rascal/ApiGen.java
87ab12ff56271d0e71dd1fa2a6073eaa1774a002
[]
no_license
SimonBaars/rascal
https://github.com/SimonBaars/rascal
975301122c0fbe7c0bf940ed115794fa2f8aa380
10492640cc85fd50326608a1733fdfe8b9fc5934
refs/heads/master
2020-04-01T19:57:40.588000
2018-10-24T17:58:53
2018-10-24T17:58:53
153,580,582
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Copyright (c) 2016, paulklint, Centrum Wiskunde & Informatica (CWI) * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.java2rascal; import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import org.rascalmpl.interpreter.types.DefaultRascalTypeVisitor; import org.rascalmpl.interpreter.types.FunctionType; import org.rascalmpl.interpreter.types.NonTerminalType; import org.rascalmpl.interpreter.types.RascalType; import org.rascalmpl.interpreter.types.ReifiedType; import org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.InternalCompilerError; import org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.Function; import org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMExecutable; import io.usethesource.vallang.IMap; import io.usethesource.vallang.IString; import io.usethesource.vallang.IValue; import io.usethesource.vallang.IValueFactory; import io.usethesource.vallang.type.Type; import org.rascalmpl.values.ValueFactoryFactory; public class ApiGen { static final String keywords[] = { "abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "extends", "false", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "null", "package", "private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "true", "try", "void", "volatile", "while" }; public static boolean isJavaKeyword(String keyword) { return (Arrays.binarySearch(keywords, keyword) >= 0); } public static String escapeJavaKeyword(String name){ return isJavaKeyword(name) ? name + "$" : name.replaceAll("-", "_"); } public static String generate(RVMExecutable rvmExec, String moduleName, String javaPackage) throws Exception{ StringWriter sw = new StringWriter(); int b = moduleName.lastIndexOf("::"); String baseName = b < 0 ? moduleName : moduleName.substring(b + 2); String packageContrib = (b < 0 ? "" : "." + moduleName.substring(0, b)).replaceAll("::", "."); sw.append("package " + javaPackage + packageContrib + ";\n\n"); sw.append("import io.usethesource.vallang.*;\n\n"); sw.append("import org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.java2rascal.RascalKeywordParameters;\n"); sw.append("import org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.java2rascal.RascalModule;\n\n"); sw.append("/* Automatically generated code; do not change */\n\n"); sw.append("@RascalModule(\"" + moduleName + "\")\n"); sw.append("public interface I").append(baseName ).append(" {\n"); ArrayList<String> lines = new ArrayList<>(); String kwclasses = ""; HashMap<Type, String> generatedKWClasses = new HashMap<>(); for(Function fun : rvmExec.getFunctionStore()){ String funName = fun.getName(); System.err.println(funName); if(fun.ftype instanceof FunctionType && !funName.endsWith("companion-defaults") && !funName.contains("closure#") && (funName.contains(moduleName) || funName.endsWith("companion"))){ FunctionType ftype = (FunctionType) fun.ftype; Type returnType; Type argTypes; boolean isConstructor = false; int k = funName.lastIndexOf("::companion"); if(k > 0){ isConstructor = true; String consName = funName.substring(0, k); int cn = rvmExec.getConstructorMap().get(consName); Type consType = rvmExec.getConstructorStore()[cn]; returnType = consType.getAbstractDataType(); argTypes = consType.getFieldTypes(); } else { returnType = ftype.getReturnType(); argTypes = ftype.getArgumentTypes(); } int arity = argTypes.getArity(); StringWriter sw2 = new StringWriter(); sw2.append("\t"); sw2.append(toJavaType(returnType)); sw2.append(" "); if(isConstructor){ sw2.append(removeTypeParams(returnType)).append("_"); } sw2.append(escapeJavaKeyword(fun.getPrintableName())); sw2.append("("); IMap localNames = fun.localNames; System.err.println("localNames: " + localNames); IValueFactory vf = ValueFactoryFactory.getValueFactory(); for(int i = 0; i < arity; i++){ if(i > 0){ sw2.append(", "); } sw2.append(toJavaType(argTypes.getFieldType(i))); sw2.append(" "); if(isConstructor){ sw2.append(escapeJavaKeyword(argTypes.getFieldName(i))); } else { IValue argName = localNames.get(vf.integer(i)); sw2.append(argName == null ? "arg" + i : escapeJavaKeyword(((IString)argName).getValue())); } } Type kwType = fun.kwType; if(kwType.getArity() > 0){ if(arity > 0){ sw2.append(", "); } String gc = generatedKWClasses.get(kwType); if(gc == null){ sw2.append("KW").append(fun.getPrintableName()).append(" kwArgs"); kwclasses += KWClass(fun.getPrintableName(), kwType); generatedKWClasses.put(kwType, "KW" + fun.getPrintableName()); } else { sw2.append(gc).append(" kwArgs"); } } sw2.append(");\n"); String line = sw2.toString(); if(!lines.contains(line)){ lines.add(line); } } } for(Type consType :rvmExec.getConstructorStore()){ System.err.println(consType); Type argTypes = consType.getFieldTypes(); int arity = argTypes.getArity(); StringWriter sw3 = new StringWriter(); sw3.append("\t"); sw3.append(escapeJavaKeyword(toJavaType(consType.getAbstractDataType()))); sw3.append(" "); sw3.append(removeTypeParams(consType.getAbstractDataType())).append("_").append(escapeJavaKeyword(consType.getName())); sw3.append("("); for(int i = 0; i < arity; i++){ if(i > 0){ sw3.append(", "); } sw3.append(toJavaType(argTypes.getFieldType(i))); sw3.append(" "); sw3.append(escapeJavaKeyword(argTypes.getFieldName(i))); } sw3.append(");\n"); String line = sw3.toString(); if(!lines.contains(line)){ lines.add(line); } } for(String line : lines){ sw.append(line); } sw.append(kwclasses); sw.append("}\n"); return sw.toString(); } static String removeTypeParams(Type t){ String rt = t.toString(); int j = rt.indexOf("["); if(j >= 0){ rt = rt.substring(0, j); } return rt; } static String KWClass(String funName, Type kwType) throws Exception{ StringWriter sw = new StringWriter(); String className = "KW" + funName; sw.append("\n\t@RascalKeywordParameters\n") .append("\tinterface ").append(className).append(" {\n"); for(int i = 0; i < kwType.getArity(); i++){ String fieldName = kwType.getFieldName(i); Type fieldType = kwType.getFieldType(i); sw.append("\t\t").append(className).append(" ").append(escapeJavaKeyword(fieldName)).append("(") .append(toJavaType(fieldType)).append(" ").append("val);\n"); } sw.append("\t}\n"); sw.append("\t").append(className).append(" kw_").append(funName).append("();\n"); return sw.toString(); } static String toJavaType(Type t) throws Exception{ return t.accept(new DefaultRascalTypeVisitor<String,RuntimeException>("") { @Override public String visitReal(Type type) throws RuntimeException { return "double"; } @Override public String visitInteger(Type type) throws RuntimeException { return "int"; } @Override public String visitRational(Type type) throws RuntimeException { return "IRational"; } @Override public String visitList(Type type) throws RuntimeException { return "IList"; } @Override public String visitMap(Type type) throws RuntimeException { return "IMap"; } @Override public String visitNumber(Type type) throws RuntimeException { return "INumber"; } @Override public String visitAlias(Type type) throws RuntimeException { throw new InternalCompilerError("Alias cannot occur as interface type"); } @Override public String visitSet(Type type) throws RuntimeException { return "ISet"; } @Override public String visitSourceLocation(Type type) throws RuntimeException { return "ISourceLocation"; } @Override public String visitString(Type type) throws RuntimeException { return "String"; } @Override public String visitNode(Type type) throws RuntimeException { return "INode"; } @Override public String visitConstructor(Type type) throws RuntimeException { return "IConstructor"; } @Override public String visitAbstractData(Type type) throws RuntimeException { return "IConstructor"; } @Override public String visitTuple(Type type) throws RuntimeException { return "ITuple"; } @Override public String visitValue(Type type) throws RuntimeException { return "IValue"; } @Override public String visitVoid(Type type) throws RuntimeException { return "void"; } @Override public String visitBool(Type type) throws RuntimeException { return "boolean"; } @Override public String visitParameter(Type type) throws RuntimeException { return "IValue"; } @Override public String visitExternal(Type type) throws RuntimeException { if(type instanceof FunctionType){ return "IValue"; } else if(type instanceof ReifiedType){ return "IConstructor"; } else if(type instanceof NonTerminalType){ return "IConstructor"; } throw new InternalCompilerError("External cannot occur as interface type: " + type); } @Override public String visitNonTerminal(RascalType type) throws RuntimeException { return "IConstructor"; } @Override public String visitReified(RascalType type) throws RuntimeException { return "IConstructor"; } @Override public String visitFunction(RascalType type) throws RuntimeException { return "IValue"; } @Override public String visitOverloadedFunction(RascalType type) throws RuntimeException { throw new InternalCompilerError("External cannot occur as interface type: " + type); } @Override public String visitDateTime(Type type) throws RuntimeException { return "IDateTime"; }}); } }
UTF-8
Java
12,784
java
ApiGen.java
Java
[ { "context": "/** \n * Copyright (c) 2016, paulklint, Centrum Wiskunde & Informatica (CWI) \n * All rig", "end": 37, "score": 0.7481009364128113, "start": 28, "tag": "NAME", "value": "paulklint" } ]
null
[]
/** * Copyright (c) 2016, paulklint, Centrum Wiskunde & Informatica (CWI) * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.java2rascal; import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import org.rascalmpl.interpreter.types.DefaultRascalTypeVisitor; import org.rascalmpl.interpreter.types.FunctionType; import org.rascalmpl.interpreter.types.NonTerminalType; import org.rascalmpl.interpreter.types.RascalType; import org.rascalmpl.interpreter.types.ReifiedType; import org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.InternalCompilerError; import org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.Function; import org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.RVMExecutable; import io.usethesource.vallang.IMap; import io.usethesource.vallang.IString; import io.usethesource.vallang.IValue; import io.usethesource.vallang.IValueFactory; import io.usethesource.vallang.type.Type; import org.rascalmpl.values.ValueFactoryFactory; public class ApiGen { static final String keywords[] = { "abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "extends", "false", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "null", "package", "private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "true", "try", "void", "volatile", "while" }; public static boolean isJavaKeyword(String keyword) { return (Arrays.binarySearch(keywords, keyword) >= 0); } public static String escapeJavaKeyword(String name){ return isJavaKeyword(name) ? name + "$" : name.replaceAll("-", "_"); } public static String generate(RVMExecutable rvmExec, String moduleName, String javaPackage) throws Exception{ StringWriter sw = new StringWriter(); int b = moduleName.lastIndexOf("::"); String baseName = b < 0 ? moduleName : moduleName.substring(b + 2); String packageContrib = (b < 0 ? "" : "." + moduleName.substring(0, b)).replaceAll("::", "."); sw.append("package " + javaPackage + packageContrib + ";\n\n"); sw.append("import io.usethesource.vallang.*;\n\n"); sw.append("import org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.java2rascal.RascalKeywordParameters;\n"); sw.append("import org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.java2rascal.RascalModule;\n\n"); sw.append("/* Automatically generated code; do not change */\n\n"); sw.append("@RascalModule(\"" + moduleName + "\")\n"); sw.append("public interface I").append(baseName ).append(" {\n"); ArrayList<String> lines = new ArrayList<>(); String kwclasses = ""; HashMap<Type, String> generatedKWClasses = new HashMap<>(); for(Function fun : rvmExec.getFunctionStore()){ String funName = fun.getName(); System.err.println(funName); if(fun.ftype instanceof FunctionType && !funName.endsWith("companion-defaults") && !funName.contains("closure#") && (funName.contains(moduleName) || funName.endsWith("companion"))){ FunctionType ftype = (FunctionType) fun.ftype; Type returnType; Type argTypes; boolean isConstructor = false; int k = funName.lastIndexOf("::companion"); if(k > 0){ isConstructor = true; String consName = funName.substring(0, k); int cn = rvmExec.getConstructorMap().get(consName); Type consType = rvmExec.getConstructorStore()[cn]; returnType = consType.getAbstractDataType(); argTypes = consType.getFieldTypes(); } else { returnType = ftype.getReturnType(); argTypes = ftype.getArgumentTypes(); } int arity = argTypes.getArity(); StringWriter sw2 = new StringWriter(); sw2.append("\t"); sw2.append(toJavaType(returnType)); sw2.append(" "); if(isConstructor){ sw2.append(removeTypeParams(returnType)).append("_"); } sw2.append(escapeJavaKeyword(fun.getPrintableName())); sw2.append("("); IMap localNames = fun.localNames; System.err.println("localNames: " + localNames); IValueFactory vf = ValueFactoryFactory.getValueFactory(); for(int i = 0; i < arity; i++){ if(i > 0){ sw2.append(", "); } sw2.append(toJavaType(argTypes.getFieldType(i))); sw2.append(" "); if(isConstructor){ sw2.append(escapeJavaKeyword(argTypes.getFieldName(i))); } else { IValue argName = localNames.get(vf.integer(i)); sw2.append(argName == null ? "arg" + i : escapeJavaKeyword(((IString)argName).getValue())); } } Type kwType = fun.kwType; if(kwType.getArity() > 0){ if(arity > 0){ sw2.append(", "); } String gc = generatedKWClasses.get(kwType); if(gc == null){ sw2.append("KW").append(fun.getPrintableName()).append(" kwArgs"); kwclasses += KWClass(fun.getPrintableName(), kwType); generatedKWClasses.put(kwType, "KW" + fun.getPrintableName()); } else { sw2.append(gc).append(" kwArgs"); } } sw2.append(");\n"); String line = sw2.toString(); if(!lines.contains(line)){ lines.add(line); } } } for(Type consType :rvmExec.getConstructorStore()){ System.err.println(consType); Type argTypes = consType.getFieldTypes(); int arity = argTypes.getArity(); StringWriter sw3 = new StringWriter(); sw3.append("\t"); sw3.append(escapeJavaKeyword(toJavaType(consType.getAbstractDataType()))); sw3.append(" "); sw3.append(removeTypeParams(consType.getAbstractDataType())).append("_").append(escapeJavaKeyword(consType.getName())); sw3.append("("); for(int i = 0; i < arity; i++){ if(i > 0){ sw3.append(", "); } sw3.append(toJavaType(argTypes.getFieldType(i))); sw3.append(" "); sw3.append(escapeJavaKeyword(argTypes.getFieldName(i))); } sw3.append(");\n"); String line = sw3.toString(); if(!lines.contains(line)){ lines.add(line); } } for(String line : lines){ sw.append(line); } sw.append(kwclasses); sw.append("}\n"); return sw.toString(); } static String removeTypeParams(Type t){ String rt = t.toString(); int j = rt.indexOf("["); if(j >= 0){ rt = rt.substring(0, j); } return rt; } static String KWClass(String funName, Type kwType) throws Exception{ StringWriter sw = new StringWriter(); String className = "KW" + funName; sw.append("\n\t@RascalKeywordParameters\n") .append("\tinterface ").append(className).append(" {\n"); for(int i = 0; i < kwType.getArity(); i++){ String fieldName = kwType.getFieldName(i); Type fieldType = kwType.getFieldType(i); sw.append("\t\t").append(className).append(" ").append(escapeJavaKeyword(fieldName)).append("(") .append(toJavaType(fieldType)).append(" ").append("val);\n"); } sw.append("\t}\n"); sw.append("\t").append(className).append(" kw_").append(funName).append("();\n"); return sw.toString(); } static String toJavaType(Type t) throws Exception{ return t.accept(new DefaultRascalTypeVisitor<String,RuntimeException>("") { @Override public String visitReal(Type type) throws RuntimeException { return "double"; } @Override public String visitInteger(Type type) throws RuntimeException { return "int"; } @Override public String visitRational(Type type) throws RuntimeException { return "IRational"; } @Override public String visitList(Type type) throws RuntimeException { return "IList"; } @Override public String visitMap(Type type) throws RuntimeException { return "IMap"; } @Override public String visitNumber(Type type) throws RuntimeException { return "INumber"; } @Override public String visitAlias(Type type) throws RuntimeException { throw new InternalCompilerError("Alias cannot occur as interface type"); } @Override public String visitSet(Type type) throws RuntimeException { return "ISet"; } @Override public String visitSourceLocation(Type type) throws RuntimeException { return "ISourceLocation"; } @Override public String visitString(Type type) throws RuntimeException { return "String"; } @Override public String visitNode(Type type) throws RuntimeException { return "INode"; } @Override public String visitConstructor(Type type) throws RuntimeException { return "IConstructor"; } @Override public String visitAbstractData(Type type) throws RuntimeException { return "IConstructor"; } @Override public String visitTuple(Type type) throws RuntimeException { return "ITuple"; } @Override public String visitValue(Type type) throws RuntimeException { return "IValue"; } @Override public String visitVoid(Type type) throws RuntimeException { return "void"; } @Override public String visitBool(Type type) throws RuntimeException { return "boolean"; } @Override public String visitParameter(Type type) throws RuntimeException { return "IValue"; } @Override public String visitExternal(Type type) throws RuntimeException { if(type instanceof FunctionType){ return "IValue"; } else if(type instanceof ReifiedType){ return "IConstructor"; } else if(type instanceof NonTerminalType){ return "IConstructor"; } throw new InternalCompilerError("External cannot occur as interface type: " + type); } @Override public String visitNonTerminal(RascalType type) throws RuntimeException { return "IConstructor"; } @Override public String visitReified(RascalType type) throws RuntimeException { return "IConstructor"; } @Override public String visitFunction(RascalType type) throws RuntimeException { return "IValue"; } @Override public String visitOverloadedFunction(RascalType type) throws RuntimeException { throw new InternalCompilerError("External cannot occur as interface type: " + type); } @Override public String visitDateTime(Type type) throws RuntimeException { return "IDateTime"; }}); } }
12,784
0.628129
0.623905
361
34.412743
47.743183
759
false
false
0
0
0
0
0
0
0.684211
false
false
10
dc51b291bf412d1db0418e3129812d027c1619b5
9,543,417,391,921
2ada0c13bdf4238844a7683808830405b7d0bb71
/app/src/main/java/info/androidhive/loginandregistration/activity/calendar.java
325b6b210c4a320c6d27f98681b8a5e61d2f77ad
[]
no_license
dioscarr/CBooking
https://github.com/dioscarr/CBooking
c09c0d75b58db42be818eee44506ddfaaa246106
73722bd0f2c1ae8d653b19494664b5993bd1eb0e
refs/heads/master
2020-09-15T22:15:26.892000
2016-08-26T16:41:30
2016-08-26T16:41:30
66,105,941
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package info.androidhive.loginandregistration.activity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.CalendarView; import android.widget.Toast; import info.androidhive.loginandregistration.R; import info.androidhive.loginandregistration.helper.BuckyDB; import info.androidhive.loginandregistration.helper.SQLiteHandler; import info.androidhive.loginandregistration.helper.SessionManager; public class calendar extends AppCompatActivity { private BuckyDB db; private Toolbar toolbar; //Menu private SQLiteHandler dbApi; //database private SessionManager session;//database @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_calendar); // SqLite database handler dbApi = new SQLiteHandler(getApplicationContext()); // session manager session = new SessionManager(getApplicationContext()); // SQLite database handler db = new BuckyDB(this,null,null,1); toolbar = (Toolbar) findViewById(R.id.app_bar); //Toolbar setSupportActionBar(toolbar); //Toolbar LayoutInflater mInflater = LayoutInflater.from(this); View mCustomView = mInflater.inflate(R.layout.toolbaricon, null); getSupportActionBar().setCustomView(mCustomView); getSupportActionBar().setDisplayShowCustomEnabled(true); getSupportActionBar().setTitle("Book a session"); //Toolbar getSupportActionBar().setSubtitle("SubTitle"); //Toolbar //getSupportActionBar().setIcon(R.drawable.ic_action_name);//Toolbar getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); CalendarView calendarView = (CalendarView) findViewById(R.id.calendarviewBookaSession); calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() { @Override public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) { int d = dayOfMonth; int dmonth = month; int dyear = year; String DateBookedString = dmonth+1 + "-" + d + "-" + dyear; AddBoookeDate(DateBookedString); Toast.makeText(view.getContext(), dmonth+1 + "-" + d + "-" + dyear, Toast.LENGTH_LONG).show(); } }); } /*** * This method is inherited from the appCompatActivity class * and it initialize the menu on the toolbar * @param menu * @return */ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu, menu); return super.onCreateOptionsMenu(menu); } /** * this is a method from the inherited class that get * the selected item id from the tool bar menu * @param item * @return */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_1: // Launching the login settings Intent intent = new Intent(calendar.this, settings.class); startActivity(intent); finish(); break; case R.id.menu_2: logoutUser(); break; } return super.onContextItemSelected(item); } private void AddBoookeDate(final String DateBooked ) { String DateBookedstr = DateBooked; // Inserting row in Session_Booked table String created_at = "08-21-2016"; sessionModel model = new sessionModel(0,DateBooked,created_at); db.addsessionModel(model); Toast.makeText(getApplicationContext(), "Booked!", Toast.LENGTH_LONG).show(); // Launch login activity Intent intent = new Intent( calendar.this, mysessions.class); startActivity(intent); // finish(); }; /** * Logging out the user. Will set isLoggedIn flag to false in shared * preferences Clears the user data from sqlite users table * */ private void logoutUser() { session.setLogin(false); dbApi.deleteUsers(); // Launching the login activity Intent intent = new Intent(calendar.this, LoginActivity.class); startActivity(intent); finish(); } }
UTF-8
Java
4,694
java
calendar.java
Java
[]
null
[]
package info.androidhive.loginandregistration.activity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.CalendarView; import android.widget.Toast; import info.androidhive.loginandregistration.R; import info.androidhive.loginandregistration.helper.BuckyDB; import info.androidhive.loginandregistration.helper.SQLiteHandler; import info.androidhive.loginandregistration.helper.SessionManager; public class calendar extends AppCompatActivity { private BuckyDB db; private Toolbar toolbar; //Menu private SQLiteHandler dbApi; //database private SessionManager session;//database @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_calendar); // SqLite database handler dbApi = new SQLiteHandler(getApplicationContext()); // session manager session = new SessionManager(getApplicationContext()); // SQLite database handler db = new BuckyDB(this,null,null,1); toolbar = (Toolbar) findViewById(R.id.app_bar); //Toolbar setSupportActionBar(toolbar); //Toolbar LayoutInflater mInflater = LayoutInflater.from(this); View mCustomView = mInflater.inflate(R.layout.toolbaricon, null); getSupportActionBar().setCustomView(mCustomView); getSupportActionBar().setDisplayShowCustomEnabled(true); getSupportActionBar().setTitle("Book a session"); //Toolbar getSupportActionBar().setSubtitle("SubTitle"); //Toolbar //getSupportActionBar().setIcon(R.drawable.ic_action_name);//Toolbar getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); CalendarView calendarView = (CalendarView) findViewById(R.id.calendarviewBookaSession); calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() { @Override public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) { int d = dayOfMonth; int dmonth = month; int dyear = year; String DateBookedString = dmonth+1 + "-" + d + "-" + dyear; AddBoookeDate(DateBookedString); Toast.makeText(view.getContext(), dmonth+1 + "-" + d + "-" + dyear, Toast.LENGTH_LONG).show(); } }); } /*** * This method is inherited from the appCompatActivity class * and it initialize the menu on the toolbar * @param menu * @return */ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu, menu); return super.onCreateOptionsMenu(menu); } /** * this is a method from the inherited class that get * the selected item id from the tool bar menu * @param item * @return */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_1: // Launching the login settings Intent intent = new Intent(calendar.this, settings.class); startActivity(intent); finish(); break; case R.id.menu_2: logoutUser(); break; } return super.onContextItemSelected(item); } private void AddBoookeDate(final String DateBooked ) { String DateBookedstr = DateBooked; // Inserting row in Session_Booked table String created_at = "08-21-2016"; sessionModel model = new sessionModel(0,DateBooked,created_at); db.addsessionModel(model); Toast.makeText(getApplicationContext(), "Booked!", Toast.LENGTH_LONG).show(); // Launch login activity Intent intent = new Intent( calendar.this, mysessions.class); startActivity(intent); // finish(); }; /** * Logging out the user. Will set isLoggedIn flag to false in shared * preferences Clears the user data from sqlite users table * */ private void logoutUser() { session.setLogin(false); dbApi.deleteUsers(); // Launching the login activity Intent intent = new Intent(calendar.this, LoginActivity.class); startActivity(intent); finish(); } }
4,694
0.648914
0.645505
136
33.514706
25.364109
111
false
false
0
0
0
0
0
0
0.610294
false
false
10
a2ab2ea06b88f3067cadd0f65a14d5a9854be49a
7,842,610,347,353
c585888f406869d0e0182be8557b3e33ce743ff0
/src/main/java/com/android/tools/r8/shaking/FieldAccessInfoCollectionModifier.java
4e9d9777b47bd80c977a743f7ea7957be446d4b9
[ "BSD-3-Clause", "MIT", "Apache-2.0", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Yinkozi/R8
https://github.com/Yinkozi/R8
25623bfa8d67f553ea737472d6835740f9fc8099
af71090436ca05106ff3ac08c9533ed524163029
refs/heads/main
2023-01-04T00:13:30.647000
2020-10-21T10:40:00
2020-10-21T10:40:00
305,987,826
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// Copyright (c) 2020, the R8 project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. package com.android.tools.r8.shaking; import com.android.tools.r8.graph.AppView; import com.android.tools.r8.graph.DexField; import com.android.tools.r8.graph.DexMethod; import com.android.tools.r8.graph.FieldAccessInfoCollectionImpl; import com.android.tools.r8.graph.FieldAccessInfoImpl; import com.android.tools.r8.graph.ProgramMethod; import java.util.ArrayList; import java.util.Collection; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.function.BiConsumer; import java.util.function.Function; public class FieldAccessInfoCollectionModifier { static class FieldReferences { final List<DexMethod> writeContexts = new ArrayList<>(); final List<DexMethod> readContexts = new ArrayList<>(); void fixUpMethods(List<DexMethod> methods, Function<DexMethod, DexMethod> fixUpMethod) { for (int i = 0; i < methods.size(); i++) { DexMethod method = methods.get(i); DexMethod newMethod = fixUpMethod.apply(method); if (method != newMethod) { methods.set(i, newMethod); } } } void fixUp(Function<DexMethod, DexMethod> fixUpMethod) { fixUpMethods(writeContexts, fixUpMethod); fixUpMethods(readContexts, fixUpMethod); } } final Map<DexField, FieldReferences> newFieldAccesses; FieldAccessInfoCollectionModifier(Map<DexField, FieldReferences> newFieldAccesses) { this.newFieldAccesses = newFieldAccesses; } void forEachFieldAccess( AppView<?> appView, Collection<DexMethod> methods, DexField field, BiConsumer<DexField, ProgramMethod> record) { for (DexMethod method : methods) { ProgramMethod programMethod = appView.definitionFor(method.holder).asProgramClass().lookupProgramMethod(method); record.accept(field, programMethod); } } public void modify(AppView<AppInfoWithLiveness> appView) { FieldAccessInfoCollectionImpl impl = appView.appInfo().getMutableFieldAccessInfoCollection(); newFieldAccesses.forEach( (field, info) -> { FieldAccessInfoImpl fieldAccessInfo = new FieldAccessInfoImpl(field); forEachFieldAccess(appView, info.readContexts, field, fieldAccessInfo::recordRead); forEachFieldAccess(appView, info.writeContexts, field, fieldAccessInfo::recordWrite); impl.extend(field, fieldAccessInfo); }); } public static class Builder { final Map<DexField, FieldReferences> newFieldAccesses = new IdentityHashMap<>(); public Builder() {} public FieldAccessInfoCollectionModifier build(Function<DexMethod, DexMethod> fixupMethod) { for (FieldReferences fieldReference : newFieldAccesses.values()) { fieldReference.fixUp(fixupMethod); } return new FieldAccessInfoCollectionModifier(newFieldAccesses); } FieldReferences getFieldReferences(DexField field) { return newFieldAccesses.computeIfAbsent(field, ignore -> new FieldReferences()); } public void fieldReadByMethod(DexField field, DexMethod method) { getFieldReferences(field).readContexts.add(method); } public void fieldWrittenByMethod(DexField field, DexMethod method) { getFieldReferences(field).writeContexts.add(method); } } }
UTF-8
Java
3,479
java
FieldAccessInfoCollectionModifier.java
Java
[]
null
[]
// Copyright (c) 2020, the R8 project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. package com.android.tools.r8.shaking; import com.android.tools.r8.graph.AppView; import com.android.tools.r8.graph.DexField; import com.android.tools.r8.graph.DexMethod; import com.android.tools.r8.graph.FieldAccessInfoCollectionImpl; import com.android.tools.r8.graph.FieldAccessInfoImpl; import com.android.tools.r8.graph.ProgramMethod; import java.util.ArrayList; import java.util.Collection; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.function.BiConsumer; import java.util.function.Function; public class FieldAccessInfoCollectionModifier { static class FieldReferences { final List<DexMethod> writeContexts = new ArrayList<>(); final List<DexMethod> readContexts = new ArrayList<>(); void fixUpMethods(List<DexMethod> methods, Function<DexMethod, DexMethod> fixUpMethod) { for (int i = 0; i < methods.size(); i++) { DexMethod method = methods.get(i); DexMethod newMethod = fixUpMethod.apply(method); if (method != newMethod) { methods.set(i, newMethod); } } } void fixUp(Function<DexMethod, DexMethod> fixUpMethod) { fixUpMethods(writeContexts, fixUpMethod); fixUpMethods(readContexts, fixUpMethod); } } final Map<DexField, FieldReferences> newFieldAccesses; FieldAccessInfoCollectionModifier(Map<DexField, FieldReferences> newFieldAccesses) { this.newFieldAccesses = newFieldAccesses; } void forEachFieldAccess( AppView<?> appView, Collection<DexMethod> methods, DexField field, BiConsumer<DexField, ProgramMethod> record) { for (DexMethod method : methods) { ProgramMethod programMethod = appView.definitionFor(method.holder).asProgramClass().lookupProgramMethod(method); record.accept(field, programMethod); } } public void modify(AppView<AppInfoWithLiveness> appView) { FieldAccessInfoCollectionImpl impl = appView.appInfo().getMutableFieldAccessInfoCollection(); newFieldAccesses.forEach( (field, info) -> { FieldAccessInfoImpl fieldAccessInfo = new FieldAccessInfoImpl(field); forEachFieldAccess(appView, info.readContexts, field, fieldAccessInfo::recordRead); forEachFieldAccess(appView, info.writeContexts, field, fieldAccessInfo::recordWrite); impl.extend(field, fieldAccessInfo); }); } public static class Builder { final Map<DexField, FieldReferences> newFieldAccesses = new IdentityHashMap<>(); public Builder() {} public FieldAccessInfoCollectionModifier build(Function<DexMethod, DexMethod> fixupMethod) { for (FieldReferences fieldReference : newFieldAccesses.values()) { fieldReference.fixUp(fixupMethod); } return new FieldAccessInfoCollectionModifier(newFieldAccesses); } FieldReferences getFieldReferences(DexField field) { return newFieldAccesses.computeIfAbsent(field, ignore -> new FieldReferences()); } public void fieldReadByMethod(DexField field, DexMethod method) { getFieldReferences(field).readContexts.add(method); } public void fieldWrittenByMethod(DexField field, DexMethod method) { getFieldReferences(field).writeContexts.add(method); } } }
3,479
0.731532
0.727795
96
35.239582
29.441235
97
false
false
0
0
0
0
0
0
0.6875
false
false
10
441696681e920d9556b69c7aa5db9091231c6932
23,673,859,777,047
ee2a867fc1be02562d4e6cd5e1571969d617e6ba
/redis-demo/src/main/java/github/weizibin/controller/IndexController.java
09f48f5ce14ab71335817a9c731ccf874a5f8204
[ "MIT" ]
permissive
WEIZIBIN/Demos
https://github.com/WEIZIBIN/Demos
0a478f25df920a7a2b6a24edeee26fcef8e56638
b95af3b143d5f5c46c2b22b55f42b1314a29927a
refs/heads/master
2018-11-22T22:34:31.405000
2018-11-18T13:20:12
2018-11-18T13:20:12
114,621,867
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package github.weizibin.controller; import github.weizibin.po.KillGoods; import github.weizibin.response.ServiceResponse; import github.weizibin.service.KillGoodsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import javax.servlet.http.HttpSession; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; @Controller public class IndexController { private static final String ATTR_CUSTOMER_ID = "CUSTOMER_ID"; @Autowired private KillGoodsService killGoodsService; @RequestMapping("/web/index") public String webindex() { return "index"; } @RequestMapping(value = "/add", method = {RequestMethod.GET}) public String add() { return "add"; } @RequestMapping(value = "/add", method = {RequestMethod.POST}) public String add(KillGoods killGoods, String startKillTimeStr) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date startKillTime = sdf.parse(startKillTimeStr); killGoods.setStartKillTime(startKillTime); killGoodsService.add(killGoods); return "redirect:/web/index"; } @RequestMapping(value = "/kill", method = {RequestMethod.GET}) public String kill(HttpSession session, Model model) { if (session.getAttribute(ATTR_CUSTOMER_ID) == null) { return "redirect:/setCustomerId"; } model.addAttribute("customerId", session.getAttribute(ATTR_CUSTOMER_ID)); model.addAttribute("killGoodsList", killGoodsService.getAllInStock()); model.addAttribute("killGoodsRecordList", killGoodsService.getAllKillRecord()); return "kill"; } @RequestMapping(value = "/kill", method = {RequestMethod.POST}) public String kill(Integer killGoodsId, HttpSession session, RedirectAttributes redirectAttributes) { ServiceResponse serviceResponse = killGoodsService.killByRedis(killGoodsId, (Integer) session.getAttribute(ATTR_CUSTOMER_ID)); redirectAttributes.addFlashAttribute("msg", serviceResponse.getMsg()); return "redirect:/kill"; } @RequestMapping(value = "/setCustomerId", method = {RequestMethod.GET}) public String setCustomerId() { return "setCustomerId"; } @RequestMapping(value = "/setCustomerId", method = {RequestMethod.POST}) public String setCustomerId(Integer customerId, HttpSession session) { session.setAttribute(ATTR_CUSTOMER_ID, customerId); return "redirect:/kill"; } }
UTF-8
Java
2,827
java
IndexController.java
Java
[]
null
[]
package github.weizibin.controller; import github.weizibin.po.KillGoods; import github.weizibin.response.ServiceResponse; import github.weizibin.service.KillGoodsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import javax.servlet.http.HttpSession; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; @Controller public class IndexController { private static final String ATTR_CUSTOMER_ID = "CUSTOMER_ID"; @Autowired private KillGoodsService killGoodsService; @RequestMapping("/web/index") public String webindex() { return "index"; } @RequestMapping(value = "/add", method = {RequestMethod.GET}) public String add() { return "add"; } @RequestMapping(value = "/add", method = {RequestMethod.POST}) public String add(KillGoods killGoods, String startKillTimeStr) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date startKillTime = sdf.parse(startKillTimeStr); killGoods.setStartKillTime(startKillTime); killGoodsService.add(killGoods); return "redirect:/web/index"; } @RequestMapping(value = "/kill", method = {RequestMethod.GET}) public String kill(HttpSession session, Model model) { if (session.getAttribute(ATTR_CUSTOMER_ID) == null) { return "redirect:/setCustomerId"; } model.addAttribute("customerId", session.getAttribute(ATTR_CUSTOMER_ID)); model.addAttribute("killGoodsList", killGoodsService.getAllInStock()); model.addAttribute("killGoodsRecordList", killGoodsService.getAllKillRecord()); return "kill"; } @RequestMapping(value = "/kill", method = {RequestMethod.POST}) public String kill(Integer killGoodsId, HttpSession session, RedirectAttributes redirectAttributes) { ServiceResponse serviceResponse = killGoodsService.killByRedis(killGoodsId, (Integer) session.getAttribute(ATTR_CUSTOMER_ID)); redirectAttributes.addFlashAttribute("msg", serviceResponse.getMsg()); return "redirect:/kill"; } @RequestMapping(value = "/setCustomerId", method = {RequestMethod.GET}) public String setCustomerId() { return "setCustomerId"; } @RequestMapping(value = "/setCustomerId", method = {RequestMethod.POST}) public String setCustomerId(Integer customerId, HttpSession session) { session.setAttribute(ATTR_CUSTOMER_ID, customerId); return "redirect:/kill"; } }
2,827
0.727626
0.727626
74
37.202702
30.698614
134
false
false
0
0
0
0
0
0
0.689189
false
false
10
0a22c46358a2d651337c5f38251bf1326bb5fcbc
7,919,919,752,179
4fd5ac4d70c3f23d1d4645c1a1dd85110780aee3
/core/src/com/damian/spaceking/Bullet.java
1517329aa519baa160440f759e88c5e58b8e8096
[]
no_license
damian11131/SpaceKing
https://github.com/damian11131/SpaceKing
dc1ffa875ccd062899ed86d275b50dfa65cfe1e3
98dbf240ef566340b30e6e975933be69a9c26349
refs/heads/master
2018-04-16T09:10:52.979000
2017-06-02T18:28:22
2017-06-02T18:28:22
90,535,732
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.damian.spaceking; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; public class Bullet extends GameObject { private static final float SPEED = 900.f; private float vectorX; private float vectorY; public Bullet(final Texture texture, final float rotation) { super(texture); sprite.setRotation(rotation); float rotationInRadians = (float) (rotation * Math.PI / 180); vectorX = (float) Math.sin(rotationInRadians); vectorY = (float) -Math.cos(rotationInRadians); } @Override public void update(final float deltaTime) { sprite.translate(vectorX * -SPEED * deltaTime, vectorY * -SPEED * deltaTime); } }
UTF-8
Java
830
java
Bullet.java
Java
[]
null
[]
package com.damian.spaceking; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; public class Bullet extends GameObject { private static final float SPEED = 900.f; private float vectorX; private float vectorY; public Bullet(final Texture texture, final float rotation) { super(texture); sprite.setRotation(rotation); float rotationInRadians = (float) (rotation * Math.PI / 180); vectorX = (float) Math.sin(rotationInRadians); vectorY = (float) -Math.cos(rotationInRadians); } @Override public void update(final float deltaTime) { sprite.translate(vectorX * -SPEED * deltaTime, vectorY * -SPEED * deltaTime); } }
830
0.683133
0.673494
30
26.666666
22.471216
69
false
false
0
0
0
0
0
0
0.533333
false
false
10
43c2d1db3822ac5936239b85ac21ef836fd8f941
13,297,218,810,877
565c63e54014784ca6fa2d94b7bedfecb1ffb5b7
/Chat-Server-Oneway/app/src/main/java/edu/stevens/cs522/chatserver/providers/ChatProvider.java
3441973871ef03e07d464ac0988c07ac3dd764cb
[]
no_license
sho0p/android-async-entity
https://github.com/sho0p/android-async-entity
83bd16eed3daec2a3451b21f7527057ec578d213
b4c81035a38581bd2cba120b3f75052bf16ba3ff
refs/heads/master
2020-04-26T21:47:26.246000
2019-03-10T17:09:51
2019-03-10T17:09:51
173,851,644
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.stevens.cs522.chatserver.providers; import android.content.ContentProvider; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.database.CursorIndexOutOfBoundsException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; import android.net.Uri; import android.util.Log; import edu.stevens.cs522.chatserver.contracts.BaseContract; import edu.stevens.cs522.chatserver.contracts.MessageContract; import edu.stevens.cs522.chatserver.contracts.PeerContract; import edu.stevens.cs522.chatserver.entities.Message; public class ChatProvider extends ContentProvider { public ChatProvider() { } private static final String AUTHORITY = BaseContract.AUTHORITY; private static final String MESSAGE_CONTENT_PATH = MessageContract.CONTENT_PATH; private static final String MESSAGE_CONTENT_PATH_ITEM = MessageContract.CONTENT_PATH_ITEM; private static final String PEER_CONTENT_PATH = PeerContract.CONTENT_PATH; private static final String PEER_CONTENT_PATH_ITEM = PeerContract.CONTENT_PATH_ITEM; private static final String DATABASE_NAME = "chat.db"; private static final int DATABASE_VERSION = 1; private static final String MESSAGES_TABLE = "Message"; private static final String PEERS_TABLE = "Peer"; // Create the constants used to differentiate between the different URI requests. private static final int MESSAGES_ALL_ROWS = 1; private static final int MESSAGES_SINGLE_ROW = 2; private static final int PEERS_ALL_ROWS = 3; private static final int PEERS_SINGLE_ROW = 4; public static class DbHelper extends SQLiteOpenHelper { private static final String MESSAGE_DATABASE_CREATE = "CREATE TABLE IF NOT EXISTS " + MESSAGES_TABLE + " (" + MessageContract.MESSAGE_TEXT + " TEXT NOT NULL, " + MessageContract.TIMESTAMP + " LONG NOT NULL, " + MessageContract.SENDER + " TEXT NOT NULL, " + MessageContract.SENDER_ID + " INTEGER NOT NULL, " + MessageContract.ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + "FOREIGN KEY (" + MessageContract.SENDER_ID+ ") REFERENCES " + PEERS_TABLE + "(" + PeerContract.ID + ") ON DELETE CASCADE" + "); "; private static final String PEER_DATABASE_CREATE = "CREATE TABLE IF NOT EXISTS " + PEERS_TABLE + "( " + PeerContract.ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + PeerContract.NAME + " TEXT NOT NULL, " + PeerContract.TIMESTAMP + " TEXT NOT NULL, " + PeerContract.ADDRESS + " TEXT NOT NULL" + "); "; private static final String MESSAGES_INDEX_CREATE = "CREATE INDEX " + MessageContract.MESSAGES_PEER_INDEX + " ON " + MESSAGES_TABLE + "(" + MessageContract.SENDER_ID + ");"; private static final String PEER_INDEX_CREATE = "CREATE INDEX " + PeerContract.PEER_NAME_INDEX + " ON " + PEERS_TABLE + "(" + PeerContract.NAME + ");"; public DbHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(MESSAGE_DATABASE_CREATE); db.execSQL(PEER_DATABASE_CREATE); db.execSQL(MESSAGES_INDEX_CREATE); db.execSQL(PEER_INDEX_CREATE); db.execSQL("PRAGMA foreign_keys=ON;"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + MESSAGES_TABLE); db.execSQL("DROP TABLE IF EXISTS " + PEERS_TABLE); onCreate(db); } } private DbHelper dbHelper; @Override public boolean onCreate() { // Initialize your content provider on startup. dbHelper = new DbHelper(getContext(), DATABASE_NAME, null, DATABASE_VERSION); return true; } // Used to dispatch operation based on URI private static final UriMatcher uriMatcher; // uriMatcher.addURI(AUTHORITY, CONTENT_PATH, OPCODE) static { uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI(AUTHORITY, MESSAGE_CONTENT_PATH, MESSAGES_ALL_ROWS); uriMatcher.addURI(AUTHORITY, MESSAGE_CONTENT_PATH_ITEM, MESSAGES_SINGLE_ROW); uriMatcher.addURI(AUTHORITY, PEER_CONTENT_PATH, PEERS_ALL_ROWS); uriMatcher.addURI(AUTHORITY, PEER_CONTENT_PATH_ITEM, PEERS_SINGLE_ROW); } @Override public String getType(Uri uri) { // at the given URI. switch(uriMatcher.match(uri)){ case MESSAGES_ALL_ROWS: return "messages"; case MESSAGES_SINGLE_ROW: return "message"; case PEERS_ALL_ROWS: return "peers"; case PEERS_SINGLE_ROW: return "peer"; default: return null; } //throw new UnsupportedOperationException("Not yet implemented"); } @Override public Uri insert(Uri uri, ContentValues values) { SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentResolver cr = getContext().getContentResolver(); Log.d("Debug", "Things are getting inserted " + uriMatcher.match(uri)); switch (uriMatcher.match(uri)) { case MESSAGES_ALL_ROWS: // Make sure to notify any observers long mess_row = db.insert (MESSAGES_TABLE, null, values); if(mess_row >= 0){ Uri instanceUri = MessageContract.CONTENT_URI(mess_row); Log.d("Debug", "message instanceUri = " + instanceUri.toString()); cr.notifyChange(instanceUri, null); return instanceUri; } throw new UnsupportedOperationException("Not Supported Input: " + mess_row); case PEERS_ALL_ROWS: String selection = PeerContract.NAME + "=?"; String[] selectionArgs = {values.getAsString(PeerContract.NAME)}; Cursor isIn = query(uri, null, selection, selectionArgs, null); if(!isIn.moveToFirst()) { long peerrow = db.insert(PEERS_TABLE, null, values); if (peerrow > 0) { Uri instanceUri = PeerContract.CONTENT_URI(peerrow); Log.d("Debug", "peer instanceUri = " + instanceUri.toString()); cr.notifyChange(uri, null); return instanceUri; } } Log.d("Debug", "uri sent for updating: " + uri.toString()); String updateSelection = PeerContract.ID + "=?"; Long idToUpdate = isIn.getLong(isIn.getColumnIndexOrThrow(PeerContract.ID)); String[] updateSelectionArgs = {Long.toString(idToUpdate)}; update(PeerContract.CONTENT_URI(idToUpdate), values, updateSelection, updateSelectionArgs); Uri instanceUri = PeerContract.CONTENT_URI(idToUpdate); Log.d("Debug", "peer instanceUri = " + instanceUri.toString()); return instanceUri; case MESSAGES_SINGLE_ROW: throw new IllegalArgumentException("insert expects a whole-table URI"); default: throw new IllegalStateException("insert: bad case"); } } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteDatabase db = dbHelper.getReadableDatabase(); switch (uriMatcher.match(uri)) { case MESSAGES_ALL_ROWS: Cursor mess_all_curs=db.query(MESSAGES_TABLE, projection, selection, selectionArgs, null, null, sortOrder); if(mess_all_curs.moveToFirst()){ do{ Log.d("Debug Provider", mess_all_curs.getString(mess_all_curs.getColumnIndexOrThrow(MessageContract.MESSAGE_TEXT))); Log.d("PeerIdQuery", Long.toString(mess_all_curs.getLong(mess_all_curs.getColumnIndexOrThrow(MessageContract.SENDER_ID)))); }while(mess_all_curs.moveToNext()); } mess_all_curs.setNotificationUri(getContext().getContentResolver(), uri); return mess_all_curs; case PEERS_ALL_ROWS: Cursor peer_all_curs=db.query(PEERS_TABLE, projection, selection, selectionArgs, null, null, sortOrder); peer_all_curs.setNotificationUri(getContext().getContentResolver(), uri); if(peer_all_curs.moveToFirst()){ do{ Log.d("PeerQuery", Long.toString(peer_all_curs.getLong(peer_all_curs.getColumnIndexOrThrow(PeerContract.ID)))); }while(peer_all_curs.moveToNext()); } return peer_all_curs; case MESSAGES_SINGLE_ROW: Cursor mess_sing_row=db.query(MESSAGES_TABLE, projection, selection, selectionArgs, null, null, sortOrder); mess_sing_row.setNotificationUri(getContext().getContentResolver(), uri); return mess_sing_row; case PEERS_SINGLE_ROW: Cursor peer_sing_row = db.query(PEERS_TABLE, projection, selection, selectionArgs, null, null, sortOrder); peer_sing_row.setNotificationUri(getContext().getContentResolver(), uri); return peer_sing_row; default: throw new IllegalStateException("insert: bad case"); } } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { SQLiteDatabase db = dbHelper.getWritableDatabase(); String table = uri.toString().split("/")[3]; values.put(PeerContract.ID, Long.parseLong(uri.getLastPathSegment())); return db.update(table, values, selection, selectionArgs); } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { SQLiteDatabase db = dbHelper.getWritableDatabase(); String uripath = uri.toString(); String table = uripath.split("/")[3]; return db.delete(table, selection, selectionArgs); } }
UTF-8
Java
10,864
java
ChatProvider.java
Java
[]
null
[]
package edu.stevens.cs522.chatserver.providers; import android.content.ContentProvider; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.database.CursorIndexOutOfBoundsException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; import android.net.Uri; import android.util.Log; import edu.stevens.cs522.chatserver.contracts.BaseContract; import edu.stevens.cs522.chatserver.contracts.MessageContract; import edu.stevens.cs522.chatserver.contracts.PeerContract; import edu.stevens.cs522.chatserver.entities.Message; public class ChatProvider extends ContentProvider { public ChatProvider() { } private static final String AUTHORITY = BaseContract.AUTHORITY; private static final String MESSAGE_CONTENT_PATH = MessageContract.CONTENT_PATH; private static final String MESSAGE_CONTENT_PATH_ITEM = MessageContract.CONTENT_PATH_ITEM; private static final String PEER_CONTENT_PATH = PeerContract.CONTENT_PATH; private static final String PEER_CONTENT_PATH_ITEM = PeerContract.CONTENT_PATH_ITEM; private static final String DATABASE_NAME = "chat.db"; private static final int DATABASE_VERSION = 1; private static final String MESSAGES_TABLE = "Message"; private static final String PEERS_TABLE = "Peer"; // Create the constants used to differentiate between the different URI requests. private static final int MESSAGES_ALL_ROWS = 1; private static final int MESSAGES_SINGLE_ROW = 2; private static final int PEERS_ALL_ROWS = 3; private static final int PEERS_SINGLE_ROW = 4; public static class DbHelper extends SQLiteOpenHelper { private static final String MESSAGE_DATABASE_CREATE = "CREATE TABLE IF NOT EXISTS " + MESSAGES_TABLE + " (" + MessageContract.MESSAGE_TEXT + " TEXT NOT NULL, " + MessageContract.TIMESTAMP + " LONG NOT NULL, " + MessageContract.SENDER + " TEXT NOT NULL, " + MessageContract.SENDER_ID + " INTEGER NOT NULL, " + MessageContract.ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + "FOREIGN KEY (" + MessageContract.SENDER_ID+ ") REFERENCES " + PEERS_TABLE + "(" + PeerContract.ID + ") ON DELETE CASCADE" + "); "; private static final String PEER_DATABASE_CREATE = "CREATE TABLE IF NOT EXISTS " + PEERS_TABLE + "( " + PeerContract.ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + PeerContract.NAME + " TEXT NOT NULL, " + PeerContract.TIMESTAMP + " TEXT NOT NULL, " + PeerContract.ADDRESS + " TEXT NOT NULL" + "); "; private static final String MESSAGES_INDEX_CREATE = "CREATE INDEX " + MessageContract.MESSAGES_PEER_INDEX + " ON " + MESSAGES_TABLE + "(" + MessageContract.SENDER_ID + ");"; private static final String PEER_INDEX_CREATE = "CREATE INDEX " + PeerContract.PEER_NAME_INDEX + " ON " + PEERS_TABLE + "(" + PeerContract.NAME + ");"; public DbHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(MESSAGE_DATABASE_CREATE); db.execSQL(PEER_DATABASE_CREATE); db.execSQL(MESSAGES_INDEX_CREATE); db.execSQL(PEER_INDEX_CREATE); db.execSQL("PRAGMA foreign_keys=ON;"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + MESSAGES_TABLE); db.execSQL("DROP TABLE IF EXISTS " + PEERS_TABLE); onCreate(db); } } private DbHelper dbHelper; @Override public boolean onCreate() { // Initialize your content provider on startup. dbHelper = new DbHelper(getContext(), DATABASE_NAME, null, DATABASE_VERSION); return true; } // Used to dispatch operation based on URI private static final UriMatcher uriMatcher; // uriMatcher.addURI(AUTHORITY, CONTENT_PATH, OPCODE) static { uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI(AUTHORITY, MESSAGE_CONTENT_PATH, MESSAGES_ALL_ROWS); uriMatcher.addURI(AUTHORITY, MESSAGE_CONTENT_PATH_ITEM, MESSAGES_SINGLE_ROW); uriMatcher.addURI(AUTHORITY, PEER_CONTENT_PATH, PEERS_ALL_ROWS); uriMatcher.addURI(AUTHORITY, PEER_CONTENT_PATH_ITEM, PEERS_SINGLE_ROW); } @Override public String getType(Uri uri) { // at the given URI. switch(uriMatcher.match(uri)){ case MESSAGES_ALL_ROWS: return "messages"; case MESSAGES_SINGLE_ROW: return "message"; case PEERS_ALL_ROWS: return "peers"; case PEERS_SINGLE_ROW: return "peer"; default: return null; } //throw new UnsupportedOperationException("Not yet implemented"); } @Override public Uri insert(Uri uri, ContentValues values) { SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentResolver cr = getContext().getContentResolver(); Log.d("Debug", "Things are getting inserted " + uriMatcher.match(uri)); switch (uriMatcher.match(uri)) { case MESSAGES_ALL_ROWS: // Make sure to notify any observers long mess_row = db.insert (MESSAGES_TABLE, null, values); if(mess_row >= 0){ Uri instanceUri = MessageContract.CONTENT_URI(mess_row); Log.d("Debug", "message instanceUri = " + instanceUri.toString()); cr.notifyChange(instanceUri, null); return instanceUri; } throw new UnsupportedOperationException("Not Supported Input: " + mess_row); case PEERS_ALL_ROWS: String selection = PeerContract.NAME + "=?"; String[] selectionArgs = {values.getAsString(PeerContract.NAME)}; Cursor isIn = query(uri, null, selection, selectionArgs, null); if(!isIn.moveToFirst()) { long peerrow = db.insert(PEERS_TABLE, null, values); if (peerrow > 0) { Uri instanceUri = PeerContract.CONTENT_URI(peerrow); Log.d("Debug", "peer instanceUri = " + instanceUri.toString()); cr.notifyChange(uri, null); return instanceUri; } } Log.d("Debug", "uri sent for updating: " + uri.toString()); String updateSelection = PeerContract.ID + "=?"; Long idToUpdate = isIn.getLong(isIn.getColumnIndexOrThrow(PeerContract.ID)); String[] updateSelectionArgs = {Long.toString(idToUpdate)}; update(PeerContract.CONTENT_URI(idToUpdate), values, updateSelection, updateSelectionArgs); Uri instanceUri = PeerContract.CONTENT_URI(idToUpdate); Log.d("Debug", "peer instanceUri = " + instanceUri.toString()); return instanceUri; case MESSAGES_SINGLE_ROW: throw new IllegalArgumentException("insert expects a whole-table URI"); default: throw new IllegalStateException("insert: bad case"); } } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteDatabase db = dbHelper.getReadableDatabase(); switch (uriMatcher.match(uri)) { case MESSAGES_ALL_ROWS: Cursor mess_all_curs=db.query(MESSAGES_TABLE, projection, selection, selectionArgs, null, null, sortOrder); if(mess_all_curs.moveToFirst()){ do{ Log.d("Debug Provider", mess_all_curs.getString(mess_all_curs.getColumnIndexOrThrow(MessageContract.MESSAGE_TEXT))); Log.d("PeerIdQuery", Long.toString(mess_all_curs.getLong(mess_all_curs.getColumnIndexOrThrow(MessageContract.SENDER_ID)))); }while(mess_all_curs.moveToNext()); } mess_all_curs.setNotificationUri(getContext().getContentResolver(), uri); return mess_all_curs; case PEERS_ALL_ROWS: Cursor peer_all_curs=db.query(PEERS_TABLE, projection, selection, selectionArgs, null, null, sortOrder); peer_all_curs.setNotificationUri(getContext().getContentResolver(), uri); if(peer_all_curs.moveToFirst()){ do{ Log.d("PeerQuery", Long.toString(peer_all_curs.getLong(peer_all_curs.getColumnIndexOrThrow(PeerContract.ID)))); }while(peer_all_curs.moveToNext()); } return peer_all_curs; case MESSAGES_SINGLE_ROW: Cursor mess_sing_row=db.query(MESSAGES_TABLE, projection, selection, selectionArgs, null, null, sortOrder); mess_sing_row.setNotificationUri(getContext().getContentResolver(), uri); return mess_sing_row; case PEERS_SINGLE_ROW: Cursor peer_sing_row = db.query(PEERS_TABLE, projection, selection, selectionArgs, null, null, sortOrder); peer_sing_row.setNotificationUri(getContext().getContentResolver(), uri); return peer_sing_row; default: throw new IllegalStateException("insert: bad case"); } } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { SQLiteDatabase db = dbHelper.getWritableDatabase(); String table = uri.toString().split("/")[3]; values.put(PeerContract.ID, Long.parseLong(uri.getLastPathSegment())); return db.update(table, values, selection, selectionArgs); } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { SQLiteDatabase db = dbHelper.getWritableDatabase(); String uripath = uri.toString(); String table = uripath.split("/")[3]; return db.delete(table, selection, selectionArgs); } }
10,864
0.609444
0.607235
237
44.839661
33.081787
148
false
false
0
0
0
0
0
0
0.890295
false
false
10
27aa78fe4af1523a688ef93a87757e1e0ba41b8e
13,297,218,810,404
d97c4234e4f4e83f4a487d2c0343af43e5612f84
/src/main/java/nl/clockwork/ebms/admin/plugin/cpa/web/CreateCPAPage.java
9b243ef72237aab1ebc300a0d0055e6c82d75354
[ "Apache-2.0" ]
permissive
eluinstra/cpa-plugin
https://github.com/eluinstra/cpa-plugin
07e5787d0a5142561e8a8fb08f40fdc81ac617f8
52c0c11e0b3d9f44bcc7b7cf6ed988cc880c822f
refs/heads/master
2022-11-19T11:31:50.047000
2020-07-04T18:48:20
2020-07-04T18:48:20
282,038,386
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Copyright 2016 Ordina * * 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 nl.clockwork.ebms.admin.plugin.cpa.web; import java.io.IOException; import java.io.InputStream; import java.security.KeyException; import java.security.cert.CertificateException; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.IntStream; import javax.xml.crypto.MarshalException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import org.apache.commons.lang3.StringUtils; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.CheckBox; import org.apache.wicket.markup.html.form.ChoiceRenderer; import org.apache.wicket.markup.html.form.DropDownChoice; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.FormComponent; import org.apache.wicket.markup.html.form.TextField; import org.apache.wicket.markup.html.form.upload.FileUploadField; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.list.ListView; import org.apache.wicket.model.CompoundPropertyModel; import org.apache.wicket.model.LoadableDetachableModel; import org.apache.wicket.model.ResourceModel; import org.apache.wicket.spring.injection.annot.SpringBean; import org.apache.wicket.util.io.IClusterable; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import io.vavr.Function3; import io.vavr.Function4; import io.vavr.control.Either; import io.vavr.control.Try; import lombok.AccessLevel; import lombok.Data; import lombok.NoArgsConstructor; import lombok.val; import lombok.experimental.FieldDefaults; import lombok.extern.slf4j.Slf4j; import nl.clockwork.ebms.Eithers; import nl.clockwork.ebms.admin.plugin.cpa.common.Utils; import nl.clockwork.ebms.admin.plugin.cpa.dao.CPAPluginDAO; import nl.clockwork.ebms.admin.plugin.cpa.model.CPATemplate; import nl.clockwork.ebms.admin.plugin.cpa.model.Certificate; import nl.clockwork.ebms.admin.plugin.cpa.model.PartyInfo; import nl.clockwork.ebms.admin.plugin.cpa.model.Url; import nl.clockwork.ebms.admin.web.Action; import nl.clockwork.ebms.admin.web.AjaxFormComponentUpdatingBehavior; import nl.clockwork.ebms.admin.web.BasePage; import nl.clockwork.ebms.admin.web.BootstrapDateTimePicker; import nl.clockwork.ebms.admin.web.BootstrapFeedbackPanel; import nl.clockwork.ebms.admin.web.BootstrapFormComponentFeedbackBorder; import nl.clockwork.ebms.admin.web.Button; import nl.clockwork.ebms.admin.web.Consumer; import nl.clockwork.ebms.admin.web.ResetButton; import nl.clockwork.ebms.admin.web.WebMarkupContainer; import nl.clockwork.ebms.admin.web.service.cpa.CPAsPage; import nl.clockwork.ebms.service.cpa.CPAService; import nl.clockwork.ebms.util.DOMUtils; @Slf4j @FieldDefaults(level = AccessLevel.PRIVATE) public class CreateCPAPage extends BasePage { private class LoadableDetachableCPATemplatesModel extends LoadableDetachableModel<List<CPATemplate>> { private static final long serialVersionUID = 1L; @Override protected List<CPATemplate> load() { return cpaPluginDAO.selectCPATemplates(); } } private static final long serialVersionUID = 1L; @SpringBean(name="cpaService") CPAService cpaService; @SpringBean(name="cpaPluginDAO") CPAPluginDAO cpaPluginDAO; public CreateCPAPage() { add(new BootstrapFeedbackPanel("feedback").setOutputMarkupId(true)); add(new CreateCPAForm("form")); } @Override public String getPageTitle() { return getLocalizer().getString("createCPA",this); } public class CreateCPAForm extends Form<CreateCPAFormData> { private static final long serialVersionUID = 1L; public CreateCPAForm(String id) { super(id,new CompoundPropertyModel<>(new CreateCPAFormData())); setMultiPart(true); add(new BootstrapFormComponentFeedbackBorder("cpaTemplateFeedback",createCPATemplateChoice("cpaTemplate"))); add(new BootstrapFormComponentFeedbackBorder("cpaIdFeedback",new TextField<String>("cpaId").setLabel(new ResourceModel("lbl.cpaId")).setRequired(true)).setOutputMarkupId(true)); add(new BootstrapFormComponentFeedbackBorder("startDateFeedback",new BootstrapDateTimePicker("startDate","dd-MM-yyyy",BootstrapDateTimePicker.Type.DATE).setLabel(new ResourceModel("lbl.startDate")).setRequired(true))); add(new BootstrapFormComponentFeedbackBorder("endDateFeedback",new BootstrapDateTimePicker("endDate","dd-MM-yyyy",BootstrapDateTimePicker.Type.DATE).setLabel(new ResourceModel("lbl.endDate")).setRequired(true))); add(createPartyInfosContainer("partyInfosContainer")); add(createGenerateButton("generate")); add(new ResetButton("reset",new ResourceModel("cmd.reset"),CreateCPAPage.class)); } private DropDownChoice<CPATemplate> createCPATemplateChoice(String id) { val result = new DropDownChoice<CPATemplate>(id,new LoadableDetachableCPATemplatesModel(),new ChoiceRenderer<>("name","id")); result.setLabel(new ResourceModel("lbl.cpaTemplate")); result.setRequired(true); Consumer<AjaxRequestTarget> onUpdate = t -> { try { val model = CreateCPAForm.this.getModelObject(); if (model.getCpaTemplate() != null) { val document = DOMUtils.read(model.getCpaTemplate().getContent()); val xpath = Utils.createXPath(); model.getPartyInfos().addAll(getPartyInfos(document,xpath)); model.setCpaId(generateCPAId(model,document,xpath)); } } catch (Exception e) { log.error("",e); error(e.getMessage()); } t.add(getPage().get("feedback")); t.add(getPage().get("form")); }; result.add(new AjaxFormComponentUpdatingBehavior("change",onUpdate)); return result; } private WebMarkupContainer createPartyInfosContainer(String id) { val result = new WebMarkupContainer(id); val partyInfos = new ListView<PartyInfo>("partyInfos",CreateCPAForm.this.getModelObject().getPartyInfos()) { private static final long serialVersionUID = 1L; @Override protected void populateItem(final ListItem<PartyInfo> item) { item.setModel(new CompoundPropertyModel<>(item.getModelObject())); item.add(createEnabledCheckBox("enabled")); item.add(new BootstrapFormComponentFeedbackBorder("partyNameFeedback",new TextField<String>("partyName").setLabel(new ResourceModel("lbl.partyName")).setRequired(true)) { private static final long serialVersionUID = 1L; @Override public boolean isEnabled() { return item.getModelObject().isEnabled(); } }); item.add(new BootstrapFormComponentFeedbackBorder("partyIdFeedback",createPartyIdTextField("partyId")) { private static final long serialVersionUID = 1L; @Override public boolean isVisible() { return item.getModelObject().isEnabled(); } }); item.add(createUrlsContainer("urlsContainer",item)); item.add(createCertificatesContainer("certificatesContainer",item)); } }; result.add(partyInfos); result.setOutputMarkupId(true); return result; } private CheckBox createEnabledCheckBox(String id) { val result = new CheckBox(id); result.setLabel(new ResourceModel("lbl.enabled")); Consumer<AjaxRequestTarget> onUpdate = t -> { t.add(getPage().get("feedback")); t.add(getPage().get("form")); }; result.add(new AjaxFormComponentUpdatingBehavior("change",onUpdate)); return result; } private FormComponent<String> createPartyIdTextField(String id) { val result = new TextField<String>(id); result.setLabel(new ResourceModel("lbl.partyId")); result.setRequired(true); Consumer<AjaxRequestTarget> onUpdate = t -> { try { val o = getModelObject(); if (o.getCpaTemplate() != null) { val document = DOMUtils.read(o.getCpaTemplate().getContent()); val xpath = Utils.createXPath(); generateCPAId(o,document,xpath); } t.add(getPage().get("form:cpaIdFeedback")); } catch (Exception e) { log.error("",e); error(e.getMessage()); } }; result.add(new AjaxFormComponentUpdatingBehavior("change",onUpdate)); return result; } private WebMarkupContainer createUrlsContainer(String id, final ListItem<PartyInfo> item) { val result = WebMarkupContainer.builder() .id(id) .isVisible(() -> item.getModelObject().isEnabled()) .build(); val certificates = new ListView<Url>("urls",item.getModelObject().getUrls()) { private static final long serialVersionUID = 1L; @Override protected void populateItem(ListItem<Url> item) { item.setModel(new CompoundPropertyModel<>(item.getModelObject())); item.add(new Label("transportId")); item.add(new BootstrapFormComponentFeedbackBorder("urlFeedback",createUrlTextField("url",item.getModelObject().getTransportId()))); } }; result.add(certificates); result.setOutputMarkupId(true); return result; } private FormComponent<String> createUrlTextField(String id, String label) { return new TextField<String>(id).setLabel(new ResourceModel(label,label)).setRequired(true); } private WebMarkupContainer createCertificatesContainer(String id, final ListItem<PartyInfo> item) { val result = WebMarkupContainer.builder() .id(id) .isVisible(() -> item.getModelObject().isEnabled()) .build(); val certificates = new ListView<Certificate>("certificates",item.getModelObject().getCertificates()) { private static final long serialVersionUID = 1L; @Override protected void populateItem(ListItem<Certificate> item) { item.setModel(new CompoundPropertyModel<>(item.getModelObject())); item.add(new Label("id")); item.add(new BootstrapFormComponentFeedbackBorder("fileFeedback",createCertificateFileUploadField("file",item.getModelObject().getId()))); } }; result.add(certificates); result.setOutputMarkupId(true); return result; } private FileUploadField createCertificateFileUploadField(String id, final String label) { val result = new FileUploadField(id); result.setLabel(new ResourceModel(label,label)); result.setRequired(true); return result; } private Button createGenerateButton(String id) { Action onSubmit = () -> { try { val cpaTemplate = getModelObject().cpaTemplate; val document = DOMUtils.read(cpaTemplate.getContent()); processDocument(document,getModelObject()); cpaService.insertCPA(DOMUtils.toString(document),false); setResponsePage(new CPAsPage()); } catch (Exception e) { log.error("",e); error(e.getMessage()); } }; val result = new Button(id,new ResourceModel("cmd.generate"),onSubmit); setDefaultButton(result); return result; } private void processDocument(Document document, CreateCPAFormData modelObject) throws XPathExpressionException, CertificateException, KeyException, MarshalException, IOException { val xpath = Utils.createXPath(); getCpaId(document,xpath).setNodeValue(modelObject.cpaId); getStartDate(document,xpath).setNodeValue(Utils.toXSDDate(modelObject.startDate)); getEndDate(document,xpath).setNodeValue(Utils.toXSDDate(modelObject.endDate)); for (PartyInfo partyInfo : modelObject.getPartyInfos()) { if (partyInfo.isEnabled()) { getPartyName(document,xpath,partyInfo.getId()).setNodeValue(partyInfo.getPartyName()); getPartyId(document,xpath,partyInfo.getId()).setNodeValue(partyInfo.getPartyId()); for (Url url: partyInfo.getUrls()) getUrl(document,xpath,partyInfo.getId(),url.getTransportId()).setNodeValue(url.getUrl()); for (Certificate certificate : partyInfo.getCertificates()) { val files = certificate.getFile(); if (files != null && files.size() == 1) replaceCertificate(document,xpath,partyInfo.getId(),certificate.getId(),files.get(0).getInputStream()); } } } } private Node getCpaId(Document document, XPath xpath) throws XPathExpressionException { return (Node)xpath.evaluate("/cpa:CollaborationProtocolAgreement/@cpa:cpaid",document,XPathConstants.NODE); } private Node getStartDate(Document document, XPath xpath) throws XPathExpressionException { return (Node)xpath.evaluate("/cpa:CollaborationProtocolAgreement/cpa:Start/text()",document,XPathConstants.NODE); } private Node getEndDate(Document document, XPath xpath) throws XPathExpressionException { return (Node)xpath.evaluate("/cpa:CollaborationProtocolAgreement/cpa:End/text()",document,XPathConstants.NODE); } private Node getPartyName(Document document, XPath xpath, Integer partyInfoId) throws XPathExpressionException { return (Node)xpath.evaluate("/cpa:CollaborationProtocolAgreement/cpa:PartyInfo[" + partyInfoId + "]/@cpa:partyName",document,XPathConstants.NODE); } private Node getPartyId(Document document, XPath xpath, Integer partyInfoId) throws XPathExpressionException { return (Node)xpath.evaluate("/cpa:CollaborationProtocolAgreement/cpa:PartyInfo[" + partyInfoId + "]/cpa:PartyId/text()",document,XPathConstants.NODE); } private Node getUrl(Document document, XPath xpath, Integer partyInfoId, String transportId) throws XPathExpressionException { return (Node)xpath.evaluate( "/cpa:CollaborationProtocolAgreement/cpa:PartyInfo[" + partyInfoId + "]/cpa:Transport[@cpa:transportId = '" + transportId + "']/cpa:TransportReceiver/cpa:Endpoint[1]/@cpa:uri", document, XPathConstants.NODE); } private void replaceCertificate(Document document, XPath xpath, Integer partyInfoId, String certificateId, InputStream certificate) throws XPathExpressionException, CertificateException, KeyException, MarshalException, IOException { val certificateNode = (Node)xpath.evaluate("/cpa:CollaborationProtocolAgreement/cpa:PartyInfo[" + partyInfoId + "]//cpa:Certificate[@cpa:certId = '" + certificateId + "']",document,XPathConstants.NODE); val keyInfo = (Node)xpath.evaluate("//cpa:Certificate[@cpa:certId = '" + certificateId + "']/xmldsig:KeyInfo",document,XPathConstants.NODE); certificateNode.removeChild(keyInfo); Utils.generateKeyInfo(certificateNode,certificate); } private List<PartyInfo> getPartyInfos(Document document, XPath xpath) throws XPathExpressionException { Function3<Integer,Document,XPath,Either<XPathExpressionException,PartyInfo>> createPartyInfo = (i,d,x) -> Try.<Either<XPathExpressionException,PartyInfo>>of(() -> Either.<XPathExpressionException,PartyInfo>right(createPartyInfo(i,d,x))) .getOrElseGet(e -> Either.<XPathExpressionException,PartyInfo>left((XPathExpressionException)e)); val nodeList = (NodeList)xpath.evaluate("/cpa:CollaborationProtocolAgreement//cpa:PartyInfo",document,XPathConstants.NODESET); return Eithers.sequenceRight( IntStream.range(1,nodeList.getLength() + 1).boxed() .map(i -> createPartyInfo.apply(i,document,xpath))) .getOrElseThrow(e -> e); } private PartyInfo createPartyInfo(int id, Document document, XPath xpath) throws XPathExpressionException { val result = new PartyInfo(); result.setId(id); result.setPartyName(getPartyName(id,document,xpath)); result.setPartyId(getPartyId(id,document,xpath)); result.setUrls(getURLs(id,document,xpath)); result.setCertificates(getCertificateFiles(id,document,xpath)); return result; } private String generateCPAId(CreateCPAFormData model, Document document, XPath xpath) throws XPathExpressionException { val cpaId = (String)xpath.evaluate("/cpa:CollaborationProtocolAgreement/@cpa:cpaid",document,XPathConstants.STRING); return cpaId + "_" + toString(model.getPartyInfos()) + "_" + UUID.randomUUID(); } private String toString(List<PartyInfo> partyInfos) { return partyInfos.stream().filter(p -> !StringUtils.isEmpty(p.getPartyId())).map(p -> p.getPartyId()).collect(Collectors.joining("_")); } private String getPartyName(Integer id, Document document, XPath xpath) throws XPathExpressionException { return (String)xpath.evaluate("/cpa:CollaborationProtocolAgreement/cpa:PartyInfo[" + id + "]/@cpa:partyName",document,XPathConstants.STRING); } private String getPartyId(Integer id, Document document, XPath xpath) throws XPathExpressionException { return (String)xpath.evaluate("/cpa:CollaborationProtocolAgreement/cpa:PartyInfo[" + id + "]/cpa:PartyId/text()",document,XPathConstants.STRING); } private List<Url> getURLs(Integer id, Document document, XPath xpath) throws XPathExpressionException { Function4<Integer,String,Document,XPath,Either<XPathExpressionException,Url>> createUrl = (i,t,d,x) -> Try.<Either<XPathExpressionException,Url>>of(() -> Either.<XPathExpressionException,Url>right(createUrl(i,t,d,x))) .getOrElseGet(e -> Either.<XPathExpressionException,Url>left((XPathExpressionException)e)); val nodeList = (NodeList)xpath.evaluate("/cpa:CollaborationProtocolAgreement/cpa:PartyInfo[" + id + "]//cpa:Transport/@cpa:transportId",document,XPathConstants.NODESET); return Eithers.sequenceRight(IntStream.range(0,nodeList.getLength()).boxed() .map(i -> createUrl.apply(id,nodeList.item(i).getNodeValue(),document,xpath))) .getOrElseThrow(e -> e); } private Url createUrl(Integer id, String transportId, Document document, XPath xpath) throws XPathExpressionException { val url = (String)xpath.evaluate("/cpa:CollaborationProtocolAgreement/cpa:PartyInfo[" + id + "]/cpa:Transport[@cpa:transportId = '" + transportId + "']/cpa:TransportReceiver/cpa:Endpoint[1]/@cpa:uri",document,XPathConstants.STRING); return new Url(transportId,url); } private ArrayList<Certificate> getCertificateFiles(Integer id, Document document, XPath xpath) throws XPathExpressionException { val result = new ArrayList<Certificate>(); val nodeList = (NodeList)xpath.evaluate("/cpa:CollaborationProtocolAgreement/cpa:PartyInfo[" + id + "]//cpa:Certificate/@cpa:certId",document,XPathConstants.NODESET); val certificates = IntStream.range(0,nodeList.getLength()).boxed() .map(i -> new Certificate(nodeList.item(i).getNodeValue())) .collect(Collectors.toList()); result.addAll(certificates); return result; } } @Data @FieldDefaults(level = AccessLevel.PRIVATE) @NoArgsConstructor public class CreateCPAFormData implements IClusterable { private static final long serialVersionUID = 1L; CPATemplate cpaTemplate; String cpaId; LocalDateTime startDate = LocalDateTime.now(); LocalDateTime endDate = LocalDateTime.now().plusYears(1); List<PartyInfo> partyInfos = new ArrayList<>(); } }
UTF-8
Java
19,288
java
CreateCPAPage.java
Java
[ { "context": "/**\n * Copyright 2016 Ordina\n *\n * Licensed under the Apache License, Version ", "end": 28, "score": 0.9996856451034546, "start": 22, "tag": "NAME", "value": "Ordina" } ]
null
[]
/** * Copyright 2016 Ordina * * 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 nl.clockwork.ebms.admin.plugin.cpa.web; import java.io.IOException; import java.io.InputStream; import java.security.KeyException; import java.security.cert.CertificateException; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.IntStream; import javax.xml.crypto.MarshalException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import org.apache.commons.lang3.StringUtils; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.CheckBox; import org.apache.wicket.markup.html.form.ChoiceRenderer; import org.apache.wicket.markup.html.form.DropDownChoice; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.FormComponent; import org.apache.wicket.markup.html.form.TextField; import org.apache.wicket.markup.html.form.upload.FileUploadField; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.list.ListView; import org.apache.wicket.model.CompoundPropertyModel; import org.apache.wicket.model.LoadableDetachableModel; import org.apache.wicket.model.ResourceModel; import org.apache.wicket.spring.injection.annot.SpringBean; import org.apache.wicket.util.io.IClusterable; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import io.vavr.Function3; import io.vavr.Function4; import io.vavr.control.Either; import io.vavr.control.Try; import lombok.AccessLevel; import lombok.Data; import lombok.NoArgsConstructor; import lombok.val; import lombok.experimental.FieldDefaults; import lombok.extern.slf4j.Slf4j; import nl.clockwork.ebms.Eithers; import nl.clockwork.ebms.admin.plugin.cpa.common.Utils; import nl.clockwork.ebms.admin.plugin.cpa.dao.CPAPluginDAO; import nl.clockwork.ebms.admin.plugin.cpa.model.CPATemplate; import nl.clockwork.ebms.admin.plugin.cpa.model.Certificate; import nl.clockwork.ebms.admin.plugin.cpa.model.PartyInfo; import nl.clockwork.ebms.admin.plugin.cpa.model.Url; import nl.clockwork.ebms.admin.web.Action; import nl.clockwork.ebms.admin.web.AjaxFormComponentUpdatingBehavior; import nl.clockwork.ebms.admin.web.BasePage; import nl.clockwork.ebms.admin.web.BootstrapDateTimePicker; import nl.clockwork.ebms.admin.web.BootstrapFeedbackPanel; import nl.clockwork.ebms.admin.web.BootstrapFormComponentFeedbackBorder; import nl.clockwork.ebms.admin.web.Button; import nl.clockwork.ebms.admin.web.Consumer; import nl.clockwork.ebms.admin.web.ResetButton; import nl.clockwork.ebms.admin.web.WebMarkupContainer; import nl.clockwork.ebms.admin.web.service.cpa.CPAsPage; import nl.clockwork.ebms.service.cpa.CPAService; import nl.clockwork.ebms.util.DOMUtils; @Slf4j @FieldDefaults(level = AccessLevel.PRIVATE) public class CreateCPAPage extends BasePage { private class LoadableDetachableCPATemplatesModel extends LoadableDetachableModel<List<CPATemplate>> { private static final long serialVersionUID = 1L; @Override protected List<CPATemplate> load() { return cpaPluginDAO.selectCPATemplates(); } } private static final long serialVersionUID = 1L; @SpringBean(name="cpaService") CPAService cpaService; @SpringBean(name="cpaPluginDAO") CPAPluginDAO cpaPluginDAO; public CreateCPAPage() { add(new BootstrapFeedbackPanel("feedback").setOutputMarkupId(true)); add(new CreateCPAForm("form")); } @Override public String getPageTitle() { return getLocalizer().getString("createCPA",this); } public class CreateCPAForm extends Form<CreateCPAFormData> { private static final long serialVersionUID = 1L; public CreateCPAForm(String id) { super(id,new CompoundPropertyModel<>(new CreateCPAFormData())); setMultiPart(true); add(new BootstrapFormComponentFeedbackBorder("cpaTemplateFeedback",createCPATemplateChoice("cpaTemplate"))); add(new BootstrapFormComponentFeedbackBorder("cpaIdFeedback",new TextField<String>("cpaId").setLabel(new ResourceModel("lbl.cpaId")).setRequired(true)).setOutputMarkupId(true)); add(new BootstrapFormComponentFeedbackBorder("startDateFeedback",new BootstrapDateTimePicker("startDate","dd-MM-yyyy",BootstrapDateTimePicker.Type.DATE).setLabel(new ResourceModel("lbl.startDate")).setRequired(true))); add(new BootstrapFormComponentFeedbackBorder("endDateFeedback",new BootstrapDateTimePicker("endDate","dd-MM-yyyy",BootstrapDateTimePicker.Type.DATE).setLabel(new ResourceModel("lbl.endDate")).setRequired(true))); add(createPartyInfosContainer("partyInfosContainer")); add(createGenerateButton("generate")); add(new ResetButton("reset",new ResourceModel("cmd.reset"),CreateCPAPage.class)); } private DropDownChoice<CPATemplate> createCPATemplateChoice(String id) { val result = new DropDownChoice<CPATemplate>(id,new LoadableDetachableCPATemplatesModel(),new ChoiceRenderer<>("name","id")); result.setLabel(new ResourceModel("lbl.cpaTemplate")); result.setRequired(true); Consumer<AjaxRequestTarget> onUpdate = t -> { try { val model = CreateCPAForm.this.getModelObject(); if (model.getCpaTemplate() != null) { val document = DOMUtils.read(model.getCpaTemplate().getContent()); val xpath = Utils.createXPath(); model.getPartyInfos().addAll(getPartyInfos(document,xpath)); model.setCpaId(generateCPAId(model,document,xpath)); } } catch (Exception e) { log.error("",e); error(e.getMessage()); } t.add(getPage().get("feedback")); t.add(getPage().get("form")); }; result.add(new AjaxFormComponentUpdatingBehavior("change",onUpdate)); return result; } private WebMarkupContainer createPartyInfosContainer(String id) { val result = new WebMarkupContainer(id); val partyInfos = new ListView<PartyInfo>("partyInfos",CreateCPAForm.this.getModelObject().getPartyInfos()) { private static final long serialVersionUID = 1L; @Override protected void populateItem(final ListItem<PartyInfo> item) { item.setModel(new CompoundPropertyModel<>(item.getModelObject())); item.add(createEnabledCheckBox("enabled")); item.add(new BootstrapFormComponentFeedbackBorder("partyNameFeedback",new TextField<String>("partyName").setLabel(new ResourceModel("lbl.partyName")).setRequired(true)) { private static final long serialVersionUID = 1L; @Override public boolean isEnabled() { return item.getModelObject().isEnabled(); } }); item.add(new BootstrapFormComponentFeedbackBorder("partyIdFeedback",createPartyIdTextField("partyId")) { private static final long serialVersionUID = 1L; @Override public boolean isVisible() { return item.getModelObject().isEnabled(); } }); item.add(createUrlsContainer("urlsContainer",item)); item.add(createCertificatesContainer("certificatesContainer",item)); } }; result.add(partyInfos); result.setOutputMarkupId(true); return result; } private CheckBox createEnabledCheckBox(String id) { val result = new CheckBox(id); result.setLabel(new ResourceModel("lbl.enabled")); Consumer<AjaxRequestTarget> onUpdate = t -> { t.add(getPage().get("feedback")); t.add(getPage().get("form")); }; result.add(new AjaxFormComponentUpdatingBehavior("change",onUpdate)); return result; } private FormComponent<String> createPartyIdTextField(String id) { val result = new TextField<String>(id); result.setLabel(new ResourceModel("lbl.partyId")); result.setRequired(true); Consumer<AjaxRequestTarget> onUpdate = t -> { try { val o = getModelObject(); if (o.getCpaTemplate() != null) { val document = DOMUtils.read(o.getCpaTemplate().getContent()); val xpath = Utils.createXPath(); generateCPAId(o,document,xpath); } t.add(getPage().get("form:cpaIdFeedback")); } catch (Exception e) { log.error("",e); error(e.getMessage()); } }; result.add(new AjaxFormComponentUpdatingBehavior("change",onUpdate)); return result; } private WebMarkupContainer createUrlsContainer(String id, final ListItem<PartyInfo> item) { val result = WebMarkupContainer.builder() .id(id) .isVisible(() -> item.getModelObject().isEnabled()) .build(); val certificates = new ListView<Url>("urls",item.getModelObject().getUrls()) { private static final long serialVersionUID = 1L; @Override protected void populateItem(ListItem<Url> item) { item.setModel(new CompoundPropertyModel<>(item.getModelObject())); item.add(new Label("transportId")); item.add(new BootstrapFormComponentFeedbackBorder("urlFeedback",createUrlTextField("url",item.getModelObject().getTransportId()))); } }; result.add(certificates); result.setOutputMarkupId(true); return result; } private FormComponent<String> createUrlTextField(String id, String label) { return new TextField<String>(id).setLabel(new ResourceModel(label,label)).setRequired(true); } private WebMarkupContainer createCertificatesContainer(String id, final ListItem<PartyInfo> item) { val result = WebMarkupContainer.builder() .id(id) .isVisible(() -> item.getModelObject().isEnabled()) .build(); val certificates = new ListView<Certificate>("certificates",item.getModelObject().getCertificates()) { private static final long serialVersionUID = 1L; @Override protected void populateItem(ListItem<Certificate> item) { item.setModel(new CompoundPropertyModel<>(item.getModelObject())); item.add(new Label("id")); item.add(new BootstrapFormComponentFeedbackBorder("fileFeedback",createCertificateFileUploadField("file",item.getModelObject().getId()))); } }; result.add(certificates); result.setOutputMarkupId(true); return result; } private FileUploadField createCertificateFileUploadField(String id, final String label) { val result = new FileUploadField(id); result.setLabel(new ResourceModel(label,label)); result.setRequired(true); return result; } private Button createGenerateButton(String id) { Action onSubmit = () -> { try { val cpaTemplate = getModelObject().cpaTemplate; val document = DOMUtils.read(cpaTemplate.getContent()); processDocument(document,getModelObject()); cpaService.insertCPA(DOMUtils.toString(document),false); setResponsePage(new CPAsPage()); } catch (Exception e) { log.error("",e); error(e.getMessage()); } }; val result = new Button(id,new ResourceModel("cmd.generate"),onSubmit); setDefaultButton(result); return result; } private void processDocument(Document document, CreateCPAFormData modelObject) throws XPathExpressionException, CertificateException, KeyException, MarshalException, IOException { val xpath = Utils.createXPath(); getCpaId(document,xpath).setNodeValue(modelObject.cpaId); getStartDate(document,xpath).setNodeValue(Utils.toXSDDate(modelObject.startDate)); getEndDate(document,xpath).setNodeValue(Utils.toXSDDate(modelObject.endDate)); for (PartyInfo partyInfo : modelObject.getPartyInfos()) { if (partyInfo.isEnabled()) { getPartyName(document,xpath,partyInfo.getId()).setNodeValue(partyInfo.getPartyName()); getPartyId(document,xpath,partyInfo.getId()).setNodeValue(partyInfo.getPartyId()); for (Url url: partyInfo.getUrls()) getUrl(document,xpath,partyInfo.getId(),url.getTransportId()).setNodeValue(url.getUrl()); for (Certificate certificate : partyInfo.getCertificates()) { val files = certificate.getFile(); if (files != null && files.size() == 1) replaceCertificate(document,xpath,partyInfo.getId(),certificate.getId(),files.get(0).getInputStream()); } } } } private Node getCpaId(Document document, XPath xpath) throws XPathExpressionException { return (Node)xpath.evaluate("/cpa:CollaborationProtocolAgreement/@cpa:cpaid",document,XPathConstants.NODE); } private Node getStartDate(Document document, XPath xpath) throws XPathExpressionException { return (Node)xpath.evaluate("/cpa:CollaborationProtocolAgreement/cpa:Start/text()",document,XPathConstants.NODE); } private Node getEndDate(Document document, XPath xpath) throws XPathExpressionException { return (Node)xpath.evaluate("/cpa:CollaborationProtocolAgreement/cpa:End/text()",document,XPathConstants.NODE); } private Node getPartyName(Document document, XPath xpath, Integer partyInfoId) throws XPathExpressionException { return (Node)xpath.evaluate("/cpa:CollaborationProtocolAgreement/cpa:PartyInfo[" + partyInfoId + "]/@cpa:partyName",document,XPathConstants.NODE); } private Node getPartyId(Document document, XPath xpath, Integer partyInfoId) throws XPathExpressionException { return (Node)xpath.evaluate("/cpa:CollaborationProtocolAgreement/cpa:PartyInfo[" + partyInfoId + "]/cpa:PartyId/text()",document,XPathConstants.NODE); } private Node getUrl(Document document, XPath xpath, Integer partyInfoId, String transportId) throws XPathExpressionException { return (Node)xpath.evaluate( "/cpa:CollaborationProtocolAgreement/cpa:PartyInfo[" + partyInfoId + "]/cpa:Transport[@cpa:transportId = '" + transportId + "']/cpa:TransportReceiver/cpa:Endpoint[1]/@cpa:uri", document, XPathConstants.NODE); } private void replaceCertificate(Document document, XPath xpath, Integer partyInfoId, String certificateId, InputStream certificate) throws XPathExpressionException, CertificateException, KeyException, MarshalException, IOException { val certificateNode = (Node)xpath.evaluate("/cpa:CollaborationProtocolAgreement/cpa:PartyInfo[" + partyInfoId + "]//cpa:Certificate[@cpa:certId = '" + certificateId + "']",document,XPathConstants.NODE); val keyInfo = (Node)xpath.evaluate("//cpa:Certificate[@cpa:certId = '" + certificateId + "']/xmldsig:KeyInfo",document,XPathConstants.NODE); certificateNode.removeChild(keyInfo); Utils.generateKeyInfo(certificateNode,certificate); } private List<PartyInfo> getPartyInfos(Document document, XPath xpath) throws XPathExpressionException { Function3<Integer,Document,XPath,Either<XPathExpressionException,PartyInfo>> createPartyInfo = (i,d,x) -> Try.<Either<XPathExpressionException,PartyInfo>>of(() -> Either.<XPathExpressionException,PartyInfo>right(createPartyInfo(i,d,x))) .getOrElseGet(e -> Either.<XPathExpressionException,PartyInfo>left((XPathExpressionException)e)); val nodeList = (NodeList)xpath.evaluate("/cpa:CollaborationProtocolAgreement//cpa:PartyInfo",document,XPathConstants.NODESET); return Eithers.sequenceRight( IntStream.range(1,nodeList.getLength() + 1).boxed() .map(i -> createPartyInfo.apply(i,document,xpath))) .getOrElseThrow(e -> e); } private PartyInfo createPartyInfo(int id, Document document, XPath xpath) throws XPathExpressionException { val result = new PartyInfo(); result.setId(id); result.setPartyName(getPartyName(id,document,xpath)); result.setPartyId(getPartyId(id,document,xpath)); result.setUrls(getURLs(id,document,xpath)); result.setCertificates(getCertificateFiles(id,document,xpath)); return result; } private String generateCPAId(CreateCPAFormData model, Document document, XPath xpath) throws XPathExpressionException { val cpaId = (String)xpath.evaluate("/cpa:CollaborationProtocolAgreement/@cpa:cpaid",document,XPathConstants.STRING); return cpaId + "_" + toString(model.getPartyInfos()) + "_" + UUID.randomUUID(); } private String toString(List<PartyInfo> partyInfos) { return partyInfos.stream().filter(p -> !StringUtils.isEmpty(p.getPartyId())).map(p -> p.getPartyId()).collect(Collectors.joining("_")); } private String getPartyName(Integer id, Document document, XPath xpath) throws XPathExpressionException { return (String)xpath.evaluate("/cpa:CollaborationProtocolAgreement/cpa:PartyInfo[" + id + "]/@cpa:partyName",document,XPathConstants.STRING); } private String getPartyId(Integer id, Document document, XPath xpath) throws XPathExpressionException { return (String)xpath.evaluate("/cpa:CollaborationProtocolAgreement/cpa:PartyInfo[" + id + "]/cpa:PartyId/text()",document,XPathConstants.STRING); } private List<Url> getURLs(Integer id, Document document, XPath xpath) throws XPathExpressionException { Function4<Integer,String,Document,XPath,Either<XPathExpressionException,Url>> createUrl = (i,t,d,x) -> Try.<Either<XPathExpressionException,Url>>of(() -> Either.<XPathExpressionException,Url>right(createUrl(i,t,d,x))) .getOrElseGet(e -> Either.<XPathExpressionException,Url>left((XPathExpressionException)e)); val nodeList = (NodeList)xpath.evaluate("/cpa:CollaborationProtocolAgreement/cpa:PartyInfo[" + id + "]//cpa:Transport/@cpa:transportId",document,XPathConstants.NODESET); return Eithers.sequenceRight(IntStream.range(0,nodeList.getLength()).boxed() .map(i -> createUrl.apply(id,nodeList.item(i).getNodeValue(),document,xpath))) .getOrElseThrow(e -> e); } private Url createUrl(Integer id, String transportId, Document document, XPath xpath) throws XPathExpressionException { val url = (String)xpath.evaluate("/cpa:CollaborationProtocolAgreement/cpa:PartyInfo[" + id + "]/cpa:Transport[@cpa:transportId = '" + transportId + "']/cpa:TransportReceiver/cpa:Endpoint[1]/@cpa:uri",document,XPathConstants.STRING); return new Url(transportId,url); } private ArrayList<Certificate> getCertificateFiles(Integer id, Document document, XPath xpath) throws XPathExpressionException { val result = new ArrayList<Certificate>(); val nodeList = (NodeList)xpath.evaluate("/cpa:CollaborationProtocolAgreement/cpa:PartyInfo[" + id + "]//cpa:Certificate/@cpa:certId",document,XPathConstants.NODESET); val certificates = IntStream.range(0,nodeList.getLength()).boxed() .map(i -> new Certificate(nodeList.item(i).getNodeValue())) .collect(Collectors.toList()); result.addAll(certificates); return result; } } @Data @FieldDefaults(level = AccessLevel.PRIVATE) @NoArgsConstructor public class CreateCPAFormData implements IClusterable { private static final long serialVersionUID = 1L; CPATemplate cpaTemplate; String cpaId; LocalDateTime startDate = LocalDateTime.now(); LocalDateTime endDate = LocalDateTime.now().plusYears(1); List<PartyInfo> partyInfos = new ArrayList<>(); } }
19,288
0.749844
0.747926
480
39.183334
42.333839
235
false
false
0
0
0
0
0
0
3.216667
false
false
10
4566c0d6cb1ff574090fd07e66cfbe657aa493a7
15,315,853,422,914
45c33538e0d05c68e0dda9127203c09c94307f73
/StudentProject/src/main/java/com/spring/biz/vo/GradeVO.java
4f491062a4f69bb83fb731bb5f2e1556be7838cd
[]
no_license
insik-han/KHspring
https://github.com/insik-han/KHspring
c843ab5698bf50f3e5598436a9ead266be582bd4
fb2471b5dcab73eca776b97834130a941d664d11
refs/heads/master
2023-01-03T14:17:44.923000
2020-10-20T02:44:04
2020-10-20T02:44:04
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.spring.biz.vo; public class GradeVO { private int gradeCode; private int stuNum; private int korScore; private int mathScore; private int engScore; public int getGradeCode() { return gradeCode; } public void setGradeCode(int gradeCode) { this.gradeCode = gradeCode; } public int getStuNum() { return stuNum; } public void setStuNum(int stuNum) { this.stuNum = stuNum; } public int getKorScore() { return korScore; } public void setKorScore(int korScore) { this.korScore = korScore; } public int getMathScore() { return mathScore; } public void setMathScore(int mathScore) { this.mathScore = mathScore; } public int getEngScore() { return engScore; } public void setEngScore(int engScore) { this.engScore = engScore; } }
UTF-8
Java
750
java
GradeVO.java
Java
[]
null
[]
package com.spring.biz.vo; public class GradeVO { private int gradeCode; private int stuNum; private int korScore; private int mathScore; private int engScore; public int getGradeCode() { return gradeCode; } public void setGradeCode(int gradeCode) { this.gradeCode = gradeCode; } public int getStuNum() { return stuNum; } public void setStuNum(int stuNum) { this.stuNum = stuNum; } public int getKorScore() { return korScore; } public void setKorScore(int korScore) { this.korScore = korScore; } public int getMathScore() { return mathScore; } public void setMathScore(int mathScore) { this.mathScore = mathScore; } public int getEngScore() { return engScore; } public void setEngScore(int engScore) { this.engScore = engScore; } }
750
0.745333
0.745333
46
15.304348
13.575665
41
false
false
0
0
0
0
0
0
0.673913
false
false
10
4086868352aff1b50fa84c9446280cc7e20008b4
27,049,704,031,742
d45b2096a731e88a1c5d894bec85a70339e43ead
/src/main/java/com/sinnerschrader/s2b/accounttool/presentation/controller/MainController.java
45c0cf9084390c32c9b326de3602e0edef299a72
[ "MIT" ]
permissive
toread/account-tool
https://github.com/toread/account-tool
657b7658880acbb955bde873975fb96465807e49
1edd6bda3233d46623b46fa2cdc9faa7f4193106
refs/heads/master
2021-05-05T01:13:15.549000
2018-01-23T09:40:05
2018-01-23T09:40:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sinnerschrader.s2b.accounttool.presentation.controller; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.sinnerschrader.s2b.accounttool.config.WebConstants; import com.sinnerschrader.s2b.accounttool.config.authentication.LdapUserDetails; import com.sinnerschrader.s2b.accounttool.config.ldap.LdapConfiguration; import com.sinnerschrader.s2b.accounttool.logic.component.ldap.LdapService; import com.sinnerschrader.s2b.accounttool.presentation.RequestUtils; import org.apache.catalina.servlet4preview.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.core.env.Environment; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.DisabledException; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import java.io.StringWriter; @Controller public class MainController { private final static Logger log = LoggerFactory.getLogger(MainController.class); @Autowired private Environment environment; @Autowired private ApplicationContext applicationContext; @Autowired private LdapConfiguration ldapConfiguration; @Autowired private LdapService ldapService; @RequestMapping(path = "/") public String root() { return "redirect:/profile"; } @RequestMapping(value = "/login", method = RequestMethod.GET) public ModelAndView login( HttpServletRequest request, @CookieValue(name = WebConstants.COMPANY_COOKIE_NAME, defaultValue = "") String company, @RequestParam(value = "error", required = false) String error, @RequestParam(value = "logout", required = false) String logout) { ModelAndView model = new ModelAndView("pages/login.html"); LdapUserDetails details = RequestUtils.getCurrentUserDetails(); if (details != null) { // redirect on login page, if the user is already logged in. return new ModelAndView("redirect:/profile"); } if (error != null) { model.addObject("error", getErrorCode(request)); } if (logout != null) { model.addObject("msg", "logout.success"); } model.addObject("selectedCompany", company); model.addObject("companies", ldapConfiguration.getCompanies()); return model; } //customize the error message private String getErrorCode(HttpServletRequest request) { final String key = "SPRING_SECURITY_LAST_EXCEPTION"; Exception exception = (Exception) request.getSession().getAttribute(key); String error; if (exception instanceof BadCredentialsException) { error = "login.invalid.credentials"; } else if (exception instanceof DisabledException) { error = "login.account.disabled"; } else { error = "login.general.error"; } return error; } @RequestMapping(path = "/logout", method = RequestMethod.GET) public String logout(HttpServletRequest request) { LdapUserDetails details = RequestUtils.getCurrentUserDetails(); if (details != null) { log.debug("{} has been successfully logged off", details.getUid()); } request.getSession().invalidate(); return "redirect:/login?logout"; } @RequestMapping(path = "/csp-report", method = RequestMethod.POST) @ResponseBody public ResponseEntity<String> cspReport(@RequestBody(required = false) String cspReportString) { HttpStatus status; if (cspReportString != null) { status = HttpStatus.OK; try { ObjectMapper om = new ObjectMapper(); JsonNode cspReportRoot = om.readTree(cspReportString); om.enable(SerializationFeature.INDENT_OUTPUT); StringWriter writer = new StringWriter(); om.writeValue(writer, cspReportRoot); log.warn("CSP-Report: \n{}", writer.toString()); } catch (Exception e) { // ignore exception and print request body plain log.warn("CSP-Report: {}", cspReportString); } } else { status = HttpStatus.NOT_FOUND; } return new ResponseEntity<>(status); } }
UTF-8
Java
4,769
java
MainController.java
Java
[ { "context": "letRequest request) {\n final String key = \"SPRING_SECURITY_LAST_EXCEPTION\";\n Exception exception = (Exception) reque", "end": 2964, "score": 0.999590277671814, "start": 2934, "tag": "KEY", "value": "SPRING_SECURITY_LAST_EXCEPTION" } ]
null
[]
package com.sinnerschrader.s2b.accounttool.presentation.controller; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.sinnerschrader.s2b.accounttool.config.WebConstants; import com.sinnerschrader.s2b.accounttool.config.authentication.LdapUserDetails; import com.sinnerschrader.s2b.accounttool.config.ldap.LdapConfiguration; import com.sinnerschrader.s2b.accounttool.logic.component.ldap.LdapService; import com.sinnerschrader.s2b.accounttool.presentation.RequestUtils; import org.apache.catalina.servlet4preview.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.core.env.Environment; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.DisabledException; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import java.io.StringWriter; @Controller public class MainController { private final static Logger log = LoggerFactory.getLogger(MainController.class); @Autowired private Environment environment; @Autowired private ApplicationContext applicationContext; @Autowired private LdapConfiguration ldapConfiguration; @Autowired private LdapService ldapService; @RequestMapping(path = "/") public String root() { return "redirect:/profile"; } @RequestMapping(value = "/login", method = RequestMethod.GET) public ModelAndView login( HttpServletRequest request, @CookieValue(name = WebConstants.COMPANY_COOKIE_NAME, defaultValue = "") String company, @RequestParam(value = "error", required = false) String error, @RequestParam(value = "logout", required = false) String logout) { ModelAndView model = new ModelAndView("pages/login.html"); LdapUserDetails details = RequestUtils.getCurrentUserDetails(); if (details != null) { // redirect on login page, if the user is already logged in. return new ModelAndView("redirect:/profile"); } if (error != null) { model.addObject("error", getErrorCode(request)); } if (logout != null) { model.addObject("msg", "logout.success"); } model.addObject("selectedCompany", company); model.addObject("companies", ldapConfiguration.getCompanies()); return model; } //customize the error message private String getErrorCode(HttpServletRequest request) { final String key = "SPRING_SECURITY_LAST_EXCEPTION"; Exception exception = (Exception) request.getSession().getAttribute(key); String error; if (exception instanceof BadCredentialsException) { error = "login.invalid.credentials"; } else if (exception instanceof DisabledException) { error = "login.account.disabled"; } else { error = "login.general.error"; } return error; } @RequestMapping(path = "/logout", method = RequestMethod.GET) public String logout(HttpServletRequest request) { LdapUserDetails details = RequestUtils.getCurrentUserDetails(); if (details != null) { log.debug("{} has been successfully logged off", details.getUid()); } request.getSession().invalidate(); return "redirect:/login?logout"; } @RequestMapping(path = "/csp-report", method = RequestMethod.POST) @ResponseBody public ResponseEntity<String> cspReport(@RequestBody(required = false) String cspReportString) { HttpStatus status; if (cspReportString != null) { status = HttpStatus.OK; try { ObjectMapper om = new ObjectMapper(); JsonNode cspReportRoot = om.readTree(cspReportString); om.enable(SerializationFeature.INDENT_OUTPUT); StringWriter writer = new StringWriter(); om.writeValue(writer, cspReportRoot); log.warn("CSP-Report: \n{}", writer.toString()); } catch (Exception e) { // ignore exception and print request body plain log.warn("CSP-Report: {}", cspReportString); } } else { status = HttpStatus.NOT_FOUND; } return new ResponseEntity<>(status); } }
4,769
0.689033
0.687146
124
37.459679
26.698858
100
false
false
0
0
0
0
0
0
0.620968
false
false
10
5e7f74c436ce1b5b5a72faa5b6143ddaae64362a
22,342,419,919,149
45037bd557db24dbc77a243bbebc0cc6860abfdc
/src/Numbers.java
f51ff3385728e80b917e4010d24ea2019adc620f
[]
no_license
Damaan/Numbers
https://github.com/Damaan/Numbers
2628b11083dc9c05964302e6cb0b76a89f2b3347
fe02f4872935c124d47a265b4cb1274730ec7c30
refs/heads/master
2020-03-20T03:00:34.543000
2018-06-12T21:51:12
2018-06-12T21:51:12
137,131,685
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Numbers { //Translate a number to its equivalent in letters. public static String say(long n) { //Here we have the special numbers stored, that is, the ones that are not repeated. switch ((int) n){ case 0: return "Zero"; case 1: return "One"; case 2: return "Two"; case 3: return "Three"; case 4: return "Four"; case 5: return "Five"; case 6: return "Six"; case 7: return "Seven"; case 8: return "Eight"; case 9: return "Nine"; case 10: return "Ten"; case 11: return "Eleven"; case 12: return "Twelve"; case 13: return "Thirteen"; case 14: return "Fourteen"; case 15: return "Fifteen"; case 16: return "Sixteen"; case 17: return "Seventeen"; case 18: return "Eighteen"; case 19: return "Nineteen"; } //Transform the long variable into a string to be able to calculate its length. String strLong = Long.toString(n); long larg = strLong.length(); //Here we define which function should return the number solved depending on the length of the number. //This function will be called from the rest of functions to resolve the rest of the number, used in this methodology as we will see below. if (n > 19 && larg == 2) { return tens(n); } else if (larg == 3) { return hundreds(n); } else if (larg == 4 || larg == 5){ return thousands(n); }else if (larg == 6) { return huntho(n); } else if (larg == 7 || larg == 8 || larg == 9){ return million(n); } else if (larg == 10 || larg == 11 || larg == 12){ return billion(n); } else if (larg == 13 || larg == 14 || larg == 15){ return trillion(n); } else if (larg == 16 || larg == 17 || larg == 18){ return quadrillion(n); }else if (larg == 19 || larg == 20 || larg == 21){ return quintillion(n); }else { return "No pot ser"; } } static String decenas(long x){ //Here we have the numbers from 20 to 90 stored of ten in ten. switch ((int) x){ case 2: return "Twenty"; case 3: return "Thirty"; case 4: return "Forty"; case 5: return "Fifty"; case 6: return "Sixty"; case 7: return "Seventy"; case 8: return "Eighty"; case 9: return "Ninety"; } return "Número invalid"; } static String tens(long n){ // transforms the numbers from 20 to 99. //Discover the tens long q = n /10; //Discover the units long rest = n % 10; //check if the number is finished in 0. if ( rest == 0) { return decenas(q); } //In case the number does not end at 0, the function will return tens and units concatenated. else { return decenas(q) + "-" + say(rest).toLowerCase(); } } static String hundreds(long n){ //Transforms the numbers from 100 to 999 //Same methodology to decompose the number. long q = n /100; long rest = n % 100; //Solve the exact hundreds(100-900) if (rest == 0) { return say(q) + " hundred"; } else { //In this case and in the remainder of cases the rest of the division will be sent to the function "say" which will be responsible for returning the necessary number. return say(q) +" hundred and " +say(rest).toLowerCase() ; } } static String thousands(long n){ //Transforms the numbers from 1000 to 99999 //Same methodology to decompose the number. long q = n / 1000; long rest = n % 1000; //Same methodology as with the hundreds changing the word "hundred" for the "thousand" one. if (rest == 0) { return say(q) + " thousand"; } else{ return say(q) + " thousand " +say(rest).toLowerCase(); } } static String huntho(long n) { //Transforms the numbers from 100.000 to 999.999 long q = n / 100000; long rest = n % 100000; long q2 = n / 1000; long rest2 = rest % 1000; //Same methodology as with the hundreds changing the word "hundred" for the "hundred thousand" or "thousand" one. if (rest == 0) { return say(q) + " hundred thousand"; } else { return say(q2) + " thousand " + say(rest2).toLowerCase(); } } static String million(long n) { //Transforms the numbers from 1.000.000 to 999.999.999 long q = n / 1000000; long rest = n % 1000000; //Same methodology as with the hundreds changing the word "hundred" for the "million" one. if (rest == 0) { return say(q) + " million"; } else { return say(q) + " million " + say(rest).toLowerCase(); } } static String billion(long n){ //Transforms the numbers from 1.000.000.000 to 999.999.999.999 long q = n / 1000000000; long rest = n % 1000000000; //Same methodology as with the hundreds changing the word "hundred" for the "billion" one. if (rest == 0) { return say(q) + " billion"; } else { return say(q) + " billion " + say(rest).toLowerCase(); } } static String trillion(long n) { //Transforms the numbers from 1.000.000.000.000 to 999.999.999.999.999 long q = n / 1_000_000_000_000L; long rest = n % 1_000_000_000_000L; //Same methodology as with the hundreds changing the word "hundred" for the "trillion" one. if (rest == 0) { return say(q) + " trillion"; } else { return say(q) + " trillion " + say(rest).toLowerCase(); } } static String quadrillion(long n) { //Transforms the numbers from 1.000.000.000.000.000 to 999.999.999.999.999.999 long q = n / 1_000_000_000_000_000L; long rest = n % 1_000_000_000_000_000L; //Same methodology as with the hundreds changing the word "hundred" for the "quadrillion" one. if (rest == 0) { return say(q) + " quadrillion"; } else { return say(q) + " quadrillion " + say(rest).toLowerCase(); } } static String quintillion (long n) { //Transforms the numbers from 1.000.000.000.000.000.000 to 999.999.999.999.999.999.999 long q = n / 1_000_000_000_000_000_000L; long rest = n % 1_000_000_000_000_000_000L; //Same methodology as with the hundreds changing the word "hundred" for the "quintillion" one. if (rest == 0) { return say(q) + " quintillion"; } else { return say(q) +" quintillion " + say(rest).toLowerCase(); } } //Transform a number written in letters to one written in digits public static long words(String s) { //we will receive a string which we'll store in an array of strings separated by spaces. String[] paraules = s.split(" "); //Here we declare the variable cont which will be what the program returns long cont = 0; //Here we identify and translate the numbers from 0 to 99 if (paraules.length == 1 & s.contains("-")){ return DToW(s); } else if (paraules.length == 1 & !s.contains("-")){ cont = cont + db(paraules[0]); //Here we identify the rest of the numbers up to the hundreds of quintillion. } else { if (s.contains("quintillion") & paraules[1].contains("hundred")){ return HQTToW(s); } else if (s.contains("quintillion")){ return QTToW(s); } else if (s.contains("quadrillion") & paraules[1].contains("hundred")){ return HQToW(s); } else if (s.contains("quadrillion")){ return QToW(s); } else if (s.contains("trillion") & paraules[1].contains("hundred")){ return HTRToW(s); } else if (s.contains("trillion")){ return TRToW(s); } else if (s.contains("billion") & paraules[1].contains("hundred")) { return HBToW(s); } else if (s.contains("billion")) { return BToW(s); } else if (s.contains("million") & paraules[1].contains("hundred")) { return HMToW(s); } else if (s.contains("million")) { return MToW(s); } else if (s.contains("hundred thousand") || s.contains("thousand") & paraules[1].contains("hundred")) { return HTToW(s); } else if (s.contains("thousand")) { return TToW(s); } else if (s.contains("hundred")) { return HToW(s); } } return cont; } static long db (String s){ //Here we have the special numbers stored, that is, the ones that are not repeated, and the numbers from 20 to 90 stored of ten in ten. switch (s) { case "zero": return(0); case "one": return(1); case "two": return(2); case "three": return(3); case "four": return(4); case "five": return(5); case "six": return(6); case "seven": return(7); case "eight": return(8); case "nine": return(9); case "ten": return(10); case "eleven": return(11); case "twelve": return(12); case "thirteen": return(13); case "fourteen": return(14); case "fifteen": return(15); case "sixteen": return(16); case "seventeen":return(17); case "eighteen": return(18); case "nineteen": return(19); case "twenty": return(20); case "thirty": return(30); case "forty": return(40); case "fifty": return(50); case "sixty": return(60); case "seventy": return(70); case "eighty": return(80); case "ninety": return(90); } return 0; } static long DToW (String s){ //Solve the numbers from 20 to 99 but only the ones with a hyphens on it. //in this case, as the string that we pass has a hyphens, we separate the string by hyphens to process it. long cont = 0; //Then we just have to request to the function sb the values from each word and add it. String[] s2 = s.split("-"); cont = cont + db(s2[0]); cont = cont + db(s2[1]); return cont; } static long HToW (String s) { //Solve the numbers from 100 to 999. //Here we divide the string by spaces to be able to process it and store those parts on a array. long cont = 0; String[] paraules = s.split(" "); //Solve the exact numbers(100,200...). cont = cont + db(paraules[0]); cont = cont * 100; //If the number is not exact, add the result of the rest. if (paraules.length == 4) { cont = cont + words(paraules[3]); } return cont; } static long TToW (String s) { //Solve the numbers from 1000 to 99999. //Same procedure and reason as the case of the hundreds. long cont = 0; String[] paraules = s.split(" "); //Resolve the exact thousands(1000,2000...). if (paraules.length == 2){ cont = cont + words(paraules[0].toLowerCase()); cont = cont * 1000; //Solve the thousands with a rest } else { //Here we calculate the equivalent in numbers form the 2 first words. cont = cont + words(paraules[0].toLowerCase()); cont = cont * 1000; //Transforms the part of the array not used to build a shorter string to process. StringBuilder sb = new StringBuilder(); for (int i = 2; i < paraules.length; i++) { sb.append(paraules[i]); sb.append(" "); } //Once we have the string shortened we send it to the global purpose function, which will be responsible for calculating its equivalent, this methodology will be repeated in every function. String ns = sb.toString(); cont = cont + words(ns); } return cont; } static long HTToW (String s){ //Solve the numbers from 100.000 to 999.999. long cont = 0; //Same procedure and reason as the case of the hundreds. String[] paraules = s.split(" "); //Here we solve the exact hundred thousands(100.000, 200.000...). if (paraules.length == 3) { cont = cont + words(paraules[0].toLowerCase()); cont = cont * 100000; //Here we solve the hundred thousand with some kind of rest. } else { cont = cont + words(paraules[0].toLowerCase()); cont = cont * 100000; //Here we create again a new string shortened from the first,not counting the used parts. StringBuilder sb = new StringBuilder(); for (int i = 3; i < paraules.length; i++) { sb.append(paraules[i]); sb.append(" "); } //Same procedure and reason as in the TToW function String ns = sb.toString(); cont = cont + words(ns); } return cont; } //The next 2 functions solve the numbers from 1.000.000 to 999.999.999. static long MToW(String s) { long cont = 0; String[] paraules = s.split(" "); //Solve the exact millions. if (paraules.length == 2) { cont = cont + words(paraules[0].toLowerCase()); cont = cont * 1000000; //Solve the millions with a rest. } else { cont = cont + words(paraules[0].toLowerCase()); cont = cont * 1000000; //Solve the millions WITHOUT a hundred thousand part if (paraules[2].contains("and")){ //We shortened the string again to process it. StringBuilder sb = new StringBuilder(); for (int i = 3; i < paraules.length; i++) { sb.append(paraules[i]); sb.append(" "); } String ns = sb.toString(); cont = cont + words(ns); //Solve the millions WITH a hundred thousand part. }else { //We shortened the string again to process it,the difference with the one above is the number of words taken. StringBuilder sb = new StringBuilder(); for (int i = 2; i < paraules.length; i++) { sb.append(paraules[i]); sb.append(" "); } String ns = sb.toString(); cont = cont + words(ns); } } return cont; } static long HMToW(String s) { long cont = 0; String[] paraules = s.split(" "); //Solve the exact hundred of millions. if (s.contains("hundred million")) { cont = cont + words(paraules[0]); cont = cont * 100_000_000; //Solve the hundreds of millions with a rest. } else { //Here we create a string containing only the hundred part from the hundred million, and we multiply it by a million to obtain the hundred millions StringBuilder sb = new StringBuilder(); for (int i = 0; i < 4; i++) { sb.append(paraules[i]); sb.append(" "); } String ns = sb.toString(); cont = cont + words(ns.toLowerCase()); cont = cont * 1_000_000; //Here we create a string with the not processed part from the original string to process it and add it to the return value. StringBuilder sb2 = new StringBuilder(); for (int i = 5; i < paraules.length; i++) { sb2.append(paraules[i]); sb2.append(" "); } String ns2 = sb2.toString(); cont = cont + words(ns2); } return cont; } //From this point on, the procedure is exactly the same as the one showed on the million and hundred millions, varying only in the number to process. //The next 2 functions solve the numbers from 1.000.000.000 to 999.999.999.999 static long BToW(String s){ //Same procedure than the showed in the millions, but this time we don't need to pay attention to the word "and". long cont = 0; String[] paraules = s.split(" "); if (paraules.length == 2) { cont = cont + words(paraules[0].toLowerCase()); cont = cont * 1_000_000_000; } else { cont = cont + words(paraules[0].toLowerCase()); cont = cont * 1_000_000_000; StringBuilder sb = new StringBuilder(); for (int i = 2; i < paraules.length; i++) { sb.append(paraules[i]); sb.append(" "); } String ns = sb.toString(); cont = cont + words(ns); } return cont; } static long HBToW(String s){ //Same procedure than the ones showed on the function "HMToW" changing the number that we use to multiply. long cont = 0; String[] paraules = s.split(" "); if (s.contains("hundred billion")) { cont = cont + words(paraules[0]); cont = cont * 100_000_000_000L; } else { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 4; i++) { sb.append(paraules[i]); sb.append(" "); } String ns = sb.toString(); cont = cont + words(ns.toLowerCase()); cont = cont * 1_000_000_000L; StringBuilder sb2 = new StringBuilder(); for (int i = 5; i < paraules.length; i++) { sb2.append(paraules[i]); sb2.append(" "); } String ns2 = sb2.toString(); cont = cont + words(ns2); } return cont; } //The next 2 functions solve the numbers from 1.000.000.000.000 to 999.999.999.999.999 static long TRToW(String s){ //Same procedure than the one showed on the function "BToW" changing the number that we use to multiply. long cont = 0; String[] paraules = s.split(" "); if (paraules.length == 2) { cont = cont + words(paraules[0].toLowerCase()); cont = cont * 1_000_000_000_000L; } else { cont = cont + words(paraules[0].toLowerCase()); cont = cont * 1_000_000_000_000L; StringBuilder sb = new StringBuilder(); for (int i = 2; i < paraules.length; i++) { sb.append(paraules[i].toLowerCase()); sb.append(" "); } String ns = sb.toString(); cont = cont + words(ns.toLowerCase()); } return cont; } static long HTRToW(String s){ //Same procedure than the ones showed on the function "HBToW" changing the number that we use to multiply. long cont = 0; String[] paraules = s.split(" "); if (s.contains("hundred trillion")) { cont = cont + words(paraules[0]); cont = cont * 100_000_000_000_000L; } else { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 4; i++) { sb.append(paraules[i].toLowerCase()); sb.append(" "); } String ns = sb.toString(); cont = cont + words(ns.toLowerCase()); cont = cont * 1_000_000_000_000L; StringBuilder sb2 = new StringBuilder(); for (int i = 5; i < paraules.length; i++) { sb2.append(paraules[i].toLowerCase()); sb2.append(" "); } String ns2 = sb2.toString(); cont = cont + words(ns2.toLowerCase()); } return cont; } //The next 2 functions solve the numbers from 1.000.000.000.000.000 to 999.999.999.999.999.999 static long QToW(String s){ //Same procedure than the one showed on the function "BToW" changing the number that we use to multiply. long cont = 0; String[] paraules = s.split(" "); if (paraules.length == 2) { cont = cont + words(paraules[0].toLowerCase()); cont = cont * 1_000_000_000_000_000L; } else { cont = cont + words(paraules[0].toLowerCase()); cont = cont * 1_000_000_000_000_000L; StringBuilder sb = new StringBuilder(); for (int i = 2; i < paraules.length; i++) { sb.append(paraules[i].toLowerCase()); sb.append(" "); } String ns = sb.toString(); cont = cont + words(ns.toLowerCase()); } return cont; } static long HQToW(String s){ //Same procedure than the ones showed on the function "HBToW" changing the number that we use to multiply. long cont = 0; String[] paraules = s.split(" "); if (s.contains("hundred quadrillion")) { cont = cont + words(paraules[0]); cont = cont * 100_000_000_000_000_000L; } else { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 4; i++) { sb.append(paraules[i].toLowerCase()); sb.append(" "); } String ns = sb.toString(); cont = cont + words(ns.toLowerCase()); cont = cont * 1_000_000_000_000_000L; StringBuilder sb2 = new StringBuilder(); for (int i = 5; i < paraules.length; i++) { sb2.append(paraules[i].toLowerCase()); sb2.append(" "); } String ns2 = sb2.toString(); cont = cont + words(ns2.toLowerCase()); } return cont; } //The next 2 functions solve the numbers from 1.000.000.000.000.000.000 to 999.999.999.999.999.999.999 static long QTToW(String s){ //Same procedure than the one showed on the function "BToW" changing the number that we use to multiply. long cont = 0; String[] paraules = s.split(" "); if (paraules.length == 2) { cont = cont + words(paraules[0].toLowerCase()); cont = cont * 1_000_000_000_000_000_000L; } else { cont = cont + words(paraules[0].toLowerCase()); cont = cont * 1_000_000_000_000_000_000L; StringBuilder sb = new StringBuilder(); for (int i = 2; i < paraules.length; i++) { sb.append(paraules[i].toLowerCase()); sb.append(" "); } String ns = sb.toString(); cont = cont + words(ns.toLowerCase()); } return cont; } static long HQTToW(String s){ //Same procedure than the ones showed on the function "HBToW" changing the number that we use to multiply. long cont = 0; String[] paraules = s.split(" "); if (s.contains("hundred quintillion")) { cont = cont + words(paraules[0]); cont = cont * 1_000_000_000_000_000_000L; } else { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 4; i++) { sb.append(paraules[i].toLowerCase()); sb.append(" "); } String ns = sb.toString(); cont = cont + words(ns.toLowerCase()); cont = cont * 1_000_000_000_000_000_000L; StringBuilder sb2 = new StringBuilder(); for (int i = 5; i < paraules.length; i++) { sb2.append(paraules[i].toLowerCase()); sb2.append(" "); } String ns2 = sb2.toString(); cont = cont + words(ns2.toLowerCase()); } return cont; } }
UTF-8
Java
24,699
java
Numbers.java
Java
[]
null
[]
public class Numbers { //Translate a number to its equivalent in letters. public static String say(long n) { //Here we have the special numbers stored, that is, the ones that are not repeated. switch ((int) n){ case 0: return "Zero"; case 1: return "One"; case 2: return "Two"; case 3: return "Three"; case 4: return "Four"; case 5: return "Five"; case 6: return "Six"; case 7: return "Seven"; case 8: return "Eight"; case 9: return "Nine"; case 10: return "Ten"; case 11: return "Eleven"; case 12: return "Twelve"; case 13: return "Thirteen"; case 14: return "Fourteen"; case 15: return "Fifteen"; case 16: return "Sixteen"; case 17: return "Seventeen"; case 18: return "Eighteen"; case 19: return "Nineteen"; } //Transform the long variable into a string to be able to calculate its length. String strLong = Long.toString(n); long larg = strLong.length(); //Here we define which function should return the number solved depending on the length of the number. //This function will be called from the rest of functions to resolve the rest of the number, used in this methodology as we will see below. if (n > 19 && larg == 2) { return tens(n); } else if (larg == 3) { return hundreds(n); } else if (larg == 4 || larg == 5){ return thousands(n); }else if (larg == 6) { return huntho(n); } else if (larg == 7 || larg == 8 || larg == 9){ return million(n); } else if (larg == 10 || larg == 11 || larg == 12){ return billion(n); } else if (larg == 13 || larg == 14 || larg == 15){ return trillion(n); } else if (larg == 16 || larg == 17 || larg == 18){ return quadrillion(n); }else if (larg == 19 || larg == 20 || larg == 21){ return quintillion(n); }else { return "No pot ser"; } } static String decenas(long x){ //Here we have the numbers from 20 to 90 stored of ten in ten. switch ((int) x){ case 2: return "Twenty"; case 3: return "Thirty"; case 4: return "Forty"; case 5: return "Fifty"; case 6: return "Sixty"; case 7: return "Seventy"; case 8: return "Eighty"; case 9: return "Ninety"; } return "Número invalid"; } static String tens(long n){ // transforms the numbers from 20 to 99. //Discover the tens long q = n /10; //Discover the units long rest = n % 10; //check if the number is finished in 0. if ( rest == 0) { return decenas(q); } //In case the number does not end at 0, the function will return tens and units concatenated. else { return decenas(q) + "-" + say(rest).toLowerCase(); } } static String hundreds(long n){ //Transforms the numbers from 100 to 999 //Same methodology to decompose the number. long q = n /100; long rest = n % 100; //Solve the exact hundreds(100-900) if (rest == 0) { return say(q) + " hundred"; } else { //In this case and in the remainder of cases the rest of the division will be sent to the function "say" which will be responsible for returning the necessary number. return say(q) +" hundred and " +say(rest).toLowerCase() ; } } static String thousands(long n){ //Transforms the numbers from 1000 to 99999 //Same methodology to decompose the number. long q = n / 1000; long rest = n % 1000; //Same methodology as with the hundreds changing the word "hundred" for the "thousand" one. if (rest == 0) { return say(q) + " thousand"; } else{ return say(q) + " thousand " +say(rest).toLowerCase(); } } static String huntho(long n) { //Transforms the numbers from 100.000 to 999.999 long q = n / 100000; long rest = n % 100000; long q2 = n / 1000; long rest2 = rest % 1000; //Same methodology as with the hundreds changing the word "hundred" for the "hundred thousand" or "thousand" one. if (rest == 0) { return say(q) + " hundred thousand"; } else { return say(q2) + " thousand " + say(rest2).toLowerCase(); } } static String million(long n) { //Transforms the numbers from 1.000.000 to 999.999.999 long q = n / 1000000; long rest = n % 1000000; //Same methodology as with the hundreds changing the word "hundred" for the "million" one. if (rest == 0) { return say(q) + " million"; } else { return say(q) + " million " + say(rest).toLowerCase(); } } static String billion(long n){ //Transforms the numbers from 1.000.000.000 to 999.999.999.999 long q = n / 1000000000; long rest = n % 1000000000; //Same methodology as with the hundreds changing the word "hundred" for the "billion" one. if (rest == 0) { return say(q) + " billion"; } else { return say(q) + " billion " + say(rest).toLowerCase(); } } static String trillion(long n) { //Transforms the numbers from 1.000.000.000.000 to 999.999.999.999.999 long q = n / 1_000_000_000_000L; long rest = n % 1_000_000_000_000L; //Same methodology as with the hundreds changing the word "hundred" for the "trillion" one. if (rest == 0) { return say(q) + " trillion"; } else { return say(q) + " trillion " + say(rest).toLowerCase(); } } static String quadrillion(long n) { //Transforms the numbers from 1.000.000.000.000.000 to 999.999.999.999.999.999 long q = n / 1_000_000_000_000_000L; long rest = n % 1_000_000_000_000_000L; //Same methodology as with the hundreds changing the word "hundred" for the "quadrillion" one. if (rest == 0) { return say(q) + " quadrillion"; } else { return say(q) + " quadrillion " + say(rest).toLowerCase(); } } static String quintillion (long n) { //Transforms the numbers from 1.000.000.000.000.000.000 to 999.999.999.999.999.999.999 long q = n / 1_000_000_000_000_000_000L; long rest = n % 1_000_000_000_000_000_000L; //Same methodology as with the hundreds changing the word "hundred" for the "quintillion" one. if (rest == 0) { return say(q) + " quintillion"; } else { return say(q) +" quintillion " + say(rest).toLowerCase(); } } //Transform a number written in letters to one written in digits public static long words(String s) { //we will receive a string which we'll store in an array of strings separated by spaces. String[] paraules = s.split(" "); //Here we declare the variable cont which will be what the program returns long cont = 0; //Here we identify and translate the numbers from 0 to 99 if (paraules.length == 1 & s.contains("-")){ return DToW(s); } else if (paraules.length == 1 & !s.contains("-")){ cont = cont + db(paraules[0]); //Here we identify the rest of the numbers up to the hundreds of quintillion. } else { if (s.contains("quintillion") & paraules[1].contains("hundred")){ return HQTToW(s); } else if (s.contains("quintillion")){ return QTToW(s); } else if (s.contains("quadrillion") & paraules[1].contains("hundred")){ return HQToW(s); } else if (s.contains("quadrillion")){ return QToW(s); } else if (s.contains("trillion") & paraules[1].contains("hundred")){ return HTRToW(s); } else if (s.contains("trillion")){ return TRToW(s); } else if (s.contains("billion") & paraules[1].contains("hundred")) { return HBToW(s); } else if (s.contains("billion")) { return BToW(s); } else if (s.contains("million") & paraules[1].contains("hundred")) { return HMToW(s); } else if (s.contains("million")) { return MToW(s); } else if (s.contains("hundred thousand") || s.contains("thousand") & paraules[1].contains("hundred")) { return HTToW(s); } else if (s.contains("thousand")) { return TToW(s); } else if (s.contains("hundred")) { return HToW(s); } } return cont; } static long db (String s){ //Here we have the special numbers stored, that is, the ones that are not repeated, and the numbers from 20 to 90 stored of ten in ten. switch (s) { case "zero": return(0); case "one": return(1); case "two": return(2); case "three": return(3); case "four": return(4); case "five": return(5); case "six": return(6); case "seven": return(7); case "eight": return(8); case "nine": return(9); case "ten": return(10); case "eleven": return(11); case "twelve": return(12); case "thirteen": return(13); case "fourteen": return(14); case "fifteen": return(15); case "sixteen": return(16); case "seventeen":return(17); case "eighteen": return(18); case "nineteen": return(19); case "twenty": return(20); case "thirty": return(30); case "forty": return(40); case "fifty": return(50); case "sixty": return(60); case "seventy": return(70); case "eighty": return(80); case "ninety": return(90); } return 0; } static long DToW (String s){ //Solve the numbers from 20 to 99 but only the ones with a hyphens on it. //in this case, as the string that we pass has a hyphens, we separate the string by hyphens to process it. long cont = 0; //Then we just have to request to the function sb the values from each word and add it. String[] s2 = s.split("-"); cont = cont + db(s2[0]); cont = cont + db(s2[1]); return cont; } static long HToW (String s) { //Solve the numbers from 100 to 999. //Here we divide the string by spaces to be able to process it and store those parts on a array. long cont = 0; String[] paraules = s.split(" "); //Solve the exact numbers(100,200...). cont = cont + db(paraules[0]); cont = cont * 100; //If the number is not exact, add the result of the rest. if (paraules.length == 4) { cont = cont + words(paraules[3]); } return cont; } static long TToW (String s) { //Solve the numbers from 1000 to 99999. //Same procedure and reason as the case of the hundreds. long cont = 0; String[] paraules = s.split(" "); //Resolve the exact thousands(1000,2000...). if (paraules.length == 2){ cont = cont + words(paraules[0].toLowerCase()); cont = cont * 1000; //Solve the thousands with a rest } else { //Here we calculate the equivalent in numbers form the 2 first words. cont = cont + words(paraules[0].toLowerCase()); cont = cont * 1000; //Transforms the part of the array not used to build a shorter string to process. StringBuilder sb = new StringBuilder(); for (int i = 2; i < paraules.length; i++) { sb.append(paraules[i]); sb.append(" "); } //Once we have the string shortened we send it to the global purpose function, which will be responsible for calculating its equivalent, this methodology will be repeated in every function. String ns = sb.toString(); cont = cont + words(ns); } return cont; } static long HTToW (String s){ //Solve the numbers from 100.000 to 999.999. long cont = 0; //Same procedure and reason as the case of the hundreds. String[] paraules = s.split(" "); //Here we solve the exact hundred thousands(100.000, 200.000...). if (paraules.length == 3) { cont = cont + words(paraules[0].toLowerCase()); cont = cont * 100000; //Here we solve the hundred thousand with some kind of rest. } else { cont = cont + words(paraules[0].toLowerCase()); cont = cont * 100000; //Here we create again a new string shortened from the first,not counting the used parts. StringBuilder sb = new StringBuilder(); for (int i = 3; i < paraules.length; i++) { sb.append(paraules[i]); sb.append(" "); } //Same procedure and reason as in the TToW function String ns = sb.toString(); cont = cont + words(ns); } return cont; } //The next 2 functions solve the numbers from 1.000.000 to 999.999.999. static long MToW(String s) { long cont = 0; String[] paraules = s.split(" "); //Solve the exact millions. if (paraules.length == 2) { cont = cont + words(paraules[0].toLowerCase()); cont = cont * 1000000; //Solve the millions with a rest. } else { cont = cont + words(paraules[0].toLowerCase()); cont = cont * 1000000; //Solve the millions WITHOUT a hundred thousand part if (paraules[2].contains("and")){ //We shortened the string again to process it. StringBuilder sb = new StringBuilder(); for (int i = 3; i < paraules.length; i++) { sb.append(paraules[i]); sb.append(" "); } String ns = sb.toString(); cont = cont + words(ns); //Solve the millions WITH a hundred thousand part. }else { //We shortened the string again to process it,the difference with the one above is the number of words taken. StringBuilder sb = new StringBuilder(); for (int i = 2; i < paraules.length; i++) { sb.append(paraules[i]); sb.append(" "); } String ns = sb.toString(); cont = cont + words(ns); } } return cont; } static long HMToW(String s) { long cont = 0; String[] paraules = s.split(" "); //Solve the exact hundred of millions. if (s.contains("hundred million")) { cont = cont + words(paraules[0]); cont = cont * 100_000_000; //Solve the hundreds of millions with a rest. } else { //Here we create a string containing only the hundred part from the hundred million, and we multiply it by a million to obtain the hundred millions StringBuilder sb = new StringBuilder(); for (int i = 0; i < 4; i++) { sb.append(paraules[i]); sb.append(" "); } String ns = sb.toString(); cont = cont + words(ns.toLowerCase()); cont = cont * 1_000_000; //Here we create a string with the not processed part from the original string to process it and add it to the return value. StringBuilder sb2 = new StringBuilder(); for (int i = 5; i < paraules.length; i++) { sb2.append(paraules[i]); sb2.append(" "); } String ns2 = sb2.toString(); cont = cont + words(ns2); } return cont; } //From this point on, the procedure is exactly the same as the one showed on the million and hundred millions, varying only in the number to process. //The next 2 functions solve the numbers from 1.000.000.000 to 999.999.999.999 static long BToW(String s){ //Same procedure than the showed in the millions, but this time we don't need to pay attention to the word "and". long cont = 0; String[] paraules = s.split(" "); if (paraules.length == 2) { cont = cont + words(paraules[0].toLowerCase()); cont = cont * 1_000_000_000; } else { cont = cont + words(paraules[0].toLowerCase()); cont = cont * 1_000_000_000; StringBuilder sb = new StringBuilder(); for (int i = 2; i < paraules.length; i++) { sb.append(paraules[i]); sb.append(" "); } String ns = sb.toString(); cont = cont + words(ns); } return cont; } static long HBToW(String s){ //Same procedure than the ones showed on the function "HMToW" changing the number that we use to multiply. long cont = 0; String[] paraules = s.split(" "); if (s.contains("hundred billion")) { cont = cont + words(paraules[0]); cont = cont * 100_000_000_000L; } else { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 4; i++) { sb.append(paraules[i]); sb.append(" "); } String ns = sb.toString(); cont = cont + words(ns.toLowerCase()); cont = cont * 1_000_000_000L; StringBuilder sb2 = new StringBuilder(); for (int i = 5; i < paraules.length; i++) { sb2.append(paraules[i]); sb2.append(" "); } String ns2 = sb2.toString(); cont = cont + words(ns2); } return cont; } //The next 2 functions solve the numbers from 1.000.000.000.000 to 999.999.999.999.999 static long TRToW(String s){ //Same procedure than the one showed on the function "BToW" changing the number that we use to multiply. long cont = 0; String[] paraules = s.split(" "); if (paraules.length == 2) { cont = cont + words(paraules[0].toLowerCase()); cont = cont * 1_000_000_000_000L; } else { cont = cont + words(paraules[0].toLowerCase()); cont = cont * 1_000_000_000_000L; StringBuilder sb = new StringBuilder(); for (int i = 2; i < paraules.length; i++) { sb.append(paraules[i].toLowerCase()); sb.append(" "); } String ns = sb.toString(); cont = cont + words(ns.toLowerCase()); } return cont; } static long HTRToW(String s){ //Same procedure than the ones showed on the function "HBToW" changing the number that we use to multiply. long cont = 0; String[] paraules = s.split(" "); if (s.contains("hundred trillion")) { cont = cont + words(paraules[0]); cont = cont * 100_000_000_000_000L; } else { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 4; i++) { sb.append(paraules[i].toLowerCase()); sb.append(" "); } String ns = sb.toString(); cont = cont + words(ns.toLowerCase()); cont = cont * 1_000_000_000_000L; StringBuilder sb2 = new StringBuilder(); for (int i = 5; i < paraules.length; i++) { sb2.append(paraules[i].toLowerCase()); sb2.append(" "); } String ns2 = sb2.toString(); cont = cont + words(ns2.toLowerCase()); } return cont; } //The next 2 functions solve the numbers from 1.000.000.000.000.000 to 999.999.999.999.999.999 static long QToW(String s){ //Same procedure than the one showed on the function "BToW" changing the number that we use to multiply. long cont = 0; String[] paraules = s.split(" "); if (paraules.length == 2) { cont = cont + words(paraules[0].toLowerCase()); cont = cont * 1_000_000_000_000_000L; } else { cont = cont + words(paraules[0].toLowerCase()); cont = cont * 1_000_000_000_000_000L; StringBuilder sb = new StringBuilder(); for (int i = 2; i < paraules.length; i++) { sb.append(paraules[i].toLowerCase()); sb.append(" "); } String ns = sb.toString(); cont = cont + words(ns.toLowerCase()); } return cont; } static long HQToW(String s){ //Same procedure than the ones showed on the function "HBToW" changing the number that we use to multiply. long cont = 0; String[] paraules = s.split(" "); if (s.contains("hundred quadrillion")) { cont = cont + words(paraules[0]); cont = cont * 100_000_000_000_000_000L; } else { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 4; i++) { sb.append(paraules[i].toLowerCase()); sb.append(" "); } String ns = sb.toString(); cont = cont + words(ns.toLowerCase()); cont = cont * 1_000_000_000_000_000L; StringBuilder sb2 = new StringBuilder(); for (int i = 5; i < paraules.length; i++) { sb2.append(paraules[i].toLowerCase()); sb2.append(" "); } String ns2 = sb2.toString(); cont = cont + words(ns2.toLowerCase()); } return cont; } //The next 2 functions solve the numbers from 1.000.000.000.000.000.000 to 999.999.999.999.999.999.999 static long QTToW(String s){ //Same procedure than the one showed on the function "BToW" changing the number that we use to multiply. long cont = 0; String[] paraules = s.split(" "); if (paraules.length == 2) { cont = cont + words(paraules[0].toLowerCase()); cont = cont * 1_000_000_000_000_000_000L; } else { cont = cont + words(paraules[0].toLowerCase()); cont = cont * 1_000_000_000_000_000_000L; StringBuilder sb = new StringBuilder(); for (int i = 2; i < paraules.length; i++) { sb.append(paraules[i].toLowerCase()); sb.append(" "); } String ns = sb.toString(); cont = cont + words(ns.toLowerCase()); } return cont; } static long HQTToW(String s){ //Same procedure than the ones showed on the function "HBToW" changing the number that we use to multiply. long cont = 0; String[] paraules = s.split(" "); if (s.contains("hundred quintillion")) { cont = cont + words(paraules[0]); cont = cont * 1_000_000_000_000_000_000L; } else { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 4; i++) { sb.append(paraules[i].toLowerCase()); sb.append(" "); } String ns = sb.toString(); cont = cont + words(ns.toLowerCase()); cont = cont * 1_000_000_000_000_000_000L; StringBuilder sb2 = new StringBuilder(); for (int i = 5; i < paraules.length; i++) { sb2.append(paraules[i].toLowerCase()); sb2.append(" "); } String ns2 = sb2.toString(); cont = cont + words(ns2.toLowerCase()); } return cont; } }
24,699
0.515467
0.471091
706
33.984421
28.673626
201
false
false
0
0
0
0
0
0
0.548159
false
false
10
11c92657fe86dc1181254393ec3e0c5a4c64a3f5
14,611,478,771,148
be5ba74b98547bd1c5d900da0190084c34aba517
/Assignment8_Methods/Question13_waterTax.java
0c9ae7f3d25cd4fa13284636e2bd61d78273b19f
[]
no_license
letmetest1822-sami/JAVA_EU2_Assignments_Sami_K
https://github.com/letmetest1822-sami/JAVA_EU2_Assignments_Sami_K
70fd6962a8fdd78363923253499d348d19b6d643
0ffd10ade307b0da95ea9a10279d57497948655d
refs/heads/master
2020-11-30T22:05:17.195000
2020-04-24T22:08:06
2020-04-24T22:08:06
230,491,284
5
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package assignments.Assignment8_Methods; import java.util.Scanner; public class Question13_waterTax { public static void main(String[] args) { /* * This method calculates a water bill, the method gets a double and returns a double. * The more water you use the more it will cost you (as a fine for wasting water). for example: waterTax(50) returns 30 waterTax(55) returns 49.5 waterTax(101) returns 140.9 waterTax(151) returns 235.9 the regular calculation under 50 is bill = units * 0.60; above 50 is: bill = units * 0.90; above 100 the calculation is like above 50 but with a 50 as fine and above 150 it is the same as above 50 (units *0.90) but with a 100 fine added to the price. */ System.out.println(waterTax()); } public static double waterTax() { Scanner number = new Scanner (System.in); System.out.print("Please enter the unit spent : "); int units = number.nextInt(); double bill = 0; if (units<=50) { bill = units * 0.60; } else if (units>50 && units <=100) { bill = (units * 0.90); } else if (units>100 && units <=150) { bill = units * 0.90 + 50; }else if (units>150) { bill = units * 0.90 + 100; } return bill; } }
UTF-8
Java
1,288
java
Question13_waterTax.java
Java
[]
null
[]
package assignments.Assignment8_Methods; import java.util.Scanner; public class Question13_waterTax { public static void main(String[] args) { /* * This method calculates a water bill, the method gets a double and returns a double. * The more water you use the more it will cost you (as a fine for wasting water). for example: waterTax(50) returns 30 waterTax(55) returns 49.5 waterTax(101) returns 140.9 waterTax(151) returns 235.9 the regular calculation under 50 is bill = units * 0.60; above 50 is: bill = units * 0.90; above 100 the calculation is like above 50 but with a 50 as fine and above 150 it is the same as above 50 (units *0.90) but with a 100 fine added to the price. */ System.out.println(waterTax()); } public static double waterTax() { Scanner number = new Scanner (System.in); System.out.print("Please enter the unit spent : "); int units = number.nextInt(); double bill = 0; if (units<=50) { bill = units * 0.60; } else if (units>50 && units <=100) { bill = (units * 0.90); } else if (units>100 && units <=150) { bill = units * 0.90 + 50; }else if (units>150) { bill = units * 0.90 + 100; } return bill; } }
1,288
0.619565
0.551242
64
18.125
21.932068
94
false
false
0
0
0
0
0
0
1.296875
false
false
10
67b4e250b86dd7f387662c1462eb2ace7ff7f6e5
17,626,545,821,213
6c25252f8f4fdbb7cd4b86b57e73ceef168c5976
/src/test/java/cn/edu/swpu/cins/house/test/DetailsTest.java
c336af61320105ff95b398e59e3265aae8debee8
[]
no_license
kbyyd24/cinsHouse
https://github.com/kbyyd24/cinsHouse
a48c64acf8200b5852ed7b24c10be4287be098a3
a32a45b0aec26dc903350f6146a8701a8f25db6b
refs/heads/master
2019-08-28T03:57:35.698000
2016-05-04T14:48:13
2016-05-04T14:48:13
58,059,407
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.edu.swpu.cins.house.test; import cn.edu.swpu.cins.house.service.BuildingDetailsService; import org.json.JSONObject; import org.junit.Test; /** * Created by gaoyx_melo on 2016/4/13. */ public class DetailsTest { @Test public void testgetDetails() { JSONObject obj = new BuildingDetailsService().getDetails("3211121118"); System.out.println(obj); } }
UTF-8
Java
392
java
DetailsTest.java
Java
[ { "context": "NObject;\nimport org.junit.Test;\n\n/**\n * Created by gaoyx_melo on 2016/4/13.\n */\npublic class DetailsTest {\n ", "end": 180, "score": 0.9996940493583679, "start": 170, "tag": "USERNAME", "value": "gaoyx_melo" } ]
null
[]
package cn.edu.swpu.cins.house.test; import cn.edu.swpu.cins.house.service.BuildingDetailsService; import org.json.JSONObject; import org.junit.Test; /** * Created by gaoyx_melo on 2016/4/13. */ public class DetailsTest { @Test public void testgetDetails() { JSONObject obj = new BuildingDetailsService().getDetails("3211121118"); System.out.println(obj); } }
392
0.706633
0.663265
16
23.5
22.444376
79
false
false
0
0
0
0
0
0
0.375
false
false
10
6430cd2bc2ff1b6033d0023bfcddf8845a934641
24,206,435,709,748
8e90e85ea146b8dc8ae2650c5f1788bf7248b8a6
/app/src/main/java/com/example/mac_204/test/data/ui/models/LocationUIModel.java
a8ce31555133d1fd8848d1cd3bca5c8d1a7e7e90
[]
no_license
Test12332111/test_gm
https://github.com/Test12332111/test_gm
9bc2f44faa6d7a5a35f136e56f482c8b72053980
199f9b04146dbdd10fa5b57fc9fd4d3288f49d66
refs/heads/master
2021-01-01T07:59:05.632000
2017-07-18T08:16:45
2017-07-18T08:16:45
97,569,244
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.mac_204.test.data.ui.models; import com.example.mac_204.test.data.remote.models.SightRestModel; import com.google.gson.annotations.SerializedName; import java.io.Serializable; import java.util.List; /** * Created by mac-204 on 7/13/17. */ public class LocationUIModel implements Serializable{ private String id; private String name; private String iconUrl; private String backgroundUrl; private double lat; private double lan; private List<SightUIModel> sights; private boolean isFavorite; public LocationUIModel(String id, String name, String iconUrl, String backgroundUrl, double lat, double lan, List<SightUIModel> sights) { this.id = id; this.name = name; this.iconUrl = iconUrl; this.backgroundUrl = backgroundUrl; this.lat = lat; this.lan = lan; this.sights = sights; } public String getName() { return name; } public String getIconUrl() { return iconUrl; } public String getBackgroundUrl() { return backgroundUrl; } public double getLat() { return lat; } public double getLan() { return lan; } public List<SightUIModel> getSights() { return sights; } public boolean isFavorite() { return isFavorite; } public void setFavorite(boolean favorite) { isFavorite = favorite; } public String getId() { return id; } }
UTF-8
Java
1,528
java
LocationUIModel.java
Java
[ { "context": "lizable;\nimport java.util.List;\n\n/**\n * Created by mac-204 on 7/13/17.\n */\n\npublic class LocationUIModel imp", "end": 247, "score": 0.9995803833007812, "start": 240, "tag": "USERNAME", "value": "mac-204" } ]
null
[]
package com.example.mac_204.test.data.ui.models; import com.example.mac_204.test.data.remote.models.SightRestModel; import com.google.gson.annotations.SerializedName; import java.io.Serializable; import java.util.List; /** * Created by mac-204 on 7/13/17. */ public class LocationUIModel implements Serializable{ private String id; private String name; private String iconUrl; private String backgroundUrl; private double lat; private double lan; private List<SightUIModel> sights; private boolean isFavorite; public LocationUIModel(String id, String name, String iconUrl, String backgroundUrl, double lat, double lan, List<SightUIModel> sights) { this.id = id; this.name = name; this.iconUrl = iconUrl; this.backgroundUrl = backgroundUrl; this.lat = lat; this.lan = lan; this.sights = sights; } public String getName() { return name; } public String getIconUrl() { return iconUrl; } public String getBackgroundUrl() { return backgroundUrl; } public double getLat() { return lat; } public double getLan() { return lan; } public List<SightUIModel> getSights() { return sights; } public boolean isFavorite() { return isFavorite; } public void setFavorite(boolean favorite) { isFavorite = favorite; } public String getId() { return id; } }
1,528
0.625
0.615838
77
18.844156
19.568769
100
false
false
0
0
0
0
0
0
0.454545
false
false
10
127ebe8cbe0a383afaa0e44afbde4e76dff65d36
13,709,535,662,402
e4a7ab1aa1159c91dba20bbf6c73f406e6923468
/src/main/java/com/aomei/system/dao/ManufactureOrderDetailMapperImpl.java
1092159df3792258ec65dfcad14b0e6d51d2b217
[]
no_license
dingjianglei/AMManage
https://github.com/dingjianglei/AMManage
e7acb5ca1c1d07476fba93551d96b84573da7fe3
be6b77718932702fb2784b0a1b14cb3a52013132
refs/heads/master
2020-04-11T00:38:47.463000
2016-01-01T11:27:14
2016-01-01T11:27:14
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.aomei.system.dao; import com.aomei.dao.ManufactureOrderDetailMapper; import com.aomei.dao.impl.MBaseDaoImpl; import com.aomei.model.ManufactureOrderDetail; import org.springframework.stereotype.Repository; /** * Created by Administrator on 2015/12/5. */ @Repository("manufactureOrderDetailMapper") public class ManufactureOrderDetailMapperImpl extends MBaseDaoImpl<ManufactureOrderDetail> implements ManufactureOrderDetailMapper { public ManufactureOrderDetail selectByOrderId(Integer orderId) throws Exception{ Object obj=getSqlSession().selectOne(getClassName()+".selectByOrderId",orderId); if(obj==null){ return null; }else{ return (ManufactureOrderDetail)obj; } } }
UTF-8
Java
750
java
ManufactureOrderDetailMapperImpl.java
Java
[]
null
[]
package com.aomei.system.dao; import com.aomei.dao.ManufactureOrderDetailMapper; import com.aomei.dao.impl.MBaseDaoImpl; import com.aomei.model.ManufactureOrderDetail; import org.springframework.stereotype.Repository; /** * Created by Administrator on 2015/12/5. */ @Repository("manufactureOrderDetailMapper") public class ManufactureOrderDetailMapperImpl extends MBaseDaoImpl<ManufactureOrderDetail> implements ManufactureOrderDetailMapper { public ManufactureOrderDetail selectByOrderId(Integer orderId) throws Exception{ Object obj=getSqlSession().selectOne(getClassName()+".selectByOrderId",orderId); if(obj==null){ return null; }else{ return (ManufactureOrderDetail)obj; } } }
750
0.758667
0.749333
21
34.714287
33.392532
132
false
false
0
0
0
0
0
0
0.428571
false
false
10
07c0e7e42e4f84a2231977a4571ce5f54e9dbc1c
2,388,001,858,748
024bcb7901ce9d6bc9aef94a78f2038dabc74248
/src/main/java/com/villcore/game/tetris/model/Theme.java
3286cf9dbf4a47da4978d1e517d5dd68c14ebf1a
[]
no_license
villcore/tetris
https://github.com/villcore/tetris
fffb7ced280fd5d3f18b3e3d77279b960723627b
78ed701133e6f0d8bc483ff1e9925729c2eb9004
refs/heads/master
2023-08-05T10:11:34.940000
2021-09-15T14:05:26
2021-09-15T14:05:26
403,135,948
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.villcore.game.tetris.model; public class Theme { // 背景图片 // block背景图片 }
UTF-8
Java
110
java
Theme.java
Java
[]
null
[]
package com.villcore.game.tetris.model; public class Theme { // 背景图片 // block背景图片 }
110
0.659574
0.659574
7
12.428572
13.189359
39
false
false
0
0
0
0
0
0
0.142857
false
false
10
6487c27fcbb08be41fa5b95dcc3f99f487ff1a62
6,081,673,721,846
4d84fa9ba5867f9b17b0a637a822ae6556db2e7a
/app/src/main/java/com/example/flinstagram/models/Post.java
7211c6fe1b2592611bd769e91391a87ea1bd336f
[ "Apache-2.0" ]
permissive
kanbi18/Flinstagram
https://github.com/kanbi18/Flinstagram
4be3561bc77d515f11c4a0c35e17a8ac849fdfa7
c803660002c01fd75ecaf4d8ece6b88233d953e9
refs/heads/master
2023-01-03T08:25:07.978000
2020-10-31T23:48:36
2020-10-31T23:48:36
306,796,892
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.flinstagram.models; import android.util.Log; import com.parse.ParseClassName; import com.parse.ParseException; import com.parse.ParseFile; import com.parse.ParseObject; import com.parse.ParseUser; import com.parse.SaveCallback; import java.io.File; @ParseClassName("Post") public class Post extends ParseObject { public static final String KEY_USER = "user"; public static final String KEY_IMAGE = "image"; public static final String KEY_DESCRIPTION = "description"; public ParseUser getUser() { return getParseUser(KEY_USER); } public String getDescription() { return getString(KEY_DESCRIPTION); } public ParseFile getImage() { return getParseFile(KEY_IMAGE); } public void setDescription(String description) { put(KEY_DESCRIPTION, description); } public void setImage(ParseFile image) { put(KEY_IMAGE, image); } public void setUser(ParseUser user) { put(KEY_USER, user); } public void createObject(String user, String description, String image) { ParseObject entity = new ParseObject("Post"); entity.put("description", description); entity.put("image", new ParseFile("resume.txt", "My string content".getBytes())); entity.put("user", ParseUser.getCurrentUser()); // Saves the new object. // Notice that the SaveCallback is totally optional! entity.saveInBackground(new SaveCallback() { @Override public void done(ParseException e) { Log.e("Post", "Problem with saving post"); } }); } }
UTF-8
Java
1,653
java
Post.java
Java
[ { "context": "ject {\n public static final String KEY_USER = \"user\";\n public static final String KEY_IMAGE = \"ima", "end": 384, "score": 0.6155382990837097, "start": 380, "tag": "KEY", "value": "user" } ]
null
[]
package com.example.flinstagram.models; import android.util.Log; import com.parse.ParseClassName; import com.parse.ParseException; import com.parse.ParseFile; import com.parse.ParseObject; import com.parse.ParseUser; import com.parse.SaveCallback; import java.io.File; @ParseClassName("Post") public class Post extends ParseObject { public static final String KEY_USER = "user"; public static final String KEY_IMAGE = "image"; public static final String KEY_DESCRIPTION = "description"; public ParseUser getUser() { return getParseUser(KEY_USER); } public String getDescription() { return getString(KEY_DESCRIPTION); } public ParseFile getImage() { return getParseFile(KEY_IMAGE); } public void setDescription(String description) { put(KEY_DESCRIPTION, description); } public void setImage(ParseFile image) { put(KEY_IMAGE, image); } public void setUser(ParseUser user) { put(KEY_USER, user); } public void createObject(String user, String description, String image) { ParseObject entity = new ParseObject("Post"); entity.put("description", description); entity.put("image", new ParseFile("resume.txt", "My string content".getBytes())); entity.put("user", ParseUser.getCurrentUser()); // Saves the new object. // Notice that the SaveCallback is totally optional! entity.saveInBackground(new SaveCallback() { @Override public void done(ParseException e) { Log.e("Post", "Problem with saving post"); } }); } }
1,653
0.656987
0.656987
60
26.549999
22.393023
89
false
false
0
0
0
0
0
0
0.566667
false
false
10
328c13521331c45d133621fb49db79d8e5495d09
19,052,474,979,157
9deba9ea8c281af77aa86580d2c092497b01501c
/colink-core/src/main/java/com/ifinancesys/system/action/SysResponsibilityAction.java
2005412ea2d5060427b2509847031999aab3de35
[]
no_license
baihuili/colink
https://github.com/baihuili/colink
3650c1e20b129def3ea2a310120ad5a8e0b9b0ad
ea2130668866d023a29fcf1560bdafffcf1dea2d
refs/heads/master
2020-04-03T03:18:00.822000
2018-11-18T12:58:48
2018-11-18T12:58:48
154,981,727
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ifinancesys.system.action; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import com.ifinancesys.system.SystemConstant; import org.apache.log4j.Logger; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.ParentPackage; import org.apache.struts2.convention.annotation.Result; import org.springframework.beans.factory.annotation.Autowired; import com.ifinancesys.core.Constant; import com.ifinancesys.core.domain.Page; import com.ifinancesys.core.action.BaseAction; import com.ifinancesys.core.entity.BackMessage; import com.ifinancesys.core.entity.TreeVo; import com.ifinancesys.core.exception.BusinessException; import com.ifinancesys.system.entity.Organization; import com.ifinancesys.system.entity.SysMenu; import com.ifinancesys.system.entity.SysResponsibility; import com.ifinancesys.system.entity.SysResponsibilityPrivilege; import com.ifinancesys.system.service.OrganizationService; import com.ifinancesys.system.service.SysMenuService; import com.ifinancesys.system.service.SysResponsibilityService; /** * 职责管理action * @author yyzhai * * 2014-11-20 上午11:36:38 */ @ParentPackage("struts-default") public class SysResponsibilityAction extends BaseAction { private static final long serialVersionUID = 1L; private Logger logger = Logger.getLogger(SysResponsibilityAction.class); private SysResponsibility responsibility; private SysResponsibilityPrivilege responsibilityPrivilege; @Autowired private SysResponsibilityService responsibilityService; @Autowired private OrganizationService organizationService; @Autowired private SysMenuService sysMenuService; /** * 显示职责页面 * @author yyzhai * 2014-11-20 下午12:09:25 * @return */ @Action(value = "menu_responsibilityAction", results = { @Result(name = "success", location = "/page/basic/responsibility/responsibilityList.jsp") }) public String search() { return SUCCESS; } /** * 职责列表 * @author yyzhai * 2014-11-20 下午12:09:36 */ @Action(value = "listResponsibilityAction") public void list() { Map<String, Object> jsonMap = new HashMap<String, Object>(); try { if(responsibility==null){ responsibility=new SysResponsibility(); } responsibility.setTenantid(this.getTenantId()); Page page = responsibilityService.pageList(this.getPage(), this.getRows(), responsibility, this .getLoginOrganizationId(), null); jsonMap.put("total", page.getTotalCount());// total 存放总记录数 jsonMap.put("rows", page.getData());// rows 存放每页记录 list } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } outJson(jsonMap); } /** * 适用单位树 * @author yyzhai * 2014-11-20 下午12:13:57 */ @Action(value = "listOrganizationTreeAction") public void organizationTree() { List<TreeVo> result = new ArrayList<TreeVo>(); try { List all = organizationService.getCurOrganizationAndBelongOrg(this.getLoginOrganization() .getId(),this.getTenantId()); result = creatOrgTree(all); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } outJson(result); } /** * 拼接组织机构数 * @author yyzhai * 2014-11-21 下午5:08:00 * @param orgList * @return */ private List<TreeVo> creatOrgTree(List<Organization> orgList) { List<TreeVo> treeList = new ArrayList<TreeVo>(); Map<Long, TreeVo> nodeMap = new HashMap<Long, TreeVo>(); // 存放id --节点 // 对应,方便查找父对象 //当前职责适用单位 Map orgMap = new HashMap(); orgMap = responsibilityService.getSysRoleByResponsibilityId(responsibility); // 将节点对象存入Map for (Organization org : orgList) { TreeVo node = new TreeVo(); node.setId(org.getId()); node.setText(org.getOrgName()); if (orgMap != null && orgMap.size() > 0) { if (orgMap.containsKey(org.getId())) { node.setChecked(true); } else { node.setChecked(false); } } Map attr = new HashMap(); attr.put("orgStatus", org.getOrgStatus()); attr.put("fatherOrgID", org.getFatherOrgID()); node.setAttributes(attr); nodeMap.put(org.getId(), node); } // 将节点对象存入Map for (Organization org : orgList) { Long fartherId = org.getFatherOrgID(); TreeVo fartherNode = nodeMap.get(fartherId); // 父节点 TreeVo node = nodeMap.get(org.getId()); // 当前节点 if (fartherNode != null) { // 父节点不为空,加入父节点 fartherNode.getChildren().add(node); } else { // 父节点为空,为根节点 加入List treeList.add(node); } } return treeList; } /** * 功能菜单树 * @author yyzhai * 2014-11-20 下午12:13:57 */ @Action(value = "listMenuTreeAction") public void menuTree() { List<TreeVo> result = new ArrayList<TreeVo>(); try { List<SysMenu> all = sysMenuService.getBusinessSysMenuList(this.getTenantId()); result = creatMenuTree(all); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } outJson(result); } /** * 拼接菜单树 * @author yyzhai * 2014-11-21 下午5:08:31 * @param menuList * @return * @throws Exception */ private List<TreeVo> creatMenuTree(List<SysMenu> menuList) throws Exception { responsibility = responsibilityService.getSysResponsibilityById(responsibility.getId()); Map priMap = new HashMap(); if (responsibility.getResponsibilityStatus() != null && responsibility.getResponsibilityStatus().longValue() == SystemConstant.ResponsibilityStatus.WAITCHECK) { //菜单临时权限ID集合 priMap = responsibilityService.getPriTempMapByResponsibilityId(responsibility.getId()); } else { //菜单权限ID集合 priMap = responsibilityService.getMenuListByResponsibilityId(responsibility.getId()); } List<TreeVo> treeList = new ArrayList<TreeVo>(); Map<Long, TreeVo> nodeMap = new HashMap<Long, TreeVo>(); // 存放id --节点 // 对应,方便查找父对象 // 将节点对象存入Map for (SysMenu menu : menuList) { TreeVo node = new TreeVo(); node.setId(menu.getId()); node.setText(super.getText(menu.getMenuname())); Map attr = new HashMap(); if (priMap != null && priMap.size() > 0) { if (priMap.containsKey(menu.getId())) { node.setChecked(true); } else { node.setChecked(false); } } attr.put("menuStatus", "1"); attr.put("fatherMenuID", menu.getParentid()); node.setAttributes(attr); nodeMap.put(menu.getId(), node); } // 将节点对象存入Map for (SysMenu menu : menuList) { Long fartherId = menu.getParentid(); TreeVo fartherNode = nodeMap.get(fartherId); // 父节点 TreeVo node = nodeMap.get(menu.getId()); // 当前节点 if (fartherNode != null) { // 父节点不为空,加入父节点 fartherNode.getChildren().add(node); } else { // 父节点为空,为根节点 加入List treeList.add(node); } } return treeList; } /** * 职责状态下拉框 * @author yyzhai * 2014-11-20 下午2:39:58 */ @Action(value = "getResponsibilityStatusSelect") public void getResponsibilityStatusSelect() { try { outJson(Constant.showList(SystemConstant.ResponsibilityStatus.class, null)); } catch (Exception e) { e.printStackTrace(); } } /** * 职责新增 * @author yyzhai * 2014-11-20 下午5:02:23 */ @Action(value = "addResponsibilityAction", results = { @Result(name = "success", location = "/page/basic/responsibility/responsibilityAdd.jsp") }) public String add() { try { if (responsibility == null) { responsibility = new SysResponsibility(); responsibility.setCode(responsibilityService.getNewCodeForAdd()); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return SUCCESS; } /** * 职责修改 * @author yyzhai * 2014-11-20 下午5:02:23 */ @Action(value = "updateResponsibilityAction", results = { @Result(name = "success", location = "/page/basic/responsibility/responsibilityAdd.jsp") }) public String update() { try { responsibility = responsibilityService.getSysResponsibilityById(responsibility.getId()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return SUCCESS; } /** * 保存职责 * @author yyzhai * 2014-11-20 下午5:12:14 */ @Action(value = "saveResponsibilityAction") public void save() { BackMessage result = new BackMessage(); result.setSuccess(true); try { //校验编号是否重复 if (!responsibilityService.checkDuplicateCode(responsibility)) { throw new BusinessException("core.SysResponsibility.responsibilityFailByRepeat"); } else { if (responsibility.getId() == null) { responsibility.setInputDate(new Date()); responsibility.setInputUserID(this.getLoginUser().getId()); responsibility.setTenantid(this.getTenantId());//租户 responsibility.setLastModifyUserID(this.getLoginUser().getId()); responsibility.setResponsibilityStatus(SystemConstant.ResponsibilityStatus.USED); responsibility.setStatus(Constant.RecordStatus.VALID); responsibility.setResponsibilityType(SystemConstant.ResponsibilityType.BUSINESS); responsibility.setInputOrgID(this.getLoginOrganizationId()); responsibilityService.saveSysResponsibility(responsibility); } else { responsibilityService.updateSysResponsibility(responsibility); } } }catch(BusinessException e){ result.setSuccess(false); result.setMessage(this.getText(e)); }catch (Exception e) { result.setSuccess(false); result.setMessage(this.getText("global.msg.operaterFailed")+e.getMessage()); e.printStackTrace(); } outJson(result); } /** * 删除职责 * @author yyzhai * 2014-11-21 上午10:07:52 */ @Action(value = "deleteResponsibilityAction") public void delete() { BackMessage result = new BackMessage(); result.setSuccess(true); try { responsibility = responsibilityService.getSysResponsibilityById(responsibility.getId()); if (responsibility != null && responsibility.getId() != null) { if (responsibilityService.checkUsed(responsibility)) { throw new BusinessException("core.SysResponsibility.responsibilityFailByApple"); } else { responsibilityService.deleteSysResponsibility(responsibility); } } else { throw new BusinessException("core.SysResponsibility.responsibilityFailByDelete"); } } catch(BusinessException e){ result.setSuccess(false); result.setMessage(this.getText(e)); }catch (Exception e) { result.setSuccess(false); result.setMessage(this.getText("global.msg.operaterFailed")+e.getMessage()); e.printStackTrace(); } outJson(result); } @Action(value = "saveResponsibilityPriAction") public void savePri() { BackMessage result = new BackMessage(); result.setSuccess(true); try { String menuIds = this.getRequest().getParameter("menuIds"); String[] menuIdsArr = menuIds.split(","); responsibility = responsibilityService.getSysResponsibilityById(responsibility.getId()); if (responsibility.getResponsibilityStatus().longValue() == SystemConstant.ResponsibilityStatus.WAITCHECK) { throw new BusinessException("core.SysResponsibility.responsibilityFailByStatusError"); } else { responsibilityService.savePrivilegeForCheck(responsibility, menuIdsArr, this.getLoginUser()); } } catch(BusinessException e){ result.setSuccess(false); result.setMessage(this.getText(e)); }catch (Exception e) { result.setSuccess(false); result.setMessage(this.getText("global.msg.operaterFailed")+e.getMessage()); e.printStackTrace(); } outJson(result); } @Action(value = "saveResponsibilityOrgAction") public void saveOrg() { BackMessage result = new BackMessage(); result.setSuccess(true); String orgNames = ""; String noDelIds = "";//校验未通过的ID try { String orgIds = this.getRequest().getParameter("orgIds"); //校验不能取消的单位 if (orgIds != null && !"".equals(orgIds) && orgIds.length() > 1) { orgIds = orgIds.substring(0, orgIds.length() - 1); } //本次需要删除的,但是已经关联了权限的单位 List<Organization> list = responsibilityService.getOrganizationNotInOrgIds(orgIds, responsibility.getId()); if (list != null && list.size() > 0) { for (Organization org : list) { orgNames = orgNames + org.getOrgName() + ","; noDelIds = noDelIds + org.getId() + ","; } } String[] orgIdsArr = orgIds.split(","); if (!"".equals(orgNames)) { result.setSuccess(false); result.addMessage(this.getText("core.SysResponsibility.responsibilityFailByAppleLinked","orgNames")); responsibilityService.saveSysRoleWithResponsibility(responsibility, orgIdsArr, this.getLoginUser(), noDelIds); } else { responsibilityService.saveSysRoleWithResponsibility(responsibility, orgIdsArr, this.getLoginUser(), null); } } catch(BusinessException e){ result.setSuccess(false); result.setMessage(this.getText(e)); }catch (Exception e) { result.setSuccess(false); result.setMessage(this.getText("global.msg.operaterFailed")+e.getMessage()); e.printStackTrace(); } outJson(result); } public SysResponsibility getResponsibility() { return responsibility; } public void setResponsibility(SysResponsibility responsibility) { this.responsibility = responsibility; } public SysResponsibilityPrivilege getResponsibilityPrivilege() { return responsibilityPrivilege; } public void setResponsibilityPrivilege(SysResponsibilityPrivilege responsibilityPrivilege) { this.responsibilityPrivilege = responsibilityPrivilege; } public SysResponsibilityService getResponsibilityService() { return responsibilityService; } public void setResponsibilityService(SysResponsibilityService responsibilityService) { this.responsibilityService = responsibilityService; } }
UTF-8
Java
14,052
java
SysResponsibilityAction.java
Java
[ { "context": "sponsibilityService;\n\n/**\n * 职责管理action\n * @author yyzhai\n *\n * 2014-11-20 上午11:36:38\n */\n@ParentPackage(\"s", "end": 1185, "score": 0.9995277523994446, "start": 1179, "tag": "USERNAME", "value": "yyzhai" }, { "context": "rvice sysMenuService;\n\n\t/**\n\t * 显示职责页面\n\t * @author yyzhai\n\t * 2014-11-20 下午12:09:25\n\t * @return\n\t */\n\t@Acti", "end": 1762, "score": 0.999546229839325, "start": 1756, "tag": "USERNAME", "value": "yyzhai" }, { "context": "{\n\n\t\treturn SUCCESS;\n\t}\n\n\t/**\n\t * 职责列表\n\t * @author yyzhai\n\t * 2014-11-20 下午12:09:36\n\t */\n\t@Action(value = \"", "end": 2038, "score": 0.9995658993721008, "start": 2032, "tag": "USERNAME", "value": "yyzhai" }, { "context": "\t\toutJson(jsonMap);\n\t}\n\n\t/**\n\t * 适用单位树\n\t * @author yyzhai\n\t * 2014-11-20 下午12:13:57\n\t */\n\t@Action(value = \"", "end": 2747, "score": 0.9995933175086975, "start": 2741, "tag": "USERNAME", "value": "yyzhai" }, { "context": "outJson(result);\n\n\t}\n\n\t/**\n\t * 拼接组织机构数\n\t * @author yyzhai\n\t * 2014-11-21 下午5:08:00\n\t * @param orgList\n\t * @", "end": 3229, "score": 0.999576985836029, "start": 3223, "tag": "USERNAME", "value": "yyzhai" }, { "context": "\n\t\treturn treeList;\n\t}\n\n\t/**\n\t * 功能菜单树\n\t * @author yyzhai\n\t * 2014-11-20 下午12:13:57\n\t */\n\t@Action(value = \"", "end": 4549, "score": 0.9996471405029297, "start": 4543, "tag": "USERNAME", "value": "yyzhai" }, { "context": "\t\toutJson(result);\n\n\t}\n\n\t/**\n\t * 拼接菜单树\n\t * @author yyzhai\n\t * 2014-11-21 下午5:08:31\n\t * @param menuList\n\t * ", "end": 4967, "score": 0.9995536804199219, "start": 4961, "tag": "USERNAME", "value": "yyzhai" }, { "context": "\treturn treeList;\n\t}\n\n\t/**\n\t * 职责状态下拉框\n\t * @author yyzhai\n\t * 2014-11-20 下午2:39:58\n\t */\n\t@Action(value = \"g", "end": 6716, "score": 0.9994757175445557, "start": 6710, "tag": "USERNAME", "value": "yyzhai" }, { "context": "intStackTrace();\n\t\t}\n\t}\n\n\t/**\n\t * 职责新增\n\t * @author yyzhai\n\t * 2014-11-20 下午5:02:23\n\t */\n\t@Action(value = \"a", "end": 7022, "score": 0.9994687438011169, "start": 7016, "tag": "USERNAME", "value": "yyzhai" }, { "context": "\t}\n\t\treturn SUCCESS;\n\t}\n\n\t/**\n\t * 职责修改\n\t * @author yyzhai\n\t * 2014-11-20 下午5:02:23\n\t */\n\t@Action(value = \"u", "end": 7532, "score": 0.9994933605194092, "start": 7526, "tag": "USERNAME", "value": "yyzhai" }, { "context": "\t}\n\t\treturn SUCCESS;\n\t}\n\n\t/**\n\t * 保存职责\n\t * @author yyzhai\n\t * 2014-11-20 下午5:12:14\n\t */\n\t@Action(value = \"s", "end": 7986, "score": 0.9994339942932129, "start": 7980, "tag": "USERNAME", "value": "yyzhai" }, { "context": "}\n\t\toutJson(result);\n\t}\n\n\t/**\n\t * 删除职责\n\t * @author yyzhai\n\t * 2014-11-21 上午10:07:52\n\t */\n\t@Action(value = \"", "end": 9398, "score": 0.9994909167289734, "start": 9392, "tag": "USERNAME", "value": "yyzhai" } ]
null
[]
package com.ifinancesys.system.action; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import com.ifinancesys.system.SystemConstant; import org.apache.log4j.Logger; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.ParentPackage; import org.apache.struts2.convention.annotation.Result; import org.springframework.beans.factory.annotation.Autowired; import com.ifinancesys.core.Constant; import com.ifinancesys.core.domain.Page; import com.ifinancesys.core.action.BaseAction; import com.ifinancesys.core.entity.BackMessage; import com.ifinancesys.core.entity.TreeVo; import com.ifinancesys.core.exception.BusinessException; import com.ifinancesys.system.entity.Organization; import com.ifinancesys.system.entity.SysMenu; import com.ifinancesys.system.entity.SysResponsibility; import com.ifinancesys.system.entity.SysResponsibilityPrivilege; import com.ifinancesys.system.service.OrganizationService; import com.ifinancesys.system.service.SysMenuService; import com.ifinancesys.system.service.SysResponsibilityService; /** * 职责管理action * @author yyzhai * * 2014-11-20 上午11:36:38 */ @ParentPackage("struts-default") public class SysResponsibilityAction extends BaseAction { private static final long serialVersionUID = 1L; private Logger logger = Logger.getLogger(SysResponsibilityAction.class); private SysResponsibility responsibility; private SysResponsibilityPrivilege responsibilityPrivilege; @Autowired private SysResponsibilityService responsibilityService; @Autowired private OrganizationService organizationService; @Autowired private SysMenuService sysMenuService; /** * 显示职责页面 * @author yyzhai * 2014-11-20 下午12:09:25 * @return */ @Action(value = "menu_responsibilityAction", results = { @Result(name = "success", location = "/page/basic/responsibility/responsibilityList.jsp") }) public String search() { return SUCCESS; } /** * 职责列表 * @author yyzhai * 2014-11-20 下午12:09:36 */ @Action(value = "listResponsibilityAction") public void list() { Map<String, Object> jsonMap = new HashMap<String, Object>(); try { if(responsibility==null){ responsibility=new SysResponsibility(); } responsibility.setTenantid(this.getTenantId()); Page page = responsibilityService.pageList(this.getPage(), this.getRows(), responsibility, this .getLoginOrganizationId(), null); jsonMap.put("total", page.getTotalCount());// total 存放总记录数 jsonMap.put("rows", page.getData());// rows 存放每页记录 list } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } outJson(jsonMap); } /** * 适用单位树 * @author yyzhai * 2014-11-20 下午12:13:57 */ @Action(value = "listOrganizationTreeAction") public void organizationTree() { List<TreeVo> result = new ArrayList<TreeVo>(); try { List all = organizationService.getCurOrganizationAndBelongOrg(this.getLoginOrganization() .getId(),this.getTenantId()); result = creatOrgTree(all); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } outJson(result); } /** * 拼接组织机构数 * @author yyzhai * 2014-11-21 下午5:08:00 * @param orgList * @return */ private List<TreeVo> creatOrgTree(List<Organization> orgList) { List<TreeVo> treeList = new ArrayList<TreeVo>(); Map<Long, TreeVo> nodeMap = new HashMap<Long, TreeVo>(); // 存放id --节点 // 对应,方便查找父对象 //当前职责适用单位 Map orgMap = new HashMap(); orgMap = responsibilityService.getSysRoleByResponsibilityId(responsibility); // 将节点对象存入Map for (Organization org : orgList) { TreeVo node = new TreeVo(); node.setId(org.getId()); node.setText(org.getOrgName()); if (orgMap != null && orgMap.size() > 0) { if (orgMap.containsKey(org.getId())) { node.setChecked(true); } else { node.setChecked(false); } } Map attr = new HashMap(); attr.put("orgStatus", org.getOrgStatus()); attr.put("fatherOrgID", org.getFatherOrgID()); node.setAttributes(attr); nodeMap.put(org.getId(), node); } // 将节点对象存入Map for (Organization org : orgList) { Long fartherId = org.getFatherOrgID(); TreeVo fartherNode = nodeMap.get(fartherId); // 父节点 TreeVo node = nodeMap.get(org.getId()); // 当前节点 if (fartherNode != null) { // 父节点不为空,加入父节点 fartherNode.getChildren().add(node); } else { // 父节点为空,为根节点 加入List treeList.add(node); } } return treeList; } /** * 功能菜单树 * @author yyzhai * 2014-11-20 下午12:13:57 */ @Action(value = "listMenuTreeAction") public void menuTree() { List<TreeVo> result = new ArrayList<TreeVo>(); try { List<SysMenu> all = sysMenuService.getBusinessSysMenuList(this.getTenantId()); result = creatMenuTree(all); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } outJson(result); } /** * 拼接菜单树 * @author yyzhai * 2014-11-21 下午5:08:31 * @param menuList * @return * @throws Exception */ private List<TreeVo> creatMenuTree(List<SysMenu> menuList) throws Exception { responsibility = responsibilityService.getSysResponsibilityById(responsibility.getId()); Map priMap = new HashMap(); if (responsibility.getResponsibilityStatus() != null && responsibility.getResponsibilityStatus().longValue() == SystemConstant.ResponsibilityStatus.WAITCHECK) { //菜单临时权限ID集合 priMap = responsibilityService.getPriTempMapByResponsibilityId(responsibility.getId()); } else { //菜单权限ID集合 priMap = responsibilityService.getMenuListByResponsibilityId(responsibility.getId()); } List<TreeVo> treeList = new ArrayList<TreeVo>(); Map<Long, TreeVo> nodeMap = new HashMap<Long, TreeVo>(); // 存放id --节点 // 对应,方便查找父对象 // 将节点对象存入Map for (SysMenu menu : menuList) { TreeVo node = new TreeVo(); node.setId(menu.getId()); node.setText(super.getText(menu.getMenuname())); Map attr = new HashMap(); if (priMap != null && priMap.size() > 0) { if (priMap.containsKey(menu.getId())) { node.setChecked(true); } else { node.setChecked(false); } } attr.put("menuStatus", "1"); attr.put("fatherMenuID", menu.getParentid()); node.setAttributes(attr); nodeMap.put(menu.getId(), node); } // 将节点对象存入Map for (SysMenu menu : menuList) { Long fartherId = menu.getParentid(); TreeVo fartherNode = nodeMap.get(fartherId); // 父节点 TreeVo node = nodeMap.get(menu.getId()); // 当前节点 if (fartherNode != null) { // 父节点不为空,加入父节点 fartherNode.getChildren().add(node); } else { // 父节点为空,为根节点 加入List treeList.add(node); } } return treeList; } /** * 职责状态下拉框 * @author yyzhai * 2014-11-20 下午2:39:58 */ @Action(value = "getResponsibilityStatusSelect") public void getResponsibilityStatusSelect() { try { outJson(Constant.showList(SystemConstant.ResponsibilityStatus.class, null)); } catch (Exception e) { e.printStackTrace(); } } /** * 职责新增 * @author yyzhai * 2014-11-20 下午5:02:23 */ @Action(value = "addResponsibilityAction", results = { @Result(name = "success", location = "/page/basic/responsibility/responsibilityAdd.jsp") }) public String add() { try { if (responsibility == null) { responsibility = new SysResponsibility(); responsibility.setCode(responsibilityService.getNewCodeForAdd()); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return SUCCESS; } /** * 职责修改 * @author yyzhai * 2014-11-20 下午5:02:23 */ @Action(value = "updateResponsibilityAction", results = { @Result(name = "success", location = "/page/basic/responsibility/responsibilityAdd.jsp") }) public String update() { try { responsibility = responsibilityService.getSysResponsibilityById(responsibility.getId()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return SUCCESS; } /** * 保存职责 * @author yyzhai * 2014-11-20 下午5:12:14 */ @Action(value = "saveResponsibilityAction") public void save() { BackMessage result = new BackMessage(); result.setSuccess(true); try { //校验编号是否重复 if (!responsibilityService.checkDuplicateCode(responsibility)) { throw new BusinessException("core.SysResponsibility.responsibilityFailByRepeat"); } else { if (responsibility.getId() == null) { responsibility.setInputDate(new Date()); responsibility.setInputUserID(this.getLoginUser().getId()); responsibility.setTenantid(this.getTenantId());//租户 responsibility.setLastModifyUserID(this.getLoginUser().getId()); responsibility.setResponsibilityStatus(SystemConstant.ResponsibilityStatus.USED); responsibility.setStatus(Constant.RecordStatus.VALID); responsibility.setResponsibilityType(SystemConstant.ResponsibilityType.BUSINESS); responsibility.setInputOrgID(this.getLoginOrganizationId()); responsibilityService.saveSysResponsibility(responsibility); } else { responsibilityService.updateSysResponsibility(responsibility); } } }catch(BusinessException e){ result.setSuccess(false); result.setMessage(this.getText(e)); }catch (Exception e) { result.setSuccess(false); result.setMessage(this.getText("global.msg.operaterFailed")+e.getMessage()); e.printStackTrace(); } outJson(result); } /** * 删除职责 * @author yyzhai * 2014-11-21 上午10:07:52 */ @Action(value = "deleteResponsibilityAction") public void delete() { BackMessage result = new BackMessage(); result.setSuccess(true); try { responsibility = responsibilityService.getSysResponsibilityById(responsibility.getId()); if (responsibility != null && responsibility.getId() != null) { if (responsibilityService.checkUsed(responsibility)) { throw new BusinessException("core.SysResponsibility.responsibilityFailByApple"); } else { responsibilityService.deleteSysResponsibility(responsibility); } } else { throw new BusinessException("core.SysResponsibility.responsibilityFailByDelete"); } } catch(BusinessException e){ result.setSuccess(false); result.setMessage(this.getText(e)); }catch (Exception e) { result.setSuccess(false); result.setMessage(this.getText("global.msg.operaterFailed")+e.getMessage()); e.printStackTrace(); } outJson(result); } @Action(value = "saveResponsibilityPriAction") public void savePri() { BackMessage result = new BackMessage(); result.setSuccess(true); try { String menuIds = this.getRequest().getParameter("menuIds"); String[] menuIdsArr = menuIds.split(","); responsibility = responsibilityService.getSysResponsibilityById(responsibility.getId()); if (responsibility.getResponsibilityStatus().longValue() == SystemConstant.ResponsibilityStatus.WAITCHECK) { throw new BusinessException("core.SysResponsibility.responsibilityFailByStatusError"); } else { responsibilityService.savePrivilegeForCheck(responsibility, menuIdsArr, this.getLoginUser()); } } catch(BusinessException e){ result.setSuccess(false); result.setMessage(this.getText(e)); }catch (Exception e) { result.setSuccess(false); result.setMessage(this.getText("global.msg.operaterFailed")+e.getMessage()); e.printStackTrace(); } outJson(result); } @Action(value = "saveResponsibilityOrgAction") public void saveOrg() { BackMessage result = new BackMessage(); result.setSuccess(true); String orgNames = ""; String noDelIds = "";//校验未通过的ID try { String orgIds = this.getRequest().getParameter("orgIds"); //校验不能取消的单位 if (orgIds != null && !"".equals(orgIds) && orgIds.length() > 1) { orgIds = orgIds.substring(0, orgIds.length() - 1); } //本次需要删除的,但是已经关联了权限的单位 List<Organization> list = responsibilityService.getOrganizationNotInOrgIds(orgIds, responsibility.getId()); if (list != null && list.size() > 0) { for (Organization org : list) { orgNames = orgNames + org.getOrgName() + ","; noDelIds = noDelIds + org.getId() + ","; } } String[] orgIdsArr = orgIds.split(","); if (!"".equals(orgNames)) { result.setSuccess(false); result.addMessage(this.getText("core.SysResponsibility.responsibilityFailByAppleLinked","orgNames")); responsibilityService.saveSysRoleWithResponsibility(responsibility, orgIdsArr, this.getLoginUser(), noDelIds); } else { responsibilityService.saveSysRoleWithResponsibility(responsibility, orgIdsArr, this.getLoginUser(), null); } } catch(BusinessException e){ result.setSuccess(false); result.setMessage(this.getText(e)); }catch (Exception e) { result.setSuccess(false); result.setMessage(this.getText("global.msg.operaterFailed")+e.getMessage()); e.printStackTrace(); } outJson(result); } public SysResponsibility getResponsibility() { return responsibility; } public void setResponsibility(SysResponsibility responsibility) { this.responsibility = responsibility; } public SysResponsibilityPrivilege getResponsibilityPrivilege() { return responsibilityPrivilege; } public void setResponsibilityPrivilege(SysResponsibilityPrivilege responsibilityPrivilege) { this.responsibilityPrivilege = responsibilityPrivilege; } public SysResponsibilityService getResponsibilityService() { return responsibilityService; } public void setResponsibilityService(SysResponsibilityService responsibilityService) { this.responsibilityService = responsibilityService; } }
14,052
0.71598
0.703083
467
27.892933
27.361042
150
false
false
0
0
0
0
0
0
2.312634
false
false
10
f50240b8117658c9ee264edd081fec1ca7b57d31
19,052,474,982,711
a8f8f4a24698709debaca26400799b465192728f
/digtle/src/main/java/com/phone1000/groupproject/fragment/TeamFragmentRight.java
717d8cd5c9ce1bb5bd13a7a9df3b08795d854831
[]
no_license
digtle/TeamWork
https://github.com/digtle/TeamWork
de26fc38163b8aeee59e0a019596ad408d1cdf72
07f38ec48e792a56b23005afb681bc809f7092cb
refs/heads/master
2020-09-24T22:35:36.174000
2016-09-19T06:33:09
2016-09-19T06:33:09
67,585,498
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.phone1000.groupproject.fragment; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import com.phone1000.groupproject.R; import com.phone1000.groupproject.adapter.TeamNewListAdapter; import com.phone1000.groupproject.bean.DigtleUrl; import com.phone1000.groupproject.bean.MostnewListInfo; import com.phone1000.groupproject.http.JsonHttpUtils; import com.phone1000.groupproject.ui.TeamNewAritcleActivity; import com.phone1000.groupproject.view.IjsonView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Created by Administrator on 2016/9/7. */ public class TeamFragmentRight extends Fragment implements IjsonView { private Context mContext; private View view; private List<String> datas = new ArrayList<>(); private JsonHttpUtils jsonHttpUtils; private TeamNewListAdapter adapter; private List<MostnewListInfo> beanList = new ArrayList<>(); //重写抽象工厂方法 public static TeamFragmentRight newInstance(){ TeamFragmentRight teamFragmentRight = new TeamFragmentRight(); return teamFragmentRight; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mContext = getContext(); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.team_ftagment_right, container, false); loadDatas(); initView(); return view; } private void loadDatas() { jsonHttpUtils = JsonHttpUtils.newInstance(); jsonHttpUtils.load(DigtleUrl.GROUP_WELL_CHOSEN,null,this,JsonHttpUtils.REQUEST_METHOD_GET); } private void initView() { final SwipeRefreshLayout myRefreshListView = (SwipeRefreshLayout) view.findViewById(R.id.swipe_layout); final ListView mListView = (ListView) view.findViewById(R.id.list_view); adapter = new TeamNewListAdapter(mContext,beanList); mListView.setAdapter(adapter); //设置下拉刷新监听器 myRefreshListView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { myRefreshListView.postDelayed(new Runnable() { @Override public void run() { //加载数据 beanList.clear(); jsonHttpUtils.load(DigtleUrl.GROUP_WELL_CHOSEN,null,TeamFragmentRight.this,JsonHttpUtils.REQUEST_METHOD_GET); //刷新适配器 //更新完后调用该方法结束刷新 myRefreshListView.setRefreshing(false); } },2000); } }); //设置加载监听器 mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(mContext, TeamNewAritcleActivity.class); String tid = beanList.get(position).getTid(); intent.putExtra("tid",tid); startActivity(intent); } }); } @Override public void getJsonString(String jsonString) { JSONObject jsonObject = null; try { jsonObject = new JSONObject(jsonString); JSONArray jsonArray = jsonObject.getJSONArray("newlist"); for (int i = 0; i < jsonArray.length(); i++) { MostnewListInfo mostnewListInfo = new MostnewListInfo(); JSONObject jsonObject1 = jsonArray.getJSONObject(i); int attchcount = jsonObject1.getInt("attachcount"); List<String> attachList = new ArrayList<>(); if (attchcount != 0) { JSONObject imageList = jsonObject1.getJSONObject("attachlist"); Iterator<String> keys = imageList.keys(); while (keys.hasNext()) { String key = keys.next(); String imageUrl = imageList.getString(key); attachList.add(imageUrl); } } mostnewListInfo.setAttachList(attachList); mostnewListInfo.setAttachcount(attchcount); mostnewListInfo.setTid(jsonObject1.getString("tid")); mostnewListInfo.setAuthor(jsonObject1.getString("author")); mostnewListInfo.setAuthorid(jsonObject1.getString("authorid")); mostnewListInfo.setDateline(jsonObject1.getString("dateline")); mostnewListInfo.setForum_icon(jsonObject1.getString("forum_icon")); mostnewListInfo.setPostcommentcount(jsonObject1.getString("postcommentcount")); mostnewListInfo.setForum_name(jsonObject1.getString("forum_name")); mostnewListInfo.setReplies(jsonObject1.getString("replies")); mostnewListInfo.setSubject(jsonObject1.getString("subject")); mostnewListInfo.setSummary(jsonObject1.getString("summary")); mostnewListInfo.setRecommend_add(jsonObject1.getString("recommend_add")); beanList.add(mostnewListInfo); } adapter.notifyDataSetChanged(); } catch (JSONException e) { e.printStackTrace(); } } }
UTF-8
Java
6,007
java
TeamFragmentRight.java
Java
[ { "context": "terator;\nimport java.util.List;\n\n/**\n * Created by Administrator on 2016/9/7.\n */\npublic class TeamFragmentRight e", "end": 1001, "score": 0.7622458934783936, "start": 988, "tag": "NAME", "value": "Administrator" } ]
null
[]
package com.phone1000.groupproject.fragment; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import com.phone1000.groupproject.R; import com.phone1000.groupproject.adapter.TeamNewListAdapter; import com.phone1000.groupproject.bean.DigtleUrl; import com.phone1000.groupproject.bean.MostnewListInfo; import com.phone1000.groupproject.http.JsonHttpUtils; import com.phone1000.groupproject.ui.TeamNewAritcleActivity; import com.phone1000.groupproject.view.IjsonView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Created by Administrator on 2016/9/7. */ public class TeamFragmentRight extends Fragment implements IjsonView { private Context mContext; private View view; private List<String> datas = new ArrayList<>(); private JsonHttpUtils jsonHttpUtils; private TeamNewListAdapter adapter; private List<MostnewListInfo> beanList = new ArrayList<>(); //重写抽象工厂方法 public static TeamFragmentRight newInstance(){ TeamFragmentRight teamFragmentRight = new TeamFragmentRight(); return teamFragmentRight; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mContext = getContext(); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.team_ftagment_right, container, false); loadDatas(); initView(); return view; } private void loadDatas() { jsonHttpUtils = JsonHttpUtils.newInstance(); jsonHttpUtils.load(DigtleUrl.GROUP_WELL_CHOSEN,null,this,JsonHttpUtils.REQUEST_METHOD_GET); } private void initView() { final SwipeRefreshLayout myRefreshListView = (SwipeRefreshLayout) view.findViewById(R.id.swipe_layout); final ListView mListView = (ListView) view.findViewById(R.id.list_view); adapter = new TeamNewListAdapter(mContext,beanList); mListView.setAdapter(adapter); //设置下拉刷新监听器 myRefreshListView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { myRefreshListView.postDelayed(new Runnable() { @Override public void run() { //加载数据 beanList.clear(); jsonHttpUtils.load(DigtleUrl.GROUP_WELL_CHOSEN,null,TeamFragmentRight.this,JsonHttpUtils.REQUEST_METHOD_GET); //刷新适配器 //更新完后调用该方法结束刷新 myRefreshListView.setRefreshing(false); } },2000); } }); //设置加载监听器 mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(mContext, TeamNewAritcleActivity.class); String tid = beanList.get(position).getTid(); intent.putExtra("tid",tid); startActivity(intent); } }); } @Override public void getJsonString(String jsonString) { JSONObject jsonObject = null; try { jsonObject = new JSONObject(jsonString); JSONArray jsonArray = jsonObject.getJSONArray("newlist"); for (int i = 0; i < jsonArray.length(); i++) { MostnewListInfo mostnewListInfo = new MostnewListInfo(); JSONObject jsonObject1 = jsonArray.getJSONObject(i); int attchcount = jsonObject1.getInt("attachcount"); List<String> attachList = new ArrayList<>(); if (attchcount != 0) { JSONObject imageList = jsonObject1.getJSONObject("attachlist"); Iterator<String> keys = imageList.keys(); while (keys.hasNext()) { String key = keys.next(); String imageUrl = imageList.getString(key); attachList.add(imageUrl); } } mostnewListInfo.setAttachList(attachList); mostnewListInfo.setAttachcount(attchcount); mostnewListInfo.setTid(jsonObject1.getString("tid")); mostnewListInfo.setAuthor(jsonObject1.getString("author")); mostnewListInfo.setAuthorid(jsonObject1.getString("authorid")); mostnewListInfo.setDateline(jsonObject1.getString("dateline")); mostnewListInfo.setForum_icon(jsonObject1.getString("forum_icon")); mostnewListInfo.setPostcommentcount(jsonObject1.getString("postcommentcount")); mostnewListInfo.setForum_name(jsonObject1.getString("forum_name")); mostnewListInfo.setReplies(jsonObject1.getString("replies")); mostnewListInfo.setSubject(jsonObject1.getString("subject")); mostnewListInfo.setSummary(jsonObject1.getString("summary")); mostnewListInfo.setRecommend_add(jsonObject1.getString("recommend_add")); beanList.add(mostnewListInfo); } adapter.notifyDataSetChanged(); } catch (JSONException e) { e.printStackTrace(); } } }
6,007
0.643449
0.633305
146
39.513699
28.9123
133
false
false
0
0
0
0
0
0
0.69863
false
false
10
d855a0c78cd4bb29af3eae449642febb0c5a957a
33,208,687,193,002
f3bd3526e500eb34975d84cce0ec5487f88a4aa6
/Project2/src/utility/ContextSingleton.java
e74c208b7926e182ccf88a406cbe3e84ae3400d1
[]
no_license
lukasicar/Agenti2
https://github.com/lukasicar/Agenti2
9e1373c85ebbe85fe14bd37e264f93a226673467
1a5c7510330f6b4f80963f9ed24fbb18d0154b21
refs/heads/master
2021-01-23T14:07:20.346000
2017-06-21T10:36:16
2017-06-21T10:36:16
93,243,403
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package utility; import java.util.Hashtable; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; public abstract class ContextSingleton { private static Context context; private static Context initContext() { try { Hashtable<String, Object> jndiProps = new Hashtable<>(); jndiProps.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming"); //RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean(); //List<String> arguments = runtimeMxBean.getInputArguments(); return new InitialContext(jndiProps); } catch (NamingException e) { System.err.println("Context initialization error." + e.getMessage()); return null; } } public static Context getContext() { if (context == null) { context = initContext(); } return context; } }
UTF-8
Java
956
java
ContextSingleton.java
Java
[]
null
[]
package utility; import java.util.Hashtable; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; public abstract class ContextSingleton { private static Context context; private static Context initContext() { try { Hashtable<String, Object> jndiProps = new Hashtable<>(); jndiProps.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming"); //RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean(); //List<String> arguments = runtimeMxBean.getInputArguments(); return new InitialContext(jndiProps); } catch (NamingException e) { System.err.println("Context initialization error." + e.getMessage()); return null; } } public static Context getContext() { if (context == null) { context = initContext(); } return context; } }
956
0.643305
0.643305
31
29.870968
25.54912
83
false
false
0
0
0
0
0
0
0.548387
false
false
10
67f3ff56bcc0e0076d08e2fae1162f1fadab5791
30,751,965,847,292
e47aebb5bea13012c94a52e281cb6e278d5cd712
/src/main/java/prj/datagen/MainTest1.java
9d2b98988c44d9fe023e7471c78df5f1ab61ae95
[ "MIT" ]
permissive
martincanaval/datagen
https://github.com/martincanaval/datagen
d848b6f4f0f49ebc69adfcbac5fec31c04d593f9
5796484685068326200a178fe479dccffeaf3998
refs/heads/master
2020-09-20T19:05:45.358000
2016-09-01T16:00:51
2016-09-01T16:00:51
67,145,923
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package prj.datagen; import org.fluttercode.datafactory.impl.DataFactory; public class MainTest1 { public static void main(String[] args) { DataFactory df = new DataFactory(); for (int i = 0; i < 100; i++) { String name = df.getFirstName() + " " + df.getLastName(); System.out.println(name); } } }
UTF-8
Java
382
java
MainTest1.java
Java
[]
null
[]
package prj.datagen; import org.fluttercode.datafactory.impl.DataFactory; public class MainTest1 { public static void main(String[] args) { DataFactory df = new DataFactory(); for (int i = 0; i < 100; i++) { String name = df.getFirstName() + " " + df.getLastName(); System.out.println(name); } } }
382
0.549738
0.536649
14
25.285715
22.603504
69
false
false
0
0
0
0
0
0
0.5
false
false
10
29a5ca957c0a0055b9d633355a7306fe12944aa0
27,109,833,604,712
e9affefd4e89b3c7e2064fee8833d7838c0e0abc
/aws-java-sdk-paymentcryptographydata/src/main/java/com/amazonaws/services/paymentcryptographydata/model/transform/SymmetricEncryptionAttributesMarshaller.java
6d69bc21998511dd096cc74c3cde28452f979d73
[ "Apache-2.0" ]
permissive
aws/aws-sdk-java
https://github.com/aws/aws-sdk-java
2c6199b12b47345b5d3c50e425dabba56e279190
bab987ab604575f41a76864f755f49386e3264b4
refs/heads/master
2023-08-29T10:49:07.379000
2023-08-28T21:05:55
2023-08-28T21:05:55
574,877
3,695
3,092
Apache-2.0
false
2023-09-13T23:35:28
2010-03-22T23:34:58
2023-09-13T22:30:40
2023-09-13T21:56:58
4,866,710
3,998
2,861
114
null
false
false
/* * Copyright 2018-2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.paymentcryptographydata.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.paymentcryptographydata.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * SymmetricEncryptionAttributesMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class SymmetricEncryptionAttributesMarshaller { private static final MarshallingInfo<String> INITIALIZATIONVECTOR_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("InitializationVector").build(); private static final MarshallingInfo<String> MODE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Mode").build(); private static final MarshallingInfo<String> PADDINGTYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("PaddingType").build(); private static final SymmetricEncryptionAttributesMarshaller instance = new SymmetricEncryptionAttributesMarshaller(); public static SymmetricEncryptionAttributesMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(SymmetricEncryptionAttributes symmetricEncryptionAttributes, ProtocolMarshaller protocolMarshaller) { if (symmetricEncryptionAttributes == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(symmetricEncryptionAttributes.getInitializationVector(), INITIALIZATIONVECTOR_BINDING); protocolMarshaller.marshall(symmetricEncryptionAttributes.getMode(), MODE_BINDING); protocolMarshaller.marshall(symmetricEncryptionAttributes.getPaddingType(), PADDINGTYPE_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
UTF-8
Java
2,790
java
SymmetricEncryptionAttributesMarshaller.java
Java
[]
null
[]
/* * Copyright 2018-2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.paymentcryptographydata.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.paymentcryptographydata.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * SymmetricEncryptionAttributesMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class SymmetricEncryptionAttributesMarshaller { private static final MarshallingInfo<String> INITIALIZATIONVECTOR_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("InitializationVector").build(); private static final MarshallingInfo<String> MODE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Mode").build(); private static final MarshallingInfo<String> PADDINGTYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("PaddingType").build(); private static final SymmetricEncryptionAttributesMarshaller instance = new SymmetricEncryptionAttributesMarshaller(); public static SymmetricEncryptionAttributesMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(SymmetricEncryptionAttributes symmetricEncryptionAttributes, ProtocolMarshaller protocolMarshaller) { if (symmetricEncryptionAttributes == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(symmetricEncryptionAttributes.getInitializationVector(), INITIALIZATIONVECTOR_BINDING); protocolMarshaller.marshall(symmetricEncryptionAttributes.getMode(), MODE_BINDING); protocolMarshaller.marshall(symmetricEncryptionAttributes.getPaddingType(), PADDINGTYPE_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
2,790
0.761649
0.757348
61
44.737705
46.019207
154
false
false
0
0
0
0
0
0
0.409836
false
false
10
c40736cfc248c60ccd63a1c81ad137c13714b43b
17,815,524,345,590
b6889db6692c033b17b8d42537f371a7f9355f4c
/fan-biz-service/src/main/java/com/genogram/service/impl/FanNewsTongpuPersonServiceImpl.java
826c58d65314acfb1147411cceebcc5eae916e07
[]
no_license
jackie19870917/genogram_cloud
https://github.com/jackie19870917/genogram_cloud
8a72d3cd99596ca8d2e3c7faf8828fa191d47462
2232279eda14386f2e7e5bd76336a309a2183d21
refs/heads/master
2020-04-24T07:50:04.925000
2019-02-20T08:57:26
2019-02-20T08:57:26
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.genogram.service.impl; import com.genogram.entity.FanNewsTongpuPerson; import com.genogram.mapper.FanNewsTongpuPersonMapper; import com.genogram.service.IFanNewsTongpuPersonService; import com.baomidou.mybatisplus.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** * <p> * 统谱资料-人物 服务实现类 * </p> * * @author wangwei * @since 2018-11-05 */ @Service public class FanNewsTongpuPersonServiceImpl extends ServiceImpl<FanNewsTongpuPersonMapper, FanNewsTongpuPerson> implements IFanNewsTongpuPersonService { }
UTF-8
Java
571
java
FanNewsTongpuPersonServiceImpl.java
Java
[ { "context": "\n/**\n * <p>\n * 统谱资料-人物 服务实现类\n * </p>\n *\n * @author wangwei\n * @since 2018-11-05\n */\n@Service\npublic class Fa", "end": 358, "score": 0.9994319081306458, "start": 351, "tag": "USERNAME", "value": "wangwei" } ]
null
[]
package com.genogram.service.impl; import com.genogram.entity.FanNewsTongpuPerson; import com.genogram.mapper.FanNewsTongpuPersonMapper; import com.genogram.service.IFanNewsTongpuPersonService; import com.baomidou.mybatisplus.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** * <p> * 统谱资料-人物 服务实现类 * </p> * * @author wangwei * @since 2018-11-05 */ @Service public class FanNewsTongpuPersonServiceImpl extends ServiceImpl<FanNewsTongpuPersonMapper, FanNewsTongpuPerson> implements IFanNewsTongpuPersonService { }
571
0.814208
0.799636
20
26.450001
35.312145
152
false
false
0
0
0
0
0
0
0.35
false
false
10
abbf4132b1bfc43a5f495df587a1607772987521
19,628,000,593,755
145b4d0eb76240fc9947b7fca168e763ffe09e1b
/common/model/src/main/java/oleg/sopilnyak/common/model/transport/HotelAgreementDto.java
0704ea8cd5f5d9104c92898d5b050722964fc275
[]
no_license
OlegSopilnyak/hotel-pms
https://github.com/OlegSopilnyak/hotel-pms
b9c78ffdc69a48b9e550fd487ddecbccea9003a4
f1539e243f091fb4a1fdea1cde0e69b5a20a6a94
refs/heads/master
2021-01-20T09:46:12.734000
2017-09-12T17:59:14
2017-09-12T17:59:14
100,206,106
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package oleg.sopilnyak.common.model.transport; import lombok.*; import oleg.sopilnyak.common.model.business.Guest; import oleg.sopilnyak.common.model.business.HotelAgreement; import java.time.LocalDateTime; import java.util.LinkedHashSet; import java.util.Set; /** * Transport Model type for manage agreements with guests */ @Data @EqualsAndHashCode(of = {"id"}) @ToString(of = {"id", "createdAt"}) public class HotelAgreementDto implements HotelAgreement{ private static final long serialVersionUID = 727687912955790115L; private String id; private LocalDateTime createdAt; private ReservationDto reservation = new ReservationDto(); private HabitationDto habitation = new HabitationDto(); private CreditCardDto card = new CreditCardDto(); @Getter(AccessLevel.NONE) private Set guestSet = new LinkedHashSet<>(); // private Set<GuestDto> guestSet = new LinkedHashSet<>(); @SuppressWarnings("unchecked") public Set<Guest> getGuestSet(){ return guestSet; } }
UTF-8
Java
1,053
java
HotelAgreementDto.java
Java
[]
null
[]
package oleg.sopilnyak.common.model.transport; import lombok.*; import oleg.sopilnyak.common.model.business.Guest; import oleg.sopilnyak.common.model.business.HotelAgreement; import java.time.LocalDateTime; import java.util.LinkedHashSet; import java.util.Set; /** * Transport Model type for manage agreements with guests */ @Data @EqualsAndHashCode(of = {"id"}) @ToString(of = {"id", "createdAt"}) public class HotelAgreementDto implements HotelAgreement{ private static final long serialVersionUID = 727687912955790115L; private String id; private LocalDateTime createdAt; private ReservationDto reservation = new ReservationDto(); private HabitationDto habitation = new HabitationDto(); private CreditCardDto card = new CreditCardDto(); @Getter(AccessLevel.NONE) private Set guestSet = new LinkedHashSet<>(); // private Set<GuestDto> guestSet = new LinkedHashSet<>(); @SuppressWarnings("unchecked") public Set<Guest> getGuestSet(){ return guestSet; } }
1,053
0.721747
0.704653
32
30.90625
22.411436
69
false
false
0
0
0
0
0
0
0.53125
false
false
10
2c7758787cedb86d0bf2c3e4c088e7e8692bea76
4,776,003,671,943
795de4c47e623201ac7779ea889c2a8638db3a68
/src/test/java/com/unistore/product/controller/PriceControllerTest.java
4ca2bb3dd4f4322bf6f131a6a763a3a729a3161d
[]
no_license
ramabhay/product
https://github.com/ramabhay/product
633f970b8ed9deff1624d7cee468bc4750b68750
f67832e371fc65624be706db50e700307bd2b51d
refs/heads/master
2021-05-21T04:23:00.913000
2020-04-12T17:40:21
2020-04-12T17:40:21
252,540,743
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.unistore.product.controller; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class PriceControllerTest { @Test void postProductPrice() { } }
UTF-8
Java
206
java
PriceControllerTest.java
Java
[]
null
[]
package com.unistore.product.controller; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class PriceControllerTest { @Test void postProductPrice() { } }
206
0.73301
0.73301
13
14.923077
17.406725
49
false
false
0
0
0
0
0
0
0.230769
false
false
10
01dd9779caf7af244ade8fb9848eb7b92040d5f2
11,510,512,383,306
5862b50a9745b032996aec6453ea06abf437ac2f
/app/src/main/java/br/com/fiap/app/sektorapp/LoginActivity.java
8bf32d6a7380e41ed36f8f2e2cd66b47b86646eb
[]
no_license
Brunier/FiapAndroid2016
https://github.com/Brunier/FiapAndroid2016
7b87384495bb06380967bee59b81933acd336f29
fbbbb0548311b45ba55016a74e70f31c3d4e2e8f
refs/heads/master
2021-01-17T15:09:31.026000
2016-10-08T01:33:53
2016-10-08T01:33:53
69,679,555
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.fiap.app.sektorapp; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.preference.PreferenceManager; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.CheckBox; import android.widget.EditText; import org.json.JSONObject; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.concurrent.ExecutionException; import br.com.fiap.java.helpers.WebServiceHelper; import br.com.fiap.java.helpers.WebservicesUrl; public class LoginActivity extends AppCompatActivity { private EditText email; private EditText senha; private CheckBox cbConectado; private SharedPreferences sp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(getString(R.string.login)); setContentView(R.layout.activity_login); sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); Log.d("debugManeiro", sp.getString("conectado", "false")); if(sp.getString("conectado", "false").equals("true")) { Intent noticias = new Intent(LoginActivity.this, NoticiasActionBar.class); startActivity(noticias); finish(); } email = (EditText) findViewById(R.id.edtEmail); senha = (EditText) findViewById(R.id.edtSenha); cbConectado = (CheckBox) findViewById(R.id.cbConectado); } public void login(View v) { AuthTask task = new AuthTask(); task.execute(email.getText().toString(), senha.getText().toString()); } public void criarConta(View v) { Intent cadastro = new Intent(LoginActivity.this, CadastroActivity.class); startActivity(cadastro); } private class AuthTask extends AsyncTask<String, Void, String> { private ProgressDialog progress; @Override protected void onPreExecute() { progress = ProgressDialog.show(LoginActivity.this, getString(R.string.aguarde), getString(R.string.realizando_login)); super.onPreExecute(); } @Override protected String doInBackground(String... params) { try { JSONObject auth = new JSONObject(); auth.put("email", params[0]); auth.put("senha", params[1]); return WebServiceHelper.postRequest(WebservicesUrl.Login.getUrl(), auth); } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String s) { progress.dismiss(); if(s != null) { try{ JSONObject res = new JSONObject(s); //Falha no login if (res.getString("success").equals("false")) { new AlertDialog.Builder(LoginActivity.this).setTitle(getString(R.string.falha_login)).setMessage(getString(R.string.incorreto)).show(); } else { SharedPreferences.Editor e= sp.edit(); if(cbConectado.isChecked()) { e.putString("conectado", "true"); } else { e.putString("conectado", "false"); } e.apply(); Intent noticias = new Intent(LoginActivity.this, NoticiasActionBar.class); startActivity(noticias); finish(); } }catch (Exception e) { e.printStackTrace(); } } } } }
UTF-8
Java
4,172
java
LoginActivity.java
Java
[]
null
[]
package br.com.fiap.app.sektorapp; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.preference.PreferenceManager; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.CheckBox; import android.widget.EditText; import org.json.JSONObject; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.concurrent.ExecutionException; import br.com.fiap.java.helpers.WebServiceHelper; import br.com.fiap.java.helpers.WebservicesUrl; public class LoginActivity extends AppCompatActivity { private EditText email; private EditText senha; private CheckBox cbConectado; private SharedPreferences sp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(getString(R.string.login)); setContentView(R.layout.activity_login); sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); Log.d("debugManeiro", sp.getString("conectado", "false")); if(sp.getString("conectado", "false").equals("true")) { Intent noticias = new Intent(LoginActivity.this, NoticiasActionBar.class); startActivity(noticias); finish(); } email = (EditText) findViewById(R.id.edtEmail); senha = (EditText) findViewById(R.id.edtSenha); cbConectado = (CheckBox) findViewById(R.id.cbConectado); } public void login(View v) { AuthTask task = new AuthTask(); task.execute(email.getText().toString(), senha.getText().toString()); } public void criarConta(View v) { Intent cadastro = new Intent(LoginActivity.this, CadastroActivity.class); startActivity(cadastro); } private class AuthTask extends AsyncTask<String, Void, String> { private ProgressDialog progress; @Override protected void onPreExecute() { progress = ProgressDialog.show(LoginActivity.this, getString(R.string.aguarde), getString(R.string.realizando_login)); super.onPreExecute(); } @Override protected String doInBackground(String... params) { try { JSONObject auth = new JSONObject(); auth.put("email", params[0]); auth.put("senha", params[1]); return WebServiceHelper.postRequest(WebservicesUrl.Login.getUrl(), auth); } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String s) { progress.dismiss(); if(s != null) { try{ JSONObject res = new JSONObject(s); //Falha no login if (res.getString("success").equals("false")) { new AlertDialog.Builder(LoginActivity.this).setTitle(getString(R.string.falha_login)).setMessage(getString(R.string.incorreto)).show(); } else { SharedPreferences.Editor e= sp.edit(); if(cbConectado.isChecked()) { e.putString("conectado", "true"); } else { e.putString("conectado", "false"); } e.apply(); Intent noticias = new Intent(LoginActivity.this, NoticiasActionBar.class); startActivity(noticias); finish(); } }catch (Exception e) { e.printStackTrace(); } } } } }
4,172
0.610738
0.609779
127
31.850393
27.019993
159
false
false
0
0
0
0
0
0
0.645669
false
false
10
211ef16b272720871686b79c1e77f20c1b8ced15
10,960,756,545,936
c659f5a1b2a895dd35068818f25648da78524c8c
/src/test/java/C3/C3Testing/StepDef.java
1b367f76a8734979c48a7e896cf0d34b7e5125ca
[]
no_license
ssankhe1/ATDD
https://github.com/ssankhe1/ATDD
f27f581e96426b84e7440fe8f10f05cb28d881ba
34005a19851b30d285b58e6ec35cf5fbd42c74a0
refs/heads/master
2021-01-11T16:17:23.395000
2017-05-03T20:42:51
2017-05-03T20:42:51
80,057,422
1
0
null
false
2017-04-17T21:29:09
2017-01-25T21:00:18
2017-02-14T20:08:55
2017-04-17T21:29:09
147
1
0
0
Java
null
null
package C3.C3Testing; import java.io.File; import java.io.FileInputStream; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.junit.Assert; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.WebDriverWait; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; public class StepDef extends TestingExcel{ public WebDriver driver = new FirefoxDriver(); public static String Assessment="/html/body/div[2]/div[1]/span[1]/div/div/ul/li[10]/a/span"; public static String Provider="/html/body/div[2]/div[1]/span[1]/div/div/ul/li[3]"; public static String MemberDetail="/html/body/div[2]/div[1]/span[1]/div/div/ul/li[2]"; public String username; public String password; @Given("^I want to write a step with precondition$") public void i_want_to_write_a_step_with_precondition() throws Throwable { // Write code here that turns the phrase above into concrete actions System.out.println("Helloworld- This is a Given Statement"); Login(); } @When("^I complete action$") public void i_complete_action() throws Throwable { // Write code here that turns the phrase above into concrete actions System.out.println("Helloworld- This is a When Statement"); SearchMember(); } @Then("^I validate the outcomes$") public void i_validate_the_outcomes() throws Throwable { // Write code here that turns the phrase above into concrete actions System.out.println("Helloworld- This is a Then Statement"); ClickAssessment(); driver.close(); } private WebDriver Login() { // TODO Auto-generated method stub System.out.println("I am in Login"); driver.get("http://icuealpha.uhc.com/icue/index.jsp"); //Read from Excel try { // Specify the path of file File src=new File("C:\\Users\\ssankhe1\\workspacemars\\C3Testing\\src\\test\\DataSheets\\TestData.xlsx"); // load file FileInputStream fis=new FileInputStream(src); // Load workbook XSSFWorkbook wb=new XSSFWorkbook(fis); // Load sheet- Here we are loading first sheetonly XSSFSheet sh1= wb.getSheetAt(0); // getRow() specify which row we want to read. // and getCell() specify which column to read. // getStringCellValue() specify that we are reading String data. username = sh1.getRow(0).getCell(0).getStringCellValue(); password = sh1.getRow(1).getCell(1).getStringCellValue(); System.out.println(username); System.out.println(password); } catch (Exception e) { System.out.println(e.getMessage()); } driver.findElement(By.id("userID")).sendKeys("SSANKHE1"); driver.findElement(By.id("password")).sendKeys("Spring123$%"); driver.findElement(By.name("action")).click(); return driver; } protected WebDriver SearchMember() { // TODO Auto-generated method stub System.out.println("I am in SearchMember"); driver.findElement(By.id("7")).click(); waitForPageLoaded(); driver.findElement(By.id("memberIDTextmbrIdSearch")).sendKeys("00999072010"); driver.findElement(By.name("PerformAction")).click(); driver.findElement(By.xpath("/html/body/div[2]/div/form/div[3]/div/div/div/div/div[1]/div[2]/div/div/table/tbody/tr[1]/td[2]/div/a")).click(); return driver; } private WebDriver ClickAssessment() { driver.findElement(By.xpath(Assessment)).click(); //driver.findElement(By.xpath(Provider)).click(); //driver.findElement(By.xpath(MemberDetail)).click(); //driver.getPageSource().contains("ACO Network Name:"); return driver; // TODO Auto-generated method stub } private WebDriver waitForPageLoaded() { ExpectedCondition<Boolean> expectation = new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver driver) { return ((JavascriptExecutor) driver).executeScript("return document.readyState").toString().equals("complete"); } }; try { Thread.sleep(3000); WebDriverWait wait = new WebDriverWait(driver, 30); wait.until(expectation); } catch (Throwable error) { Assert.fail("Timeout waiting for Page Load Request to complete."); } return driver; } }
UTF-8
Java
4,648
java
StepDef.java
Java
[ { "context": "path of file\n \t File src=new File(\"C:\\\\Users\\\\ssankhe1\\\\workspacemars\\\\C3Testing\\\\src\\\\test\\\\DataSheets\\", "end": 2079, "score": 0.9967430233955383, "start": 2071, "tag": "USERNAME", "value": "ssankhe1" }, { "context": " driver.findElement(By.id(\"userID\")).sendKeys(\"SSANKHE1\");\n driver.findElement(By.id(\"password\")).send", "end": 3002, "score": 0.9976987242698669, "start": 2994, "tag": "USERNAME", "value": "SSANKHE1" }, { "context": " driver.findElement(By.id(\"password\")).sendKeys(\"Spring123$%\");\n driver.findElement(By.name(\"action\")).clic", "end": 3067, "score": 0.9993863701820374, "start": 3058, "tag": "PASSWORD", "value": "Spring123" } ]
null
[]
package C3.C3Testing; import java.io.File; import java.io.FileInputStream; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.junit.Assert; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.WebDriverWait; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; public class StepDef extends TestingExcel{ public WebDriver driver = new FirefoxDriver(); public static String Assessment="/html/body/div[2]/div[1]/span[1]/div/div/ul/li[10]/a/span"; public static String Provider="/html/body/div[2]/div[1]/span[1]/div/div/ul/li[3]"; public static String MemberDetail="/html/body/div[2]/div[1]/span[1]/div/div/ul/li[2]"; public String username; public String password; @Given("^I want to write a step with precondition$") public void i_want_to_write_a_step_with_precondition() throws Throwable { // Write code here that turns the phrase above into concrete actions System.out.println("Helloworld- This is a Given Statement"); Login(); } @When("^I complete action$") public void i_complete_action() throws Throwable { // Write code here that turns the phrase above into concrete actions System.out.println("Helloworld- This is a When Statement"); SearchMember(); } @Then("^I validate the outcomes$") public void i_validate_the_outcomes() throws Throwable { // Write code here that turns the phrase above into concrete actions System.out.println("Helloworld- This is a Then Statement"); ClickAssessment(); driver.close(); } private WebDriver Login() { // TODO Auto-generated method stub System.out.println("I am in Login"); driver.get("http://icuealpha.uhc.com/icue/index.jsp"); //Read from Excel try { // Specify the path of file File src=new File("C:\\Users\\ssankhe1\\workspacemars\\C3Testing\\src\\test\\DataSheets\\TestData.xlsx"); // load file FileInputStream fis=new FileInputStream(src); // Load workbook XSSFWorkbook wb=new XSSFWorkbook(fis); // Load sheet- Here we are loading first sheetonly XSSFSheet sh1= wb.getSheetAt(0); // getRow() specify which row we want to read. // and getCell() specify which column to read. // getStringCellValue() specify that we are reading String data. username = sh1.getRow(0).getCell(0).getStringCellValue(); password = sh1.getRow(1).getCell(1).getStringCellValue(); System.out.println(username); System.out.println(password); } catch (Exception e) { System.out.println(e.getMessage()); } driver.findElement(By.id("userID")).sendKeys("SSANKHE1"); driver.findElement(By.id("password")).sendKeys("<PASSWORD>$%"); driver.findElement(By.name("action")).click(); return driver; } protected WebDriver SearchMember() { // TODO Auto-generated method stub System.out.println("I am in SearchMember"); driver.findElement(By.id("7")).click(); waitForPageLoaded(); driver.findElement(By.id("memberIDTextmbrIdSearch")).sendKeys("00999072010"); driver.findElement(By.name("PerformAction")).click(); driver.findElement(By.xpath("/html/body/div[2]/div/form/div[3]/div/div/div/div/div[1]/div[2]/div/div/table/tbody/tr[1]/td[2]/div/a")).click(); return driver; } private WebDriver ClickAssessment() { driver.findElement(By.xpath(Assessment)).click(); //driver.findElement(By.xpath(Provider)).click(); //driver.findElement(By.xpath(MemberDetail)).click(); //driver.getPageSource().contains("ACO Network Name:"); return driver; // TODO Auto-generated method stub } private WebDriver waitForPageLoaded() { ExpectedCondition<Boolean> expectation = new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver driver) { return ((JavascriptExecutor) driver).executeScript("return document.readyState").toString().equals("complete"); } }; try { Thread.sleep(3000); WebDriverWait wait = new WebDriverWait(driver, 30); wait.until(expectation); } catch (Throwable error) { Assert.fail("Timeout waiting for Page Load Request to complete."); } return driver; } }
4,649
0.671687
0.660284
122
37.106556
27.812254
146
false
false
0
0
0
0
0
0
0.942623
false
false
10
003ec4c5555c72760cf65aaae778e393a68030e9
10,960,756,545,327
3d64db65f032080207f5b3ce0320b8ee319c8d3e
/tools/src/main/java/com/rake/rakeapi/tools/queue/QueueState.java
08aad46db1d0005768d9916cbcacd1677dd2ad41
[]
no_license
skpdi/rakeapi-java
https://github.com/skpdi/rakeapi-java
1d1015844395a3f3d301bd048fe4e6e4fd2c2a0b
e2655049f25d4f6ce0b1db87b6a2858db7d5bcc2
refs/heads/master
2016-09-15T17:41:06.991000
2016-08-26T06:19:15
2016-08-26T06:19:15
64,652,112
3
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rake.rakeapi.tools.queue; import com.rake.rakeapi.queue.FileBlockingQueue; public class QueueState { private String promptPrefix; private String prompt; private String promptSuffix; private String queueDir; private FileBlockingQueue<String> fileBlockingQueue; private boolean isOpened; public QueueState() { setPromptPrefix(" "); setPromptSuffix("> "); setPrompt(""); } public String getAllPrompt() { return getPromptPrefix() + getPrompt() + getPromptSuffix(); } public String getPromptPrefix() { return promptPrefix; } public void setPromptPrefix(String promptPrefix) { this.promptPrefix = promptPrefix; } public String getPrompt() { return prompt; } public void setPrompt(String prompt) { this.prompt = prompt; } public String getPromptSuffix() { return promptSuffix; } public void setPromptSuffix(String promptSuffix) { this.promptSuffix = promptSuffix; } public String getQueueDir() { return queueDir; } public void setQueueDir(String queueDir) { this.queueDir = queueDir; } public FileBlockingQueue<String> getFileBlockingQueue() { return fileBlockingQueue; } public void setFileBlockingQueue(FileBlockingQueue<String> fileBlockingQueue) { this.fileBlockingQueue = fileBlockingQueue; } public boolean isOpened() { return isOpened; } public void setOpened(boolean isOpened) { this.isOpened = isOpened; } }
UTF-8
Java
1,602
java
QueueState.java
Java
[]
null
[]
package com.rake.rakeapi.tools.queue; import com.rake.rakeapi.queue.FileBlockingQueue; public class QueueState { private String promptPrefix; private String prompt; private String promptSuffix; private String queueDir; private FileBlockingQueue<String> fileBlockingQueue; private boolean isOpened; public QueueState() { setPromptPrefix(" "); setPromptSuffix("> "); setPrompt(""); } public String getAllPrompt() { return getPromptPrefix() + getPrompt() + getPromptSuffix(); } public String getPromptPrefix() { return promptPrefix; } public void setPromptPrefix(String promptPrefix) { this.promptPrefix = promptPrefix; } public String getPrompt() { return prompt; } public void setPrompt(String prompt) { this.prompt = prompt; } public String getPromptSuffix() { return promptSuffix; } public void setPromptSuffix(String promptSuffix) { this.promptSuffix = promptSuffix; } public String getQueueDir() { return queueDir; } public void setQueueDir(String queueDir) { this.queueDir = queueDir; } public FileBlockingQueue<String> getFileBlockingQueue() { return fileBlockingQueue; } public void setFileBlockingQueue(FileBlockingQueue<String> fileBlockingQueue) { this.fileBlockingQueue = fileBlockingQueue; } public boolean isOpened() { return isOpened; } public void setOpened(boolean isOpened) { this.isOpened = isOpened; } }
1,602
0.655431
0.655431
70
21.885714
20.167543
83
false
false
0
0
0
0
0
0
0.342857
false
false
10
340279801e53c0d79f0fd7e3b6532a9711dfeef8
19,842,748,942,660
8cb4592d165aae53d43f8ead302360a6cac33fb9
/src/service/Studentservice.java
2d41293607eb8b1f427d228b5500ff3ee8d5ff1b
[]
no_license
Srividya19715/iihtdemo
https://github.com/Srividya19715/iihtdemo
344464ef60270d56dc794b99f7da3a5e37a31def
8b3ce30e629ed37f126ddee34788d8eb6458eced
refs/heads/master
2023-08-16T17:09:43.208000
2021-10-07T13:34:50
2021-10-07T13:34:50
412,705,811
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package service; import java.util.List; import entity.Student; import exception.ServiceException; public interface Studentservice { public boolean insertrecord( List <Student>s) throws ServiceException; }
UTF-8
Java
227
java
Studentservice.java
Java
[]
null
[]
package service; import java.util.List; import entity.Student; import exception.ServiceException; public interface Studentservice { public boolean insertrecord( List <Student>s) throws ServiceException; }
227
0.748899
0.748899
13
15.461538
20.390856
71
false
false
0
0
0
0
0
0
0.615385
false
false
10
d451a6b150fb98970e7baf51c644b8bde0ba99a8
16,698,832,906,089
58c93922cf4c40dd3f3c21fdcf153e85a7840a41
/src/kr/co/howfarhaveyoubeen/www/handler/dao/file/FileDAO.java
c56deeb5094dd0ace8db6140406d7913771afb20
[]
no_license
kkw01234/Howfarhaveyoubeen
https://github.com/kkw01234/Howfarhaveyoubeen
dbc875c31d3262a1a8a1613e813b41d9d222d15e
4cd0b8856031628751e8b309c3b25888dd1849d1
refs/heads/master
2020-04-05T04:17:49.663000
2019-07-07T15:03:12
2019-07-07T15:03:12
156,545,361
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package kr.co.howfarhaveyoubeen.www.handler.dao.file; import java.io.File; import javax.servlet.http.HttpServletRequest; public class FileDAO { public static FileDAO it; public static FileDAO getInstance() { if(it == null) it = new FileDAO(); return it; } public boolean deleteFile(String fileurl, HttpServletRequest request) { // 부적절하거나 취소를 누를경우 파일을 삭제시키는 코드 String filename; String path = request.getServletContext().getRealPath("/image/ticket"); int index = fileurl.lastIndexOf("/"); if(index==-1) { filename = fileurl; }else filename = fileurl.substring(index+1); System.out.println(filename); try { File deletefile = new File(path,filename); deletefile.delete(); return true; }catch(Exception e){ e.printStackTrace(); } return false; } }
UTF-8
Java
849
java
FileDAO.java
Java
[]
null
[]
package kr.co.howfarhaveyoubeen.www.handler.dao.file; import java.io.File; import javax.servlet.http.HttpServletRequest; public class FileDAO { public static FileDAO it; public static FileDAO getInstance() { if(it == null) it = new FileDAO(); return it; } public boolean deleteFile(String fileurl, HttpServletRequest request) { // 부적절하거나 취소를 누를경우 파일을 삭제시키는 코드 String filename; String path = request.getServletContext().getRealPath("/image/ticket"); int index = fileurl.lastIndexOf("/"); if(index==-1) { filename = fileurl; }else filename = fileurl.substring(index+1); System.out.println(filename); try { File deletefile = new File(path,filename); deletefile.delete(); return true; }catch(Exception e){ e.printStackTrace(); } return false; } }
849
0.701121
0.69863
34
22.617647
22.417187
105
false
false
0
0
0
0
0
0
2.147059
false
false
10
5451cd208170ff23e57728bfbe8d34672f4ad70b
7,662,221,708,298
a5b911fc31880df18f5acb440d0f5650b734286b
/app/src/main/java/events/jarvi/events/common/BaseView.java
0356b0e05fb91b7ba38fca8a5d32a272dab05d33
[]
no_license
alexmalishev270896/events
https://github.com/alexmalishev270896/events
6a91634fcf2c61bb4ffe0763067dfe3e7a05987e
bccb036f8c4a79ba6c19ccb4f7128b39dfe04619
refs/heads/master
2019-08-31T17:32:03.653000
2017-07-25T12:33:36
2017-07-25T12:33:36
98,196,200
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package events.jarvi.events.common; /** * Created by jarvi on 01.06.2017. */ public interface BaseView { }
UTF-8
Java
111
java
BaseView.java
Java
[ { "context": "age events.jarvi.events.common;\n\n/**\n * Created by jarvi on 01.06.2017.\n */\n\npublic interface BaseView {\n}", "end": 60, "score": 0.9987505674362183, "start": 55, "tag": "USERNAME", "value": "jarvi" } ]
null
[]
package events.jarvi.events.common; /** * Created by jarvi on 01.06.2017. */ public interface BaseView { }
111
0.693694
0.621622
8
12.875
15.011974
35
false
false
0
0
0
0
0
0
0.125
false
false
10
ff4d244e19cb0099d112ae49d5924434c446f08d
2,216,203,148,365
6f3f2ce686c4d48cb13a6fa4244d55efce49dd82
/Proyecto_De_Luz/Interfaz_Grafica_Nivel_Medio/src/com/starbucks/sistema/venta/graficas/Dialogs/ListaDeClientesModificar.java
66c604241b19096f104a140d4e34abe44b56082a
[]
no_license
Joaquin121416/Proyecto_Lenguaje_De_Programacion_I
https://github.com/Joaquin121416/Proyecto_Lenguaje_De_Programacion_I
906805de97c413d1e85da9a2540ddc27a4c123cc
e1bb87deea5ac8607cc4d0a50ba38e4865473596
refs/heads/master
2020-08-04T04:55:04.068000
2019-10-01T04:45:19
2019-10-01T04:45:19
212,014,004
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.starbucks.sistema.venta.graficas.Dialogs; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumnModel; import com.mysql.jdbc.PreparedStatement; import com.starbucks.sistema.venta.datos.utils.MySQLConexion; import com.starbucks.sistema.venta.logica.Hilaso.HiloActualizar; import com.starbucks.sistema.venta.logica.Mantenimiento.GestionCliente; @SuppressWarnings("serial") public class ListaDeClientesModificar extends JDialog implements ActionListener { private static JTable tblClientes; private JScrollPane scrollPane; private JLabel lblImagen; private JButton btnModificar; private JButton btnSalir; private GestionCliente ge = new GestionCliente(); private JButton btnBorrar; static DefaultTableModel model; static DefaultTableModel modelCambiante; /** * Launch the application. */ public static void main(String[] args) { try { ListaDeClientesModificar dialog = new ListaDeClientesModificar(); dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); dialog.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } /** * Create the dialog. */ public ListaDeClientesModificar() { setUndecorated(true); setBounds(100, 100, 800, 550); getContentPane().setLayout(null); scrollPane = new JScrollPane(); scrollPane.setBounds(22, 11, 600, 528); getContentPane().add(scrollPane); Cargar(); tblClientes = new JTable(model); tblClientes.setFont(new Font("Tahoma", Font.PLAIN, 11)); // tblProductos.setModel(model); tblClientes.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); tblClientes.setFillsViewportHeight(true); tblClientes.getSelectionModel().setSelectionInterval(0, 0); tblClientes.getTableHeader().setReorderingAllowed(false); tblClientes.setDefaultEditor(Object.class, null); scrollPane.setViewportView(tblClientes); lblImagen = new JLabel(""); lblImagen.setIcon(new ImageIcon(ListaDeClientesModificar.class.getResource("/data/imgpro1.jpg"))); lblImagen.setBounds(632, 18, 158, 135); getContentPane().add(lblImagen); btnModificar = new JButton("Modificar"); btnModificar.addActionListener(this); btnModificar.setBounds(632, 163, 158, 49); getContentPane().add(btnModificar); btnSalir = new JButton("Salir"); btnSalir.addActionListener(this); btnSalir.setBounds(632, 335, 158, 49); getContentPane().add(btnSalir); btnBorrar = new JButton("Borrar"); btnBorrar.addActionListener(this); btnBorrar.setBounds(632, 250, 158, 49); getContentPane().add(btnBorrar); } int anchoColumna(int porcentaje) { return porcentaje * scrollPane.getWidth() / 100; } void ajustarAnchoColumnas() { TableColumnModel tcm = tblClientes.getColumnModel(); tcm.getColumn(0).setPreferredWidth(anchoColumna(7)); // numero tcm.getColumn(1).setPreferredWidth(anchoColumna(12)); // categoria tcm.getColumn(2).setPreferredWidth(anchoColumna(4)); // estado } public void actionPerformed(ActionEvent arg0) { if (arg0.getSource() == btnBorrar) { actionPerformedBtnBorrar(arg0); } if (arg0.getSource() == btnModificar) { actionPerformedBtnModificar(arg0); } if (arg0.getSource() == btnSalir) { actionPerformedBtnSalir(arg0); } } protected void actionPerformedBtnSalir(ActionEvent arg0) { ge.listado(); dispose(); } protected void actionPerformedBtnModificar(ActionEvent arg0) { try { int fila = tblClientes.getSelectedRow(); String dato = String.valueOf(tblClientes.getValueAt(fila, 0)); String codigo = dato; ModificarCliente mocl = new ModificarCliente(codigo); mocl.setVisible(true); mocl.setLocationRelativeTo(null); } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "Error al intentar Modificar", "Error", JOptionPane.ERROR_MESSAGE); } } protected void actionPerformedBtnBorrar(ActionEvent arg0) { try { int fila = tblClientes.getSelectedRow(); String dato = String.valueOf(tblClientes.getValueAt(fila, 0)); String codigo = dato; ge.Eliminar(codigo); HiloActualizar h = new HiloActualizar(); h.run(3); JOptionPane.showMessageDialog(null, "Se Borro con exito"); } catch (Exception e) { // e.printStackTrace(); JOptionPane.showMessageDialog(null, "Error al intentar Borrar", "Error", JOptionPane.ERROR_MESSAGE); } } public static void Cambiar() { tblClientes.setModel(modelCambiante); } public static void Cargar() { model = new DefaultTableModel(); model.addColumn("Codigo"); model.addColumn("Nombre"); model.addColumn("Apellidos"); model.addColumn("Tipo de Cliente"); model.addColumn("Puntos"); ResultSet rs = null; Connection con = null; PreparedStatement pst = null; try { con = MySQLConexion.getConexion(); String sql = "select `id_cliente`,`nombre`,`apellido`,tipo_cliente,nmr_puntos from TB_Cliente"; pst = (PreparedStatement) con.prepareStatement(sql); rs = pst.executeQuery(); try { while (rs.next()) { Object[] fila = new Object[5]; for (int i = 0; i < 5; i++) try { if (i == 3) { int Condicion = rs.getInt(i + 1); if (Condicion == 0) { fila[i] = "Comun"; } else { fila[i] = "Empresarial"; } } else { fila[i] = rs.getObject(i + 1); } } catch (SQLException e) { e.printStackTrace(); } model.addRow(fila); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (Exception e) { System.out.println("Error en la sentencia"); e.printStackTrace(); } finally { try { if (pst != null) pst.close(); if (con != null) con.close(); } catch (SQLException e) { System.out.println("Error al cerrar"); } } modelCambiante = model; model.fireTableDataChanged(); } }
UTF-8
Java
6,265
java
ListaDeClientesModificar.java
Java
[]
null
[]
package com.starbucks.sistema.venta.graficas.Dialogs; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumnModel; import com.mysql.jdbc.PreparedStatement; import com.starbucks.sistema.venta.datos.utils.MySQLConexion; import com.starbucks.sistema.venta.logica.Hilaso.HiloActualizar; import com.starbucks.sistema.venta.logica.Mantenimiento.GestionCliente; @SuppressWarnings("serial") public class ListaDeClientesModificar extends JDialog implements ActionListener { private static JTable tblClientes; private JScrollPane scrollPane; private JLabel lblImagen; private JButton btnModificar; private JButton btnSalir; private GestionCliente ge = new GestionCliente(); private JButton btnBorrar; static DefaultTableModel model; static DefaultTableModel modelCambiante; /** * Launch the application. */ public static void main(String[] args) { try { ListaDeClientesModificar dialog = new ListaDeClientesModificar(); dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); dialog.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } /** * Create the dialog. */ public ListaDeClientesModificar() { setUndecorated(true); setBounds(100, 100, 800, 550); getContentPane().setLayout(null); scrollPane = new JScrollPane(); scrollPane.setBounds(22, 11, 600, 528); getContentPane().add(scrollPane); Cargar(); tblClientes = new JTable(model); tblClientes.setFont(new Font("Tahoma", Font.PLAIN, 11)); // tblProductos.setModel(model); tblClientes.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); tblClientes.setFillsViewportHeight(true); tblClientes.getSelectionModel().setSelectionInterval(0, 0); tblClientes.getTableHeader().setReorderingAllowed(false); tblClientes.setDefaultEditor(Object.class, null); scrollPane.setViewportView(tblClientes); lblImagen = new JLabel(""); lblImagen.setIcon(new ImageIcon(ListaDeClientesModificar.class.getResource("/data/imgpro1.jpg"))); lblImagen.setBounds(632, 18, 158, 135); getContentPane().add(lblImagen); btnModificar = new JButton("Modificar"); btnModificar.addActionListener(this); btnModificar.setBounds(632, 163, 158, 49); getContentPane().add(btnModificar); btnSalir = new JButton("Salir"); btnSalir.addActionListener(this); btnSalir.setBounds(632, 335, 158, 49); getContentPane().add(btnSalir); btnBorrar = new JButton("Borrar"); btnBorrar.addActionListener(this); btnBorrar.setBounds(632, 250, 158, 49); getContentPane().add(btnBorrar); } int anchoColumna(int porcentaje) { return porcentaje * scrollPane.getWidth() / 100; } void ajustarAnchoColumnas() { TableColumnModel tcm = tblClientes.getColumnModel(); tcm.getColumn(0).setPreferredWidth(anchoColumna(7)); // numero tcm.getColumn(1).setPreferredWidth(anchoColumna(12)); // categoria tcm.getColumn(2).setPreferredWidth(anchoColumna(4)); // estado } public void actionPerformed(ActionEvent arg0) { if (arg0.getSource() == btnBorrar) { actionPerformedBtnBorrar(arg0); } if (arg0.getSource() == btnModificar) { actionPerformedBtnModificar(arg0); } if (arg0.getSource() == btnSalir) { actionPerformedBtnSalir(arg0); } } protected void actionPerformedBtnSalir(ActionEvent arg0) { ge.listado(); dispose(); } protected void actionPerformedBtnModificar(ActionEvent arg0) { try { int fila = tblClientes.getSelectedRow(); String dato = String.valueOf(tblClientes.getValueAt(fila, 0)); String codigo = dato; ModificarCliente mocl = new ModificarCliente(codigo); mocl.setVisible(true); mocl.setLocationRelativeTo(null); } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "Error al intentar Modificar", "Error", JOptionPane.ERROR_MESSAGE); } } protected void actionPerformedBtnBorrar(ActionEvent arg0) { try { int fila = tblClientes.getSelectedRow(); String dato = String.valueOf(tblClientes.getValueAt(fila, 0)); String codigo = dato; ge.Eliminar(codigo); HiloActualizar h = new HiloActualizar(); h.run(3); JOptionPane.showMessageDialog(null, "Se Borro con exito"); } catch (Exception e) { // e.printStackTrace(); JOptionPane.showMessageDialog(null, "Error al intentar Borrar", "Error", JOptionPane.ERROR_MESSAGE); } } public static void Cambiar() { tblClientes.setModel(modelCambiante); } public static void Cargar() { model = new DefaultTableModel(); model.addColumn("Codigo"); model.addColumn("Nombre"); model.addColumn("Apellidos"); model.addColumn("Tipo de Cliente"); model.addColumn("Puntos"); ResultSet rs = null; Connection con = null; PreparedStatement pst = null; try { con = MySQLConexion.getConexion(); String sql = "select `id_cliente`,`nombre`,`apellido`,tipo_cliente,nmr_puntos from TB_Cliente"; pst = (PreparedStatement) con.prepareStatement(sql); rs = pst.executeQuery(); try { while (rs.next()) { Object[] fila = new Object[5]; for (int i = 0; i < 5; i++) try { if (i == 3) { int Condicion = rs.getInt(i + 1); if (Condicion == 0) { fila[i] = "Comun"; } else { fila[i] = "Empresarial"; } } else { fila[i] = rs.getObject(i + 1); } } catch (SQLException e) { e.printStackTrace(); } model.addRow(fila); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (Exception e) { System.out.println("Error en la sentencia"); e.printStackTrace(); } finally { try { if (pst != null) pst.close(); if (con != null) con.close(); } catch (SQLException e) { System.out.println("Error al cerrar"); } } modelCambiante = model; model.fireTableDataChanged(); } }
6,265
0.711093
0.694972
237
25.434599
22.043325
106
false
false
0
0
0
0
0
0
2.527426
false
false
10
5c535e3fde47c08599126719d74e61a06952affc
20,916,490,763,064
15723262dd5ac594fc61978f5cd4c5796d92b678
/mq/rabbitmq/01-basic/src/main/java/com/s2u2m/study/mq/rabbitmq/basic/publisher/Publisher.java
82ef24905211026c8a7cfcb460c8e55b24624d2c
[]
no_license
xiayy860612/study
https://github.com/xiayy860612/study
2869a91b217a74a7c5436144c2d8e38cb9498e55
ffa31054219d1c807ce461f6c5e871fdd39446e1
refs/heads/main
2023-08-01T12:40:22.757000
2021-09-15T05:19:19
2021-09-15T05:19:19
341,821,477
0
0
null
false
2021-09-15T05:19:20
2021-02-24T07:53:08
2021-02-24T07:53:10
2021-09-15T05:19:19
2,256
0
0
0
null
false
false
package com.s2u2m.study.mq.rabbitmq.basic.publisher; import com.rabbitmq.client.*; import com.s2u2m.study.mq.rabbitmq.basic.RabbitMqConfig; import java.io.*; import java.util.*; import java.util.concurrent.TimeoutException; /** * - enable AE for missing msg, priority: AE > mandatory * - publish confirm */ public class Publisher { private Channel channel; private final SortedMap<Long, Msg> nackMsg = new TreeMap<>(); private static class Msg { private String queue; private Long deliveryTag; private String msg; private Integer sendAmount = 0; } public Publisher(Connection connection) throws IOException { channel = connection.createChannel(); enablePublishConfirm(channel); declareAe(channel); declareExAndQueue(channel); } private void enablePublishConfirm(Channel channel) throws IOException { channel.confirmSelect(); channel.addConfirmListener(this::ackCallback, this::nackCallback); } private void ackCallback(long deliveryTag, boolean multiple) { Collection<Msg> msgs; if (multiple) { msgs = nackMsg.headMap(deliveryTag).values(); nackMsg.headMap(deliveryTag).clear(); } else { msgs = Collections.singleton(nackMsg.get(deliveryTag)); nackMsg.remove(deliveryTag); } for (Msg msg : msgs) { System.out.printf("Send [%s][%s] Success\n", msg.deliveryTag, msg.msg); } } private void nackCallback(long deliveryTag, boolean multiple) throws IOException { Collection<Msg> msgs; if (multiple) { msgs = nackMsg.headMap(deliveryTag).values(); nackMsg.headMap(deliveryTag).clear(); } else { msgs = Collections.singleton(nackMsg.get(deliveryTag)); nackMsg.remove(deliveryTag); } // re-send for (Msg msg : msgs) { if (msg.sendAmount > 3) { System.out.printf("Re-Send touch max time, [%s][%s]\n", msg.deliveryTag, msg.msg); continue; } System.out.printf("Re-Send [%s][%s]\n", msg.deliveryTag, msg.msg); sendMsg(msg); } } private void declareExAndQueue(Channel channel) throws IOException { Map<String, Object> args = new HashMap<>(); args.put("alternate-exchange", RabbitMqConfig.BASIC_DEMO_AE); channel.exchangeDeclare(RabbitMqConfig.BASIC_DEMO_EX, BuiltinExchangeType.DIRECT, true, false, args); channel.queueDeclare( RabbitMqConfig.BASIC_DEMO_QUEUE, true, false, false, null); channel.queueBind(RabbitMqConfig.BASIC_DEMO_QUEUE, RabbitMqConfig.BASIC_DEMO_EX, RabbitMqConfig.BASIC_DEMO_QUEUE); channel.queueDeclare( RabbitMqConfig.BASIC_DEMO_QUEUE_2, true, false, false, null); channel.queueBind(RabbitMqConfig.BASIC_DEMO_QUEUE_2, RabbitMqConfig.BASIC_DEMO_EX, RabbitMqConfig.BASIC_DEMO_QUEUE_2); } private void declareAe(Channel channel) throws IOException { channel.exchangeDeclare(RabbitMqConfig.BASIC_DEMO_AE, BuiltinExchangeType.FANOUT, true, false, null); channel.queueDeclare(RabbitMqConfig.BASIC_DEMO_AE, true, false, false, null); channel.queueBind(RabbitMqConfig.BASIC_DEMO_AE, RabbitMqConfig.BASIC_DEMO_AE, ""); } public void sendMsg(Msg msg) throws IOException { if (msg.queue.equals("")) { msg.queue = RabbitMqConfig.BASIC_DEMO_QUEUE; } msg.deliveryTag = channel.getNextPublishSeqNo(); msg.sendAmount += 1; nackMsg.put(msg.deliveryTag, msg); channel.basicPublish(RabbitMqConfig.BASIC_DEMO_EX, msg.queue, false, null, msg.msg.getBytes()); } public static void main(String[] args) { ConnectionFactory factory = RabbitMqConfig.connectionFactory(); try (Connection connection = factory.newConnection()) { var publisher = new Publisher(connection); try (InputStreamReader input = new InputStreamReader(System.in); BufferedReader reader = new BufferedReader(input)) { do { System.out.println("Input Queue and Msg: "); String str = reader.readLine(); String[] inputs = str.split(" "); if (inputs.length < 2) { System.out.println("Invalid Parameters"); continue; } String queue = inputs[0]; String msg = inputs[1]; if (msg.equals("")) { break; } if (queue.equals("")) { queue = RabbitMqConfig.BASIC_DEMO_QUEUE; } Msg message = new Msg(); message.sendAmount = 0; message.msg = msg; message.queue = queue; publisher.sendMsg(message); System.out.println("Send!!!"); } while (true); } } catch (TimeoutException | IOException e) { e.printStackTrace(); } } }
UTF-8
Java
5,396
java
Publisher.java
Java
[]
null
[]
package com.s2u2m.study.mq.rabbitmq.basic.publisher; import com.rabbitmq.client.*; import com.s2u2m.study.mq.rabbitmq.basic.RabbitMqConfig; import java.io.*; import java.util.*; import java.util.concurrent.TimeoutException; /** * - enable AE for missing msg, priority: AE > mandatory * - publish confirm */ public class Publisher { private Channel channel; private final SortedMap<Long, Msg> nackMsg = new TreeMap<>(); private static class Msg { private String queue; private Long deliveryTag; private String msg; private Integer sendAmount = 0; } public Publisher(Connection connection) throws IOException { channel = connection.createChannel(); enablePublishConfirm(channel); declareAe(channel); declareExAndQueue(channel); } private void enablePublishConfirm(Channel channel) throws IOException { channel.confirmSelect(); channel.addConfirmListener(this::ackCallback, this::nackCallback); } private void ackCallback(long deliveryTag, boolean multiple) { Collection<Msg> msgs; if (multiple) { msgs = nackMsg.headMap(deliveryTag).values(); nackMsg.headMap(deliveryTag).clear(); } else { msgs = Collections.singleton(nackMsg.get(deliveryTag)); nackMsg.remove(deliveryTag); } for (Msg msg : msgs) { System.out.printf("Send [%s][%s] Success\n", msg.deliveryTag, msg.msg); } } private void nackCallback(long deliveryTag, boolean multiple) throws IOException { Collection<Msg> msgs; if (multiple) { msgs = nackMsg.headMap(deliveryTag).values(); nackMsg.headMap(deliveryTag).clear(); } else { msgs = Collections.singleton(nackMsg.get(deliveryTag)); nackMsg.remove(deliveryTag); } // re-send for (Msg msg : msgs) { if (msg.sendAmount > 3) { System.out.printf("Re-Send touch max time, [%s][%s]\n", msg.deliveryTag, msg.msg); continue; } System.out.printf("Re-Send [%s][%s]\n", msg.deliveryTag, msg.msg); sendMsg(msg); } } private void declareExAndQueue(Channel channel) throws IOException { Map<String, Object> args = new HashMap<>(); args.put("alternate-exchange", RabbitMqConfig.BASIC_DEMO_AE); channel.exchangeDeclare(RabbitMqConfig.BASIC_DEMO_EX, BuiltinExchangeType.DIRECT, true, false, args); channel.queueDeclare( RabbitMqConfig.BASIC_DEMO_QUEUE, true, false, false, null); channel.queueBind(RabbitMqConfig.BASIC_DEMO_QUEUE, RabbitMqConfig.BASIC_DEMO_EX, RabbitMqConfig.BASIC_DEMO_QUEUE); channel.queueDeclare( RabbitMqConfig.BASIC_DEMO_QUEUE_2, true, false, false, null); channel.queueBind(RabbitMqConfig.BASIC_DEMO_QUEUE_2, RabbitMqConfig.BASIC_DEMO_EX, RabbitMqConfig.BASIC_DEMO_QUEUE_2); } private void declareAe(Channel channel) throws IOException { channel.exchangeDeclare(RabbitMqConfig.BASIC_DEMO_AE, BuiltinExchangeType.FANOUT, true, false, null); channel.queueDeclare(RabbitMqConfig.BASIC_DEMO_AE, true, false, false, null); channel.queueBind(RabbitMqConfig.BASIC_DEMO_AE, RabbitMqConfig.BASIC_DEMO_AE, ""); } public void sendMsg(Msg msg) throws IOException { if (msg.queue.equals("")) { msg.queue = RabbitMqConfig.BASIC_DEMO_QUEUE; } msg.deliveryTag = channel.getNextPublishSeqNo(); msg.sendAmount += 1; nackMsg.put(msg.deliveryTag, msg); channel.basicPublish(RabbitMqConfig.BASIC_DEMO_EX, msg.queue, false, null, msg.msg.getBytes()); } public static void main(String[] args) { ConnectionFactory factory = RabbitMqConfig.connectionFactory(); try (Connection connection = factory.newConnection()) { var publisher = new Publisher(connection); try (InputStreamReader input = new InputStreamReader(System.in); BufferedReader reader = new BufferedReader(input)) { do { System.out.println("Input Queue and Msg: "); String str = reader.readLine(); String[] inputs = str.split(" "); if (inputs.length < 2) { System.out.println("Invalid Parameters"); continue; } String queue = inputs[0]; String msg = inputs[1]; if (msg.equals("")) { break; } if (queue.equals("")) { queue = RabbitMqConfig.BASIC_DEMO_QUEUE; } Msg message = new Msg(); message.sendAmount = 0; message.msg = msg; message.queue = queue; publisher.sendMsg(message); System.out.println("Send!!!"); } while (true); } } catch (TimeoutException | IOException e) { e.printStackTrace(); } } }
5,396
0.572461
0.569867
152
34.5
25.514187
98
false
false
0
0
0
0
0
0
0.75
false
false
10
da43bbd2f638850dc34d1d86a5a2091029148b27
9,723,806,003,743
2b2c733182bcc1c2f0cfc0b4f97766cce41a47ab
/src/main/java/com/qs/model/base/permission/data/StationOrg.java
54ab21a1dde7f6dc98643b4ad426c27632342cf1
[]
no_license
StevFang/video
https://github.com/StevFang/video
7e8e7851567b1e29a91e9c0d4b87a2fe6dfbcf9d
c6f9e8bf2d7c71e54e58d29cda856fd43c7d1884
refs/heads/master
2020-03-19T04:07:40.356000
2019-04-09T00:10:54
2019-04-09T00:10:54
135,797,268
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.qs.model.base.permission.data; import com.qs.enums.base.OrgRangeTypeEnum; import com.qs.model.AbstractModel; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; /** * @author FBin * @time 2019/1/7 18:09 */ @Data @AllArgsConstructor @NoArgsConstructor @Builder public class StationOrg extends AbstractModel implements Serializable { private Long stationId; private OrgRangeTypeEnum rangeType; private Long orgId; }
UTF-8
Java
535
java
StationOrg.java
Java
[ { "context": "tor;\n\nimport java.io.Serializable;\n\n/**\n * @author FBin\n * @time 2019/1/7 18:09\n */\n@Data\n@AllArgsConstru", "end": 282, "score": 0.9839797019958496, "start": 278, "tag": "USERNAME", "value": "FBin" } ]
null
[]
package com.qs.model.base.permission.data; import com.qs.enums.base.OrgRangeTypeEnum; import com.qs.model.AbstractModel; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; /** * @author FBin * @time 2019/1/7 18:09 */ @Data @AllArgsConstructor @NoArgsConstructor @Builder public class StationOrg extends AbstractModel implements Serializable { private Long stationId; private OrgRangeTypeEnum rangeType; private Long orgId; }
535
0.783178
0.764486
28
18.107143
17.538404
71
false
false
0
0
0
0
0
0
0.392857
false
false
10
8cba5bf3604cf0a0941dc4d5aaa91bf2f8ea8497
33,294,586,511,073
abec86446eef678b1db232a009af5a0d382b54f3
/data/perfin/data/dao/expense/MySQLExpenseDAOImpl.java
34dcbb10bf1d1c06a56760ac0a10a3e7005b4a0f
[]
no_license
skbiswas/perfin
https://github.com/skbiswas/perfin
a82516d52a4191fee970a244204068dc6951953b
8006e119835323e6ab01d3d057b918cab65e51a7
refs/heads/master
2021-01-25T10:07:41.296000
2011-08-24T18:04:07
2011-08-24T18:04:07
2,262,006
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package perfin.data.dao.expense; import java.sql.SQLException; import java.util.List; import java.util.Map; import perfin.data.util.DBManager; import perfin.data.util.Query; import perfin.finance.expense.ExpenseDTO; /** * @author skbiswas * */ public class MySQLExpenseDAOImpl implements ExpenseDAO { private Map<String, String> dbDetails; private static MySQLExpenseDAOImpl expDaoImpl; private static final String ADD_EXPENSE_QRY = "INSERT INTO `perfin`.`expense` (`desc`, `transaction_dt`, `amount`, `category`, `recipient`) VALUES (?, ?, ?, ?, ?)"; private static final String UPDATE_EXPENSE_QRY = "UPDATE `perfin`.`expense` SET `desc`=?, `transaction_dt`=?, `amount`=?, `category`=?, `recipient`=? WHERE `id`=? () VALUES (?, ?, ?, ?, ?)"; /***************** Singleton Implementation **************/ private MySQLExpenseDAOImpl(final Map<String, String> dbDetails) { this.dbDetails = dbDetails; } private MySQLExpenseDAOImpl() { throw new RuntimeException("Database details are not provided!"); } public static ExpenseDAO getInstance(final Map<String, String> dbDetails) { return SingletonHolder.getInstance(dbDetails); } private static class SingletonHolder { private static final MySQLExpenseDAOImpl getInstance( final Map<String, String> dbDetails) { if (expDaoImpl == null) { expDaoImpl = new MySQLExpenseDAOImpl(dbDetails); } return expDaoImpl; } } /** * @throws ClassNotFoundException *******************************************************/ @Override public int addExpense(ExpenseDTO expenseDTO) throws SQLException, ClassNotFoundException { // Form a query object Object[] params = { expenseDTO.getDesc(), expenseDTO.getTransDate(), expenseDTO.getAmount(), expenseDTO.getCategory(), expenseDTO.getRecipient() }; Query query = new Query(); query.setQueryString(ADD_EXPENSE_QRY); query.setParams(params); return DBManager.executeUpdate(query, this.dbDetails); } @Override public boolean updateExpense(ExpenseDTO expenseDTO, int expenseId) throws SQLException { return false; } @Override public boolean deleteExpense(int expenseId) throws SQLException { return false; } @Override public List<ExpenseDTO> viewExpenses() throws SQLException { // TODO Auto-generated method stub return null; } /* * private boolean updateTotalExpense(float amount) { Connection con = null; * * } */ }
UTF-8
Java
2,433
java
MySQLExpenseDAOImpl.java
Java
[ { "context": "perfin.finance.expense.ExpenseDTO;\n\n/**\n * @author skbiswas\n * \n */\npublic class MySQLExpenseDAOImpl implemen", "end": 254, "score": 0.9996592402458191, "start": 246, "tag": "USERNAME", "value": "skbiswas" } ]
null
[]
/** * */ package perfin.data.dao.expense; import java.sql.SQLException; import java.util.List; import java.util.Map; import perfin.data.util.DBManager; import perfin.data.util.Query; import perfin.finance.expense.ExpenseDTO; /** * @author skbiswas * */ public class MySQLExpenseDAOImpl implements ExpenseDAO { private Map<String, String> dbDetails; private static MySQLExpenseDAOImpl expDaoImpl; private static final String ADD_EXPENSE_QRY = "INSERT INTO `perfin`.`expense` (`desc`, `transaction_dt`, `amount`, `category`, `recipient`) VALUES (?, ?, ?, ?, ?)"; private static final String UPDATE_EXPENSE_QRY = "UPDATE `perfin`.`expense` SET `desc`=?, `transaction_dt`=?, `amount`=?, `category`=?, `recipient`=? WHERE `id`=? () VALUES (?, ?, ?, ?, ?)"; /***************** Singleton Implementation **************/ private MySQLExpenseDAOImpl(final Map<String, String> dbDetails) { this.dbDetails = dbDetails; } private MySQLExpenseDAOImpl() { throw new RuntimeException("Database details are not provided!"); } public static ExpenseDAO getInstance(final Map<String, String> dbDetails) { return SingletonHolder.getInstance(dbDetails); } private static class SingletonHolder { private static final MySQLExpenseDAOImpl getInstance( final Map<String, String> dbDetails) { if (expDaoImpl == null) { expDaoImpl = new MySQLExpenseDAOImpl(dbDetails); } return expDaoImpl; } } /** * @throws ClassNotFoundException *******************************************************/ @Override public int addExpense(ExpenseDTO expenseDTO) throws SQLException, ClassNotFoundException { // Form a query object Object[] params = { expenseDTO.getDesc(), expenseDTO.getTransDate(), expenseDTO.getAmount(), expenseDTO.getCategory(), expenseDTO.getRecipient() }; Query query = new Query(); query.setQueryString(ADD_EXPENSE_QRY); query.setParams(params); return DBManager.executeUpdate(query, this.dbDetails); } @Override public boolean updateExpense(ExpenseDTO expenseDTO, int expenseId) throws SQLException { return false; } @Override public boolean deleteExpense(int expenseId) throws SQLException { return false; } @Override public List<ExpenseDTO> viewExpenses() throws SQLException { // TODO Auto-generated method stub return null; } /* * private boolean updateTotalExpense(float amount) { Connection con = null; * * } */ }
2,433
0.692561
0.692561
92
25.445652
32.592133
191
false
false
0
0
0
0
0
0
1.673913
false
false
10
2e922335a6a6243388398573177ae15c17fcec90
29,111,288,385,643
b60d02329c887274e5758ce7f70517fb043aab9b
/boot-util/src/main/java/cn/bevol/util/CompatibleDesUtil.java
69722226d3772837efb8a411f8dffe2bd1a68b80
[]
no_license
smartgits/test_app
https://github.com/smartgits/test_app
39104b8f14aa19a1234f707b19cce8286ddfe49f
1f1caf71e5b09f9e4a3c815707ad6a007998ed80
refs/heads/master
2020-03-08T21:28:53.871000
2018-04-06T14:56:47
2018-04-06T14:57:08
128,407,315
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.bevol.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESedeKeySpec; import javax.crypto.spec.IvParameterSpec; import java.io.UnsupportedEncodingException; import java.util.Date; public class CompatibleDesUtil { public static Log log = LogFactory.getLog(CompatibleDesUtil.class); private static final String MCRYPT_TRIPLEDES = "DESede"; private static final String TRANSFORMATION = "DESede/CBC/PKCS5Padding"; private static void asciiToBcdBytes(String str, byte[] hex, int count)// throws // Exception { byte[] inputBytes = str.getBytes(); for (int i = 0, j = 0; j < inputBytes.length && i < count; ++i) { byte v = inputBytes[j]; ++j; if (v <= 0x39) hex[i] = (byte) (v - 0x30); else hex[i] = (byte) (v - 0x41 + 10); hex[i] <<= 4; if (j >= inputBytes.length) break; v = inputBytes[j]; ++j; if (v <= 0x39) hex[i] += (byte) (v - 0x30); else hex[i] += (byte) (v - 0x41 + 10); } } public static String decrypt(String data, String key, byte[] vis) { if (data == null) return null; String result = null; try { DESedeKeySpec spec = new DESedeKeySpec(new BASE64Decoder().decodeBuffer(key)); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(MCRYPT_TRIPLEDES); SecretKey sec = keyFactory.generateSecret(spec); IvParameterSpec IvParameters = new IvParameterSpec(vis); Cipher cipher = Cipher.getInstance(TRANSFORMATION); cipher.init(Cipher.DECRYPT_MODE, sec, IvParameters); result = new String(cipher.doFinal(new BASE64Decoder().decodeBuffer(data)), "UTF-8"); } catch (Exception e) { e.printStackTrace(); } return result; } public static String encrypt(String data,String key, byte[] vis ) { String result = null; try { DESedeKeySpec spec = new DESedeKeySpec(new BASE64Decoder().decodeBuffer(key)); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(MCRYPT_TRIPLEDES); SecretKey sec = keyFactory.generateSecret(spec); IvParameterSpec IvParameters = new IvParameterSpec(vis); Cipher cipher = Cipher.getInstance(TRANSFORMATION); cipher.init(Cipher.ENCRYPT_MODE, sec, IvParameters); result = new BASE64Encoder().encodeBuffer(cipher.doFinal(data.getBytes("UTF-8"))); } catch (Exception e) { log.error("encrypt error", e); } return result; } public static byte[] getSecretKey() { return "PA18SHOPLIFEINCUSTOMERACTIVESA".getBytes(); } public static byte[] getIVBytes() { byte[] bytes = new byte[8]; bytes[0] = (byte) 'm'; bytes[1] = (byte) 'b'; bytes[2] = (byte) 'e'; bytes[3] = (byte) 'v'; bytes[4] = (byte) 'o'; bytes[5] = (byte) 'l'; return bytes; } public static String processDecrypt(String str) { if (str == null) return null; str = str.replaceAll("+", "+"); str = str.replaceAll("/", "/"); str = str.replaceAll("=", "="); return str; } public static String processEncrypt(String str) { if (str == null) return null; str = str.replaceAll("[+]", "+"); str = str.replaceAll("[/]", "/"); str = str.replaceAll("[=]", "="); return str; } public static void main(String[] args) { /*加密*/ String idcode="219dv"; String id="890"; String keycode=MD5Utils.encode("bevol20160107"); String msg = id+""+idcode+""+DateUtils.nowInSeconds(); //动态cookie byte[] bytes = new byte[8]; bytes[0] = (byte) 'm'; bytes[1] = (byte) 'b'; bytes[2] = (byte) 'e'; bytes[3] = (byte) 'v'; bytes[4] = (byte) 'o'; bytes[5] = (byte) 'l'; //String encryptData= encrypt(msg,new BASE64Encoder().encodeBuffer(keycode.getBytes()),bytes); String encryptData="okEGE4c3d5vR6FnE2uVlrA=="; if(encryptData.indexOf("%")!=-1) { try { encryptData = java.net.URLDecoder.decode(encryptData, "utf-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /*echo $rs1 . '<br />'; $rs2 = $des->decrypt($rs1); echo $rs2;*/ /*解密*/ /** * 3des 解密 */ // encryptData = "+Q0Ji/X7V0EVPrdv4id/Ev1kpc+5IGoL";// encrypt(source, String str = decrypt(encryptData, new BASE64Encoder().encodeBuffer(keycode.getBytes()), bytes); // String str = decrypt(encryptData, CommonUtils.getMd5(key),vi); id=str.substring(0, str.lastIndexOf(idcode)); } }
UTF-8
Java
4,517
java
CompatibleDesUtil.java
Java
[ { "context": "\n\tpublic static byte[] getSecretKey() {\n\t\treturn \"PA18SHOPLIFEINCUSTOMERACTIVESA\".getBytes();\n\t}\n\n\tpublic static byte[] getIVBytes", "end": 2630, "score": 0.9988981485366821, "start": 2600, "tag": "KEY", "value": "PA18SHOPLIFEINCUSTOMERACTIVESA" }, { "context": "Key() {\n\t\treturn \"PA18SHOPLIFEINCUSTOMERACTIVESA\".getBytes();\n\t}\n\n\tpublic static byte[] getIVBytes() {\n\t\tbyt", "end": 2640, "score": 0.6676713824272156, "start": 2632, "tag": "KEY", "value": "getBytes" }, { "context": "code=\"219dv\";\n\t\tString id=\"890\";\n\t\tString keycode=MD5Utils.encode(\"bevol20160107\");\n\t\tString msg = id+\"\"+idc", "end": 3427, "score": 0.8306498527526855, "start": 3419, "tag": "KEY", "value": "MD5Utils" }, { "context": "dv\";\n\t\tString id=\"890\";\n\t\tString keycode=MD5Utils.encode(\"bevol20160107\");\n\t\tString msg = id+\"\"+idcode+\"\"+", "end": 3434, "score": 0.5281285643577576, "start": 3428, "tag": "KEY", "value": "encode" }, { "context": "tring id=\"890\";\n\t\tString keycode=MD5Utils.encode(\"bevol20160107\");\n\t\tString msg = id+\"\"+idcode+\"\"+DateUtils.nowIn", "end": 3449, "score": 0.9984849095344543, "start": 3436, "tag": "KEY", "value": "bevol20160107" } ]
null
[]
package cn.bevol.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESedeKeySpec; import javax.crypto.spec.IvParameterSpec; import java.io.UnsupportedEncodingException; import java.util.Date; public class CompatibleDesUtil { public static Log log = LogFactory.getLog(CompatibleDesUtil.class); private static final String MCRYPT_TRIPLEDES = "DESede"; private static final String TRANSFORMATION = "DESede/CBC/PKCS5Padding"; private static void asciiToBcdBytes(String str, byte[] hex, int count)// throws // Exception { byte[] inputBytes = str.getBytes(); for (int i = 0, j = 0; j < inputBytes.length && i < count; ++i) { byte v = inputBytes[j]; ++j; if (v <= 0x39) hex[i] = (byte) (v - 0x30); else hex[i] = (byte) (v - 0x41 + 10); hex[i] <<= 4; if (j >= inputBytes.length) break; v = inputBytes[j]; ++j; if (v <= 0x39) hex[i] += (byte) (v - 0x30); else hex[i] += (byte) (v - 0x41 + 10); } } public static String decrypt(String data, String key, byte[] vis) { if (data == null) return null; String result = null; try { DESedeKeySpec spec = new DESedeKeySpec(new BASE64Decoder().decodeBuffer(key)); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(MCRYPT_TRIPLEDES); SecretKey sec = keyFactory.generateSecret(spec); IvParameterSpec IvParameters = new IvParameterSpec(vis); Cipher cipher = Cipher.getInstance(TRANSFORMATION); cipher.init(Cipher.DECRYPT_MODE, sec, IvParameters); result = new String(cipher.doFinal(new BASE64Decoder().decodeBuffer(data)), "UTF-8"); } catch (Exception e) { e.printStackTrace(); } return result; } public static String encrypt(String data,String key, byte[] vis ) { String result = null; try { DESedeKeySpec spec = new DESedeKeySpec(new BASE64Decoder().decodeBuffer(key)); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(MCRYPT_TRIPLEDES); SecretKey sec = keyFactory.generateSecret(spec); IvParameterSpec IvParameters = new IvParameterSpec(vis); Cipher cipher = Cipher.getInstance(TRANSFORMATION); cipher.init(Cipher.ENCRYPT_MODE, sec, IvParameters); result = new BASE64Encoder().encodeBuffer(cipher.doFinal(data.getBytes("UTF-8"))); } catch (Exception e) { log.error("encrypt error", e); } return result; } public static byte[] getSecretKey() { return "PA18SHOPLIFEINCUSTOMERACTIVESA".getBytes(); } public static byte[] getIVBytes() { byte[] bytes = new byte[8]; bytes[0] = (byte) 'm'; bytes[1] = (byte) 'b'; bytes[2] = (byte) 'e'; bytes[3] = (byte) 'v'; bytes[4] = (byte) 'o'; bytes[5] = (byte) 'l'; return bytes; } public static String processDecrypt(String str) { if (str == null) return null; str = str.replaceAll("+", "+"); str = str.replaceAll("/", "/"); str = str.replaceAll("=", "="); return str; } public static String processEncrypt(String str) { if (str == null) return null; str = str.replaceAll("[+]", "+"); str = str.replaceAll("[/]", "/"); str = str.replaceAll("[=]", "="); return str; } public static void main(String[] args) { /*加密*/ String idcode="219dv"; String id="890"; String keycode=MD5Utils.encode("bevol20160107"); String msg = id+""+idcode+""+DateUtils.nowInSeconds(); //动态cookie byte[] bytes = new byte[8]; bytes[0] = (byte) 'm'; bytes[1] = (byte) 'b'; bytes[2] = (byte) 'e'; bytes[3] = (byte) 'v'; bytes[4] = (byte) 'o'; bytes[5] = (byte) 'l'; //String encryptData= encrypt(msg,new BASE64Encoder().encodeBuffer(keycode.getBytes()),bytes); String encryptData="okEGE4c3d5vR6FnE2uVlrA=="; if(encryptData.indexOf("%")!=-1) { try { encryptData = java.net.URLDecoder.decode(encryptData, "utf-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /*echo $rs1 . '<br />'; $rs2 = $des->decrypt($rs1); echo $rs2;*/ /*解密*/ /** * 3des 解密 */ // encryptData = "+Q0Ji/X7V0EVPrdv4id/Ev1kpc+5IGoL";// encrypt(source, String str = decrypt(encryptData, new BASE64Encoder().encodeBuffer(keycode.getBytes()), bytes); // String str = decrypt(encryptData, CommonUtils.getMd5(key),vi); id=str.substring(0, str.lastIndexOf(idcode)); } }
4,517
0.65852
0.637414
176
24.573864
24.249067
96
false
false
0
0
0
0
0
0
2.261364
false
false
10
59c25f67432a6f270fb001838557fe64330d29db
29,145,648,098,191
cebbb5b38b94bb3d681ba693055224f7a90dd1f0
/src/main/java/xyz/lexteam/meta/api/value/ValueHolder.java
08bcd9f4a828348399bf066421b40b951a0a09f1
[ "MIT" ]
permissive
Lexteam/Meta
https://github.com/Lexteam/Meta
6776ebd437e136b43146f9746ae772e9be06cac3
5efe81394523fac54b1c5fdc6a3e2fa937906867
refs/heads/master
2021-01-10T16:57:57.147000
2016-02-12T17:20:50
2016-02-12T17:20:50
44,771,895
2
0
null
false
2015-11-01T01:02:48
2015-10-22T20:38:14
2015-10-31T23:57:45
2015-11-01T00:50:58
208
1
0
0
Java
null
null
/* * This file is part of MetaAPI, licensed under the MIT License (MIT). * * Copyright (c) 2015-2016, Lexteam <http://www.lexteam.xyz/> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package xyz.lexteam.meta.api.value; import xyz.lexteam.meta.api.key.Key; import java.util.Optional; /** * Represents an object which holds key values. * * @author Jamie Mansfield */ public interface ValueHolder { /** * Gets a value from it's key. * * @param key the specified key. * @param <T> the value type. * @return the value. */ <T> Optional<T> get(Key<Value<T>> key); /** * Gets a value from it's key, and if it doesn't exist the gets null. * * @param key the specified key. * @param <T> the value type. * @return the value. */ default <T> T getOrNull(Key<Value<T>> key) { return this.get(key).orElse(null); } /** * Checks to see if this owner supports that key. * * @param key the specified key. * @param <T> the value type. * @return the value. */ <T> boolean supports(Key<Value<T>> key); /** * Offers the given value to the value processor. * * @param key the key of which you are offering to. * @param value the value you wish to set. * @param <T> the value type. * @return {@code true} if the value was set. */ <T> boolean offer(Key<Value<T>> key, T value); }
UTF-8
Java
2,469
java
ValueHolder.java
Java
[ { "context": "ts an object which holds key values.\n *\n * @author Jamie Mansfield\n */\npublic interface ValueHolder {\n\n /**\n ", "end": 1402, "score": 0.9998323321342468, "start": 1387, "tag": "NAME", "value": "Jamie Mansfield" } ]
null
[]
/* * This file is part of MetaAPI, licensed under the MIT License (MIT). * * Copyright (c) 2015-2016, Lexteam <http://www.lexteam.xyz/> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package xyz.lexteam.meta.api.value; import xyz.lexteam.meta.api.key.Key; import java.util.Optional; /** * Represents an object which holds key values. * * @author <NAME> */ public interface ValueHolder { /** * Gets a value from it's key. * * @param key the specified key. * @param <T> the value type. * @return the value. */ <T> Optional<T> get(Key<Value<T>> key); /** * Gets a value from it's key, and if it doesn't exist the gets null. * * @param key the specified key. * @param <T> the value type. * @return the value. */ default <T> T getOrNull(Key<Value<T>> key) { return this.get(key).orElse(null); } /** * Checks to see if this owner supports that key. * * @param key the specified key. * @param <T> the value type. * @return the value. */ <T> boolean supports(Key<Value<T>> key); /** * Offers the given value to the value processor. * * @param key the key of which you are offering to. * @param value the value you wish to set. * @param <T> the value type. * @return {@code true} if the value was set. */ <T> boolean offer(Key<Value<T>> key, T value); }
2,460
0.667072
0.663832
75
31.92
27.684778
80
false
false
0
0
0
0
0
0
0.44
false
false
10
31e34aedca298266d2eb3265681d3171c7dd0758
15,487,652,109,548
9821426ca32b707134eee8dbda9ef4ce64a97045
/MiuiSystemUI/raphael/systemui/doze/DozeAuthRemover.java
291644b3ef574744dbaf46c38c623649f5629c9c
[]
no_license
mooseIre/arsc_compare
https://github.com/mooseIre/arsc_compare
a28af8205cc75647b3f6e8c1b3310ca2b2140725
3df667d4e4d4924e11cbcfd9df29346a3c259e32
refs/heads/master
2023-06-21T13:30:23.511000
2021-08-12T15:13:08
2021-08-12T15:13:08
277,633,842
3
3
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.android.systemui.doze; import android.content.Context; import com.android.keyguard.KeyguardUpdateMonitor; import com.android.systemui.Dependency; import com.android.systemui.doze.DozeMachine; public class DozeAuthRemover implements DozeMachine.Part { private final KeyguardUpdateMonitor mKeyguardUpdateMonitor = ((KeyguardUpdateMonitor) Dependency.get(KeyguardUpdateMonitor.class)); public DozeAuthRemover(Context context) { } @Override // com.android.systemui.doze.DozeMachine.Part public void transitionTo(DozeMachine.State state, DozeMachine.State state2) { if (state2 == DozeMachine.State.DOZE || state2 == DozeMachine.State.DOZE_AOD) { if (this.mKeyguardUpdateMonitor.getUserUnlockedWithBiometric(KeyguardUpdateMonitor.getCurrentUser())) { this.mKeyguardUpdateMonitor.clearBiometricRecognized(); } } } }
UTF-8
Java
905
java
DozeAuthRemover.java
Java
[]
null
[]
package com.android.systemui.doze; import android.content.Context; import com.android.keyguard.KeyguardUpdateMonitor; import com.android.systemui.Dependency; import com.android.systemui.doze.DozeMachine; public class DozeAuthRemover implements DozeMachine.Part { private final KeyguardUpdateMonitor mKeyguardUpdateMonitor = ((KeyguardUpdateMonitor) Dependency.get(KeyguardUpdateMonitor.class)); public DozeAuthRemover(Context context) { } @Override // com.android.systemui.doze.DozeMachine.Part public void transitionTo(DozeMachine.State state, DozeMachine.State state2) { if (state2 == DozeMachine.State.DOZE || state2 == DozeMachine.State.DOZE_AOD) { if (this.mKeyguardUpdateMonitor.getUserUnlockedWithBiometric(KeyguardUpdateMonitor.getCurrentUser())) { this.mKeyguardUpdateMonitor.clearBiometricRecognized(); } } } }
905
0.754696
0.751381
22
40.136364
38.443932
135
false
false
0
0
0
0
0
0
0.454545
false
false
10
a48b944b88aeb982f3db1dc79647f89c348542a0
10,402,410,847,204
e8801c79d100623610a705c06a398e7309911cd7
/src/main/java/com/song/controller/View.java
6cf4a764aa71d02e81cbe097f676d829713c9d4b
[]
no_license
swd19941030/springboot01
https://github.com/swd19941030/springboot01
d67023b0fb8e7bb6a30d5332b45a2602bbb60ae3
74a69536711543150ac45e58603678e7cb687f34
refs/heads/master
2021-07-25T09:10:21.189000
2021-07-09T02:12:31
2021-07-09T02:12:31
199,965,267
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.song.controller; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; @RestController public class View { @Value("${hschefu}") private String name; @Value("${hschefu1}") private String name1; @RequestMapping(value = "view01", method = RequestMethod.GET) public ModelAndView view (){ System.out.println(1111); ModelAndView modelAndView = new ModelAndView("view"); System.out.printf(name); modelAndView.addObject("name",name1); return modelAndView; } }
UTF-8
Java
892
java
View.java
Java
[]
null
[]
package com.song.controller; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; @RestController public class View { @Value("${hschefu}") private String name; @Value("${hschefu1}") private String name1; @RequestMapping(value = "view01", method = RequestMethod.GET) public ModelAndView view (){ System.out.println(1111); ModelAndView modelAndView = new ModelAndView("view"); System.out.printf(name); modelAndView.addObject("name",name1); return modelAndView; } }
892
0.75
0.73991
27
32.037037
22.225246
65
false
false
0
0
0
0
0
0
0.62963
false
false
10
74be86919257d7ef66084c3588ae8ae4b896b709
25,967,372,290,014
2391e4ad5561aacbd2a17c4abeedf2796a179558
/src/test/java/MavenTest1.java
3a6d3c53af2fe4a3ba1ae19904c6be2e5679c180
[ "MIT" ]
permissive
sharvarirane555/Java1
https://github.com/sharvarirane555/Java1
0da67aa7a2522a03fbc0a27dff9a46342cecd621
b94971bf1849cbd44d05a2a323ceb3789f85e88f
refs/heads/master
2022-12-16T00:37:40.374000
2020-09-08T07:42:32
2020-09-08T07:42:32
287,201,632
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.combo; import static org.junit.Assert.*; import java.util.Scanner; import org.junit.Test; public class MavenTest1 { @Test public void test() { Scanner sc = new Scanner(System.in); int count=sc.nextInt(); assertTrue(count==3); } }
UTF-8
Java
257
java
MavenTest1.java
Java
[]
null
[]
package com.combo; import static org.junit.Assert.*; import java.util.Scanner; import org.junit.Test; public class MavenTest1 { @Test public void test() { Scanner sc = new Scanner(System.in); int count=sc.nextInt(); assertTrue(count==3); } }
257
0.696498
0.688716
17
14.117647
13.096395
39
false
false
0
0
0
0
0
0
0.941176
false
false
10
1fe0c28a33a6d7948a98953cce2d65914b0a23e1
26,336,739,488,614
0bc60acc434b3344194b2f65b0e3688becc4cdd7
/proj.android-studio/app/src/org/cocos2dx/cpp/MasterData.java
af59ec780b9843b238bfc8d69acab2b82f285a02
[ "MIT" ]
permissive
TakuKobayashi/HearWeGo
https://github.com/TakuKobayashi/HearWeGo
efff568e264eb301d3e795b92a7d6464317eae92
99b66daa8d0ed93e6c32beb79fee8a840bce02a9
refs/heads/master
2018-01-08T08:53:45.707000
2016-03-20T08:07:49
2016-03-20T08:07:49
52,936,457
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.cocos2dx.cpp; import android.content.Context; import android.graphics.Bitmap; import android.util.Log; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class MasterData extends ContextSingletonBase<MasterData> { public List<Machiko> machikos; public void init(Context context) { super.init(context); Gson gson = new Gson(); Type collectionType = new TypeToken<Collection<Machiko>>(){}.getType(); machikos = gson.fromJson(ApplicationHelper.loadTextFromAsset(context, "machiko_mst.json"), collectionType); } public void clear(){ machikos.clear(); } }
UTF-8
Java
738
java
MasterData.java
Java
[]
null
[]
package org.cocos2dx.cpp; import android.content.Context; import android.graphics.Bitmap; import android.util.Log; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class MasterData extends ContextSingletonBase<MasterData> { public List<Machiko> machikos; public void init(Context context) { super.init(context); Gson gson = new Gson(); Type collectionType = new TypeToken<Collection<Machiko>>(){}.getType(); machikos = gson.fromJson(ApplicationHelper.loadTextFromAsset(context, "machiko_mst.json"), collectionType); } public void clear(){ machikos.clear(); } }
738
0.753388
0.752033
28
25.321428
24.982927
111
false
false
0
0
0
0
0
0
0.642857
false
false
10
475e21ec49ed521480dd4b62b12214348477b0b4
28,509,992,965,635
5b2bd7af36711ac74ae880c9a25fee7065bcedb0
/Sokoban.java
fc1f46f2da3173732cf10b2c05a39e8cf2287e87
[]
no_license
ariaSebastian/sokoban
https://github.com/ariaSebastian/sokoban
4ce991f404d024c9e5ee56242cd8b4b2dca00da6
51c37ecafe7cad9aded14aaf29d30fa7e7889d19
refs/heads/master
2022-02-01T00:08:32.719000
2019-07-23T03:30:06
2019-07-23T03:30:06
198,150,489
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.*; class Board { String cur, sol; int x, y, level; Board(String s1, String s2, int px, int py, int level) { cur = s1; sol = s2; x = px; y = py; this.level = level; } } public class Sokoban { String destBoard, currBoard; boolean player = false; int playerX, playerY, nCols; int amplitudeCount = 0; int depthCount = 0; boolean prints = false; Sokoban(String[] ruta) throws FileNotFoundException, IOException { // nCols = board[0].length(); nCols = 0; destBoard = ""; currBoard = ""; String line; String board = ""; for(int i = 0; i < ruta.length; i++){ line = ruta[i]; if(line.length() > 0){ // System.out.println("Line:"); // System.out.println(line); // System.out.println("---"); if(line.contains(",")){ if(!player){ player = true; destBoard = "" + board; String[] position = line.split(","); playerX = Integer.parseInt(position[1]); playerY = Integer.parseInt(position[0]); int pos = playerY * nCols + playerX; char[] sceneChar = board.toCharArray(); sceneChar[pos] = '@'; board = new String(sceneChar); } else { String[] position = line.split(","); int x = Integer.parseInt(position[1]); int y = Integer.parseInt(position[0]); int pos = y * nCols + x; char[] sceneChar = board.toCharArray(); sceneChar[pos] = 'B'; board = new String(sceneChar); } } else { board += line; } if(nCols == 0){ nCols = line.length(); } } } for (int c = 0; c < board.length(); c++) { char ch = board.charAt(c); char newCharCurr = ch != 'X' ? ch : '0'; currBoard += newCharCurr; } // System.out.println("DEST:"); // printBoard(destBoard); // System.out.println("CURR:"); // printBoard(currBoard); } String move(int x, int y, int dx, int dy, String trialBoard) { int newPlayerPos = (y + dy) * nCols + x + dx; if (trialBoard.charAt(newPlayerPos) != '0') return null; char[] trial = trialBoard.toCharArray(); trial[y * nCols + x] = '0'; trial[newPlayerPos] = '@'; return new String(trial); } String push(int x, int y, int dx, int dy, String trialBoard) { int newBoxPos = (y + 2 * dy) * nCols + x + 2 * dx; if (trialBoard.charAt(newBoxPos) != '0') return null; char[] trial = trialBoard.toCharArray(); trial[y * nCols + x] = '0'; trial[(y + dy) * nCols + x + dx] = '@'; trial[newBoxPos] = 'B'; return new String(trial); } boolean isSolved(String trialBoard) { for (int i = 0; i < trialBoard.length(); i++) if ((destBoard.charAt(i) == 'X') != (trialBoard.charAt(i) == 'B')) return false; if(prints){ System.out.println("SOL:"); printBoard(trialBoard); } return true; } void printBoard(String board){ String sol = ""; System.out.println(""); System.out.println(board); System.out.println(""); for (int i = 0; i < board.length(); i++){ sol += board.charAt(i); if(((i + 1 ) % nCols) == 0){ System.out.println(sol); sol = ""; } } System.out.println(""); } void solve() { int[][] dirs = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}}; // La primera pos se pensaba para indicar que el movimiento fue simple, y la segunda pos para indicar que el movimiento implico mover una caja // Se dejan iguales debido a las especificaciones del taller char[][] dirLabels = {{'U', 'U'}, {'D', 'D'}, {'L', 'L'}, {'R', 'R'}}; // solveWithAllPrints(dirs, dirLabels); solveSinglePrint(dirs, dirLabels); } void solveSinglePrint(int[][] dirs, char[][] dirLabels){ System.out.println(algAmplitude(dirs, dirLabels)); System.out.println(algDepth(dirs, dirLabels)); System.out.println(algIterativeDepth(dirs, dirLabels, 20)); } void solveWithAllPrints(int[][] dirs, char[][] dirLabels){ prints = true; System.out.println(""); System.out.println("INITIAL BOARD:"); printBoard(destBoard); System.out.println(""); System.out.println("=================================================="); System.out.println("============= ALGORITHM BY AMPLITUDE ============="); System.out.println("=================================================="); System.out.println(""); long tInicio, tFin, time; tInicio = System.currentTimeMillis(); System.out.println("Movimientos: " + algAmplitude(dirs, dirLabels)); tFin = System.currentTimeMillis(); time = tFin - tInicio; System.out.println(""); System.out.println("Tiempo de ejecución en milisegundos: " + time); System.out.println(""); System.out.println(""); System.out.println("=================================================="); System.out.println("=============== ALGORITHM BY DEPTH ==============="); System.out.println("=================================================="); System.out.println(""); tInicio = System.currentTimeMillis(); System.out.println("Movimientos: " + algDepth(dirs, dirLabels)); tFin = System.currentTimeMillis(); time = tFin - tInicio; System.out.println(""); System.out.println("Tiempo de ejecución en milisegundos: " + time); System.out.println(""); System.out.println(""); System.out.println("=================================================="); System.out.println("========== ALGORITHM BY ITERATIVE DEPTH =========="); System.out.println("=================================================="); System.out.println(""); tInicio = System.currentTimeMillis(); System.out.println("Movimientos: " + algIterativeDepth(dirs, dirLabels, 20)); tFin = System.currentTimeMillis(); time = tFin - tInicio; // System.out.println("depthCount: " + depthCount); System.out.println(""); System.out.println("Tiempo de ejecución en milisegundos: " + time); System.out.println(""); } String algAmplitude(int[][] dirs, char[][] dirLabels){ Set<String> history = new HashSet<>(); LinkedList<Board> open = new LinkedList<>(); history.add(currBoard); open.add(new Board(currBoard, "", playerX, playerY, 0)); while (!open.isEmpty()) { Board item = open.poll(); String cur = item.cur; String sol = item.sol; int x = item.x; int y = item.y; int level = item.level; for (int i = 0; i < dirs.length; i++) { String trial = cur; int dx = dirs[i][0]; int dy = dirs[i][1]; if (trial.charAt((y + dy) * nCols + x + dx) == 'B') { if ((trial = push(x, y, dx, dy, trial)) != null) { if (!history.contains(trial)) { String newSol = sol + dirLabels[i][1]; if (isSolved(trial)){ if(prints){ System.out.println("Level: " + level); } return newSol; } open.add(new Board(trial, newSol, x + dx, y + dy, level + 1)); history.add(trial); } } // otherwise try changing position } else if ((trial = move(x, y, dx, dy, trial)) != null) { if (!history.contains(trial)) { String newSol = sol + dirLabels[i][0]; open.add(new Board(trial, newSol, x + dx, y + dy, level + 1)); history.add(trial); } } } } return "No solution"; } String algDepth(int[][] dirs, char[][] dirLabels){ Set<String> history = new HashSet<>(); LinkedList<Board> open = new LinkedList<>(); history.add(currBoard); open.add(new Board(currBoard, "", playerX, playerY, 0)); while (!open.isEmpty()) { Board item = open.poll(); String cur = item.cur; String sol = item.sol; int x = item.x; int y = item.y; int level = item.level; for (int i = 0; i < dirs.length; i++) { String trial = cur; int dx = dirs[i][0]; int dy = dirs[i][1]; // are we standing next to a box ? if (trial.charAt((y + dy) * nCols + x + dx) == 'B') { // can we push it ? if ((trial = push(x, y, dx, dy, trial)) != null) { // or did we already try this one ? if (!history.contains(trial)) { String newSol = sol + dirLabels[i][1]; if (isSolved(trial)){ if(prints){ System.out.println("Level: " + level); } return newSol; } open.addFirst(new Board(trial, newSol, x + dx, y + dy, level + 1)); history.add(trial); } } // otherwise try changing position } else if ((trial = move(x, y, dx, dy, trial)) != null) { if (!history.contains(trial)) { String newSol = sol + dirLabels[i][0]; open.add(new Board(trial, newSol, x + dx, y + dy, level + 1)); history.add(trial); } } } } return "No solution"; } String algIterativeDepth(int[][] dirs, char[][] dirLabels, int maxLevel){ Set<String> history = new HashSet<>(); LinkedList<Board> open = new LinkedList<>(); history.add(currBoard); open.add(new Board(currBoard, "", playerX, playerY, 0)); while (!open.isEmpty()) { Board item = open.poll(); String cur = item.cur; String sol = item.sol; int x = item.x; int y = item.y; int level = item.level; if(level <= maxLevel){ for (int i = 0; i < dirs.length; i++) { String trial = cur; int dx = dirs[i][0]; int dy = dirs[i][1]; // are we standing next to a box ? if (trial.charAt((y + dy) * nCols + x + dx) == 'B') { // can we push it ? if ((trial = push(x, y, dx, dy, trial)) != null) { // or did we already try this one ? if (!history.contains(trial)) { String newSol = sol + dirLabels[i][1]; if (isSolved(trial)){ if(prints){ System.out.println("Level: " + level); } return newSol; } open.addFirst(new Board(trial, newSol, x + dx, y + dy, level + 1)); history.add(trial); } } // otherwise try changing position } else if ((trial = move(x, y, dx, dy, trial)) != null) { if (!history.contains(trial)) { String newSol = sol + dirLabels[i][0]; open.add(new Board(trial, newSol, x + dx, y + dy, level + 1)); history.add(trial); } } } } } if(maxLevel < 1000){ return algIterativeDepth(dirs, dirLabels, maxLevel + 1); } else { return "No solution"; } } public static void main(String[] args) throws IOException { new Sokoban(args[0].split(";")).solve(); } }
UTF-8
Java
13,587
java
Sokoban.java
Java
[]
null
[]
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.*; class Board { String cur, sol; int x, y, level; Board(String s1, String s2, int px, int py, int level) { cur = s1; sol = s2; x = px; y = py; this.level = level; } } public class Sokoban { String destBoard, currBoard; boolean player = false; int playerX, playerY, nCols; int amplitudeCount = 0; int depthCount = 0; boolean prints = false; Sokoban(String[] ruta) throws FileNotFoundException, IOException { // nCols = board[0].length(); nCols = 0; destBoard = ""; currBoard = ""; String line; String board = ""; for(int i = 0; i < ruta.length; i++){ line = ruta[i]; if(line.length() > 0){ // System.out.println("Line:"); // System.out.println(line); // System.out.println("---"); if(line.contains(",")){ if(!player){ player = true; destBoard = "" + board; String[] position = line.split(","); playerX = Integer.parseInt(position[1]); playerY = Integer.parseInt(position[0]); int pos = playerY * nCols + playerX; char[] sceneChar = board.toCharArray(); sceneChar[pos] = '@'; board = new String(sceneChar); } else { String[] position = line.split(","); int x = Integer.parseInt(position[1]); int y = Integer.parseInt(position[0]); int pos = y * nCols + x; char[] sceneChar = board.toCharArray(); sceneChar[pos] = 'B'; board = new String(sceneChar); } } else { board += line; } if(nCols == 0){ nCols = line.length(); } } } for (int c = 0; c < board.length(); c++) { char ch = board.charAt(c); char newCharCurr = ch != 'X' ? ch : '0'; currBoard += newCharCurr; } // System.out.println("DEST:"); // printBoard(destBoard); // System.out.println("CURR:"); // printBoard(currBoard); } String move(int x, int y, int dx, int dy, String trialBoard) { int newPlayerPos = (y + dy) * nCols + x + dx; if (trialBoard.charAt(newPlayerPos) != '0') return null; char[] trial = trialBoard.toCharArray(); trial[y * nCols + x] = '0'; trial[newPlayerPos] = '@'; return new String(trial); } String push(int x, int y, int dx, int dy, String trialBoard) { int newBoxPos = (y + 2 * dy) * nCols + x + 2 * dx; if (trialBoard.charAt(newBoxPos) != '0') return null; char[] trial = trialBoard.toCharArray(); trial[y * nCols + x] = '0'; trial[(y + dy) * nCols + x + dx] = '@'; trial[newBoxPos] = 'B'; return new String(trial); } boolean isSolved(String trialBoard) { for (int i = 0; i < trialBoard.length(); i++) if ((destBoard.charAt(i) == 'X') != (trialBoard.charAt(i) == 'B')) return false; if(prints){ System.out.println("SOL:"); printBoard(trialBoard); } return true; } void printBoard(String board){ String sol = ""; System.out.println(""); System.out.println(board); System.out.println(""); for (int i = 0; i < board.length(); i++){ sol += board.charAt(i); if(((i + 1 ) % nCols) == 0){ System.out.println(sol); sol = ""; } } System.out.println(""); } void solve() { int[][] dirs = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}}; // La primera pos se pensaba para indicar que el movimiento fue simple, y la segunda pos para indicar que el movimiento implico mover una caja // Se dejan iguales debido a las especificaciones del taller char[][] dirLabels = {{'U', 'U'}, {'D', 'D'}, {'L', 'L'}, {'R', 'R'}}; // solveWithAllPrints(dirs, dirLabels); solveSinglePrint(dirs, dirLabels); } void solveSinglePrint(int[][] dirs, char[][] dirLabels){ System.out.println(algAmplitude(dirs, dirLabels)); System.out.println(algDepth(dirs, dirLabels)); System.out.println(algIterativeDepth(dirs, dirLabels, 20)); } void solveWithAllPrints(int[][] dirs, char[][] dirLabels){ prints = true; System.out.println(""); System.out.println("INITIAL BOARD:"); printBoard(destBoard); System.out.println(""); System.out.println("=================================================="); System.out.println("============= ALGORITHM BY AMPLITUDE ============="); System.out.println("=================================================="); System.out.println(""); long tInicio, tFin, time; tInicio = System.currentTimeMillis(); System.out.println("Movimientos: " + algAmplitude(dirs, dirLabels)); tFin = System.currentTimeMillis(); time = tFin - tInicio; System.out.println(""); System.out.println("Tiempo de ejecución en milisegundos: " + time); System.out.println(""); System.out.println(""); System.out.println("=================================================="); System.out.println("=============== ALGORITHM BY DEPTH ==============="); System.out.println("=================================================="); System.out.println(""); tInicio = System.currentTimeMillis(); System.out.println("Movimientos: " + algDepth(dirs, dirLabels)); tFin = System.currentTimeMillis(); time = tFin - tInicio; System.out.println(""); System.out.println("Tiempo de ejecución en milisegundos: " + time); System.out.println(""); System.out.println(""); System.out.println("=================================================="); System.out.println("========== ALGORITHM BY ITERATIVE DEPTH =========="); System.out.println("=================================================="); System.out.println(""); tInicio = System.currentTimeMillis(); System.out.println("Movimientos: " + algIterativeDepth(dirs, dirLabels, 20)); tFin = System.currentTimeMillis(); time = tFin - tInicio; // System.out.println("depthCount: " + depthCount); System.out.println(""); System.out.println("Tiempo de ejecución en milisegundos: " + time); System.out.println(""); } String algAmplitude(int[][] dirs, char[][] dirLabels){ Set<String> history = new HashSet<>(); LinkedList<Board> open = new LinkedList<>(); history.add(currBoard); open.add(new Board(currBoard, "", playerX, playerY, 0)); while (!open.isEmpty()) { Board item = open.poll(); String cur = item.cur; String sol = item.sol; int x = item.x; int y = item.y; int level = item.level; for (int i = 0; i < dirs.length; i++) { String trial = cur; int dx = dirs[i][0]; int dy = dirs[i][1]; if (trial.charAt((y + dy) * nCols + x + dx) == 'B') { if ((trial = push(x, y, dx, dy, trial)) != null) { if (!history.contains(trial)) { String newSol = sol + dirLabels[i][1]; if (isSolved(trial)){ if(prints){ System.out.println("Level: " + level); } return newSol; } open.add(new Board(trial, newSol, x + dx, y + dy, level + 1)); history.add(trial); } } // otherwise try changing position } else if ((trial = move(x, y, dx, dy, trial)) != null) { if (!history.contains(trial)) { String newSol = sol + dirLabels[i][0]; open.add(new Board(trial, newSol, x + dx, y + dy, level + 1)); history.add(trial); } } } } return "No solution"; } String algDepth(int[][] dirs, char[][] dirLabels){ Set<String> history = new HashSet<>(); LinkedList<Board> open = new LinkedList<>(); history.add(currBoard); open.add(new Board(currBoard, "", playerX, playerY, 0)); while (!open.isEmpty()) { Board item = open.poll(); String cur = item.cur; String sol = item.sol; int x = item.x; int y = item.y; int level = item.level; for (int i = 0; i < dirs.length; i++) { String trial = cur; int dx = dirs[i][0]; int dy = dirs[i][1]; // are we standing next to a box ? if (trial.charAt((y + dy) * nCols + x + dx) == 'B') { // can we push it ? if ((trial = push(x, y, dx, dy, trial)) != null) { // or did we already try this one ? if (!history.contains(trial)) { String newSol = sol + dirLabels[i][1]; if (isSolved(trial)){ if(prints){ System.out.println("Level: " + level); } return newSol; } open.addFirst(new Board(trial, newSol, x + dx, y + dy, level + 1)); history.add(trial); } } // otherwise try changing position } else if ((trial = move(x, y, dx, dy, trial)) != null) { if (!history.contains(trial)) { String newSol = sol + dirLabels[i][0]; open.add(new Board(trial, newSol, x + dx, y + dy, level + 1)); history.add(trial); } } } } return "No solution"; } String algIterativeDepth(int[][] dirs, char[][] dirLabels, int maxLevel){ Set<String> history = new HashSet<>(); LinkedList<Board> open = new LinkedList<>(); history.add(currBoard); open.add(new Board(currBoard, "", playerX, playerY, 0)); while (!open.isEmpty()) { Board item = open.poll(); String cur = item.cur; String sol = item.sol; int x = item.x; int y = item.y; int level = item.level; if(level <= maxLevel){ for (int i = 0; i < dirs.length; i++) { String trial = cur; int dx = dirs[i][0]; int dy = dirs[i][1]; // are we standing next to a box ? if (trial.charAt((y + dy) * nCols + x + dx) == 'B') { // can we push it ? if ((trial = push(x, y, dx, dy, trial)) != null) { // or did we already try this one ? if (!history.contains(trial)) { String newSol = sol + dirLabels[i][1]; if (isSolved(trial)){ if(prints){ System.out.println("Level: " + level); } return newSol; } open.addFirst(new Board(trial, newSol, x + dx, y + dy, level + 1)); history.add(trial); } } // otherwise try changing position } else if ((trial = move(x, y, dx, dy, trial)) != null) { if (!history.contains(trial)) { String newSol = sol + dirLabels[i][0]; open.add(new Board(trial, newSol, x + dx, y + dy, level + 1)); history.add(trial); } } } } } if(maxLevel < 1000){ return algIterativeDepth(dirs, dirLabels, maxLevel + 1); } else { return "No solution"; } } public static void main(String[] args) throws IOException { new Sokoban(args[0].split(";")).solve(); } }
13,587
0.42528
0.4202
392
33.655613
24.858297
150
false
false
0
0
0
0
0
0
0.834184
false
false
10
5574b109be8725a390267976e918efc6f018dc5f
35,038,343,209,486
446b6b61555b9be0c8fd540b81d2aa5135d6a5ca
/src/main/java/de/flingelli/security/openvas/reports/data/Preference.java
21511970d1256508e31aee2af8b981340e3bcfaf
[]
no_license
mflingelli/openvas-helper
https://github.com/mflingelli/openvas-helper
02d95e82c2512b9ae646e73aa7e4592ab712faed
11f3d698239b6477e94af882dd95d1d0d2be927a
refs/heads/master
2022-09-24T06:13:15.845000
2017-08-12T17:34:20
2017-08-12T17:34:20
100,158,854
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.flingelli.security.openvas.reports.data; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; @XmlAccessorType(XmlAccessType.FIELD) public class Preference { @XmlElement private String name; @XmlElement(name = "scanner_name") private String scannerName; @XmlElement private int value; public String getName() { return name; } public String getScannerName() { return scannerName; } public int getValue() { return value; } }
UTF-8
Java
601
java
Preference.java
Java
[]
null
[]
package de.flingelli.security.openvas.reports.data; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; @XmlAccessorType(XmlAccessType.FIELD) public class Preference { @XmlElement private String name; @XmlElement(name = "scanner_name") private String scannerName; @XmlElement private int value; public String getName() { return name; } public String getScannerName() { return scannerName; } public int getValue() { return value; } }
601
0.700499
0.700499
27
21.25926
16.516193
51
false
false
0
0
0
0
0
0
0.37037
false
false
10
d0a28d2beddc0fcdbedacd604125b0d5dad7226c
7,739,531,131,888
0d8dfeb9cae93fc08d6bf1c9309c77a6b1e383ec
/src/main/java/com/wucan/handler/ExceptionHd.java
a04bf4ae9784c50f36aa8986d06dee9d4cd6e53e
[]
no_license
wucan533/test01
https://github.com/wucan533/test01
b8596852badf235b6fdc7435023acd5f40ec5a12
f446e93e5e908c43193368abc672be18adfc4937
refs/heads/master
2023-02-01T18:23:43.433000
2020-12-12T11:44:23
2020-12-12T11:44:23
320,785,045
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wucan.handler; import com.wucan.exception.AgeErrorException; import com.wucan.exception.NameErrorException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.servlet.ModelAndView; @ControllerAdvice public class ExceptionHd { @ExceptionHandler(NameErrorException.class) public ModelAndView doNameException(Exception ex){ ModelAndView mv = new ModelAndView(); mv.addObject("msg","姓名必须是张三"); mv.addObject("ex",ex); mv.setViewName("nameError"); return mv; } @ExceptionHandler(AgeErrorException.class) public ModelAndView doAgeException(Exception ex){ ModelAndView mv = new ModelAndView(); mv.addObject("msg","年龄不能大于80,或者为空"); mv.addObject("ex",ex); mv.setViewName("ageError"); return mv; } }
UTF-8
Java
954
java
ExceptionHd.java
Java
[]
null
[]
package com.wucan.handler; import com.wucan.exception.AgeErrorException; import com.wucan.exception.NameErrorException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.servlet.ModelAndView; @ControllerAdvice public class ExceptionHd { @ExceptionHandler(NameErrorException.class) public ModelAndView doNameException(Exception ex){ ModelAndView mv = new ModelAndView(); mv.addObject("msg","姓名必须是张三"); mv.addObject("ex",ex); mv.setViewName("nameError"); return mv; } @ExceptionHandler(AgeErrorException.class) public ModelAndView doAgeException(Exception ex){ ModelAndView mv = new ModelAndView(); mv.addObject("msg","年龄不能大于80,或者为空"); mv.addObject("ex",ex); mv.setViewName("ageError"); return mv; } }
954
0.717865
0.715686
28
31.785715
19.720108
64
false
false
0
0
0
0
0
0
0.714286
false
false
10
1b619141bdc046ea9df2a315610c27c69e8133a5
7,739,531,128,540
20ca701e4ac7effa2d4a7c9c8def524d46d75588
/ca.mcgill.ecse223.kingdomino/src/test/java/ca/mcgill/ecse223/kingdomino/features/VerifyNeighborAdjacencyStepDefinitions.java
c2a43ac12e0ff8444706d861dbc860096c68821d
[]
no_license
chaggysen/McGill-ModelBasedProgramming-Project
https://github.com/chaggysen/McGill-ModelBasedProgramming-Project
e5bea5461683e6cd7faf703a9148c3817533e718
12add5c0e0f3580e58700880f77c60220655f738
refs/heads/master
2023-02-09T23:36:53.480000
2020-12-22T23:24:39
2020-12-22T23:24:39
323,751,323
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ca.mcgill.ecse223.kingdomino.features; import static org.junit.Assert.assertEquals; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.List; import java.util.Map; import ca.mcgill.ecse223.kingdomino.KingdominoApplication; import ca.mcgill.ecse223.kingdomino.controller.KingdominoController; import ca.mcgill.ecse223.kingdomino.model.Castle; import ca.mcgill.ecse223.kingdomino.model.Domino; import ca.mcgill.ecse223.kingdomino.model.Domino.DominoStatus; import ca.mcgill.ecse223.kingdomino.model.DominoInKingdom; import ca.mcgill.ecse223.kingdomino.model.DominoInKingdom.DirectionKind; import ca.mcgill.ecse223.kingdomino.model.Draft.DraftStatus; import ca.mcgill.ecse223.kingdomino.model.Game; import ca.mcgill.ecse223.kingdomino.model.Kingdom; import ca.mcgill.ecse223.kingdomino.model.Kingdomino; import ca.mcgill.ecse223.kingdomino.model.Player; import ca.mcgill.ecse223.kingdomino.model.Player.PlayerColor; import ca.mcgill.ecse223.kingdomino.model.TerrainType; import io.cucumber.java.en.Given; import io.cucumber.java.en.Then; import io.cucumber.java.en.When; /** * * @author Sen Wang * */ public class VerifyNeighborAdjacencyStepDefinitions { @Given("the game is initialized for neighbor adjacency") public void the_game_is_initialized_for_neighbor_adjacency() { // Intialize empty game Kingdomino kingdomino = new Kingdomino(); Game game = new Game(48, kingdomino); kingdomino.setCurrentGame(game); // Populate game addDefaultUsersAndPlayers(game); createAllDominoes(game); game.setNextPlayer(game.getPlayer(0)); KingdominoApplication.setKingdomino(kingdomino); } @When("check current preplaced domino adjacency is initiated") public void check_current_preplaced_domino_adjacency_is_initiated() { Game game = KingdominoApplication.getKingdomino().getCurrentGame(); Kingdom kingdom = game.getPlayer(0).getKingdom(); // Domino 1 int id_1 = 15; int posx_1 = 1; int posy_1 = 2; DirectionKind dir_1 = DirectionKind.Right; Domino dominoToPlace_1 = getdominoByID(id_1); DominoInKingdom domInKingdom_1 = new DominoInKingdom(posx_1, posy_1, kingdom, dominoToPlace_1); domInKingdom_1.setDirection(dir_1); for (int i = 1; i < game.getPlayers().get(0).getKingdom().getTerritories().size(); i++) { DominoInKingdom dominoToBeCompared = (DominoInKingdom) game.getPlayer(0).getKingdom().getTerritories() .get(i); if (KingdominoController.neighborAdjacency(domInKingdom_1, dominoToBeCompared)) { dominoToPlace_1.setStatus(DominoStatus.CorrectlyPreplaced); } } // Domino 2 int id_2 = 15; int posx_2 = 1; int posy_2 = 3; DirectionKind dir_2 = DirectionKind.Down; Domino dominoToPlace_2 = getdominoByID(id_2); DominoInKingdom domInKingdom_2 = new DominoInKingdom(posx_2, posy_2, kingdom, dominoToPlace_2); domInKingdom_2.setDirection(dir_2); for (int i = 1; i < game.getPlayers().get(0).getKingdom().getTerritories().size(); i++) { DominoInKingdom dominoToBeCompared = (DominoInKingdom) game.getPlayer(0).getKingdom().getTerritories() .get(i); if (KingdominoController.neighborAdjacency(domInKingdom_2, dominoToBeCompared)) { dominoToPlace_2.setStatus(DominoStatus.CorrectlyPreplaced); } } // Domino 3 int id_3 = 20; int posx_3 = 2; int posy_3 = 2; DirectionKind dir_3 = DirectionKind.Left; Domino dominoToPlace_3 = getdominoByID(id_3); DominoInKingdom domInKingdom_3 = new DominoInKingdom(posx_3, posy_3, kingdom, dominoToPlace_3); domInKingdom_3.setDirection(dir_3); for (int i = 1; i < game.getPlayers().get(0).getKingdom().getTerritories().size(); i++) { DominoInKingdom dominoToBeCompared = (DominoInKingdom) game.getPlayer(0).getKingdom().getTerritories() .get(i); if (KingdominoController.neighborAdjacency(domInKingdom_3, dominoToBeCompared)) { dominoToPlace_3.setStatus(DominoStatus.CorrectlyPreplaced); } } // Domino 4 int id_4 = 12; int posx_4 = -1; int posy_4 = 0; DirectionKind dir_4 = DirectionKind.Up; Domino dominoToPlace_4 = getdominoByID(id_4); DominoInKingdom domInKingdom_4 = new DominoInKingdom(posx_4, posy_4, kingdom, dominoToPlace_4); domInKingdom_4.setDirection(dir_4); for (int i = 1; i < game.getPlayers().get(0).getKingdom().getTerritories().size(); i++) { DominoInKingdom dominoToBeCompared = (DominoInKingdom) game.getPlayer(0).getKingdom().getTerritories() .get(i); if (KingdominoController.neighborAdjacency(domInKingdom_4, dominoToBeCompared)) { dominoToPlace_4.setStatus(DominoStatus.CorrectlyPreplaced); } } // Domino 5 int id_5 = 12; int posx_5 = -1; int posy_5 = 1; DirectionKind dir_5 = DirectionKind.Up; Domino dominoToPlace_5 = getdominoByID(id_5); DominoInKingdom domInKingdom_5 = new DominoInKingdom(posx_5, posy_5, kingdom, dominoToPlace_5); domInKingdom_5.setDirection(dir_5); for (int i = 1; i < game.getPlayers().get(0).getKingdom().getTerritories().size(); i++) { DominoInKingdom dominoToBeCompared = (DominoInKingdom) game.getPlayer(0).getKingdom().getTerritories() .get(i); if (KingdominoController.neighborAdjacency(domInKingdom_5, dominoToBeCompared)) { dominoToPlace_5.setStatus(DominoStatus.CorrectlyPreplaced); } } // Domino 6 int id_6 = 44; int posx_6 = 2; int posy_6 = 0; DirectionKind dir_6 = DirectionKind.Down; Domino dominoToPlace_6 = getdominoByID(id_6); DominoInKingdom domInKingdom_6 = new DominoInKingdom(posx_6, posy_6, kingdom, dominoToPlace_6); domInKingdom_6.setDirection(dir_6); for (int i = 1; i < game.getPlayers().get(0).getKingdom().getTerritories().size(); i++) { DominoInKingdom dominoToBeCompared = (DominoInKingdom) game.getPlayer(0).getKingdom().getTerritories() .get(i); if (KingdominoController.neighborAdjacency(domInKingdom_6, dominoToBeCompared)) { dominoToPlace_6.setStatus(DominoStatus.CorrectlyPreplaced); } } // Domino 8 int id_8 = 29; int posx_8 = 1; int posy_8 = 2; DirectionKind dir_8 = DirectionKind.Up; Domino dominoToPlace_8 = getdominoByID(id_8); DominoInKingdom domInKingdom_8 = new DominoInKingdom(posx_8, posy_8, kingdom, dominoToPlace_8); domInKingdom_8.setDirection(dir_8); for (int i = 1; i < game.getPlayers().get(0).getKingdom().getTerritories().size(); i++) { DominoInKingdom dominoToBeCompared = (DominoInKingdom) game.getPlayer(0).getKingdom().getTerritories() .get(i); if (KingdominoController.neighborAdjacency(domInKingdom_8, dominoToBeCompared)) { dominoToPlace_8.setStatus(DominoStatus.CorrectlyPreplaced); } } // Domino 9 int id_9 = 48; int posx_9 = -1; int posy_9 = 3; DirectionKind dir_9 = DirectionKind.Down; Domino dominoToPlace_9 = getdominoByID(id_9); DominoInKingdom domInKingdom_9 = new DominoInKingdom(posx_9, posy_9, kingdom, dominoToPlace_9); domInKingdom_9.setDirection(dir_9); for (int i = 1; i < game.getPlayers().get(0).getKingdom().getTerritories().size(); i++) { DominoInKingdom dominoToBeCompared = (DominoInKingdom) game.getPlayer(0).getKingdom().getTerritories() .get(i); if (KingdominoController.neighborAdjacency(domInKingdom_9, dominoToBeCompared)) { dominoToPlace_9.setStatus(DominoStatus.CorrectlyPreplaced); } } // Domino 10 int id_10 = 43; int posx_10 = 1; int posy_10 = -1; DirectionKind dir_10 = DirectionKind.Right; Domino dominoToPlace_10 = getdominoByID(id_10); DominoInKingdom domInKingdom_10 = new DominoInKingdom(posx_10, posy_10, kingdom, dominoToPlace_10); domInKingdom_10.setDirection(dir_10); for (int i = 1; i < game.getPlayers().get(0).getKingdom().getTerritories().size(); i++) { DominoInKingdom dominoToBeCompared = (DominoInKingdom) game.getPlayer(0).getKingdom().getTerritories() .get(i); if (KingdominoController.neighborAdjacency(domInKingdom_10, dominoToBeCompared)) { dominoToPlace_10.setStatus(DominoStatus.CorrectlyPreplaced); } } } @Then("the current-domino\\/existing-domino adjacency is {string}") public void the_current_domino_existing_domino_adjacency_is(String string) { int correctlyPreplacedCount = 0; Game game = KingdominoApplication.getKingdomino().getCurrentGame(); for (int i = 0; i < game.getAllDominos().size(); i++) { if (game.getAllDomino(i).getStatus() == DominoStatus.CorrectlyPreplaced) { correctlyPreplacedCount += 1; } } assertEquals(4, correctlyPreplacedCount); } /////////////////////////////////////// /// -----Private Helper Methods---- /// /////////////////////////////////////// private void addDefaultUsersAndPlayers(Game game) { String[] users = { "User1", "User2", "User3", "User4" }; for (int i = 0; i < users.length; i++) { game.getKingdomino().addUser(users[i]); Player player = new Player(game); player.setColor(PlayerColor.values()[i]); Kingdom kingdom = new Kingdom(player); new Castle(0, 0, kingdom, player); } } private void createAllDominoes(Game game) { try { BufferedReader br = new BufferedReader(new FileReader("src/main/resources/alldominoes.dat")); String line = ""; String delimiters = "[:\\+()]"; while ((line = br.readLine()) != null) { String[] dominoString = line.split(delimiters); // {id, leftTerrain, rightTerrain, crowns} int dominoId = Integer.decode(dominoString[0]); TerrainType leftTerrain = getTerrainType(dominoString[1]); TerrainType rightTerrain = getTerrainType(dominoString[2]); int numCrown = 0; if (dominoString.length > 3) { numCrown = Integer.decode(dominoString[3]); } new Domino(dominoId, leftTerrain, rightTerrain, numCrown, game); } br.close(); } catch (IOException e) { e.printStackTrace(); throw new java.lang.IllegalArgumentException( "Error occured while trying to read alldominoes.dat: " + e.getMessage()); } } private Domino getdominoByID(int id) { Game game = KingdominoApplication.getKingdomino().getCurrentGame(); for (Domino domino : game.getAllDominos()) { if (domino.getId() == id) { return domino; } } throw new java.lang.IllegalArgumentException("Domino with ID " + id + " not found."); } private TerrainType getTerrainType(String terrain) { switch (terrain) { case "W": return TerrainType.WheatField; case "F": return TerrainType.Forest; case "M": return TerrainType.Mountain; case "G": return TerrainType.Grass; case "S": return TerrainType.Swamp; case "L": return TerrainType.Lake; default: throw new java.lang.IllegalArgumentException("Invalid terrain type: " + terrain); } } private DirectionKind getDirection(String dir) { switch (dir) { case "up": return DirectionKind.Up; case "down": return DirectionKind.Down; case "left": return DirectionKind.Left; case "right": return DirectionKind.Right; default: throw new java.lang.IllegalArgumentException("Invalid direction: " + dir); } } private DominoStatus getDominoStatus(String status) { switch (status) { case "inPile": return DominoStatus.InPile; case "excluded": return DominoStatus.Excluded; case "inCurrentDraft": return DominoStatus.InCurrentDraft; case "inNextDraft": return DominoStatus.InNextDraft; case "erroneouslyPreplaced": return DominoStatus.ErroneouslyPreplaced; case "correctlyPreplaced": return DominoStatus.CorrectlyPreplaced; case "placedInKingdom": return DominoStatus.PlacedInKingdom; case "discarded": return DominoStatus.Discarded; default: throw new java.lang.IllegalArgumentException("Invalid domino status: " + status); } } }
UTF-8
Java
11,576
java
VerifyNeighborAdjacencyStepDefinitions.java
Java
[ { "context": "port io.cucumber.java.en.When;\n\n/**\n * \n * @author Sen Wang\n *\n */\npublic class VerifyNeighborAdjacencyStepDe", "end": 1158, "score": 0.9997556209564209, "start": 1150, "tag": "NAME", "value": "Sen Wang" } ]
null
[]
package ca.mcgill.ecse223.kingdomino.features; import static org.junit.Assert.assertEquals; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.List; import java.util.Map; import ca.mcgill.ecse223.kingdomino.KingdominoApplication; import ca.mcgill.ecse223.kingdomino.controller.KingdominoController; import ca.mcgill.ecse223.kingdomino.model.Castle; import ca.mcgill.ecse223.kingdomino.model.Domino; import ca.mcgill.ecse223.kingdomino.model.Domino.DominoStatus; import ca.mcgill.ecse223.kingdomino.model.DominoInKingdom; import ca.mcgill.ecse223.kingdomino.model.DominoInKingdom.DirectionKind; import ca.mcgill.ecse223.kingdomino.model.Draft.DraftStatus; import ca.mcgill.ecse223.kingdomino.model.Game; import ca.mcgill.ecse223.kingdomino.model.Kingdom; import ca.mcgill.ecse223.kingdomino.model.Kingdomino; import ca.mcgill.ecse223.kingdomino.model.Player; import ca.mcgill.ecse223.kingdomino.model.Player.PlayerColor; import ca.mcgill.ecse223.kingdomino.model.TerrainType; import io.cucumber.java.en.Given; import io.cucumber.java.en.Then; import io.cucumber.java.en.When; /** * * @author <NAME> * */ public class VerifyNeighborAdjacencyStepDefinitions { @Given("the game is initialized for neighbor adjacency") public void the_game_is_initialized_for_neighbor_adjacency() { // Intialize empty game Kingdomino kingdomino = new Kingdomino(); Game game = new Game(48, kingdomino); kingdomino.setCurrentGame(game); // Populate game addDefaultUsersAndPlayers(game); createAllDominoes(game); game.setNextPlayer(game.getPlayer(0)); KingdominoApplication.setKingdomino(kingdomino); } @When("check current preplaced domino adjacency is initiated") public void check_current_preplaced_domino_adjacency_is_initiated() { Game game = KingdominoApplication.getKingdomino().getCurrentGame(); Kingdom kingdom = game.getPlayer(0).getKingdom(); // Domino 1 int id_1 = 15; int posx_1 = 1; int posy_1 = 2; DirectionKind dir_1 = DirectionKind.Right; Domino dominoToPlace_1 = getdominoByID(id_1); DominoInKingdom domInKingdom_1 = new DominoInKingdom(posx_1, posy_1, kingdom, dominoToPlace_1); domInKingdom_1.setDirection(dir_1); for (int i = 1; i < game.getPlayers().get(0).getKingdom().getTerritories().size(); i++) { DominoInKingdom dominoToBeCompared = (DominoInKingdom) game.getPlayer(0).getKingdom().getTerritories() .get(i); if (KingdominoController.neighborAdjacency(domInKingdom_1, dominoToBeCompared)) { dominoToPlace_1.setStatus(DominoStatus.CorrectlyPreplaced); } } // Domino 2 int id_2 = 15; int posx_2 = 1; int posy_2 = 3; DirectionKind dir_2 = DirectionKind.Down; Domino dominoToPlace_2 = getdominoByID(id_2); DominoInKingdom domInKingdom_2 = new DominoInKingdom(posx_2, posy_2, kingdom, dominoToPlace_2); domInKingdom_2.setDirection(dir_2); for (int i = 1; i < game.getPlayers().get(0).getKingdom().getTerritories().size(); i++) { DominoInKingdom dominoToBeCompared = (DominoInKingdom) game.getPlayer(0).getKingdom().getTerritories() .get(i); if (KingdominoController.neighborAdjacency(domInKingdom_2, dominoToBeCompared)) { dominoToPlace_2.setStatus(DominoStatus.CorrectlyPreplaced); } } // Domino 3 int id_3 = 20; int posx_3 = 2; int posy_3 = 2; DirectionKind dir_3 = DirectionKind.Left; Domino dominoToPlace_3 = getdominoByID(id_3); DominoInKingdom domInKingdom_3 = new DominoInKingdom(posx_3, posy_3, kingdom, dominoToPlace_3); domInKingdom_3.setDirection(dir_3); for (int i = 1; i < game.getPlayers().get(0).getKingdom().getTerritories().size(); i++) { DominoInKingdom dominoToBeCompared = (DominoInKingdom) game.getPlayer(0).getKingdom().getTerritories() .get(i); if (KingdominoController.neighborAdjacency(domInKingdom_3, dominoToBeCompared)) { dominoToPlace_3.setStatus(DominoStatus.CorrectlyPreplaced); } } // Domino 4 int id_4 = 12; int posx_4 = -1; int posy_4 = 0; DirectionKind dir_4 = DirectionKind.Up; Domino dominoToPlace_4 = getdominoByID(id_4); DominoInKingdom domInKingdom_4 = new DominoInKingdom(posx_4, posy_4, kingdom, dominoToPlace_4); domInKingdom_4.setDirection(dir_4); for (int i = 1; i < game.getPlayers().get(0).getKingdom().getTerritories().size(); i++) { DominoInKingdom dominoToBeCompared = (DominoInKingdom) game.getPlayer(0).getKingdom().getTerritories() .get(i); if (KingdominoController.neighborAdjacency(domInKingdom_4, dominoToBeCompared)) { dominoToPlace_4.setStatus(DominoStatus.CorrectlyPreplaced); } } // Domino 5 int id_5 = 12; int posx_5 = -1; int posy_5 = 1; DirectionKind dir_5 = DirectionKind.Up; Domino dominoToPlace_5 = getdominoByID(id_5); DominoInKingdom domInKingdom_5 = new DominoInKingdom(posx_5, posy_5, kingdom, dominoToPlace_5); domInKingdom_5.setDirection(dir_5); for (int i = 1; i < game.getPlayers().get(0).getKingdom().getTerritories().size(); i++) { DominoInKingdom dominoToBeCompared = (DominoInKingdom) game.getPlayer(0).getKingdom().getTerritories() .get(i); if (KingdominoController.neighborAdjacency(domInKingdom_5, dominoToBeCompared)) { dominoToPlace_5.setStatus(DominoStatus.CorrectlyPreplaced); } } // Domino 6 int id_6 = 44; int posx_6 = 2; int posy_6 = 0; DirectionKind dir_6 = DirectionKind.Down; Domino dominoToPlace_6 = getdominoByID(id_6); DominoInKingdom domInKingdom_6 = new DominoInKingdom(posx_6, posy_6, kingdom, dominoToPlace_6); domInKingdom_6.setDirection(dir_6); for (int i = 1; i < game.getPlayers().get(0).getKingdom().getTerritories().size(); i++) { DominoInKingdom dominoToBeCompared = (DominoInKingdom) game.getPlayer(0).getKingdom().getTerritories() .get(i); if (KingdominoController.neighborAdjacency(domInKingdom_6, dominoToBeCompared)) { dominoToPlace_6.setStatus(DominoStatus.CorrectlyPreplaced); } } // Domino 8 int id_8 = 29; int posx_8 = 1; int posy_8 = 2; DirectionKind dir_8 = DirectionKind.Up; Domino dominoToPlace_8 = getdominoByID(id_8); DominoInKingdom domInKingdom_8 = new DominoInKingdom(posx_8, posy_8, kingdom, dominoToPlace_8); domInKingdom_8.setDirection(dir_8); for (int i = 1; i < game.getPlayers().get(0).getKingdom().getTerritories().size(); i++) { DominoInKingdom dominoToBeCompared = (DominoInKingdom) game.getPlayer(0).getKingdom().getTerritories() .get(i); if (KingdominoController.neighborAdjacency(domInKingdom_8, dominoToBeCompared)) { dominoToPlace_8.setStatus(DominoStatus.CorrectlyPreplaced); } } // Domino 9 int id_9 = 48; int posx_9 = -1; int posy_9 = 3; DirectionKind dir_9 = DirectionKind.Down; Domino dominoToPlace_9 = getdominoByID(id_9); DominoInKingdom domInKingdom_9 = new DominoInKingdom(posx_9, posy_9, kingdom, dominoToPlace_9); domInKingdom_9.setDirection(dir_9); for (int i = 1; i < game.getPlayers().get(0).getKingdom().getTerritories().size(); i++) { DominoInKingdom dominoToBeCompared = (DominoInKingdom) game.getPlayer(0).getKingdom().getTerritories() .get(i); if (KingdominoController.neighborAdjacency(domInKingdom_9, dominoToBeCompared)) { dominoToPlace_9.setStatus(DominoStatus.CorrectlyPreplaced); } } // Domino 10 int id_10 = 43; int posx_10 = 1; int posy_10 = -1; DirectionKind dir_10 = DirectionKind.Right; Domino dominoToPlace_10 = getdominoByID(id_10); DominoInKingdom domInKingdom_10 = new DominoInKingdom(posx_10, posy_10, kingdom, dominoToPlace_10); domInKingdom_10.setDirection(dir_10); for (int i = 1; i < game.getPlayers().get(0).getKingdom().getTerritories().size(); i++) { DominoInKingdom dominoToBeCompared = (DominoInKingdom) game.getPlayer(0).getKingdom().getTerritories() .get(i); if (KingdominoController.neighborAdjacency(domInKingdom_10, dominoToBeCompared)) { dominoToPlace_10.setStatus(DominoStatus.CorrectlyPreplaced); } } } @Then("the current-domino\\/existing-domino adjacency is {string}") public void the_current_domino_existing_domino_adjacency_is(String string) { int correctlyPreplacedCount = 0; Game game = KingdominoApplication.getKingdomino().getCurrentGame(); for (int i = 0; i < game.getAllDominos().size(); i++) { if (game.getAllDomino(i).getStatus() == DominoStatus.CorrectlyPreplaced) { correctlyPreplacedCount += 1; } } assertEquals(4, correctlyPreplacedCount); } /////////////////////////////////////// /// -----Private Helper Methods---- /// /////////////////////////////////////// private void addDefaultUsersAndPlayers(Game game) { String[] users = { "User1", "User2", "User3", "User4" }; for (int i = 0; i < users.length; i++) { game.getKingdomino().addUser(users[i]); Player player = new Player(game); player.setColor(PlayerColor.values()[i]); Kingdom kingdom = new Kingdom(player); new Castle(0, 0, kingdom, player); } } private void createAllDominoes(Game game) { try { BufferedReader br = new BufferedReader(new FileReader("src/main/resources/alldominoes.dat")); String line = ""; String delimiters = "[:\\+()]"; while ((line = br.readLine()) != null) { String[] dominoString = line.split(delimiters); // {id, leftTerrain, rightTerrain, crowns} int dominoId = Integer.decode(dominoString[0]); TerrainType leftTerrain = getTerrainType(dominoString[1]); TerrainType rightTerrain = getTerrainType(dominoString[2]); int numCrown = 0; if (dominoString.length > 3) { numCrown = Integer.decode(dominoString[3]); } new Domino(dominoId, leftTerrain, rightTerrain, numCrown, game); } br.close(); } catch (IOException e) { e.printStackTrace(); throw new java.lang.IllegalArgumentException( "Error occured while trying to read alldominoes.dat: " + e.getMessage()); } } private Domino getdominoByID(int id) { Game game = KingdominoApplication.getKingdomino().getCurrentGame(); for (Domino domino : game.getAllDominos()) { if (domino.getId() == id) { return domino; } } throw new java.lang.IllegalArgumentException("Domino with ID " + id + " not found."); } private TerrainType getTerrainType(String terrain) { switch (terrain) { case "W": return TerrainType.WheatField; case "F": return TerrainType.Forest; case "M": return TerrainType.Mountain; case "G": return TerrainType.Grass; case "S": return TerrainType.Swamp; case "L": return TerrainType.Lake; default: throw new java.lang.IllegalArgumentException("Invalid terrain type: " + terrain); } } private DirectionKind getDirection(String dir) { switch (dir) { case "up": return DirectionKind.Up; case "down": return DirectionKind.Down; case "left": return DirectionKind.Left; case "right": return DirectionKind.Right; default: throw new java.lang.IllegalArgumentException("Invalid direction: " + dir); } } private DominoStatus getDominoStatus(String status) { switch (status) { case "inPile": return DominoStatus.InPile; case "excluded": return DominoStatus.Excluded; case "inCurrentDraft": return DominoStatus.InCurrentDraft; case "inNextDraft": return DominoStatus.InNextDraft; case "erroneouslyPreplaced": return DominoStatus.ErroneouslyPreplaced; case "correctlyPreplaced": return DominoStatus.CorrectlyPreplaced; case "placedInKingdom": return DominoStatus.PlacedInKingdom; case "discarded": return DominoStatus.Discarded; default: throw new java.lang.IllegalArgumentException("Invalid domino status: " + status); } } }
11,574
0.720888
0.696786
322
34.95031
30.138252
105
false
false
0
0
0
0
0
0
2.695652
false
false
10
baee88a5ee8068870e231534e7b823681f746ee1
22,187,801,097,726
bce4a3b63c26f8b8dd62a5fc6a490d3d102c184d
/api/src/main/java/com/handyman/api/controllers/CustomerOpsController.java
8a61a616f3c1cc216c79aa70489b0dae6e9614e0
[]
no_license
DarkCrawler/handyman
https://github.com/DarkCrawler/handyman
f126e55344522af2bf1043bbfc8b405f7ab9d17a
16fdb92679eedb4ad0ea0ffe126b143884e2e5a7
refs/heads/master
2021-09-06T21:29:06.426000
2018-02-11T19:08:08
2018-02-11T19:08:08
115,243,133
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.handyman.api.controllers; import com.handyman.api.services.UserRelatedServices; import com.handyman.models.implementation.users.UserImpl; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import javax.validation.Valid; @RestController @Slf4j public class CustomerOpsController { @Resource UserRelatedServices userRelatedService; @RequestMapping(method = RequestMethod.POST, value = "/user/insert", produces = "application/json") public String insertNewUser(@RequestBody @Valid UserImpl newUser) { log.info("Recieved new user creation request"); return userRelatedService.createAndPersistNewUser(newUser); } }
UTF-8
Java
916
java
CustomerOpsController.java
Java
[]
null
[]
package com.handyman.api.controllers; import com.handyman.api.services.UserRelatedServices; import com.handyman.models.implementation.users.UserImpl; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import javax.validation.Valid; @RestController @Slf4j public class CustomerOpsController { @Resource UserRelatedServices userRelatedService; @RequestMapping(method = RequestMethod.POST, value = "/user/insert", produces = "application/json") public String insertNewUser(@RequestBody @Valid UserImpl newUser) { log.info("Recieved new user creation request"); return userRelatedService.createAndPersistNewUser(newUser); } }
916
0.814411
0.811135
25
35.639999
28.464546
102
false
false
0
0
0
0
0
0
0.6
false
false
10
96cec9b04c68737d58b8674bd20c674dd080217c
19,035,295,091,947
20ecb37012c8b4e8dffdf1bf1180a7c4224d399d
/part-time-platform/src/main/java/com/ruoyi/partTime/domain/PtpWorkExperience.java
a4fc4363c4c885b6bf0514afad98f17a69a98cf4
[ "MIT" ]
permissive
kxr224/wanglei
https://github.com/kxr224/wanglei
6313e1ae8bb72fad929993dd8235ee83a7e99709
d1c1baa1eed2a72d697216e738f504657e9539aa
refs/heads/master
2022-09-15T02:41:31.711000
2019-05-26T16:10:23
2019-05-26T16:10:23
187,741,800
0
0
MIT
false
2022-09-01T23:07:25
2019-05-21T01:49:14
2019-05-26T16:10:40
2022-09-01T23:07:22
6,903
0
0
7
Java
false
false
package com.ruoyi.partTime.domain; import lombok.AllArgsConstructor; import lombok.NoArgsConstructor; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import com.ruoyi.common.core.domain.BaseEntity; import lombok.Data; import lombok.EqualsAndHashCode; /** * 工作经历表 ptp_work_experience * * @author ruoyi * @date 2019-05-20 */ @Data @AllArgsConstructor @NoArgsConstructor @EqualsAndHashCode(callSuper = true) public class PtpWorkExperience extends BaseEntity{ private static final long serialVersionUID = 1L; /** 主键 */ private Integer id; /** 用户主键 */ private Integer userId; /** 工作经历 */ private String workExperience; public PtpWorkExperience(Integer userId, String workExperience) { this.userId = userId; this.workExperience = workExperience; } }
UTF-8
Java
862
java
PtpWorkExperience.java
Java
[ { "context": ";\n\n/**\n * 工作经历表 ptp_work_experience\n * \n * @author ruoyi\n * @date 2019-05-20\n */\n@Data\n@AllArgsConstructor", "end": 370, "score": 0.9993861317634583, "start": 365, "tag": "USERNAME", "value": "ruoyi" } ]
null
[]
package com.ruoyi.partTime.domain; import lombok.AllArgsConstructor; import lombok.NoArgsConstructor; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import com.ruoyi.common.core.domain.BaseEntity; import lombok.Data; import lombok.EqualsAndHashCode; /** * 工作经历表 ptp_work_experience * * @author ruoyi * @date 2019-05-20 */ @Data @AllArgsConstructor @NoArgsConstructor @EqualsAndHashCode(callSuper = true) public class PtpWorkExperience extends BaseEntity{ private static final long serialVersionUID = 1L; /** 主键 */ private Integer id; /** 用户主键 */ private Integer userId; /** 工作经历 */ private String workExperience; public PtpWorkExperience(Integer userId, String workExperience) { this.userId = userId; this.workExperience = workExperience; } }
862
0.77524
0.762019
35
22.771429
18.391125
66
false
false
0
0
0
0
0
0
0.828571
false
false
10
ac2abfa9a7c30e551abae11ae214b7804e16ace7
17,300,128,299,608
d5377f7edb9a7cc9367e5db460e661aba6219570
/app/src/main/java/com/cloudvision/tanzhenv2/order/wifi/ping/connectivity/RemoteResource.java
3914d9373f3a7a5292e53c67b698176312ce7098
[]
no_license
LP1991/NETAPP
https://github.com/LP1991/NETAPP
3665f07201e25bb00a36fede64d70dff2348ab07
95875b58010ab68c8699c2c71eb7fb7097cf4c57
refs/heads/master
2021-01-20T19:56:36.445000
2016-07-05T07:17:02
2016-07-05T07:17:02
62,614,475
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cloudvision.tanzhenv2.order.wifi.ping.connectivity; import java.net.MalformedURLException; import java.net.URL; /** * Created by User on 17/07/2015. */ public class RemoteResource implements IRemoteResource { private String protocol; private String path; private IRemoteDestination destination; private URL url; public RemoteResource(String protocol, IRemoteDestination destination, String path) { this.protocol = protocol; this.destination = destination; this.path = path; try { this.url = new URL(protocol, destination.getAddress().getHostAddress(), destination.getPort(), path); } catch (MalformedURLException e) { e.printStackTrace(); System.exit(1); } } @Override public String getProtocol() { return protocol; } @Override public String getPath() { return path; } @Override public IRemoteDestination getDestination() { return destination; } @Override public URL getURL() { return url; } }
UTF-8
Java
1,104
java
RemoteResource.java
Java
[]
null
[]
package com.cloudvision.tanzhenv2.order.wifi.ping.connectivity; import java.net.MalformedURLException; import java.net.URL; /** * Created by User on 17/07/2015. */ public class RemoteResource implements IRemoteResource { private String protocol; private String path; private IRemoteDestination destination; private URL url; public RemoteResource(String protocol, IRemoteDestination destination, String path) { this.protocol = protocol; this.destination = destination; this.path = path; try { this.url = new URL(protocol, destination.getAddress().getHostAddress(), destination.getPort(), path); } catch (MalformedURLException e) { e.printStackTrace(); System.exit(1); } } @Override public String getProtocol() { return protocol; } @Override public String getPath() { return path; } @Override public IRemoteDestination getDestination() { return destination; } @Override public URL getURL() { return url; } }
1,104
0.641304
0.632246
47
22.489361
23.246021
113
false
false
0
0
0
0
0
0
0.468085
false
false
10
724559d68e2b74ac818c4e28cb02efc6f3065c40
22,445,499,124,063
ea344095ec704a74be8a97aace1cd38872863303
/workspace/PBP3/src/main/java/com/buckwa/service/impl/admin/HolidayServiceImpl.java
406bdc293ba2ae74b2eadcd2a9aa8aa1fe365803
[]
no_license
buckwa/BaiwaFramework
https://github.com/buckwa/BaiwaFramework
bf63a690ddb5518bb9bafd03d4cde8f1898c041c
fd89a0d0424f15ad58cd18681fc9e56451f2547b
refs/heads/master
2021-01-24T10:40:47.852000
2018-09-13T06:56:12
2018-09-13T06:56:12
70,311,217
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.buckwa.service.impl.admin; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.slf4j.Logger;import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DuplicateKeyException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.buckwa.dao.intf.admin.HolidayDao; import com.buckwa.domain.admin.Holiday; import com.buckwa.domain.admin.HolidayCriteria; import com.buckwa.domain.common.BuckWaRequest; import com.buckwa.domain.common.BuckWaResponse; import com.buckwa.domain.common.PagingBean; import com.buckwa.service.intf.admin.HolidayService; import com.buckwa.util.BuckWaConstants; @Service("holidayService") public class HolidayServiceImpl implements HolidayService { private static Logger logger = LoggerFactory.getLogger(HolidayServiceImpl.class); @Autowired private HolidayDao holidayDao; @Override public BuckWaResponse getAll() { if(logger.isInfoEnabled()){ logger.info(this.getClass().toString()+"-getAll-"); } BuckWaResponse response = new BuckWaResponse(); try{ List<Holiday> holidayList = holidayDao.getAllHoliday(); response.addResponse("holidayList",holidayList); }catch(Exception ex){ ex.printStackTrace(); response.setStatus(BuckWaConstants.FAIL); response.setErrorCode("E001"); } // response.setSuccessCode("S001"); return response; } @Override @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW) public BuckWaResponse create(BuckWaRequest request) { if(logger.isInfoEnabled()){ logger.info(this.getClass().toString()+"-create-"); } BuckWaResponse response = new BuckWaResponse(); try{ HolidayCriteria holidayCriteria = (HolidayCriteria)request.get("holidayCriteria"); boolean isExist = false; if(holidayCriteria!=null && holidayCriteria.getHolidayName().length()>1 ){ DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); List<Date> listDuration = new ArrayList<Date>(); if(holidayCriteria.getIsDurationDate().equalsIgnoreCase("true") &&holidayCriteria.getMinDate()!=null && holidayCriteria.getMinDate().length()>0 &&holidayCriteria.getMaxDate()!=null && holidayCriteria.getMaxDate().length()>0){ if(logger.isInfoEnabled()){ logger.info("- duration Date -"); logger.info("- minDate: "+holidayCriteria.getMinDate()); logger.info("- maxDate: "+holidayCriteria.getMaxDate()); } /* BEGIN: try from * http://stackoverflow.com/questions/2689379/how-to-get-a-list-of-dates-between-two-dates-in-java */ Date startDate = (Date)formatter.parse(holidayCriteria.getMinDate()); Date endDate = (Date)formatter.parse(holidayCriteria.getMaxDate()); long interval = 24*1000 * 60 * 60; // 1 Day in millis long endTime =endDate.getTime() ; // create your endtime here, possibly using Calendar or Date long curTime = startDate.getTime(); while (curTime <= endTime) { listDuration.add(new Date(curTime)); curTime += interval; } /* END: try */ }else if(!holidayCriteria.getIsDurationDate().equalsIgnoreCase("true") && holidayCriteria.getHolidayDate()!=null && holidayCriteria.getHolidayDate().length()>0){ if(logger.isInfoEnabled()){ logger.info("- singleDate: "+ holidayCriteria.getHolidayDate()); } listDuration.add((Date)formatter.parse(holidayCriteria.getHolidayDate())); }else{ throw new Exception("Something Abnormal!"); } if(logger.isInfoEnabled()){ for(int i=0;i<listDuration.size();i++){ Date lDate =(Date)listDuration.get(i); String ds = formatter.format(lDate); logger.info(" Date is ..." + ds); } } for(int i=0; i<listDuration.size(); i++){ Holiday holiday = new Holiday(); holiday.setYearId(holidayCriteria.getYearId()); holiday.setHolidayDate(formatter.format(listDuration.get(i))); holiday.setHolidayName(holidayCriteria.getHolidayName()); holiday.setHolidayDesc(holidayCriteria.getHolidayDesc()); isExist = holidayDao.isHolidayExist(holiday); if(isExist){ response.setErrorCode("E002"); response.setStatus(BuckWaConstants.FAIL); break; } } if(!isExist){ for(int i=0; i<listDuration.size(); i++){ Holiday holiday = new Holiday(); holiday.setYearId(holidayCriteria.getYearId()); holiday.setHolidayDate(formatter.format(listDuration.get(i))); holiday.setHolidayName(holidayCriteria.getHolidayName()); holiday.setHolidayDesc(holidayCriteria.getHolidayDesc()); holiday.setEnable(holidayCriteria.isEnable()); holidayDao.create(holiday); } response.setSuccessCode("S001"); } }else{ response.setErrorCode("E017"); response.setStatus(BuckWaConstants.FAIL); } }catch(DuplicateKeyException dx){ response.setStatus(BuckWaConstants.FAIL); response.setErrorCode("E002"); }catch(Exception ex){ ex.printStackTrace(); if(ex.getMessage().equals("Something Abnormal!")){ response.setErrorCode("E017"); }else{ response.setErrorCode("E001"); } response.setStatus(BuckWaConstants.FAIL); } // Success return S001 response.setSuccessCode("S001"); return response; } @Override @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW) public BuckWaResponse update(BuckWaRequest request) { if(logger.isInfoEnabled()){ logger.info(this.getClass().toString()+"-update-"); } BuckWaResponse response = new BuckWaResponse(); try{ Holiday holiday = (Holiday)request.get("holiday"); response.setStatus(BuckWaConstants.FAIL); if(holiday.getHolidayName().length() <1){ response.setErrorCode("E017"); }else{ Holiday oldHoliday = holidayDao.getHolidayById(holiday.getHolidayId()); boolean isExist = holidayDao.isHolidayExist(holiday); boolean isSameYear = oldHoliday.getYearId().equals(holiday.getYearId()); boolean isSameDate = oldHoliday.getHolidayDate().equals(holiday.getHolidayDate()); boolean isSameDesc = oldHoliday.getHolidayDesc().equals(holiday.getHolidayDesc()); boolean isSameName = oldHoliday.getHolidayName().equals(holiday.getHolidayName()); boolean isSameEnable = oldHoliday.isEnable()==holiday.isEnable(); boolean isDirty = !(isSameYear&&isSameDate&&isSameDesc&&isSameEnable&&isSameName); if(!isExist||isDirty){ holidayDao.update(holiday); response.setSuccessCode("S002"); response.setStatus(BuckWaConstants.SUCCESS); }else{ response.setErrorCode("E002"); } } }catch(Exception ex){ ex.printStackTrace(); response.setStatus(BuckWaConstants.FAIL); response.setErrorCode("E001"); } return response; } @Override public BuckWaResponse getByOffset(BuckWaRequest request) { if(logger.isInfoEnabled()){ logger.info(this.getClass().toString()+"-getByOffset-"); } BuckWaResponse response = new BuckWaResponse(); try{ PagingBean pagingBean = (PagingBean)request.get("pagingBean"); PagingBean returnBean = holidayDao.getAllHolidayByOffset(pagingBean); response.addResponse("pagingBean",returnBean); }catch(Exception ex){ ex.printStackTrace(); response.setStatus(BuckWaConstants.FAIL); response.setErrorCode("E001"); } // Success return S001 // response.setSuccessCode("S001"); return response; } @Override public BuckWaResponse getByOffsetYear(BuckWaRequest request) { if(logger.isInfoEnabled()){ logger.info(this.getClass().toString()+"-getByOffset-"); } BuckWaResponse response = new BuckWaResponse(); try{ PagingBean pagingBean = (PagingBean)request.get("pagingBean"); PagingBean returnBean = holidayDao.getAllHolidayByOffsetYear(pagingBean); response.addResponse("pagingBean",returnBean); }catch(Exception ex){ ex.printStackTrace(); response.setStatus(BuckWaConstants.FAIL); response.setErrorCode("E001"); } // Success return S001 // response.setSuccessCode("S001"); return response; } @Override public BuckWaResponse getById(BuckWaRequest request) { if(logger.isInfoEnabled()){ logger.info(this.getClass().toString()+"-getById-"); } BuckWaResponse response = new BuckWaResponse(); try{ String holidayId = (String)request.get("holidayId"); Holiday holiday = holidayDao.getHolidayById(holidayId); response.addResponse("holiday",holiday); }catch(Exception ex){ ex.printStackTrace(); response.setStatus(BuckWaConstants.FAIL); response.setErrorCode("E001"); } // Success return S001 // response.setSuccessCode("S001"); return response; } @Override public BuckWaResponse deleteById(BuckWaRequest request) { if(logger.isInfoEnabled()){ logger.info(this.getClass().toString()+"-deleteById-"); } BuckWaResponse response = new BuckWaResponse(); try{ String id = request.get("holidayId").toString(); // Check Is using Holiday targetHoliday = holidayDao.getHolidayById(id); if(targetHoliday==null){ response.setStatus(BuckWaConstants.FAIL); response.setErrorCode("E010"); }else{ holidayDao.deleteHolidayById(id); } }catch(Exception ex){ ex.printStackTrace(); response.setStatus(BuckWaConstants.FAIL); response.setErrorCode("E001"); } response.setSuccessCode("D001"); return response; } public BuckWaResponse getHolidayByYear(BuckWaRequest request){ if(logger.isInfoEnabled()){ logger.info(this.getClass().toString()+"-getHolidayByYear-"); } BuckWaResponse response = new BuckWaResponse(); try{ String holidayId = request.get("holidayId").toString(); List<Holiday> holidayList = holidayDao.getHolidayByYear(holidayId); response.addResponse("holidayList",holidayList); }catch(Exception ex){ ex.printStackTrace(); response.setStatus(BuckWaConstants.FAIL); response.setErrorCode("E001"); } return response; } }
UTF-8
Java
10,283
java
HolidayServiceImpl.java
Java
[]
null
[]
package com.buckwa.service.impl.admin; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.slf4j.Logger;import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DuplicateKeyException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.buckwa.dao.intf.admin.HolidayDao; import com.buckwa.domain.admin.Holiday; import com.buckwa.domain.admin.HolidayCriteria; import com.buckwa.domain.common.BuckWaRequest; import com.buckwa.domain.common.BuckWaResponse; import com.buckwa.domain.common.PagingBean; import com.buckwa.service.intf.admin.HolidayService; import com.buckwa.util.BuckWaConstants; @Service("holidayService") public class HolidayServiceImpl implements HolidayService { private static Logger logger = LoggerFactory.getLogger(HolidayServiceImpl.class); @Autowired private HolidayDao holidayDao; @Override public BuckWaResponse getAll() { if(logger.isInfoEnabled()){ logger.info(this.getClass().toString()+"-getAll-"); } BuckWaResponse response = new BuckWaResponse(); try{ List<Holiday> holidayList = holidayDao.getAllHoliday(); response.addResponse("holidayList",holidayList); }catch(Exception ex){ ex.printStackTrace(); response.setStatus(BuckWaConstants.FAIL); response.setErrorCode("E001"); } // response.setSuccessCode("S001"); return response; } @Override @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW) public BuckWaResponse create(BuckWaRequest request) { if(logger.isInfoEnabled()){ logger.info(this.getClass().toString()+"-create-"); } BuckWaResponse response = new BuckWaResponse(); try{ HolidayCriteria holidayCriteria = (HolidayCriteria)request.get("holidayCriteria"); boolean isExist = false; if(holidayCriteria!=null && holidayCriteria.getHolidayName().length()>1 ){ DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); List<Date> listDuration = new ArrayList<Date>(); if(holidayCriteria.getIsDurationDate().equalsIgnoreCase("true") &&holidayCriteria.getMinDate()!=null && holidayCriteria.getMinDate().length()>0 &&holidayCriteria.getMaxDate()!=null && holidayCriteria.getMaxDate().length()>0){ if(logger.isInfoEnabled()){ logger.info("- duration Date -"); logger.info("- minDate: "+holidayCriteria.getMinDate()); logger.info("- maxDate: "+holidayCriteria.getMaxDate()); } /* BEGIN: try from * http://stackoverflow.com/questions/2689379/how-to-get-a-list-of-dates-between-two-dates-in-java */ Date startDate = (Date)formatter.parse(holidayCriteria.getMinDate()); Date endDate = (Date)formatter.parse(holidayCriteria.getMaxDate()); long interval = 24*1000 * 60 * 60; // 1 Day in millis long endTime =endDate.getTime() ; // create your endtime here, possibly using Calendar or Date long curTime = startDate.getTime(); while (curTime <= endTime) { listDuration.add(new Date(curTime)); curTime += interval; } /* END: try */ }else if(!holidayCriteria.getIsDurationDate().equalsIgnoreCase("true") && holidayCriteria.getHolidayDate()!=null && holidayCriteria.getHolidayDate().length()>0){ if(logger.isInfoEnabled()){ logger.info("- singleDate: "+ holidayCriteria.getHolidayDate()); } listDuration.add((Date)formatter.parse(holidayCriteria.getHolidayDate())); }else{ throw new Exception("Something Abnormal!"); } if(logger.isInfoEnabled()){ for(int i=0;i<listDuration.size();i++){ Date lDate =(Date)listDuration.get(i); String ds = formatter.format(lDate); logger.info(" Date is ..." + ds); } } for(int i=0; i<listDuration.size(); i++){ Holiday holiday = new Holiday(); holiday.setYearId(holidayCriteria.getYearId()); holiday.setHolidayDate(formatter.format(listDuration.get(i))); holiday.setHolidayName(holidayCriteria.getHolidayName()); holiday.setHolidayDesc(holidayCriteria.getHolidayDesc()); isExist = holidayDao.isHolidayExist(holiday); if(isExist){ response.setErrorCode("E002"); response.setStatus(BuckWaConstants.FAIL); break; } } if(!isExist){ for(int i=0; i<listDuration.size(); i++){ Holiday holiday = new Holiday(); holiday.setYearId(holidayCriteria.getYearId()); holiday.setHolidayDate(formatter.format(listDuration.get(i))); holiday.setHolidayName(holidayCriteria.getHolidayName()); holiday.setHolidayDesc(holidayCriteria.getHolidayDesc()); holiday.setEnable(holidayCriteria.isEnable()); holidayDao.create(holiday); } response.setSuccessCode("S001"); } }else{ response.setErrorCode("E017"); response.setStatus(BuckWaConstants.FAIL); } }catch(DuplicateKeyException dx){ response.setStatus(BuckWaConstants.FAIL); response.setErrorCode("E002"); }catch(Exception ex){ ex.printStackTrace(); if(ex.getMessage().equals("Something Abnormal!")){ response.setErrorCode("E017"); }else{ response.setErrorCode("E001"); } response.setStatus(BuckWaConstants.FAIL); } // Success return S001 response.setSuccessCode("S001"); return response; } @Override @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW) public BuckWaResponse update(BuckWaRequest request) { if(logger.isInfoEnabled()){ logger.info(this.getClass().toString()+"-update-"); } BuckWaResponse response = new BuckWaResponse(); try{ Holiday holiday = (Holiday)request.get("holiday"); response.setStatus(BuckWaConstants.FAIL); if(holiday.getHolidayName().length() <1){ response.setErrorCode("E017"); }else{ Holiday oldHoliday = holidayDao.getHolidayById(holiday.getHolidayId()); boolean isExist = holidayDao.isHolidayExist(holiday); boolean isSameYear = oldHoliday.getYearId().equals(holiday.getYearId()); boolean isSameDate = oldHoliday.getHolidayDate().equals(holiday.getHolidayDate()); boolean isSameDesc = oldHoliday.getHolidayDesc().equals(holiday.getHolidayDesc()); boolean isSameName = oldHoliday.getHolidayName().equals(holiday.getHolidayName()); boolean isSameEnable = oldHoliday.isEnable()==holiday.isEnable(); boolean isDirty = !(isSameYear&&isSameDate&&isSameDesc&&isSameEnable&&isSameName); if(!isExist||isDirty){ holidayDao.update(holiday); response.setSuccessCode("S002"); response.setStatus(BuckWaConstants.SUCCESS); }else{ response.setErrorCode("E002"); } } }catch(Exception ex){ ex.printStackTrace(); response.setStatus(BuckWaConstants.FAIL); response.setErrorCode("E001"); } return response; } @Override public BuckWaResponse getByOffset(BuckWaRequest request) { if(logger.isInfoEnabled()){ logger.info(this.getClass().toString()+"-getByOffset-"); } BuckWaResponse response = new BuckWaResponse(); try{ PagingBean pagingBean = (PagingBean)request.get("pagingBean"); PagingBean returnBean = holidayDao.getAllHolidayByOffset(pagingBean); response.addResponse("pagingBean",returnBean); }catch(Exception ex){ ex.printStackTrace(); response.setStatus(BuckWaConstants.FAIL); response.setErrorCode("E001"); } // Success return S001 // response.setSuccessCode("S001"); return response; } @Override public BuckWaResponse getByOffsetYear(BuckWaRequest request) { if(logger.isInfoEnabled()){ logger.info(this.getClass().toString()+"-getByOffset-"); } BuckWaResponse response = new BuckWaResponse(); try{ PagingBean pagingBean = (PagingBean)request.get("pagingBean"); PagingBean returnBean = holidayDao.getAllHolidayByOffsetYear(pagingBean); response.addResponse("pagingBean",returnBean); }catch(Exception ex){ ex.printStackTrace(); response.setStatus(BuckWaConstants.FAIL); response.setErrorCode("E001"); } // Success return S001 // response.setSuccessCode("S001"); return response; } @Override public BuckWaResponse getById(BuckWaRequest request) { if(logger.isInfoEnabled()){ logger.info(this.getClass().toString()+"-getById-"); } BuckWaResponse response = new BuckWaResponse(); try{ String holidayId = (String)request.get("holidayId"); Holiday holiday = holidayDao.getHolidayById(holidayId); response.addResponse("holiday",holiday); }catch(Exception ex){ ex.printStackTrace(); response.setStatus(BuckWaConstants.FAIL); response.setErrorCode("E001"); } // Success return S001 // response.setSuccessCode("S001"); return response; } @Override public BuckWaResponse deleteById(BuckWaRequest request) { if(logger.isInfoEnabled()){ logger.info(this.getClass().toString()+"-deleteById-"); } BuckWaResponse response = new BuckWaResponse(); try{ String id = request.get("holidayId").toString(); // Check Is using Holiday targetHoliday = holidayDao.getHolidayById(id); if(targetHoliday==null){ response.setStatus(BuckWaConstants.FAIL); response.setErrorCode("E010"); }else{ holidayDao.deleteHolidayById(id); } }catch(Exception ex){ ex.printStackTrace(); response.setStatus(BuckWaConstants.FAIL); response.setErrorCode("E001"); } response.setSuccessCode("D001"); return response; } public BuckWaResponse getHolidayByYear(BuckWaRequest request){ if(logger.isInfoEnabled()){ logger.info(this.getClass().toString()+"-getHolidayByYear-"); } BuckWaResponse response = new BuckWaResponse(); try{ String holidayId = request.get("holidayId").toString(); List<Holiday> holidayList = holidayDao.getHolidayByYear(holidayId); response.addResponse("holidayList",holidayList); }catch(Exception ex){ ex.printStackTrace(); response.setStatus(BuckWaConstants.FAIL); response.setErrorCode("E001"); } return response; } }
10,283
0.705242
0.694642
319
31.235109
24.812233
103
false
false
0
0
0
0
0
0
3.589342
false
false
10
13413d90f36847b48fe50cd58b567d83e95f2409
20,444,044,343,735
d7323d4637ae77f325d68c5a333dff897ea93555
/app/src/main/java/com/game/ludobets/StartmatchActivity.java
27c2cb252d9f6514c2c17b8c598f49e5c97b4117
[]
no_license
PrajapatiMansiRamesh/LudoBets
https://github.com/PrajapatiMansiRamesh/LudoBets
622f6ae72c323199806ae8a4ca2e39e0f265701b
ebf306d2eba906775a5449db60a8ca426be6566f
refs/heads/master
2022-12-03T04:02:00.508000
2020-08-20T06:02:09
2020-08-20T06:02:09
276,061,983
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.game.ludobets; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Color; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.firestore.CollectionReference; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.EventListener; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.FirebaseFirestoreException; import com.google.firebase.firestore.QueryDocumentSnapshot; import com.google.firebase.firestore.QuerySnapshot; import com.google.firebase.firestore.SetOptions; import com.google.firebase.firestore.WriteBatch; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.OnProgressListener; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.UUID; import butterknife.internal.Constants; public class StartmatchActivity extends AppCompatActivity { TextView notice_text, title_text, msg_text, rule_text,img_notice,calcelview; Button msgbtn, callbtn, setbtn,uploadimgbtn,sendresbtn,code_copy,yesbtn,nobtn,Cyesbtn,Cnobtn; EditText code; String price,current_user; List<String> challenger_name=new ArrayList<String>(); List<String> player_name=new ArrayList<String>(); List<String> challenger_status=new ArrayList<String>(); List<String> player_status=new ArrayList<String>(); String challenger_statusid=null; String player_statusid=null; String challenger_statusname=null; String player_statusname=null; RadioGroup radioGroup; RadioButton radioButton; ImageView res_img; LinearLayout entercode; Uri filePath; final int PICK_IMAGE_REQUEST = 71; FirebaseStorage storage; StorageReference storageReference; String checkroom=null,RCstatus=null; @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); super.onCreate(savedInstanceState); setContentView(R.layout.activity_startmatch); calcelview=findViewById(R.id.cancelview); yesbtn=findViewById(R.id.yesbtn); nobtn=findViewById(R.id.nobtn); Cyesbtn=findViewById(R.id.Cyesbtn); Cnobtn=findViewById(R.id.Cnobtn); title_text = findViewById(R.id.match_title); notice_text = findViewById(R.id.notice); msg_text = findViewById(R.id.match_msg); img_notice=findViewById(R.id.imgnotice); rule_text = findViewById(R.id.rule); code = findViewById(R.id.code); msgbtn = findViewById(R.id.msg); callbtn = findViewById(R.id.call); setbtn = findViewById(R.id.set_code); radioGroup = findViewById(R.id.bet_result); entercode=findViewById(R.id.entercode); code_copy=findViewById(R.id.copycode); uploadimgbtn=findViewById(R.id.uploadimg); res_img=findViewById(R.id.SS_result); sendresbtn=findViewById(R.id.final_res); storage = FirebaseStorage.getInstance(); storageReference = storage.getReference(); Intent intent = getIntent(); current_user = intent.getStringExtra("current_user"); String current_user_id = intent.getStringExtra("current_user_id"); // System.out.println(current_user_id); FirebaseFirestore fStore = FirebaseFirestore.getInstance(); AlertDialog.Builder acceptDialog=new AlertDialog.Builder(StartmatchActivity.this); acceptDialog.setTitle("Alert !"); acceptDialog.setMessage("You will lose your Money if:\n 1.You posted Wrong Result.\n 2.You Don't Post Result within 5 min,after the match.\nYour Account will also be Blocked.\n3.Player has to Submit result First,Before Challenger."); acceptDialog.setCancelable(true); acceptDialog.setPositiveButton("I UNDERSTAND", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(StartmatchActivity.this,"You read",Toast.LENGTH_SHORT).show(); } }); AlertDialog alertDialog=acceptDialog.create(); alertDialog.show(); CollectionReference responseRef = fStore.collection("BetRequest"); responseRef.whereEqualTo("status", "ACCEPTED").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot document : task.getResult()) { challenger_name.add((String)document.getString("Challenger_Name").toString()); player_name.add((String) document.getString("player_Name").toString()); price = (String) document.getString("amount").toString(); if(challenger_name.contains(current_user)) { CollectionReference userlabel=fStore.collection("BetRequest"); userlabel.whereEqualTo("Challenger_Name",current_user).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if(task.isSuccessful()){ for(QueryDocumentSnapshot curdoucument:task.getResult()){ String chalenger=(String)curdoucument.getString("Challenger_Name").toString(); String player=(String)curdoucument.getString("player_Name").toString(); String amount=(String)curdoucument.getString("amount").toString(); checkroom= (String)curdoucument.getString("room_Code"); RCstatus=(String)curdoucument.getString("RCstatus"); roomCode(checkroom,RCstatus,current_user,challenger_name,player_name); title_text.setText(chalenger + " VS " + player + " for " + amount ); } } } }); } if(player_name.contains(current_user)) { CollectionReference userlabel=fStore.collection("BetRequest"); userlabel.whereEqualTo("player_Name",current_user).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if(task.isSuccessful()){ for(QueryDocumentSnapshot resdoucument:task.getResult()){ String chalenger=(String)resdoucument.getString("Challenger_Name").toString(); String player=(String)resdoucument.getString("player_Name").toString(); String amount=(String)resdoucument.getString("amount").toString(); title_text.setText(chalenger + " VS " + player + " for " + amount ); checkroom= (String)resdoucument.getString("room_Code"); RCstatus=(String)resdoucument.getString("RCstatus"); roomCode(checkroom,RCstatus,current_user,challenger_name,player_name); } } } }); } } } } }); // Toast.makeText(v.getContext(),"Accepted. You can Start the Match Now",Toast.LENGTH_SHORT).show(); notice_text.setText("NOTE!!\n New Rule:If Dices of Both players are Open OR\n If 2 Dices of single Player is Open.Match will not be Cancelled.\n (Video Recording of Match is Recommened)\n\n" + "यदि दोनों खिलाड़ियों के पास खुला पासा है या यदि किसी एकल खिलाड़ी के पास 2 अंतर खुले हैं। मैच रद्द नहीं किया जायेगा"); rule_text.setText("Rules:\nWait for Room code for at least 5 min.Room Code के लिए 5 मिनट तक प्रतीक्षा करें ।\n\n" + "1.If you WON the Match Click on 'I WON' and send Result.\n 2.If you LOST the Match Click on 'I LOST' and send Result.\n\n" + "Internet, Phone hang, or any personal issues will not be Entertained.\nIf you don't SEND Result for Send WRONG RESULT.You'll lose your Money "); img_notice.setText("Uploading Screenshot may take some time, so please Be Patient."); calcelview.setText("(It may take 15 minutes)\n (इसमें 15 मिनट का समय लग सकता है)"); setbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String Room_code=code.getText().toString(); if(Room_code.isEmpty()) { Toast.makeText(StartmatchActivity.this,"Please Enter Room Code!",Toast.LENGTH_SHORT).show(); } else { if(Room_code.length()<8) { Toast.makeText(StartmatchActivity.this,"Invalid Room Code!",Toast.LENGTH_SHORT).show(); } else{ CollectionReference requestRef = fStore.collection("BetRequest"); requestRef.whereEqualTo("Challenger_Name", current_user).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot DBdocument : task.getResult()) { Map<Object, String> map = new HashMap<>(); map.put("room_Code", Room_code); requestRef.document(DBdocument.getId()).set(map, SetOptions.merge()); } Toast.makeText(StartmatchActivity.this,"Room Code Sent",Toast.LENGTH_SHORT).show(); } } }); // entercode.setVisibility(View.GONE); // msg_text.setText(Room_code); // code_copy.setVisibility(View.VISIBLE); CollectionReference responseRef = fStore.collection("BetRequest"); responseRef.whereEqualTo("room_Code",Room_code).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot document : task.getResult()) { player_name.add((String) document.getString("player_Name").toString()); checkroom= (String) document.getString("room_Code"); RCstatus=(String)document.getString("RCstatus"); roomCode(checkroom,RCstatus,current_user,challenger_name,player_name); } } else { System.out.println("NP"); } } }); } } } }); code_copy.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CollectionReference requestRef = fStore.collection("BetRequest"); requestRef.whereEqualTo("status", "ACCEPTED").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot document : task.getResult()) { String room_code=(String)document.getString("room_Code").toString(); ClipboardManager clipboard=(ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip=ClipData.newPlainText("Code",room_code); clipboard.setPrimaryClip(clip); Toast.makeText(StartmatchActivity.this, "Room Code Copied!", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(StartmatchActivity.this, "Not Copied", Toast.LENGTH_SHORT).show(); } } }); } }); uploadimgbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(radioGroup.getCheckedRadioButtonId() == -1) { Toast.makeText(StartmatchActivity.this, "Please Select Result First", Toast.LENGTH_SHORT).show(); } else { int radioId = radioGroup.getCheckedRadioButtonId(); radioButton = findViewById(radioId); String complete=radioButton.getText().toString(); if(complete.equals("I WON / मैं जीत गया")) { chooseImage(); uploadImage(current_user_id); } } } }); sendresbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(radioGroup.getCheckedRadioButtonId() == -1) { Toast.makeText(StartmatchActivity.this, "Please Select Result", Toast.LENGTH_SHORT).show(); } else { int radioId = radioGroup.getCheckedRadioButtonId(); radioButton = findViewById(radioId); String complete = radioButton.getText().toString(); if (complete.equals("I WON / मैं जीत गया") && res_img.getDrawable() == null) { Toast.makeText(StartmatchActivity.this, "Please Upload Screen Short", Toast.LENGTH_SHORT).show(); } else { CollectionReference responseRef = fStore.collection("BetRequest"); responseRef.whereEqualTo("status", "ACCEPTED").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot document : task.getResult()) { challenger_name.add((String) document.getString("Challenger_Name").toString()); player_name.add((String) document.getString("player_Name").toString()); String challenger_id = document.getString("userID").toString(); final ProgressDialog progressDialog = new ProgressDialog(StartmatchActivity.this); progressDialog.setTitle("Uploading Result,wait a few movement.Do Not press Back..."); progressDialog.show(); if(challenger_name.contains(current_user)) { Map<Object, String> map = new HashMap<>(); map.put("Challenger_status", complete); map.put("status", "COMPLETED"); map.put("Time",new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.getDefault()).format(new Date())); responseRef.document(document.getId()).set(map, SetOptions.merge()).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()) { progressDialog.dismiss(); Toast.makeText(StartmatchActivity.this, "Balance Updated", Toast.LENGTH_SHORT).show(); StartmatchActivity.this.finish(); } } }); } if(player_name.contains(current_user)) { Map<Object, String> res_map = new HashMap<>(); res_map.put("status", complete); res_map.put("Time",new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.getDefault()).format(new Date())); fStore.collection("BetRequest").document(document.getString("userID")).collection("BetResponse").document(current_user_id).set(res_map,SetOptions.merge()).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()) { progressDialog.dismiss(); Toast.makeText(StartmatchActivity.this, "Your Balance will be Updated, Ater Opponent Result", Toast.LENGTH_SHORT).show(); StartmatchActivity.this.finish(); } } }); } } } } }); if(challenger_name.contains(current_user)) { DocumentReference documentReference=fStore.collection("BetRequest").document(current_user_id); documentReference.addSnapshotListener(new EventListener<DocumentSnapshot>() { @Override public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) { challenger_status.add((String)documentSnapshot.getString("Challenger_status")); challenger_statusid=(String)documentSnapshot.getString("userID").toString(); challenger_statusname=documentSnapshot.getString("Challenger_Name").toString(); player_statusname=documentSnapshot.getString("player_Name").toString(); int bet_amount=Integer.parseInt(documentSnapshot.getString("amount")); String player=documentSnapshot.getString("player_Name").toString(); CollectionReference player_coltn=documentReference.collection("BetResponse"); player_coltn.whereEqualTo("player_Name",player).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if(task.isSuccessful()) { for(QueryDocumentSnapshot statusdoc:task.getResult()) { player_statusid=(String)statusdoc.getString("userID").toString(); player_status.add((String)statusdoc.getString("status")); player_statusname=(String)statusdoc.getString("player_Name").toString(); } if(challenger_status.contains("I WON / मैं जीत गया") && player_status.contains("I LOST / में हार गया")) { DocumentReference docRef = fStore.collection("Comission").document(challenger_statusid.toString()); docRef.addSnapshotListener(new EventListener<DocumentSnapshot>() { @Override public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) { int com_amount =bet_amount*10/100; Map<String,Object> map=new HashMap<>(); map.put("userID",challenger_statusid.toString()); map.put("Time",new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.getDefault()).format(new Date())); map.put("amount",com_amount); docRef.set(map); CollectionReference challenger_won = fStore.collection("users"); challenger_won.whereEqualTo("Name", challenger_statusname).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot document : task.getResult()) { int checkbalance=Integer.parseInt(document.getString("wallet")); int current_balance=(checkbalance + ((bet_amount+bet_amount)-com_amount)); Map<Object,String> map = new HashMap<>(); map.put("wallet",Integer.toString(current_balance)); challenger_won.document(document.getId()).set(map, SetOptions.merge()); } } } }); } }); } else if(challenger_status.contains("I LOST / में हार गया") && player_status.contains("I WON / मैं जीत गया")) { DocumentReference docRef = fStore.collection("Comission").document(player_statusid.toString()); docRef.addSnapshotListener(new EventListener<DocumentSnapshot>() { @Override public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) { int com_amount =bet_amount*10/100; Map<String,Object> map=new HashMap<>(); map.put("userID",player_statusid.toString()); map.put("Time",new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.getDefault()).format(new Date())); map.put("amount",com_amount); docRef.set(map); CollectionReference player_won = fStore.collection("users"); player_won.whereEqualTo("Name", player_statusname).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot document : task.getResult()) { int checkbalance=Integer.parseInt(document.getString("wallet")); int current_balance=(checkbalance + ((bet_amount+bet_amount)-com_amount)); Map<Object,String> map = new HashMap<>(); map.put("wallet",Integer.toString(current_balance)); player_won.document(document.getId()).set(map, SetOptions.merge()); } } } }); } }); } else if(challenger_status.contains("I WON / मैं जीत गया") && player_status.contains("Cancel Game/गेम रद्द करें")) { Toast.makeText(StartmatchActivity.this, "Show Panding", Toast.LENGTH_SHORT).show(); } else if(challenger_status.contains("Cancel Game/गेम रद्द करें") && player_status.contains("I WON / मैं जीत गया")) { Toast.makeText(StartmatchActivity.this, "Show Panding", Toast.LENGTH_SHORT).show(); } else if(challenger_status.contains("Cancel Game/गेम रद्द करें") && player_status.contains("Cancel Game/गेम रद्द करें")) { Toast.makeText(StartmatchActivity.this, "Show History", Toast.LENGTH_SHORT).show(); } else if(challenger_status.contains("I WON / मैं जीत गया") && player_status.contains("I WON / मैं जीत गया")) { Toast.makeText(StartmatchActivity.this, "Show Panding", Toast.LENGTH_SHORT).show(); } else if(player_status.contains("ACCEPTED")) { Toast.makeText(StartmatchActivity.this, "Wait for Opponent Result", Toast.LENGTH_SHORT).show(); } } } }); } }); } } } } }); yesbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final MediaPlayer mp=MediaPlayer.create(StartmatchActivity.this,R.raw.btnsound); mp.start(); CollectionReference responseRC = fStore.collection("BetRequest"); responseRC.whereEqualTo("player_Name", current_user).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot insdocument : task.getResult()) { String challengeid=insdocument.getString("userID"); Map<Object, String> map = new HashMap<>(); map.put("RCstatus", "ACCEPTED"); responseRC.document(challengeid).set(map, SetOptions.merge()); } } } }); CollectionReference responseRef = fStore.collection("BetRequest"); responseRef.whereEqualTo("RCstatus", "ACCEPTED").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot RCdocument : task.getResult()) { checkroom=(String)RCdocument.getString("room_Code").toString(); challenger_name.add((String)RCdocument.getString("Challenger_Name").toString()); player_name.add((String) RCdocument.getString("player_Name").toString()); if(challenger_name.contains(current_user)) { code.setVisibility(View.GONE); setbtn.setVisibility(View.GONE); msg_text.setText(checkroom+"\n\nStart the Match, RoomCode has been Accepted.\n\n"+" मैच शरू करे\n"); msg_text.setBackgroundResource(R.color.blue); } else if(player_name.contains(current_user)) { code.setVisibility(View.GONE); setbtn.setVisibility(View.GONE); yesbtn.setVisibility(View.GONE); nobtn.setVisibility(View.GONE); msg_text.setText(checkroom+"\n\nStart the Match, RoomCode has been Accepted.\n\n"+" मैच शरू करे\n"); msg_text.setBackgroundResource(R.color.blue); } } } } }); } }); Cyesbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { msg_text.setText("ENTER LUDOKING ROOMCODE"); code.setVisibility(View.VISIBLE); setbtn.setVisibility(View.VISIBLE); Cyesbtn.setVisibility(View.GONE); Cnobtn.setVisibility(View.GONE); } }); Cnobtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CollectionReference responseRC = fStore.collection("BetRequest"); responseRC.whereEqualTo("Challenger_Name", current_user).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot insdocument : task.getResult()) { String challengeid=insdocument.getString("userID"); Map<Object, String> map = new HashMap<>(); map.put("RCstatus", "REJECTED"); responseRC.document(challengeid).set(map, SetOptions.merge()); } } } }); CollectionReference responseRef = fStore.collection("BetRequest"); responseRef.whereEqualTo("status", "ACCEPTED").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot document : task.getResult()) { challenger_name.add((String)document.getString("Challenger_Name").toString()); player_name.add((String) document.getString("player_Name").toString()); price = (String) document.getString("amount").toString(); if(challenger_name.contains(current_user)) { CollectionReference userlabel=fStore.collection("BetRequest"); userlabel.whereEqualTo("Challenger_Name",current_user).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if(task.isSuccessful()){ for(QueryDocumentSnapshot curdoucument:task.getResult()){ checkroom= (String)curdoucument.getString("room_Code"); RCstatus=(String)curdoucument.getString("RCstatus").toString(); roomCode(checkroom,RCstatus,current_user,challenger_name,player_name); } } } }); } if(player_name.contains(current_user)) { CollectionReference userlabel=fStore.collection("BetRequest"); userlabel.whereEqualTo("player_Name",current_user).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if(task.isSuccessful()){ for(QueryDocumentSnapshot resdoucument:task.getResult()){ checkroom= (String)resdoucument.getString("room_Code"); RCstatus=(String)resdoucument.getString("RCstatus").toString(); roomCode(checkroom,RCstatus,current_user,challenger_name,player_name); } } } }); } } } } }); } }); nobtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(StartmatchActivity.this); builder.setTitle("Change Room Code?"); builder.setMessage("Are you Sure, You want to Change the Room Code?") .setCancelable(false) .setPositiveButton("YES", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { CollectionReference responseRC = fStore.collection("BetRequest"); responseRC.whereEqualTo("player_Name", current_user).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot insdocument : task.getResult()) { String challengeid=insdocument.getString("userID"); Map<Object, String> map = new HashMap<>(); map.put("RCstatus", "REJECTED"); responseRC.document(challengeid).set(map, SetOptions.merge()); } } } }); CollectionReference responseRef = fStore.collection("BetRequest"); responseRef.whereEqualTo("RCstatus", "REJECTED").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot RCdocument : task.getResult()) { checkroom=(String)RCdocument.getString("room_Code").toString(); challenger_name.add((String)RCdocument.getString("Challenger_Name").toString()); player_name.add((String) RCdocument.getString("player_Name").toString()); if(challenger_name.contains(current_user)) { code.setVisibility(View.GONE); setbtn.setVisibility(View.GONE); msg_text.setText("Old Room Code: "+checkroom+"\nNew Room Code Requested by"+player_name+"\n Can you change the Room Code?\n"); msg_text.setBackgroundResource(R.color.maroon); Cyesbtn.setVisibility(View.VISIBLE); Cnobtn.setVisibility(View.VISIBLE); } else if(player_name.contains(current_user)) { code.setVisibility(View.GONE); setbtn.setVisibility(View.GONE); yesbtn.setVisibility(View.GONE); nobtn.setVisibility(View.GONE); msg_text.setText(" Waiting for Room Code..\nOld Room Code: "+checkroom+"\n"); msg_text.setBackgroundResource(R.color.red); } } } } }); } }) .setNegativeButton("CANCEL",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { dialog.cancel(); } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } }); msgbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(challenger_name.contains(current_user)) { CollectionReference userlabel=fStore.collection("BetRequest"); userlabel.whereEqualTo("Challenger_Name",current_user).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if(task.isSuccessful()){ for(QueryDocumentSnapshot phdoucument:task.getResult()){ String player=(String)phdoucument.getString("player_Name").toString(); CollectionReference msgref=fStore.collection("users"); msgref.whereEqualTo("Name",player).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if(task.isSuccessful()) { for(QueryDocumentSnapshot phonedocument:task.getResult()){ String phoneNo="+91"+phonedocument.getString("phone"); // System.out.println("Phone:"+phoneNo); openWhatsApp(phoneNo); } } } }); } } } }); } else if(player_name.contains(current_user)) { CollectionReference userlabel=fStore.collection("BetRequest"); userlabel.whereEqualTo("player_Name",current_user).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if(task.isSuccessful()){ for(QueryDocumentSnapshot pdoucument:task.getResult()){ String chalenger=(String)pdoucument.getString("Challenger_Name").toString(); CollectionReference msgref=fStore.collection("users"); msgref.whereEqualTo("Name",chalenger).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if(task.isSuccessful()) { for(QueryDocumentSnapshot phondocument:task.getResult()){ String phoneNo="+91"+phondocument.getString("phone"); // System.out.println("Phone:"+phoneNo); openWhatsApp(phoneNo); } } } }); } } } }); } } }); callbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CollectionReference responseRef = fStore.collection("BetRequest"); responseRef.whereEqualTo("status", "ACCEPTED").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot pndocument : task.getResult()) { challenger_name.add((String)pndocument.getString("Challenger_Name").toString()); player_name.add((String) pndocument.getString("player_Name").toString()); if(challenger_name.contains(current_user)) { CollectionReference userlabel=fStore.collection("BetRequest"); userlabel.whereEqualTo("Challenger_Name",current_user).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if(task.isSuccessful()){ for(QueryDocumentSnapshot lidoucument:task.getResult()){ String player=(String)lidoucument.getString("player_Name").toString(); CollectionReference msgref=fStore.collection("users"); msgref.whereEqualTo("Name",player).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if(task.isSuccessful()) { for(QueryDocumentSnapshot phonedocument:task.getResult()){ String phoneNo="+91"+phonedocument.getString("phone"); openCall(phoneNo); } } } }); } } } }); } else if(player_name.contains(current_user)) { CollectionReference userlabel=fStore.collection("BetRequest"); userlabel.whereEqualTo("player_Name",current_user).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if(task.isSuccessful()){ for(QueryDocumentSnapshot lidoucument:task.getResult()){ String chalenger=(String)lidoucument.getString("Challenger_Name").toString(); CollectionReference msgref=fStore.collection("users"); msgref.whereEqualTo("Name",chalenger).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if(task.isSuccessful()) { for(QueryDocumentSnapshot phonedocument:task.getResult()){ String phoneNo="+91"+phonedocument.getString("phone"); openCall(phoneNo); } } } }); } } } }); } } } } }); } }); } private void roomCode(String checkroom,String RCstatus, String current_user, List<String> challenger_name, List<String> player_name) { if(checkroom!= null) { if(player_name.contains(current_user)) { if(RCstatus=="ACCEPTED") { code.setVisibility(View.GONE); setbtn.setVisibility(View.GONE); yesbtn.setVisibility(View.GONE); nobtn.setVisibility(View.GONE); msg_text.setText(checkroom+"\n\nStart the Match, RoomCode has been Accepted.\n\n"+" मैच शरू करे\n"); msg_text.setBackgroundResource(R.color.blue); } else if(RCstatus=="REJECTED"){ code.setVisibility(View.GONE); setbtn.setVisibility(View.GONE); yesbtn.setVisibility(View.GONE); nobtn.setVisibility(View.GONE); msg_text.setText(" Waiting for Room Code..\nOld Room Code: "+checkroom+"\n"); msg_text.setBackgroundResource(R.color.red); } else { final MediaPlayer mp=MediaPlayer.create(StartmatchActivity.this,R.raw.btnsound); mp.start(); msg_text.setText(checkroom + "\nStep 1.Join the Room Code in Ludoking Game.\nStep 2.If Room Code is correct,press Yes.If Room Code is invalid,press No.\n\n" + "## WITHOUT THIS,MATCH WILL BE CONSIDERED FRAUD.\n\nStep 1.Ludoking game में Room Code join हो.\nStep 2.यदि Room Code सही हे,तो Yes पर दबाये" + "\n\n## इसके बिना, मैच स्वीकार नहीं किया जाएगा\n"); msg_text.setBackgroundResource(R.color.maroon); msg_text.setTextColor(Color.WHITE); code_copy.setVisibility(View.VISIBLE); yesbtn.setVisibility(View.VISIBLE); nobtn.setVisibility(View.VISIBLE); } } else if(challenger_name.contains(current_user)) { if(RCstatus=="ACCEPTED"){ code.setVisibility(View.GONE); setbtn.setVisibility(View.GONE); msg_text.setText(checkroom+"\n\nStart the Match, RoomCode has been Accepted.\n\n"+" मैच शरू करे\n"); msg_text.setBackgroundResource(R.color.blue); } else if(RCstatus=="REJECTED"){ code.setVisibility(View.GONE); setbtn.setVisibility(View.GONE); msg_text.setText("Old Room Code: "+checkroom+"\nNew Room Code Requested by"+player_name+"\n Can you change the Room Code?\n"); msg_text.setBackgroundResource(R.color.maroon); Cyesbtn.setVisibility(View.VISIBLE); Cnobtn.setVisibility(View.VISIBLE); } else{ code.setVisibility(View.GONE); setbtn.setVisibility(View.GONE); msg_text.setText(checkroom+"\n\nWaiting for Admin to check this Room Code Do not Start Match in Ludoking Game.\n\n"+" Room Code देखने के लिए Admin की प्रतीक्षा करे LudoKing Game में मैच अभी शुरू न करे\n"); msg_text.setBackgroundResource(R.color.maroon); } } } else if(checkroom==null && RCstatus==null) { if(challenger_name.contains(current_user)) { msg_text.setText("ENTER LUDOKING ROOMCODE"); code.setVisibility(View.VISIBLE); setbtn.setVisibility(View.VISIBLE); } else if(player_name.contains(current_user)) { msg_text.setText("Waiting for Room Code..."); } } } private void chooseImage() { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Screen Short"), PICK_IMAGE_REQUEST); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null ) { filePath = data.getData(); try { Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath); res_img.setImageBitmap(bitmap); } catch (IOException e) { e.printStackTrace(); } } } private void uploadImage(String current_user_id ){ if(filePath != null) { final ProgressDialog progressDialog = new ProgressDialog(StartmatchActivity.this); progressDialog.setTitle("Uploading Screenshot Image.Do Not press Back..."); progressDialog.show(); StorageReference ref = storageReference.child(current_user_id+"/"+ UUID.randomUUID().toString()); ref.putFile(filePath) .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { progressDialog.dismiss(); Toast.makeText(StartmatchActivity.this, "Uploaded", Toast.LENGTH_SHORT).show(); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { progressDialog.dismiss(); Toast.makeText(StartmatchActivity.this, "Failed "+e.getMessage(), Toast.LENGTH_SHORT).show(); } }) .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() { @Override public void onProgress(UploadTask.TaskSnapshot taskSnapshot) { double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot .getTotalByteCount()); progressDialog.setMessage("Uploaded "+(int)progress+"%"); } }); } } public void checkButton(View v) { int radioId = radioGroup.getCheckedRadioButtonId(); radioButton = findViewById(radioId); if(radioButton.getText().equals("I WON / मैं जीत गया")) { uploadimgbtn.setVisibility(View.VISIBLE); img_notice.setVisibility(View.VISIBLE); } else if(radioButton.getText().equals("I LOST / में हार गया")) { uploadimgbtn.setVisibility(View.GONE); img_notice.setVisibility(View.GONE); } // Toast.makeText(this, "Selected Button" + radioButton.getText(), Toast.LENGTH_SHORT).show(); } public void openWhatsApp(String phoneNo){ try { String text = "This is a test";// Replace with your message. Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("http://api.whatsapp.com/send?phone="+phoneNo +"&text="+text)); startActivity(intent); } catch (Exception e){ e.printStackTrace(); } } public void openCall(String number) { Intent intent = new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", number, null)); startActivity(intent); } }
UTF-8
Java
64,459
java
StartmatchActivity.java
Java
[]
null
[]
package com.game.ludobets; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Color; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.firestore.CollectionReference; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.EventListener; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.FirebaseFirestoreException; import com.google.firebase.firestore.QueryDocumentSnapshot; import com.google.firebase.firestore.QuerySnapshot; import com.google.firebase.firestore.SetOptions; import com.google.firebase.firestore.WriteBatch; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.OnProgressListener; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.UUID; import butterknife.internal.Constants; public class StartmatchActivity extends AppCompatActivity { TextView notice_text, title_text, msg_text, rule_text,img_notice,calcelview; Button msgbtn, callbtn, setbtn,uploadimgbtn,sendresbtn,code_copy,yesbtn,nobtn,Cyesbtn,Cnobtn; EditText code; String price,current_user; List<String> challenger_name=new ArrayList<String>(); List<String> player_name=new ArrayList<String>(); List<String> challenger_status=new ArrayList<String>(); List<String> player_status=new ArrayList<String>(); String challenger_statusid=null; String player_statusid=null; String challenger_statusname=null; String player_statusname=null; RadioGroup radioGroup; RadioButton radioButton; ImageView res_img; LinearLayout entercode; Uri filePath; final int PICK_IMAGE_REQUEST = 71; FirebaseStorage storage; StorageReference storageReference; String checkroom=null,RCstatus=null; @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); super.onCreate(savedInstanceState); setContentView(R.layout.activity_startmatch); calcelview=findViewById(R.id.cancelview); yesbtn=findViewById(R.id.yesbtn); nobtn=findViewById(R.id.nobtn); Cyesbtn=findViewById(R.id.Cyesbtn); Cnobtn=findViewById(R.id.Cnobtn); title_text = findViewById(R.id.match_title); notice_text = findViewById(R.id.notice); msg_text = findViewById(R.id.match_msg); img_notice=findViewById(R.id.imgnotice); rule_text = findViewById(R.id.rule); code = findViewById(R.id.code); msgbtn = findViewById(R.id.msg); callbtn = findViewById(R.id.call); setbtn = findViewById(R.id.set_code); radioGroup = findViewById(R.id.bet_result); entercode=findViewById(R.id.entercode); code_copy=findViewById(R.id.copycode); uploadimgbtn=findViewById(R.id.uploadimg); res_img=findViewById(R.id.SS_result); sendresbtn=findViewById(R.id.final_res); storage = FirebaseStorage.getInstance(); storageReference = storage.getReference(); Intent intent = getIntent(); current_user = intent.getStringExtra("current_user"); String current_user_id = intent.getStringExtra("current_user_id"); // System.out.println(current_user_id); FirebaseFirestore fStore = FirebaseFirestore.getInstance(); AlertDialog.Builder acceptDialog=new AlertDialog.Builder(StartmatchActivity.this); acceptDialog.setTitle("Alert !"); acceptDialog.setMessage("You will lose your Money if:\n 1.You posted Wrong Result.\n 2.You Don't Post Result within 5 min,after the match.\nYour Account will also be Blocked.\n3.Player has to Submit result First,Before Challenger."); acceptDialog.setCancelable(true); acceptDialog.setPositiveButton("I UNDERSTAND", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(StartmatchActivity.this,"You read",Toast.LENGTH_SHORT).show(); } }); AlertDialog alertDialog=acceptDialog.create(); alertDialog.show(); CollectionReference responseRef = fStore.collection("BetRequest"); responseRef.whereEqualTo("status", "ACCEPTED").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot document : task.getResult()) { challenger_name.add((String)document.getString("Challenger_Name").toString()); player_name.add((String) document.getString("player_Name").toString()); price = (String) document.getString("amount").toString(); if(challenger_name.contains(current_user)) { CollectionReference userlabel=fStore.collection("BetRequest"); userlabel.whereEqualTo("Challenger_Name",current_user).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if(task.isSuccessful()){ for(QueryDocumentSnapshot curdoucument:task.getResult()){ String chalenger=(String)curdoucument.getString("Challenger_Name").toString(); String player=(String)curdoucument.getString("player_Name").toString(); String amount=(String)curdoucument.getString("amount").toString(); checkroom= (String)curdoucument.getString("room_Code"); RCstatus=(String)curdoucument.getString("RCstatus"); roomCode(checkroom,RCstatus,current_user,challenger_name,player_name); title_text.setText(chalenger + " VS " + player + " for " + amount ); } } } }); } if(player_name.contains(current_user)) { CollectionReference userlabel=fStore.collection("BetRequest"); userlabel.whereEqualTo("player_Name",current_user).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if(task.isSuccessful()){ for(QueryDocumentSnapshot resdoucument:task.getResult()){ String chalenger=(String)resdoucument.getString("Challenger_Name").toString(); String player=(String)resdoucument.getString("player_Name").toString(); String amount=(String)resdoucument.getString("amount").toString(); title_text.setText(chalenger + " VS " + player + " for " + amount ); checkroom= (String)resdoucument.getString("room_Code"); RCstatus=(String)resdoucument.getString("RCstatus"); roomCode(checkroom,RCstatus,current_user,challenger_name,player_name); } } } }); } } } } }); // Toast.makeText(v.getContext(),"Accepted. You can Start the Match Now",Toast.LENGTH_SHORT).show(); notice_text.setText("NOTE!!\n New Rule:If Dices of Both players are Open OR\n If 2 Dices of single Player is Open.Match will not be Cancelled.\n (Video Recording of Match is Recommened)\n\n" + "यदि दोनों खिलाड़ियों के पास खुला पासा है या यदि किसी एकल खिलाड़ी के पास 2 अंतर खुले हैं। मैच रद्द नहीं किया जायेगा"); rule_text.setText("Rules:\nWait for Room code for at least 5 min.Room Code के लिए 5 मिनट तक प्रतीक्षा करें ।\n\n" + "1.If you WON the Match Click on 'I WON' and send Result.\n 2.If you LOST the Match Click on 'I LOST' and send Result.\n\n" + "Internet, Phone hang, or any personal issues will not be Entertained.\nIf you don't SEND Result for Send WRONG RESULT.You'll lose your Money "); img_notice.setText("Uploading Screenshot may take some time, so please Be Patient."); calcelview.setText("(It may take 15 minutes)\n (इसमें 15 मिनट का समय लग सकता है)"); setbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String Room_code=code.getText().toString(); if(Room_code.isEmpty()) { Toast.makeText(StartmatchActivity.this,"Please Enter Room Code!",Toast.LENGTH_SHORT).show(); } else { if(Room_code.length()<8) { Toast.makeText(StartmatchActivity.this,"Invalid Room Code!",Toast.LENGTH_SHORT).show(); } else{ CollectionReference requestRef = fStore.collection("BetRequest"); requestRef.whereEqualTo("Challenger_Name", current_user).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot DBdocument : task.getResult()) { Map<Object, String> map = new HashMap<>(); map.put("room_Code", Room_code); requestRef.document(DBdocument.getId()).set(map, SetOptions.merge()); } Toast.makeText(StartmatchActivity.this,"Room Code Sent",Toast.LENGTH_SHORT).show(); } } }); // entercode.setVisibility(View.GONE); // msg_text.setText(Room_code); // code_copy.setVisibility(View.VISIBLE); CollectionReference responseRef = fStore.collection("BetRequest"); responseRef.whereEqualTo("room_Code",Room_code).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot document : task.getResult()) { player_name.add((String) document.getString("player_Name").toString()); checkroom= (String) document.getString("room_Code"); RCstatus=(String)document.getString("RCstatus"); roomCode(checkroom,RCstatus,current_user,challenger_name,player_name); } } else { System.out.println("NP"); } } }); } } } }); code_copy.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CollectionReference requestRef = fStore.collection("BetRequest"); requestRef.whereEqualTo("status", "ACCEPTED").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot document : task.getResult()) { String room_code=(String)document.getString("room_Code").toString(); ClipboardManager clipboard=(ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip=ClipData.newPlainText("Code",room_code); clipboard.setPrimaryClip(clip); Toast.makeText(StartmatchActivity.this, "Room Code Copied!", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(StartmatchActivity.this, "Not Copied", Toast.LENGTH_SHORT).show(); } } }); } }); uploadimgbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(radioGroup.getCheckedRadioButtonId() == -1) { Toast.makeText(StartmatchActivity.this, "Please Select Result First", Toast.LENGTH_SHORT).show(); } else { int radioId = radioGroup.getCheckedRadioButtonId(); radioButton = findViewById(radioId); String complete=radioButton.getText().toString(); if(complete.equals("I WON / मैं जीत गया")) { chooseImage(); uploadImage(current_user_id); } } } }); sendresbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(radioGroup.getCheckedRadioButtonId() == -1) { Toast.makeText(StartmatchActivity.this, "Please Select Result", Toast.LENGTH_SHORT).show(); } else { int radioId = radioGroup.getCheckedRadioButtonId(); radioButton = findViewById(radioId); String complete = radioButton.getText().toString(); if (complete.equals("I WON / मैं जीत गया") && res_img.getDrawable() == null) { Toast.makeText(StartmatchActivity.this, "Please Upload Screen Short", Toast.LENGTH_SHORT).show(); } else { CollectionReference responseRef = fStore.collection("BetRequest"); responseRef.whereEqualTo("status", "ACCEPTED").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot document : task.getResult()) { challenger_name.add((String) document.getString("Challenger_Name").toString()); player_name.add((String) document.getString("player_Name").toString()); String challenger_id = document.getString("userID").toString(); final ProgressDialog progressDialog = new ProgressDialog(StartmatchActivity.this); progressDialog.setTitle("Uploading Result,wait a few movement.Do Not press Back..."); progressDialog.show(); if(challenger_name.contains(current_user)) { Map<Object, String> map = new HashMap<>(); map.put("Challenger_status", complete); map.put("status", "COMPLETED"); map.put("Time",new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.getDefault()).format(new Date())); responseRef.document(document.getId()).set(map, SetOptions.merge()).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()) { progressDialog.dismiss(); Toast.makeText(StartmatchActivity.this, "Balance Updated", Toast.LENGTH_SHORT).show(); StartmatchActivity.this.finish(); } } }); } if(player_name.contains(current_user)) { Map<Object, String> res_map = new HashMap<>(); res_map.put("status", complete); res_map.put("Time",new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.getDefault()).format(new Date())); fStore.collection("BetRequest").document(document.getString("userID")).collection("BetResponse").document(current_user_id).set(res_map,SetOptions.merge()).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()) { progressDialog.dismiss(); Toast.makeText(StartmatchActivity.this, "Your Balance will be Updated, Ater Opponent Result", Toast.LENGTH_SHORT).show(); StartmatchActivity.this.finish(); } } }); } } } } }); if(challenger_name.contains(current_user)) { DocumentReference documentReference=fStore.collection("BetRequest").document(current_user_id); documentReference.addSnapshotListener(new EventListener<DocumentSnapshot>() { @Override public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) { challenger_status.add((String)documentSnapshot.getString("Challenger_status")); challenger_statusid=(String)documentSnapshot.getString("userID").toString(); challenger_statusname=documentSnapshot.getString("Challenger_Name").toString(); player_statusname=documentSnapshot.getString("player_Name").toString(); int bet_amount=Integer.parseInt(documentSnapshot.getString("amount")); String player=documentSnapshot.getString("player_Name").toString(); CollectionReference player_coltn=documentReference.collection("BetResponse"); player_coltn.whereEqualTo("player_Name",player).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if(task.isSuccessful()) { for(QueryDocumentSnapshot statusdoc:task.getResult()) { player_statusid=(String)statusdoc.getString("userID").toString(); player_status.add((String)statusdoc.getString("status")); player_statusname=(String)statusdoc.getString("player_Name").toString(); } if(challenger_status.contains("I WON / मैं जीत गया") && player_status.contains("I LOST / में हार गया")) { DocumentReference docRef = fStore.collection("Comission").document(challenger_statusid.toString()); docRef.addSnapshotListener(new EventListener<DocumentSnapshot>() { @Override public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) { int com_amount =bet_amount*10/100; Map<String,Object> map=new HashMap<>(); map.put("userID",challenger_statusid.toString()); map.put("Time",new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.getDefault()).format(new Date())); map.put("amount",com_amount); docRef.set(map); CollectionReference challenger_won = fStore.collection("users"); challenger_won.whereEqualTo("Name", challenger_statusname).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot document : task.getResult()) { int checkbalance=Integer.parseInt(document.getString("wallet")); int current_balance=(checkbalance + ((bet_amount+bet_amount)-com_amount)); Map<Object,String> map = new HashMap<>(); map.put("wallet",Integer.toString(current_balance)); challenger_won.document(document.getId()).set(map, SetOptions.merge()); } } } }); } }); } else if(challenger_status.contains("I LOST / में हार गया") && player_status.contains("I WON / मैं जीत गया")) { DocumentReference docRef = fStore.collection("Comission").document(player_statusid.toString()); docRef.addSnapshotListener(new EventListener<DocumentSnapshot>() { @Override public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) { int com_amount =bet_amount*10/100; Map<String,Object> map=new HashMap<>(); map.put("userID",player_statusid.toString()); map.put("Time",new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.getDefault()).format(new Date())); map.put("amount",com_amount); docRef.set(map); CollectionReference player_won = fStore.collection("users"); player_won.whereEqualTo("Name", player_statusname).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot document : task.getResult()) { int checkbalance=Integer.parseInt(document.getString("wallet")); int current_balance=(checkbalance + ((bet_amount+bet_amount)-com_amount)); Map<Object,String> map = new HashMap<>(); map.put("wallet",Integer.toString(current_balance)); player_won.document(document.getId()).set(map, SetOptions.merge()); } } } }); } }); } else if(challenger_status.contains("I WON / मैं जीत गया") && player_status.contains("Cancel Game/गेम रद्द करें")) { Toast.makeText(StartmatchActivity.this, "Show Panding", Toast.LENGTH_SHORT).show(); } else if(challenger_status.contains("Cancel Game/गेम रद्द करें") && player_status.contains("I WON / मैं जीत गया")) { Toast.makeText(StartmatchActivity.this, "Show Panding", Toast.LENGTH_SHORT).show(); } else if(challenger_status.contains("Cancel Game/गेम रद्द करें") && player_status.contains("Cancel Game/गेम रद्द करें")) { Toast.makeText(StartmatchActivity.this, "Show History", Toast.LENGTH_SHORT).show(); } else if(challenger_status.contains("I WON / मैं जीत गया") && player_status.contains("I WON / मैं जीत गया")) { Toast.makeText(StartmatchActivity.this, "Show Panding", Toast.LENGTH_SHORT).show(); } else if(player_status.contains("ACCEPTED")) { Toast.makeText(StartmatchActivity.this, "Wait for Opponent Result", Toast.LENGTH_SHORT).show(); } } } }); } }); } } } } }); yesbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final MediaPlayer mp=MediaPlayer.create(StartmatchActivity.this,R.raw.btnsound); mp.start(); CollectionReference responseRC = fStore.collection("BetRequest"); responseRC.whereEqualTo("player_Name", current_user).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot insdocument : task.getResult()) { String challengeid=insdocument.getString("userID"); Map<Object, String> map = new HashMap<>(); map.put("RCstatus", "ACCEPTED"); responseRC.document(challengeid).set(map, SetOptions.merge()); } } } }); CollectionReference responseRef = fStore.collection("BetRequest"); responseRef.whereEqualTo("RCstatus", "ACCEPTED").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot RCdocument : task.getResult()) { checkroom=(String)RCdocument.getString("room_Code").toString(); challenger_name.add((String)RCdocument.getString("Challenger_Name").toString()); player_name.add((String) RCdocument.getString("player_Name").toString()); if(challenger_name.contains(current_user)) { code.setVisibility(View.GONE); setbtn.setVisibility(View.GONE); msg_text.setText(checkroom+"\n\nStart the Match, RoomCode has been Accepted.\n\n"+" मैच शरू करे\n"); msg_text.setBackgroundResource(R.color.blue); } else if(player_name.contains(current_user)) { code.setVisibility(View.GONE); setbtn.setVisibility(View.GONE); yesbtn.setVisibility(View.GONE); nobtn.setVisibility(View.GONE); msg_text.setText(checkroom+"\n\nStart the Match, RoomCode has been Accepted.\n\n"+" मैच शरू करे\n"); msg_text.setBackgroundResource(R.color.blue); } } } } }); } }); Cyesbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { msg_text.setText("ENTER LUDOKING ROOMCODE"); code.setVisibility(View.VISIBLE); setbtn.setVisibility(View.VISIBLE); Cyesbtn.setVisibility(View.GONE); Cnobtn.setVisibility(View.GONE); } }); Cnobtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CollectionReference responseRC = fStore.collection("BetRequest"); responseRC.whereEqualTo("Challenger_Name", current_user).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot insdocument : task.getResult()) { String challengeid=insdocument.getString("userID"); Map<Object, String> map = new HashMap<>(); map.put("RCstatus", "REJECTED"); responseRC.document(challengeid).set(map, SetOptions.merge()); } } } }); CollectionReference responseRef = fStore.collection("BetRequest"); responseRef.whereEqualTo("status", "ACCEPTED").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot document : task.getResult()) { challenger_name.add((String)document.getString("Challenger_Name").toString()); player_name.add((String) document.getString("player_Name").toString()); price = (String) document.getString("amount").toString(); if(challenger_name.contains(current_user)) { CollectionReference userlabel=fStore.collection("BetRequest"); userlabel.whereEqualTo("Challenger_Name",current_user).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if(task.isSuccessful()){ for(QueryDocumentSnapshot curdoucument:task.getResult()){ checkroom= (String)curdoucument.getString("room_Code"); RCstatus=(String)curdoucument.getString("RCstatus").toString(); roomCode(checkroom,RCstatus,current_user,challenger_name,player_name); } } } }); } if(player_name.contains(current_user)) { CollectionReference userlabel=fStore.collection("BetRequest"); userlabel.whereEqualTo("player_Name",current_user).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if(task.isSuccessful()){ for(QueryDocumentSnapshot resdoucument:task.getResult()){ checkroom= (String)resdoucument.getString("room_Code"); RCstatus=(String)resdoucument.getString("RCstatus").toString(); roomCode(checkroom,RCstatus,current_user,challenger_name,player_name); } } } }); } } } } }); } }); nobtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(StartmatchActivity.this); builder.setTitle("Change Room Code?"); builder.setMessage("Are you Sure, You want to Change the Room Code?") .setCancelable(false) .setPositiveButton("YES", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { CollectionReference responseRC = fStore.collection("BetRequest"); responseRC.whereEqualTo("player_Name", current_user).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot insdocument : task.getResult()) { String challengeid=insdocument.getString("userID"); Map<Object, String> map = new HashMap<>(); map.put("RCstatus", "REJECTED"); responseRC.document(challengeid).set(map, SetOptions.merge()); } } } }); CollectionReference responseRef = fStore.collection("BetRequest"); responseRef.whereEqualTo("RCstatus", "REJECTED").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot RCdocument : task.getResult()) { checkroom=(String)RCdocument.getString("room_Code").toString(); challenger_name.add((String)RCdocument.getString("Challenger_Name").toString()); player_name.add((String) RCdocument.getString("player_Name").toString()); if(challenger_name.contains(current_user)) { code.setVisibility(View.GONE); setbtn.setVisibility(View.GONE); msg_text.setText("Old Room Code: "+checkroom+"\nNew Room Code Requested by"+player_name+"\n Can you change the Room Code?\n"); msg_text.setBackgroundResource(R.color.maroon); Cyesbtn.setVisibility(View.VISIBLE); Cnobtn.setVisibility(View.VISIBLE); } else if(player_name.contains(current_user)) { code.setVisibility(View.GONE); setbtn.setVisibility(View.GONE); yesbtn.setVisibility(View.GONE); nobtn.setVisibility(View.GONE); msg_text.setText(" Waiting for Room Code..\nOld Room Code: "+checkroom+"\n"); msg_text.setBackgroundResource(R.color.red); } } } } }); } }) .setNegativeButton("CANCEL",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { dialog.cancel(); } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } }); msgbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(challenger_name.contains(current_user)) { CollectionReference userlabel=fStore.collection("BetRequest"); userlabel.whereEqualTo("Challenger_Name",current_user).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if(task.isSuccessful()){ for(QueryDocumentSnapshot phdoucument:task.getResult()){ String player=(String)phdoucument.getString("player_Name").toString(); CollectionReference msgref=fStore.collection("users"); msgref.whereEqualTo("Name",player).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if(task.isSuccessful()) { for(QueryDocumentSnapshot phonedocument:task.getResult()){ String phoneNo="+91"+phonedocument.getString("phone"); // System.out.println("Phone:"+phoneNo); openWhatsApp(phoneNo); } } } }); } } } }); } else if(player_name.contains(current_user)) { CollectionReference userlabel=fStore.collection("BetRequest"); userlabel.whereEqualTo("player_Name",current_user).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if(task.isSuccessful()){ for(QueryDocumentSnapshot pdoucument:task.getResult()){ String chalenger=(String)pdoucument.getString("Challenger_Name").toString(); CollectionReference msgref=fStore.collection("users"); msgref.whereEqualTo("Name",chalenger).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if(task.isSuccessful()) { for(QueryDocumentSnapshot phondocument:task.getResult()){ String phoneNo="+91"+phondocument.getString("phone"); // System.out.println("Phone:"+phoneNo); openWhatsApp(phoneNo); } } } }); } } } }); } } }); callbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CollectionReference responseRef = fStore.collection("BetRequest"); responseRef.whereEqualTo("status", "ACCEPTED").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot pndocument : task.getResult()) { challenger_name.add((String)pndocument.getString("Challenger_Name").toString()); player_name.add((String) pndocument.getString("player_Name").toString()); if(challenger_name.contains(current_user)) { CollectionReference userlabel=fStore.collection("BetRequest"); userlabel.whereEqualTo("Challenger_Name",current_user).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if(task.isSuccessful()){ for(QueryDocumentSnapshot lidoucument:task.getResult()){ String player=(String)lidoucument.getString("player_Name").toString(); CollectionReference msgref=fStore.collection("users"); msgref.whereEqualTo("Name",player).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if(task.isSuccessful()) { for(QueryDocumentSnapshot phonedocument:task.getResult()){ String phoneNo="+91"+phonedocument.getString("phone"); openCall(phoneNo); } } } }); } } } }); } else if(player_name.contains(current_user)) { CollectionReference userlabel=fStore.collection("BetRequest"); userlabel.whereEqualTo("player_Name",current_user).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if(task.isSuccessful()){ for(QueryDocumentSnapshot lidoucument:task.getResult()){ String chalenger=(String)lidoucument.getString("Challenger_Name").toString(); CollectionReference msgref=fStore.collection("users"); msgref.whereEqualTo("Name",chalenger).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if(task.isSuccessful()) { for(QueryDocumentSnapshot phonedocument:task.getResult()){ String phoneNo="+91"+phonedocument.getString("phone"); openCall(phoneNo); } } } }); } } } }); } } } } }); } }); } private void roomCode(String checkroom,String RCstatus, String current_user, List<String> challenger_name, List<String> player_name) { if(checkroom!= null) { if(player_name.contains(current_user)) { if(RCstatus=="ACCEPTED") { code.setVisibility(View.GONE); setbtn.setVisibility(View.GONE); yesbtn.setVisibility(View.GONE); nobtn.setVisibility(View.GONE); msg_text.setText(checkroom+"\n\nStart the Match, RoomCode has been Accepted.\n\n"+" मैच शरू करे\n"); msg_text.setBackgroundResource(R.color.blue); } else if(RCstatus=="REJECTED"){ code.setVisibility(View.GONE); setbtn.setVisibility(View.GONE); yesbtn.setVisibility(View.GONE); nobtn.setVisibility(View.GONE); msg_text.setText(" Waiting for Room Code..\nOld Room Code: "+checkroom+"\n"); msg_text.setBackgroundResource(R.color.red); } else { final MediaPlayer mp=MediaPlayer.create(StartmatchActivity.this,R.raw.btnsound); mp.start(); msg_text.setText(checkroom + "\nStep 1.Join the Room Code in Ludoking Game.\nStep 2.If Room Code is correct,press Yes.If Room Code is invalid,press No.\n\n" + "## WITHOUT THIS,MATCH WILL BE CONSIDERED FRAUD.\n\nStep 1.Ludoking game में Room Code join हो.\nStep 2.यदि Room Code सही हे,तो Yes पर दबाये" + "\n\n## इसके बिना, मैच स्वीकार नहीं किया जाएगा\n"); msg_text.setBackgroundResource(R.color.maroon); msg_text.setTextColor(Color.WHITE); code_copy.setVisibility(View.VISIBLE); yesbtn.setVisibility(View.VISIBLE); nobtn.setVisibility(View.VISIBLE); } } else if(challenger_name.contains(current_user)) { if(RCstatus=="ACCEPTED"){ code.setVisibility(View.GONE); setbtn.setVisibility(View.GONE); msg_text.setText(checkroom+"\n\nStart the Match, RoomCode has been Accepted.\n\n"+" मैच शरू करे\n"); msg_text.setBackgroundResource(R.color.blue); } else if(RCstatus=="REJECTED"){ code.setVisibility(View.GONE); setbtn.setVisibility(View.GONE); msg_text.setText("Old Room Code: "+checkroom+"\nNew Room Code Requested by"+player_name+"\n Can you change the Room Code?\n"); msg_text.setBackgroundResource(R.color.maroon); Cyesbtn.setVisibility(View.VISIBLE); Cnobtn.setVisibility(View.VISIBLE); } else{ code.setVisibility(View.GONE); setbtn.setVisibility(View.GONE); msg_text.setText(checkroom+"\n\nWaiting for Admin to check this Room Code Do not Start Match in Ludoking Game.\n\n"+" Room Code देखने के लिए Admin की प्रतीक्षा करे LudoKing Game में मैच अभी शुरू न करे\n"); msg_text.setBackgroundResource(R.color.maroon); } } } else if(checkroom==null && RCstatus==null) { if(challenger_name.contains(current_user)) { msg_text.setText("ENTER LUDOKING ROOMCODE"); code.setVisibility(View.VISIBLE); setbtn.setVisibility(View.VISIBLE); } else if(player_name.contains(current_user)) { msg_text.setText("Waiting for Room Code..."); } } } private void chooseImage() { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Screen Short"), PICK_IMAGE_REQUEST); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null ) { filePath = data.getData(); try { Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath); res_img.setImageBitmap(bitmap); } catch (IOException e) { e.printStackTrace(); } } } private void uploadImage(String current_user_id ){ if(filePath != null) { final ProgressDialog progressDialog = new ProgressDialog(StartmatchActivity.this); progressDialog.setTitle("Uploading Screenshot Image.Do Not press Back..."); progressDialog.show(); StorageReference ref = storageReference.child(current_user_id+"/"+ UUID.randomUUID().toString()); ref.putFile(filePath) .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { progressDialog.dismiss(); Toast.makeText(StartmatchActivity.this, "Uploaded", Toast.LENGTH_SHORT).show(); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { progressDialog.dismiss(); Toast.makeText(StartmatchActivity.this, "Failed "+e.getMessage(), Toast.LENGTH_SHORT).show(); } }) .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() { @Override public void onProgress(UploadTask.TaskSnapshot taskSnapshot) { double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot .getTotalByteCount()); progressDialog.setMessage("Uploaded "+(int)progress+"%"); } }); } } public void checkButton(View v) { int radioId = radioGroup.getCheckedRadioButtonId(); radioButton = findViewById(radioId); if(radioButton.getText().equals("I WON / मैं जीत गया")) { uploadimgbtn.setVisibility(View.VISIBLE); img_notice.setVisibility(View.VISIBLE); } else if(radioButton.getText().equals("I LOST / में हार गया")) { uploadimgbtn.setVisibility(View.GONE); img_notice.setVisibility(View.GONE); } // Toast.makeText(this, "Selected Button" + radioButton.getText(), Toast.LENGTH_SHORT).show(); } public void openWhatsApp(String phoneNo){ try { String text = "This is a test";// Replace with your message. Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("http://api.whatsapp.com/send?phone="+phoneNo +"&text="+text)); startActivity(intent); } catch (Exception e){ e.printStackTrace(); } } public void openCall(String number) { Intent intent = new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", number, null)); startActivity(intent); } }
64,459
0.437151
0.436444
995
62.940704
42.300117
257
false
false
0
0
0
0
0
0
0.636181
false
false
10
20b961b5aee8e21038b1ebf2941da0d68812bf14
8,916,352,153,789
db96833517094f845fc73e32d86974d1a9143f6b
/tenant-service/src/main/java/com/idea/platform/tenant/vo/CommonUser.java
189715a0ab5087c5beef190dd543492a4a9032ab
[]
no_license
derrick123456/idea-service
https://github.com/derrick123456/idea-service
3a5f631b644bb47135805dd63fc84046c07f5d0c
cff01fad8e5471c32ae5e11ff07c6cf1e45ab2f1
refs/heads/master
2022-06-28T22:24:08.655000
2019-11-18T03:20:07
2019-11-18T03:20:07
218,434,451
0
0
null
false
2022-06-21T02:15:22
2019-10-30T03:19:00
2019-11-18T03:26:42
2022-06-21T02:15:19
48
0
0
2
Java
false
false
package com.idea.platform.tenant.vo; import java.io.Serializable; import java.time.LocalDateTime; import javax.persistence.Entity; import javax.persistence.Table; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import com.idea.platform.common.model.BaseVO; import com.idea.platform.common.validation.Second; import io.swagger.annotations.ApiModelProperty; /** * * This class was generated by MyBatis Generator. This class corresponds to the * database table common_user */ @Entity @Table(name = "common_user") public class CommonUser extends BaseVO implements Serializable { /** * Database Column Remarks: id * * This field was generated by MyBatis Generator. This field corresponds to the * database column common_user.id * * @mbg.generated */ private String id; /** * Database Column Remarks: 商户标识码(如HRZD 华润置地) * * This field was generated by MyBatis Generator. This field corresponds to the * database column common_user.code * * @mbg.generated */ @ApiModelProperty(value = "租户标识码,尽可能简短并保持唯一 如HRZD 华润置地,注册必填", required = false) @NotBlank(message = "租户标识码不能为空", groups = {Second.class}) @Pattern(regexp = "/^[A-Z]+$/", message = "租户标识码,尽可能简短并保持唯一 如HRZD 华润置地,注册必填", groups = { Second.class}) private String code; /** * Database Column Remarks: 商户名称 * * This field was generated by MyBatis Generator. This field corresponds to the * database column common_user.name * * @mbg.generated */ @ApiModelProperty(value = "租户名称,注册必填", required = false) @NotBlank(message = "租户名称不能为空", groups = {Second.class}) private String name; /** * Database Column Remarks: 商户全称 * * This field was generated by MyBatis Generator. This field corresponds to the * database column common_user.fullName * * @mbg.generated */ @ApiModelProperty(value = "租户全称,注册必填", required = false) @NotBlank(message = "租户全称不能为空", groups = {Second.class}) private String fullname; /** * Database Column Remarks: 居住地址 * * This field was generated by MyBatis Generator. This field corresponds to the * database column common_user.address * * @mbg.generated */ @ApiModelProperty(value = "居住地址,注册必填", required = false) private String address; /** * Database Column Remarks: 移动电话 * * This field was generated by MyBatis Generator. This field corresponds to the * database column common_user.mobile * * @mbg.generated */ @ApiModelProperty(value = "移动电话,注册必填", required = false) private String mobile; /** * Database Column Remarks: 电子邮箱 * * This field was generated by MyBatis Generator. This field corresponds to the * database column common_user.email * * @mbg.generated */ @ApiModelProperty(value = "email,注册必填", required = false) private String email; /** * Database Column Remarks: 法人代表 * * This field was generated by MyBatis Generator. This field corresponds to the * database column common_user.head * * @mbg.generated */ @ApiModelProperty(value = "法人代表,注册必填", required = false) private String head; /** * Database Column Remarks: 状态(0:申请中,1:审核用过) * * This field was generated by MyBatis Generator. This field corresponds to the * database column common_user.status * * @mbg.generated */ @ApiModelProperty(value = "当为0时可以调用审核接口", required = false) private Short status; /** * Database Column Remarks: 行号 * * This field was generated by MyBatis Generator. This field corresponds to the * database column common_user.rowNo * * @mbg.generated */ private Integer rowno; /** * Database Column Remarks: 有效标记(1:有效,0:无效) * * This field was generated by MyBatis Generator. This field corresponds to the * database column common_user.valid * * @mbg.generated */ private Short valid; /** * Database Column Remarks: 创建者 * * This field was generated by MyBatis Generator. This field corresponds to the * database column common_user.creator * * @mbg.generated */ private String creator; /** * Database Column Remarks: 创建时间 * * This field was generated by MyBatis Generator. This field corresponds to the * database column common_user.createTime * * @mbg.generated */ private LocalDateTime createtime; /** * Database Column Remarks: 修改者 * * This field was generated by MyBatis Generator. This field corresponds to the * database column common_user.editor * * @mbg.generated */ private String editor; /** * Database Column Remarks: 修改时间 * * This field was generated by MyBatis Generator. This field corresponds to the * database column common_user.editTime * * @mbg.generated */ private LocalDateTime edittime; /** * Database Column Remarks: 固定电话 * * This field was generated by MyBatis Generator. This field corresponds to the * database column common_user.telephone * * @mbg.generated */ private String telephone; /** * This field was generated by MyBatis Generator. This field corresponds to the * database table common_user * * @mbg.generated */ private static final long serialVersionUID = 1L; /** * This method was generated by MyBatis Generator. This method returns the value * of the database column common_user.id * * @return the value of common_user.id * * @mbg.generated */ public String getId() { return id; } /** * This method was generated by MyBatis Generator. This method sets the value of * the database column common_user.id * * @param id the value for common_user.id * * @mbg.generated */ public void setId(String id) { this.id = id == null ? null : id.trim(); } /** * This method was generated by MyBatis Generator. This method returns the value * of the database column common_user.code * * @return the value of common_user.code * * @mbg.generated */ public String getCode() { return code; } /** * This method was generated by MyBatis Generator. This method sets the value of * the database column common_user.code * * @param code the value for common_user.code * * @mbg.generated */ public void setCode(String code) { this.code = code == null ? null : code.trim(); } /** * This method was generated by MyBatis Generator. This method returns the value * of the database column common_user.name * * @return the value of common_user.name * * @mbg.generated */ public String getName() { return name; } /** * This method was generated by MyBatis Generator. This method sets the value of * the database column common_user.name * * @param name the value for common_user.name * * @mbg.generated */ public void setName(String name) { this.name = name == null ? null : name.trim(); } /** * This method was generated by MyBatis Generator. This method returns the value * of the database column common_user.fullName * * @return the value of common_user.fullName * * @mbg.generated */ public String getFullname() { return fullname; } /** * This method was generated by MyBatis Generator. This method sets the value of * the database column common_user.fullName * * @param fullname the value for common_user.fullName * * @mbg.generated */ public void setFullname(String fullname) { this.fullname = fullname == null ? null : fullname.trim(); } /** * This method was generated by MyBatis Generator. This method returns the value * of the database column common_user.address * * @return the value of common_user.address * * @mbg.generated */ public String getAddress() { return address; } /** * This method was generated by MyBatis Generator. This method sets the value of * the database column common_user.address * * @param address the value for common_user.address * * @mbg.generated */ public void setAddress(String address) { this.address = address == null ? null : address.trim(); } /** * This method was generated by MyBatis Generator. This method returns the value * of the database column common_user.mobile * * @return the value of common_user.mobile * * @mbg.generated */ public String getMobile() { return mobile; } /** * This method was generated by MyBatis Generator. This method sets the value of * the database column common_user.mobile * * @param mobile the value for common_user.mobile * * @mbg.generated */ public void setMobile(String mobile) { this.mobile = mobile == null ? null : mobile.trim(); } /** * This method was generated by MyBatis Generator. This method returns the value * of the database column common_user.email * * @return the value of common_user.email * * @mbg.generated */ public String getEmail() { return email; } /** * This method was generated by MyBatis Generator. This method sets the value of * the database column common_user.email * * @param email the value for common_user.email * * @mbg.generated */ public void setEmail(String email) { this.email = email == null ? null : email.trim(); } /** * This method was generated by MyBatis Generator. This method returns the value * of the database column common_user.head * * @return the value of common_user.head * * @mbg.generated */ public String getHead() { return head; } /** * This method was generated by MyBatis Generator. This method sets the value of * the database column common_user.head * * @param head the value for common_user.head * * @mbg.generated */ public void setHead(String head) { this.head = head == null ? null : head.trim(); } /** * This method was generated by MyBatis Generator. This method returns the value * of the database column common_user.status * * @return the value of common_user.status * * @mbg.generated */ public Short getStatus() { return status; } /** * This method was generated by MyBatis Generator. This method sets the value of * the database column common_user.status * * @param status the value for common_user.status * * @mbg.generated */ public void setStatus(Short status) { this.status = status; } /** * This method was generated by MyBatis Generator. This method returns the value * of the database column common_user.rowNo * * @return the value of common_user.rowNo * * @mbg.generated */ public Integer getRowno() { return rowno; } /** * This method was generated by MyBatis Generator. This method sets the value of * the database column common_user.rowNo * * @param rowno the value for common_user.rowNo * * @mbg.generated */ public void setRowno(Integer rowno) { this.rowno = rowno; } /** * This method was generated by MyBatis Generator. This method returns the value * of the database column common_user.valid * * @return the value of common_user.valid * * @mbg.generated */ public Short getValid() { return valid; } /** * This method was generated by MyBatis Generator. This method sets the value of * the database column common_user.valid * * @param valid the value for common_user.valid * * @mbg.generated */ public void setValid(Short valid) { this.valid = valid; } /** * This method was generated by MyBatis Generator. This method returns the value * of the database column common_user.creator * * @return the value of common_user.creator * * @mbg.generated */ public String getCreator() { return creator; } /** * This method was generated by MyBatis Generator. This method sets the value of * the database column common_user.creator * * @param creator the value for common_user.creator * * @mbg.generated */ public void setCreator(String creator) { this.creator = creator == null ? null : creator.trim(); } /** * This method was generated by MyBatis Generator. This method returns the value * of the database column common_user.createTime * * @return the value of common_user.createTime * * @mbg.generated */ public LocalDateTime getCreatetime() { return createtime; } /** * This method was generated by MyBatis Generator. This method sets the value of * the database column common_user.createTime * * @param createtime the value for common_user.createTime * * @mbg.generated */ public void setCreatetime(LocalDateTime createtime) { this.createtime = createtime; } /** * This method was generated by MyBatis Generator. This method returns the value * of the database column common_user.editor * * @return the value of common_user.editor * * @mbg.generated */ public String getEditor() { return editor; } /** * This method was generated by MyBatis Generator. This method sets the value of * the database column common_user.editor * * @param editor the value for common_user.editor * * @mbg.generated */ public void setEditor(String editor) { this.editor = editor == null ? null : editor.trim(); } /** * This method was generated by MyBatis Generator. This method returns the value * of the database column common_user.editTime * * @return the value of common_user.editTime * * @mbg.generated */ public LocalDateTime getEdittime() { return edittime; } /** * This method was generated by MyBatis Generator. This method sets the value of * the database column common_user.editTime * * @param edittime the value for common_user.editTime * * @mbg.generated */ public void setEdittime(LocalDateTime edittime) { this.edittime = edittime; } /** * This method was generated by MyBatis Generator. This method returns the value * of the database column common_user.telephone * * @return the value of common_user.telephone * * @mbg.generated */ public String getTelephone() { return telephone; } /** * This method was generated by MyBatis Generator. This method sets the value of * the database column common_user.telephone * * @param telephone the value for common_user.telephone * * @mbg.generated */ public void setTelephone(String telephone) { this.telephone = telephone; } /** * This method was generated by MyBatis Generator. This method corresponds to * the database table common_user * * @mbg.generated */ @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } CommonUser other = (CommonUser) that; return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId())) && (this.getCode() == null ? other.getCode() == null : this.getCode().equals(other.getCode())) && (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName())) && (this.getFullname() == null ? other.getFullname() == null : this.getFullname().equals(other.getFullname())) && (this.getAddress() == null ? other.getAddress() == null : this.getAddress().equals(other.getAddress())) && (this.getMobile() == null ? other.getMobile() == null : this.getMobile().equals(other.getMobile())) && (this.getEmail() == null ? other.getEmail() == null : this.getEmail().equals(other.getEmail())) && (this.getHead() == null ? other.getHead() == null : this.getHead().equals(other.getHead())) && (this.getStatus() == null ? other.getStatus() == null : this.getStatus().equals(other.getStatus())) && (this.getRowno() == null ? other.getRowno() == null : this.getRowno().equals(other.getRowno())) && (this.getValid() == null ? other.getValid() == null : this.getValid().equals(other.getValid())) && (this.getCreator() == null ? other.getCreator() == null : this.getCreator().equals(other.getCreator())) && (this.getCreatetime() == null ? other.getCreatetime() == null : this.getCreatetime().equals(other.getCreatetime())) && (this.getEditor() == null ? other.getEditor() == null : this.getEditor().equals(other.getEditor())) && (this.getEdittime() == null ? other.getEdittime() == null : this.getEdittime().equals(other.getEdittime())) && (this.getTelephone() == null ? other.getTelephone() == null : this.getTelephone().equals(other.getTelephone())); } /** * This method was generated by MyBatis Generator. This method corresponds to * the database table common_user * * @mbg.generated */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getId() == null) ? 0 : getId().hashCode()); result = prime * result + ((getCode() == null) ? 0 : getCode().hashCode()); result = prime * result + ((getName() == null) ? 0 : getName().hashCode()); result = prime * result + ((getFullname() == null) ? 0 : getFullname().hashCode()); result = prime * result + ((getAddress() == null) ? 0 : getAddress().hashCode()); result = prime * result + ((getMobile() == null) ? 0 : getMobile().hashCode()); result = prime * result + ((getEmail() == null) ? 0 : getEmail().hashCode()); result = prime * result + ((getHead() == null) ? 0 : getHead().hashCode()); result = prime * result + ((getStatus() == null) ? 0 : getStatus().hashCode()); result = prime * result + ((getRowno() == null) ? 0 : getRowno().hashCode()); result = prime * result + ((getValid() == null) ? 0 : getValid().hashCode()); result = prime * result + ((getCreator() == null) ? 0 : getCreator().hashCode()); result = prime * result + ((getCreatetime() == null) ? 0 : getCreatetime().hashCode()); result = prime * result + ((getEditor() == null) ? 0 : getEditor().hashCode()); result = prime * result + ((getEdittime() == null) ? 0 : getEdittime().hashCode()); result = prime * result + ((getTelephone() == null) ? 0 : getTelephone().hashCode()); return result; } /** * This method was generated by MyBatis Generator. This method corresponds to * the database table common_user * * @mbg.generated */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", code=").append(code); sb.append(", name=").append(name); sb.append(", fullname=").append(fullname); sb.append(", address=").append(address); sb.append(", mobile=").append(mobile); sb.append(", email=").append(email); sb.append(", head=").append(head); sb.append(", status=").append(status); sb.append(", rowno=").append(rowno); sb.append(", valid=").append(valid); sb.append(", creator=").append(creator); sb.append(", createtime=").append(createtime); sb.append(", editor=").append(editor); sb.append(", edittime=").append(edittime); sb.append(", telephone=").append(telephone); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
UTF-8
Java
19,298
java
CommonUser.java
Java
[]
null
[]
package com.idea.platform.tenant.vo; import java.io.Serializable; import java.time.LocalDateTime; import javax.persistence.Entity; import javax.persistence.Table; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import com.idea.platform.common.model.BaseVO; import com.idea.platform.common.validation.Second; import io.swagger.annotations.ApiModelProperty; /** * * This class was generated by MyBatis Generator. This class corresponds to the * database table common_user */ @Entity @Table(name = "common_user") public class CommonUser extends BaseVO implements Serializable { /** * Database Column Remarks: id * * This field was generated by MyBatis Generator. This field corresponds to the * database column common_user.id * * @mbg.generated */ private String id; /** * Database Column Remarks: 商户标识码(如HRZD 华润置地) * * This field was generated by MyBatis Generator. This field corresponds to the * database column common_user.code * * @mbg.generated */ @ApiModelProperty(value = "租户标识码,尽可能简短并保持唯一 如HRZD 华润置地,注册必填", required = false) @NotBlank(message = "租户标识码不能为空", groups = {Second.class}) @Pattern(regexp = "/^[A-Z]+$/", message = "租户标识码,尽可能简短并保持唯一 如HRZD 华润置地,注册必填", groups = { Second.class}) private String code; /** * Database Column Remarks: 商户名称 * * This field was generated by MyBatis Generator. This field corresponds to the * database column common_user.name * * @mbg.generated */ @ApiModelProperty(value = "租户名称,注册必填", required = false) @NotBlank(message = "租户名称不能为空", groups = {Second.class}) private String name; /** * Database Column Remarks: 商户全称 * * This field was generated by MyBatis Generator. This field corresponds to the * database column common_user.fullName * * @mbg.generated */ @ApiModelProperty(value = "租户全称,注册必填", required = false) @NotBlank(message = "租户全称不能为空", groups = {Second.class}) private String fullname; /** * Database Column Remarks: 居住地址 * * This field was generated by MyBatis Generator. This field corresponds to the * database column common_user.address * * @mbg.generated */ @ApiModelProperty(value = "居住地址,注册必填", required = false) private String address; /** * Database Column Remarks: 移动电话 * * This field was generated by MyBatis Generator. This field corresponds to the * database column common_user.mobile * * @mbg.generated */ @ApiModelProperty(value = "移动电话,注册必填", required = false) private String mobile; /** * Database Column Remarks: 电子邮箱 * * This field was generated by MyBatis Generator. This field corresponds to the * database column common_user.email * * @mbg.generated */ @ApiModelProperty(value = "email,注册必填", required = false) private String email; /** * Database Column Remarks: 法人代表 * * This field was generated by MyBatis Generator. This field corresponds to the * database column common_user.head * * @mbg.generated */ @ApiModelProperty(value = "法人代表,注册必填", required = false) private String head; /** * Database Column Remarks: 状态(0:申请中,1:审核用过) * * This field was generated by MyBatis Generator. This field corresponds to the * database column common_user.status * * @mbg.generated */ @ApiModelProperty(value = "当为0时可以调用审核接口", required = false) private Short status; /** * Database Column Remarks: 行号 * * This field was generated by MyBatis Generator. This field corresponds to the * database column common_user.rowNo * * @mbg.generated */ private Integer rowno; /** * Database Column Remarks: 有效标记(1:有效,0:无效) * * This field was generated by MyBatis Generator. This field corresponds to the * database column common_user.valid * * @mbg.generated */ private Short valid; /** * Database Column Remarks: 创建者 * * This field was generated by MyBatis Generator. This field corresponds to the * database column common_user.creator * * @mbg.generated */ private String creator; /** * Database Column Remarks: 创建时间 * * This field was generated by MyBatis Generator. This field corresponds to the * database column common_user.createTime * * @mbg.generated */ private LocalDateTime createtime; /** * Database Column Remarks: 修改者 * * This field was generated by MyBatis Generator. This field corresponds to the * database column common_user.editor * * @mbg.generated */ private String editor; /** * Database Column Remarks: 修改时间 * * This field was generated by MyBatis Generator. This field corresponds to the * database column common_user.editTime * * @mbg.generated */ private LocalDateTime edittime; /** * Database Column Remarks: 固定电话 * * This field was generated by MyBatis Generator. This field corresponds to the * database column common_user.telephone * * @mbg.generated */ private String telephone; /** * This field was generated by MyBatis Generator. This field corresponds to the * database table common_user * * @mbg.generated */ private static final long serialVersionUID = 1L; /** * This method was generated by MyBatis Generator. This method returns the value * of the database column common_user.id * * @return the value of common_user.id * * @mbg.generated */ public String getId() { return id; } /** * This method was generated by MyBatis Generator. This method sets the value of * the database column common_user.id * * @param id the value for common_user.id * * @mbg.generated */ public void setId(String id) { this.id = id == null ? null : id.trim(); } /** * This method was generated by MyBatis Generator. This method returns the value * of the database column common_user.code * * @return the value of common_user.code * * @mbg.generated */ public String getCode() { return code; } /** * This method was generated by MyBatis Generator. This method sets the value of * the database column common_user.code * * @param code the value for common_user.code * * @mbg.generated */ public void setCode(String code) { this.code = code == null ? null : code.trim(); } /** * This method was generated by MyBatis Generator. This method returns the value * of the database column common_user.name * * @return the value of common_user.name * * @mbg.generated */ public String getName() { return name; } /** * This method was generated by MyBatis Generator. This method sets the value of * the database column common_user.name * * @param name the value for common_user.name * * @mbg.generated */ public void setName(String name) { this.name = name == null ? null : name.trim(); } /** * This method was generated by MyBatis Generator. This method returns the value * of the database column common_user.fullName * * @return the value of common_user.fullName * * @mbg.generated */ public String getFullname() { return fullname; } /** * This method was generated by MyBatis Generator. This method sets the value of * the database column common_user.fullName * * @param fullname the value for common_user.fullName * * @mbg.generated */ public void setFullname(String fullname) { this.fullname = fullname == null ? null : fullname.trim(); } /** * This method was generated by MyBatis Generator. This method returns the value * of the database column common_user.address * * @return the value of common_user.address * * @mbg.generated */ public String getAddress() { return address; } /** * This method was generated by MyBatis Generator. This method sets the value of * the database column common_user.address * * @param address the value for common_user.address * * @mbg.generated */ public void setAddress(String address) { this.address = address == null ? null : address.trim(); } /** * This method was generated by MyBatis Generator. This method returns the value * of the database column common_user.mobile * * @return the value of common_user.mobile * * @mbg.generated */ public String getMobile() { return mobile; } /** * This method was generated by MyBatis Generator. This method sets the value of * the database column common_user.mobile * * @param mobile the value for common_user.mobile * * @mbg.generated */ public void setMobile(String mobile) { this.mobile = mobile == null ? null : mobile.trim(); } /** * This method was generated by MyBatis Generator. This method returns the value * of the database column common_user.email * * @return the value of common_user.email * * @mbg.generated */ public String getEmail() { return email; } /** * This method was generated by MyBatis Generator. This method sets the value of * the database column common_user.email * * @param email the value for common_user.email * * @mbg.generated */ public void setEmail(String email) { this.email = email == null ? null : email.trim(); } /** * This method was generated by MyBatis Generator. This method returns the value * of the database column common_user.head * * @return the value of common_user.head * * @mbg.generated */ public String getHead() { return head; } /** * This method was generated by MyBatis Generator. This method sets the value of * the database column common_user.head * * @param head the value for common_user.head * * @mbg.generated */ public void setHead(String head) { this.head = head == null ? null : head.trim(); } /** * This method was generated by MyBatis Generator. This method returns the value * of the database column common_user.status * * @return the value of common_user.status * * @mbg.generated */ public Short getStatus() { return status; } /** * This method was generated by MyBatis Generator. This method sets the value of * the database column common_user.status * * @param status the value for common_user.status * * @mbg.generated */ public void setStatus(Short status) { this.status = status; } /** * This method was generated by MyBatis Generator. This method returns the value * of the database column common_user.rowNo * * @return the value of common_user.rowNo * * @mbg.generated */ public Integer getRowno() { return rowno; } /** * This method was generated by MyBatis Generator. This method sets the value of * the database column common_user.rowNo * * @param rowno the value for common_user.rowNo * * @mbg.generated */ public void setRowno(Integer rowno) { this.rowno = rowno; } /** * This method was generated by MyBatis Generator. This method returns the value * of the database column common_user.valid * * @return the value of common_user.valid * * @mbg.generated */ public Short getValid() { return valid; } /** * This method was generated by MyBatis Generator. This method sets the value of * the database column common_user.valid * * @param valid the value for common_user.valid * * @mbg.generated */ public void setValid(Short valid) { this.valid = valid; } /** * This method was generated by MyBatis Generator. This method returns the value * of the database column common_user.creator * * @return the value of common_user.creator * * @mbg.generated */ public String getCreator() { return creator; } /** * This method was generated by MyBatis Generator. This method sets the value of * the database column common_user.creator * * @param creator the value for common_user.creator * * @mbg.generated */ public void setCreator(String creator) { this.creator = creator == null ? null : creator.trim(); } /** * This method was generated by MyBatis Generator. This method returns the value * of the database column common_user.createTime * * @return the value of common_user.createTime * * @mbg.generated */ public LocalDateTime getCreatetime() { return createtime; } /** * This method was generated by MyBatis Generator. This method sets the value of * the database column common_user.createTime * * @param createtime the value for common_user.createTime * * @mbg.generated */ public void setCreatetime(LocalDateTime createtime) { this.createtime = createtime; } /** * This method was generated by MyBatis Generator. This method returns the value * of the database column common_user.editor * * @return the value of common_user.editor * * @mbg.generated */ public String getEditor() { return editor; } /** * This method was generated by MyBatis Generator. This method sets the value of * the database column common_user.editor * * @param editor the value for common_user.editor * * @mbg.generated */ public void setEditor(String editor) { this.editor = editor == null ? null : editor.trim(); } /** * This method was generated by MyBatis Generator. This method returns the value * of the database column common_user.editTime * * @return the value of common_user.editTime * * @mbg.generated */ public LocalDateTime getEdittime() { return edittime; } /** * This method was generated by MyBatis Generator. This method sets the value of * the database column common_user.editTime * * @param edittime the value for common_user.editTime * * @mbg.generated */ public void setEdittime(LocalDateTime edittime) { this.edittime = edittime; } /** * This method was generated by MyBatis Generator. This method returns the value * of the database column common_user.telephone * * @return the value of common_user.telephone * * @mbg.generated */ public String getTelephone() { return telephone; } /** * This method was generated by MyBatis Generator. This method sets the value of * the database column common_user.telephone * * @param telephone the value for common_user.telephone * * @mbg.generated */ public void setTelephone(String telephone) { this.telephone = telephone; } /** * This method was generated by MyBatis Generator. This method corresponds to * the database table common_user * * @mbg.generated */ @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } CommonUser other = (CommonUser) that; return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId())) && (this.getCode() == null ? other.getCode() == null : this.getCode().equals(other.getCode())) && (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName())) && (this.getFullname() == null ? other.getFullname() == null : this.getFullname().equals(other.getFullname())) && (this.getAddress() == null ? other.getAddress() == null : this.getAddress().equals(other.getAddress())) && (this.getMobile() == null ? other.getMobile() == null : this.getMobile().equals(other.getMobile())) && (this.getEmail() == null ? other.getEmail() == null : this.getEmail().equals(other.getEmail())) && (this.getHead() == null ? other.getHead() == null : this.getHead().equals(other.getHead())) && (this.getStatus() == null ? other.getStatus() == null : this.getStatus().equals(other.getStatus())) && (this.getRowno() == null ? other.getRowno() == null : this.getRowno().equals(other.getRowno())) && (this.getValid() == null ? other.getValid() == null : this.getValid().equals(other.getValid())) && (this.getCreator() == null ? other.getCreator() == null : this.getCreator().equals(other.getCreator())) && (this.getCreatetime() == null ? other.getCreatetime() == null : this.getCreatetime().equals(other.getCreatetime())) && (this.getEditor() == null ? other.getEditor() == null : this.getEditor().equals(other.getEditor())) && (this.getEdittime() == null ? other.getEdittime() == null : this.getEdittime().equals(other.getEdittime())) && (this.getTelephone() == null ? other.getTelephone() == null : this.getTelephone().equals(other.getTelephone())); } /** * This method was generated by MyBatis Generator. This method corresponds to * the database table common_user * * @mbg.generated */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getId() == null) ? 0 : getId().hashCode()); result = prime * result + ((getCode() == null) ? 0 : getCode().hashCode()); result = prime * result + ((getName() == null) ? 0 : getName().hashCode()); result = prime * result + ((getFullname() == null) ? 0 : getFullname().hashCode()); result = prime * result + ((getAddress() == null) ? 0 : getAddress().hashCode()); result = prime * result + ((getMobile() == null) ? 0 : getMobile().hashCode()); result = prime * result + ((getEmail() == null) ? 0 : getEmail().hashCode()); result = prime * result + ((getHead() == null) ? 0 : getHead().hashCode()); result = prime * result + ((getStatus() == null) ? 0 : getStatus().hashCode()); result = prime * result + ((getRowno() == null) ? 0 : getRowno().hashCode()); result = prime * result + ((getValid() == null) ? 0 : getValid().hashCode()); result = prime * result + ((getCreator() == null) ? 0 : getCreator().hashCode()); result = prime * result + ((getCreatetime() == null) ? 0 : getCreatetime().hashCode()); result = prime * result + ((getEditor() == null) ? 0 : getEditor().hashCode()); result = prime * result + ((getEdittime() == null) ? 0 : getEdittime().hashCode()); result = prime * result + ((getTelephone() == null) ? 0 : getTelephone().hashCode()); return result; } /** * This method was generated by MyBatis Generator. This method corresponds to * the database table common_user * * @mbg.generated */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", code=").append(code); sb.append(", name=").append(name); sb.append(", fullname=").append(fullname); sb.append(", address=").append(address); sb.append(", mobile=").append(mobile); sb.append(", email=").append(email); sb.append(", head=").append(head); sb.append(", status=").append(status); sb.append(", rowno=").append(rowno); sb.append(", valid=").append(valid); sb.append(", creator=").append(creator); sb.append(", createtime=").append(createtime); sb.append(", editor=").append(editor); sb.append(", edittime=").append(edittime); sb.append(", telephone=").append(telephone); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
19,298
0.67582
0.674497
695
26.195683
27.264107
106
false
false
0
0
0
0
0
0
1.339568
false
false
10
9e55c74ee8f86728e662a1e776d914b5d7f3ebc8
31,602,369,432,998
c4ddca7a110624dd214a4284b7860b0a1f37d927
/src/AST/Build/DeclarationListener.java
f211351af123ad19da300bd9903ce1b5821a8772
[ "MIT" ]
permissive
dengwxn/Mx-Compiler
https://github.com/dengwxn/Mx-Compiler
9b719a60a6656819936eb3ab2d9081fd8258854a
805a67638b57f5dbb091796490dfa443c72abe13
refs/heads/master
2020-04-26T04:02:52.204000
2019-08-12T14:40:04
2019-08-12T14:40:04
173,288,280
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package AST.Build; import AST.Program.ClassDeclNode; import AST.Program.FuncDeclNode; import AST.Statement.VarDeclStmtNode; import AST.Type.FuncType; import AST.Type.IntType; import AST.Type.Type; import Parser.MxParser; import java.util.ArrayList; import static AST.Build.Tree.*; public class DeclarationListener extends Listener { @Override public void enterClassDeclaration(MxParser.ClassDeclarationContext ctx) { ClassDeclNode classDecl = (ClassDeclNode) map.get(ctx); symbolTable.setClassName(classDecl.getName()); for (VarDeclStmtNode varDecl : classDecl.getVarDecl()) { String varName = classDecl.getName() + "." + varDecl.getName(); symbolTable.putType(varName, typeTable.getType(varDecl.getType())); } } @Override public void exitClassDeclaration(MxParser.ClassDeclarationContext ctx) { symbolTable.setClassName(null); } @Override public void enterFunctionDeclaration(MxParser.FunctionDeclarationContext ctx) { FuncDeclNode funcDecl = (FuncDeclNode) map.get(ctx); Type retType = typeTable.getType(funcDecl.getRetType()); ArrayList<Type> paramType = new ArrayList<>(); funcDecl.getParamType().forEach(t -> paramType.add(typeTable.getType(t))); String funcName = funcDecl.getFuncName(); boolean isClassFunc = funcName != null && funcName.contains("."); symbolTable.putType(funcName, new FuncType(funcName, retType, paramType, isClassFunc)); symbolTable.getType(funcName); } private void mainPrint() { Type retType = symbolTable.getType("void"); ArrayList<Type> paramType = new ArrayList<>(); paramType.add(symbolTable.getType("string")); String funcName = "print"; symbolTable.putType(funcName, new FuncType(funcName, retType, paramType)); } private void mainPrintln() { Type retType = symbolTable.getType("void"); ArrayList<Type> paramType = new ArrayList<>(); paramType.add(symbolTable.getType("string")); String funcName = "println"; symbolTable.putType(funcName, new FuncType(funcName, retType, paramType)); } private void mainGetString() { Type retType = symbolTable.getType("string"); String funcName = "getString"; symbolTable.putType(funcName, new FuncType(funcName, retType)); } private void mainGetInt() { Type retType = symbolTable.getType("int"); String funcName = "getInt"; symbolTable.putType(funcName, new FuncType(funcName, retType)); } private void mainToString() { Type retType = symbolTable.getType("string"); ArrayList<Type> paramType = new ArrayList<>(); paramType.add(symbolTable.getType("int")); String funcName = "toString"; symbolTable.putType(funcName, new FuncType(funcName, retType, paramType)); } private void arraySize() { Type retType = symbolTable.getType("int"); String funcName = "_.size"; symbolTable.putType(funcName, new FuncType(funcName, retType)); } private void stringLength() { Type retType = symbolTable.getType("int"); String funcName = "string.length"; symbolTable.putType(funcName, new FuncType(funcName, retType)); } private void stringSubstring() { Type retType = symbolTable.getType("string"); String funcName = "string.substring"; ArrayList<Type> paramType = new ArrayList<>(); paramType.add(symbolTable.getType("int")); paramType.add(symbolTable.getType("int")); symbolTable.putType(funcName, new FuncType(funcName, retType, paramType)); } private void stringParseInt() { Type retType = symbolTable.getType("int"); String funcName = "string.parseInt"; symbolTable.putType(funcName, new FuncType(funcName, retType)); } private void stringOrd() { Type retType = symbolTable.getType("int"); String funcName = "string.ord"; ArrayList<Type> paramType = new ArrayList<>(); paramType.add(symbolTable.getType("int")); symbolTable.putType(funcName, new FuncType(funcName, retType, paramType)); } private boolean isMainValid() { FuncType funcType = (FuncType) symbolTable.getType("main"); if (funcType == null) return false; if (!(funcType.getRetType() instanceof IntType)) return false; return funcType.getParamType().size() <= 0; } @Override public void exitProgram(MxParser.ProgramContext ctx) { if (!isMainValid()) addCompileError("expect a 'int main()' function."); arraySize(); stringLength(); stringSubstring(); stringParseInt(); stringOrd(); mainPrint(); mainPrintln(); mainGetString(); mainGetInt(); mainToString(); } }
UTF-8
Java
4,921
java
DeclarationListener.java
Java
[]
null
[]
package AST.Build; import AST.Program.ClassDeclNode; import AST.Program.FuncDeclNode; import AST.Statement.VarDeclStmtNode; import AST.Type.FuncType; import AST.Type.IntType; import AST.Type.Type; import Parser.MxParser; import java.util.ArrayList; import static AST.Build.Tree.*; public class DeclarationListener extends Listener { @Override public void enterClassDeclaration(MxParser.ClassDeclarationContext ctx) { ClassDeclNode classDecl = (ClassDeclNode) map.get(ctx); symbolTable.setClassName(classDecl.getName()); for (VarDeclStmtNode varDecl : classDecl.getVarDecl()) { String varName = classDecl.getName() + "." + varDecl.getName(); symbolTable.putType(varName, typeTable.getType(varDecl.getType())); } } @Override public void exitClassDeclaration(MxParser.ClassDeclarationContext ctx) { symbolTable.setClassName(null); } @Override public void enterFunctionDeclaration(MxParser.FunctionDeclarationContext ctx) { FuncDeclNode funcDecl = (FuncDeclNode) map.get(ctx); Type retType = typeTable.getType(funcDecl.getRetType()); ArrayList<Type> paramType = new ArrayList<>(); funcDecl.getParamType().forEach(t -> paramType.add(typeTable.getType(t))); String funcName = funcDecl.getFuncName(); boolean isClassFunc = funcName != null && funcName.contains("."); symbolTable.putType(funcName, new FuncType(funcName, retType, paramType, isClassFunc)); symbolTable.getType(funcName); } private void mainPrint() { Type retType = symbolTable.getType("void"); ArrayList<Type> paramType = new ArrayList<>(); paramType.add(symbolTable.getType("string")); String funcName = "print"; symbolTable.putType(funcName, new FuncType(funcName, retType, paramType)); } private void mainPrintln() { Type retType = symbolTable.getType("void"); ArrayList<Type> paramType = new ArrayList<>(); paramType.add(symbolTable.getType("string")); String funcName = "println"; symbolTable.putType(funcName, new FuncType(funcName, retType, paramType)); } private void mainGetString() { Type retType = symbolTable.getType("string"); String funcName = "getString"; symbolTable.putType(funcName, new FuncType(funcName, retType)); } private void mainGetInt() { Type retType = symbolTable.getType("int"); String funcName = "getInt"; symbolTable.putType(funcName, new FuncType(funcName, retType)); } private void mainToString() { Type retType = symbolTable.getType("string"); ArrayList<Type> paramType = new ArrayList<>(); paramType.add(symbolTable.getType("int")); String funcName = "toString"; symbolTable.putType(funcName, new FuncType(funcName, retType, paramType)); } private void arraySize() { Type retType = symbolTable.getType("int"); String funcName = "_.size"; symbolTable.putType(funcName, new FuncType(funcName, retType)); } private void stringLength() { Type retType = symbolTable.getType("int"); String funcName = "string.length"; symbolTable.putType(funcName, new FuncType(funcName, retType)); } private void stringSubstring() { Type retType = symbolTable.getType("string"); String funcName = "string.substring"; ArrayList<Type> paramType = new ArrayList<>(); paramType.add(symbolTable.getType("int")); paramType.add(symbolTable.getType("int")); symbolTable.putType(funcName, new FuncType(funcName, retType, paramType)); } private void stringParseInt() { Type retType = symbolTable.getType("int"); String funcName = "string.parseInt"; symbolTable.putType(funcName, new FuncType(funcName, retType)); } private void stringOrd() { Type retType = symbolTable.getType("int"); String funcName = "string.ord"; ArrayList<Type> paramType = new ArrayList<>(); paramType.add(symbolTable.getType("int")); symbolTable.putType(funcName, new FuncType(funcName, retType, paramType)); } private boolean isMainValid() { FuncType funcType = (FuncType) symbolTable.getType("main"); if (funcType == null) return false; if (!(funcType.getRetType() instanceof IntType)) return false; return funcType.getParamType().size() <= 0; } @Override public void exitProgram(MxParser.ProgramContext ctx) { if (!isMainValid()) addCompileError("expect a 'int main()' function."); arraySize(); stringLength(); stringSubstring(); stringParseInt(); stringOrd(); mainPrint(); mainPrintln(); mainGetString(); mainGetInt(); mainToString(); } }
4,921
0.654542
0.654339
138
34.65942
25.95439
95
false
false
0
0
0
0
0
0
0.789855
false
false
10
4ee4cf50ceda488fa1dc64dbdaefddeb293126e9
33,354,716,055,231
b41362b44344e92f21bbcb2fa65ae3984f4c6b22
/src/main/java/org/bian/dto/SDMortgageLoanRetrieveOutputModelMortgageLoanOfferedServiceMortgageLoanServiceRecordMortgageLoanServicePoliciesandGuidelines.java
9f999dd4964be68959feb06dcc804703af3e54c6
[ "Apache-2.0" ]
permissive
bianapis/sd-mortgage-loan-v3
https://github.com/bianapis/sd-mortgage-loan-v3
b44fac80e8841bd5432c32f13527e9d64c069101
e632bc5a1c515c32539ac09404eb68476dfbf660
refs/heads/master
2022-12-19T12:50:51.361000
2020-09-26T16:07:51
2020-09-26T16:07:51
298,850,166
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.bian.dto; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.Valid; /** * SDMortgageLoanRetrieveOutputModelMortgageLoanOfferedServiceMortgageLoanServiceRecordMortgageLoanServicePoliciesandGuidelines */ public class SDMortgageLoanRetrieveOutputModelMortgageLoanOfferedServiceMortgageLoanServiceRecordMortgageLoanServicePoliciesandGuidelines { private String mortgageLoanServiceEligibility = null; private String mortgageLoanServiceIntendedUses = null; private String mortgageLoanServicePricingandTerms = null; /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: Policies and rules governing access to the offered service, includes eligibility and qualifications * @return mortgageLoanServiceEligibility **/ public String getMortgageLoanServiceEligibility() { return mortgageLoanServiceEligibility; } public void setMortgageLoanServiceEligibility(String mortgageLoanServiceEligibility) { this.mortgageLoanServiceEligibility = mortgageLoanServiceEligibility; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: Guidelines covering allowed, intended use of the service * @return mortgageLoanServiceIntendedUses **/ public String getMortgageLoanServiceIntendedUses() { return mortgageLoanServiceIntendedUses; } public void setMortgageLoanServiceIntendedUses(String mortgageLoanServiceIntendedUses) { this.mortgageLoanServiceIntendedUses = mortgageLoanServiceIntendedUses; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: Terms, prices, penalties associated with use of the service * @return mortgageLoanServicePricingandTerms **/ public String getMortgageLoanServicePricingandTerms() { return mortgageLoanServicePricingandTerms; } public void setMortgageLoanServicePricingandTerms(String mortgageLoanServicePricingandTerms) { this.mortgageLoanServicePricingandTerms = mortgageLoanServicePricingandTerms; } }
UTF-8
Java
2,316
java
SDMortgageLoanRetrieveOutputModelMortgageLoanOfferedServiceMortgageLoanServiceRecordMortgageLoanServicePoliciesandGuidelines.java
Java
[]
null
[]
package org.bian.dto; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.Valid; /** * SDMortgageLoanRetrieveOutputModelMortgageLoanOfferedServiceMortgageLoanServiceRecordMortgageLoanServicePoliciesandGuidelines */ public class SDMortgageLoanRetrieveOutputModelMortgageLoanOfferedServiceMortgageLoanServiceRecordMortgageLoanServicePoliciesandGuidelines { private String mortgageLoanServiceEligibility = null; private String mortgageLoanServiceIntendedUses = null; private String mortgageLoanServicePricingandTerms = null; /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: Policies and rules governing access to the offered service, includes eligibility and qualifications * @return mortgageLoanServiceEligibility **/ public String getMortgageLoanServiceEligibility() { return mortgageLoanServiceEligibility; } public void setMortgageLoanServiceEligibility(String mortgageLoanServiceEligibility) { this.mortgageLoanServiceEligibility = mortgageLoanServiceEligibility; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: Guidelines covering allowed, intended use of the service * @return mortgageLoanServiceIntendedUses **/ public String getMortgageLoanServiceIntendedUses() { return mortgageLoanServiceIntendedUses; } public void setMortgageLoanServiceIntendedUses(String mortgageLoanServiceIntendedUses) { this.mortgageLoanServiceIntendedUses = mortgageLoanServiceIntendedUses; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: Terms, prices, penalties associated with use of the service * @return mortgageLoanServicePricingandTerms **/ public String getMortgageLoanServicePricingandTerms() { return mortgageLoanServicePricingandTerms; } public void setMortgageLoanServicePricingandTerms(String mortgageLoanServicePricingandTerms) { this.mortgageLoanServicePricingandTerms = mortgageLoanServicePricingandTerms; } }
2,316
0.816494
0.816494
63
35.746033
49.39056
222
false
false
0
0
0
0
125
0.107513
0.301587
false
false
10
1f1220def71a5457be7f0d68720a1f2497dc59c3
24,833,500,957,961
753be36837030ee5993dba6ccf691511faf1ec41
/development/org.eclipse.wst.sse.unittests/src/org/eclipse/wst/sse/unittests/MasterListTestSuite.java
03cafb4a09186e97f9632456765d95e524ebb967
[]
no_license
kingargyle/wtp-sourceediting
https://github.com/kingargyle/wtp-sourceediting
da51c1da9dcc906a7b2cb3399d447bf148c1abbd
008173496f087062264ff4c77da2e7fdc36340c9
refs/heads/master
2016-09-06T06:42:35.379000
2011-06-16T00:59:07
2011-06-16T00:59:07
1,908,091
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/***************************************************************************** * Copyright (c) 2004, 2009 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials are made * available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: IBM Corporation - initial API and implementation * ****************************************************************************/ package org.eclipse.wst.sse.unittests; import junit.framework.Test; import junit.framework.TestSuite; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.Platform; import org.eclipse.jst.jsp.core.tests.JSPCoreTestSuite; import org.eclipse.jst.jsp.tests.encoding.JSPEncodingTestSuite; import org.eclipse.jst.jsp.ui.tests.JSPUITestSuite; import org.eclipse.wst.css.core.tests.CSSCoreTestSuite; import org.eclipse.wst.css.tests.encoding.CSSEncodingTestSuite; import org.eclipse.wst.css.ui.tests.CSSUITestSuite; import org.eclipse.wst.dtd.core.tests.DTDCoreTestSuite; import org.eclipse.wst.dtd.ui.tests.DTDUITestSuite; import org.eclipse.wst.html.core.tests.HTMLCoreTestSuite; import org.eclipse.wst.html.tests.encoding.HTMLEncodingTestSuite; import org.eclipse.wst.html.ui.tests.HTMLUITestSuite; import org.eclipse.wst.jsdt.core.tests.RunJSDTCoreTests; import org.eclipse.wst.jsdt.core.tests.compiler.JSDTCompilerTests; import org.eclipse.wst.jsdt.ui.tests.JSDTUITests; import org.eclipse.wst.jsdt.web.core.tests.AllWebCoreTests; import org.eclipse.wst.jsdt.web.ui.tests.AllWebUITests; import org.eclipse.wst.sse.core.tests.SSEModelTestSuite; import org.eclipse.wst.sse.ui.tests.SSEUITestSuite; import org.eclipse.wst.xml.core.tests.SSEModelXMLTestSuite; import org.eclipse.wst.xml.tests.encoding.EncodingTestSuite; import org.eclipse.wst.xml.ui.tests.XMLUITestSuite; import org.eclipse.wst.xml.validation.tests.internal.AllXMLTests; import org.eclipse.wst.xsd.core.tests.internal.AllXSDCoreTests; import org.eclipse.wst.xsd.validation.tests.internal.AllXSDTests; import org.eclipse.wst.xsl.tests.AllTestsSuite; public class MasterListTestSuite extends TestSuite { private static final String CLASS = "class"; private static final String EXTENSION_POINT_ID = "org.eclipse.wst.sse.unittests.additionalTests"; public MasterListTestSuite() { super("WTP Source Editing Master List Test Suite"); System.setProperty("wtp.autotest.noninteractive", "true"); addTest(SSEModelTestSuite.suite()); addTest(SSEModelXMLTestSuite.suite()); addTest(DTDCoreTestSuite.suite()); addTest(AllXSDCoreTests.suite()); addTest(CSSCoreTestSuite.suite()); addTest(HTMLCoreTestSuite.suite()); addTest(JSPCoreTestSuite.suite()); addTest(EncodingTestSuite.suite()); addTest(CSSEncodingTestSuite.suite()); addTest(HTMLEncodingTestSuite.suite()); addTest(JSPEncodingTestSuite.suite()); addTest(AllXMLTests.suite()); addTest(AllXSDTests.suite()); addTest(SSEUITestSuite.suite()); addTest(XMLUITestSuite.suite()); addTest(DTDUITestSuite.suite()); addTest(CSSUITestSuite.suite()); addTest(HTMLUITestSuite.suite()); addTest(JSPUITestSuite.suite()); addTest(RunJSDTCoreTests.suite()); addTest(JSDTCompilerTests.suite()); addTest(JSDTUITests.suite()); addTest(AllWebCoreTests.suite()); addTest(AllWebUITests.suite()); addTest(new AllTestsSuite()); // addTest(RegressionBucket.suite()); // addTest(AllTestCases.suite()); IConfigurationElement[] elements = Platform.getExtensionRegistry().getConfigurationElementsFor(EXTENSION_POINT_ID); for (int i = 0; i < elements.length; i++) { if (elements[i].getName().equals("suite")) { TestSuite suite; try { suite = (TestSuite) elements[i].createExecutableExtension(CLASS); addTestSuite(suite.getClass()); System.err.println("Adding TestSuite " + suite.getClass().getName()); } catch (CoreException e) { e.printStackTrace(System.err); Platform.getLog(Platform.getBundle("org.eclipse.wst.sse.unittests")).log(e.getStatus()); } } else if (elements[i].getName().equals("test")) { Test test; try { test = (Test) elements[i].createExecutableExtension(CLASS); addTestSuite(test.getClass()); System.err.println("Adding TestCase " + test.getClass().getName()); } catch (CoreException e) { e.printStackTrace(System.err); Platform.getLog(Platform.getBundle("org.eclipse.wst.sse.unittests")).log(e.getStatus()); } } } } public void testAll() { // this method needs to exist, but doesn't really do anything // other than to signal to create an instance of this class. // The rest it automatic from the tests added in constructor. } }
UTF-8
Java
4,844
java
MasterListTestSuite.java
Java
[]
null
[]
/***************************************************************************** * Copyright (c) 2004, 2009 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials are made * available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: IBM Corporation - initial API and implementation * ****************************************************************************/ package org.eclipse.wst.sse.unittests; import junit.framework.Test; import junit.framework.TestSuite; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.Platform; import org.eclipse.jst.jsp.core.tests.JSPCoreTestSuite; import org.eclipse.jst.jsp.tests.encoding.JSPEncodingTestSuite; import org.eclipse.jst.jsp.ui.tests.JSPUITestSuite; import org.eclipse.wst.css.core.tests.CSSCoreTestSuite; import org.eclipse.wst.css.tests.encoding.CSSEncodingTestSuite; import org.eclipse.wst.css.ui.tests.CSSUITestSuite; import org.eclipse.wst.dtd.core.tests.DTDCoreTestSuite; import org.eclipse.wst.dtd.ui.tests.DTDUITestSuite; import org.eclipse.wst.html.core.tests.HTMLCoreTestSuite; import org.eclipse.wst.html.tests.encoding.HTMLEncodingTestSuite; import org.eclipse.wst.html.ui.tests.HTMLUITestSuite; import org.eclipse.wst.jsdt.core.tests.RunJSDTCoreTests; import org.eclipse.wst.jsdt.core.tests.compiler.JSDTCompilerTests; import org.eclipse.wst.jsdt.ui.tests.JSDTUITests; import org.eclipse.wst.jsdt.web.core.tests.AllWebCoreTests; import org.eclipse.wst.jsdt.web.ui.tests.AllWebUITests; import org.eclipse.wst.sse.core.tests.SSEModelTestSuite; import org.eclipse.wst.sse.ui.tests.SSEUITestSuite; import org.eclipse.wst.xml.core.tests.SSEModelXMLTestSuite; import org.eclipse.wst.xml.tests.encoding.EncodingTestSuite; import org.eclipse.wst.xml.ui.tests.XMLUITestSuite; import org.eclipse.wst.xml.validation.tests.internal.AllXMLTests; import org.eclipse.wst.xsd.core.tests.internal.AllXSDCoreTests; import org.eclipse.wst.xsd.validation.tests.internal.AllXSDTests; import org.eclipse.wst.xsl.tests.AllTestsSuite; public class MasterListTestSuite extends TestSuite { private static final String CLASS = "class"; private static final String EXTENSION_POINT_ID = "org.eclipse.wst.sse.unittests.additionalTests"; public MasterListTestSuite() { super("WTP Source Editing Master List Test Suite"); System.setProperty("wtp.autotest.noninteractive", "true"); addTest(SSEModelTestSuite.suite()); addTest(SSEModelXMLTestSuite.suite()); addTest(DTDCoreTestSuite.suite()); addTest(AllXSDCoreTests.suite()); addTest(CSSCoreTestSuite.suite()); addTest(HTMLCoreTestSuite.suite()); addTest(JSPCoreTestSuite.suite()); addTest(EncodingTestSuite.suite()); addTest(CSSEncodingTestSuite.suite()); addTest(HTMLEncodingTestSuite.suite()); addTest(JSPEncodingTestSuite.suite()); addTest(AllXMLTests.suite()); addTest(AllXSDTests.suite()); addTest(SSEUITestSuite.suite()); addTest(XMLUITestSuite.suite()); addTest(DTDUITestSuite.suite()); addTest(CSSUITestSuite.suite()); addTest(HTMLUITestSuite.suite()); addTest(JSPUITestSuite.suite()); addTest(RunJSDTCoreTests.suite()); addTest(JSDTCompilerTests.suite()); addTest(JSDTUITests.suite()); addTest(AllWebCoreTests.suite()); addTest(AllWebUITests.suite()); addTest(new AllTestsSuite()); // addTest(RegressionBucket.suite()); // addTest(AllTestCases.suite()); IConfigurationElement[] elements = Platform.getExtensionRegistry().getConfigurationElementsFor(EXTENSION_POINT_ID); for (int i = 0; i < elements.length; i++) { if (elements[i].getName().equals("suite")) { TestSuite suite; try { suite = (TestSuite) elements[i].createExecutableExtension(CLASS); addTestSuite(suite.getClass()); System.err.println("Adding TestSuite " + suite.getClass().getName()); } catch (CoreException e) { e.printStackTrace(System.err); Platform.getLog(Platform.getBundle("org.eclipse.wst.sse.unittests")).log(e.getStatus()); } } else if (elements[i].getName().equals("test")) { Test test; try { test = (Test) elements[i].createExecutableExtension(CLASS); addTestSuite(test.getClass()); System.err.println("Adding TestCase " + test.getClass().getName()); } catch (CoreException e) { e.printStackTrace(System.err); Platform.getLog(Platform.getBundle("org.eclipse.wst.sse.unittests")).log(e.getStatus()); } } } } public void testAll() { // this method needs to exist, but doesn't really do anything // other than to signal to create an instance of this class. // The rest it automatic from the tests added in constructor. } }
4,844
0.735756
0.733072
126
37.444443
25.686312
117
false
false
0
0
0
0
0
0
2.103175
false
false
10
9c6393b0a665aade0c8f45f0ddc5356dd584e791
24,833,500,960,298
9617766ea0cb727d56866031e5d565044ab767a5
/javaAlgotithm/找出最大的对象/BiggestObject.java
597dcf368f4ad48f6d06c1773c6e5bbc95ff0563
[]
no_license
15529343201/JAVA
https://github.com/15529343201/JAVA
e8ba9c646ee3089e6ae282f2b86851faf2a6205c
1baaf91ea8af4ff4c88541c5b2f80896d9a381ec
refs/heads/master
2020-04-15T14:42:52.803000
2017-04-14T15:01:09
2017-04-14T15:01:09
68,193,045
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Date; import java.util.Scanner; public class BiggestObject { static int i; public BiggestObject() { } public static void main(String[] args) { Scanner input = new Scanner(System.in); String[] strings = new String[5]; Integer[] list = new Integer[5]; Date[] dates = new Date[10]; for (int i = 0; i < strings.length; i++) { strings[i] = input.next(); } for (int i = 0; i < list.length; i++) { list[i] = new Integer(input.nextInt()); } for (int i = 0; i < dates.length; i++) dates[i] = new Date(); System.out.println("Max string is " + max(strings)); System.out.println("Max integer is " + max(list)); System.out.println("Max circle is " + max(dates)); input.close(); } public static Object max(Comparable[] a) { Comparable max = a[0]; for (int i = 1; i < a.length; i++) { if(max.compareTo(a[i]) < 0) { max = (Comparable)a[i]; } } return max; } }
UTF-8
Java
983
java
BiggestObject.java
Java
[]
null
[]
import java.util.Date; import java.util.Scanner; public class BiggestObject { static int i; public BiggestObject() { } public static void main(String[] args) { Scanner input = new Scanner(System.in); String[] strings = new String[5]; Integer[] list = new Integer[5]; Date[] dates = new Date[10]; for (int i = 0; i < strings.length; i++) { strings[i] = input.next(); } for (int i = 0; i < list.length; i++) { list[i] = new Integer(input.nextInt()); } for (int i = 0; i < dates.length; i++) dates[i] = new Date(); System.out.println("Max string is " + max(strings)); System.out.println("Max integer is " + max(list)); System.out.println("Max circle is " + max(dates)); input.close(); } public static Object max(Comparable[] a) { Comparable max = a[0]; for (int i = 1; i < a.length; i++) { if(max.compareTo(a[i]) < 0) { max = (Comparable)a[i]; } } return max; } }
983
0.56765
0.557477
54
17.203703
17.196445
55
false
false
0
0
0
0
0
0
2.092592
false
false
10
149c95373f9e3fccccadbc9b18351b6b5be3c15b
27,882,927,737,347
664f269e7f539d2bece63143efc0e107f0dd2b11
/src/org/apache/sanselan/common/BinaryFileParser.java
d21c8cf67d3e8b8f844c8e537f4fdb34b8c4ffb3
[]
no_license
reverseengineeringer/com.konylabs.capitalone
https://github.com/reverseengineeringer/com.konylabs.capitalone
3983e570306f54502b354f90a315b622e2ef29f2
9e5d3bb5fe24a666285fc0d846c89d1f4b07858e
refs/heads/master
2019-05-26T01:55:03.827000
2015-07-05T03:25:05
2015-07-05T03:25:05
38,555,331
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.apache.sanselan.common; import java.io.InputStream; import org.apache.sanselan.ImageReadException; public class BinaryFileParser extends BinaryFileFunctions { private int b = 77; public static boolean b(byte[] paramArrayOfByte1, byte[] paramArrayOfByte2) { if ((paramArrayOfByte1 == null) || (paramArrayOfByte1.length < paramArrayOfByte2.length)) { return false; } int i = 0; for (;;) { if (i >= paramArrayOfByte2.length) { return true; } if (paramArrayOfByte1[i] != paramArrayOfByte2[i]) { break; } i += 1; } } public final int b(String paramString1, InputStream paramInputStream, String paramString2) { return a(paramString1, paramInputStream, paramString2, b); } protected final int b(String paramString, byte[] paramArrayOfByte) { return b(paramString, paramArrayOfByte, b); } protected final void b() { b = 77; } protected final void b(int paramInt1, int paramInt2) { if (paramInt1 != paramInt2) { throw new ImageReadException("Byte Order bytes don't match (" + paramInt1 + ", " + paramInt2 + ")."); } if (paramInt1 == 77) { b = paramInt1; return; } if (paramInt1 == 73) { b = paramInt1; return; } throw new ImageReadException("Unknown Byte Order hint: " + paramInt1); } protected final int c() { return b; } public final int c(String paramString1, InputStream paramInputStream, String paramString2) { return b(paramString1, paramInputStream, paramString2, b); } } /* Location: * Qualified Name: org.apache.sanselan.common.BinaryFileParser * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
UTF-8
Java
1,758
java
BinaryFileParser.java
Java
[]
null
[]
package org.apache.sanselan.common; import java.io.InputStream; import org.apache.sanselan.ImageReadException; public class BinaryFileParser extends BinaryFileFunctions { private int b = 77; public static boolean b(byte[] paramArrayOfByte1, byte[] paramArrayOfByte2) { if ((paramArrayOfByte1 == null) || (paramArrayOfByte1.length < paramArrayOfByte2.length)) { return false; } int i = 0; for (;;) { if (i >= paramArrayOfByte2.length) { return true; } if (paramArrayOfByte1[i] != paramArrayOfByte2[i]) { break; } i += 1; } } public final int b(String paramString1, InputStream paramInputStream, String paramString2) { return a(paramString1, paramInputStream, paramString2, b); } protected final int b(String paramString, byte[] paramArrayOfByte) { return b(paramString, paramArrayOfByte, b); } protected final void b() { b = 77; } protected final void b(int paramInt1, int paramInt2) { if (paramInt1 != paramInt2) { throw new ImageReadException("Byte Order bytes don't match (" + paramInt1 + ", " + paramInt2 + ")."); } if (paramInt1 == 77) { b = paramInt1; return; } if (paramInt1 == 73) { b = paramInt1; return; } throw new ImageReadException("Unknown Byte Order hint: " + paramInt1); } protected final int c() { return b; } public final int c(String paramString1, InputStream paramInputStream, String paramString2) { return b(paramString1, paramInputStream, paramString2, b); } } /* Location: * Qualified Name: org.apache.sanselan.common.BinaryFileParser * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
1,758
0.636519
0.61149
77
21.844156
26.445761
107
false
false
0
0
0
0
0
0
0.519481
false
false
10
d4f9140b20c8261433d8967230a1f3473c963e5a
18,657,337,938,639
c26fd3a70f0ac5e0a3b0b166fe74be7578148048
/src/main/java/eventListeners/TableFilteredListener.java
cf8330b03d48e309640be11598a1d65bbab352d9
[]
no_license
AKolchev/MusicManager
https://github.com/AKolchev/MusicManager
e6b41904bd0555d237b3d055b8daf20b7a5ec423
6efc098e7a7aa58ab8c4472e6ead594d9b7e3a91
refs/heads/master
2022-11-11T19:52:13.263000
2020-07-05T11:41:55
2020-07-05T11:41:55
261,032,478
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package eventListeners; /** * An interface, representing the event of applying a filter to the table * contents * * @author AKolchev, f55283 */ public interface TableFilteredListener { /** * Method fired when a filtering string has been set for the table * * @param filter The string which has been set as a table content filter */ public void tableFiltered(String filter); }
UTF-8
Java
411
java
TableFilteredListener.java
Java
[ { "context": "ng a filter to the table\n * contents\n *\n * @author AKolchev, f55283\n */\npublic interface TableFilteredListene", "end": 137, "score": 0.921334445476532, "start": 129, "tag": "NAME", "value": "AKolchev" }, { "context": "r to the table\n * contents\n *\n * @author AKolchev, f55283\n */\npublic interface TableFilteredListener {\n\n ", "end": 145, "score": 0.9993727803230286, "start": 139, "tag": "USERNAME", "value": "f55283" } ]
null
[]
package eventListeners; /** * An interface, representing the event of applying a filter to the table * contents * * @author AKolchev, f55283 */ public interface TableFilteredListener { /** * Method fired when a filtering string has been set for the table * * @param filter The string which has been set as a table content filter */ public void tableFiltered(String filter); }
411
0.695864
0.683698
17
23.17647
26.606579
76
false
false
0
0
0
0
0
0
0.235294
false
false
10
453981d7880548ad5174d151dfc51a3d655a4715
8,366,596,308,976
feee55c42e1ece2b9f878a2f03a59d7ae699bfb5
/Game Library/src/com/FOEVERGOD73/Components/Clickable.java
f8334eedc97eb78eb4e4d05895fa845d11151778
[]
no_license
zhuethanca/Game-Library
https://github.com/zhuethanca/Game-Library
51dceccb0208a4f20e88112e5a1e7de56e0d19db
8f17c5a13f271c3942a5ce8f4bd4aa02d947a04b
refs/heads/master
2021-05-29T00:38:56.475000
2015-05-31T18:00:23
2015-05-31T18:00:23
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.FOEVERGOD73.Components; import com.FOEVERGOD73.Util.Input; public class Clickable extends GameComponent { private int x, y, width, height; private int mouseCode; public Clickable(String name, int x, int y, int width, int height, int mouseCode) { super(name); this.x = x; this.y = y; this.mouseCode = mouseCode; this.width = width; this.height = height; } public void tick() { if(Input.getInstance().mouseReleased(mouseCode)) if(Input.MousePos() != null) if(Input.MousePos().x > x && Input.MousePos().x < (x + width) && Input.MousePos().y > y && Input.MousePos().y < (y + height)) parent.callBack(name, Input.Mouse_Left_Release); } }
UTF-8
Java
687
java
Clickable.java
Java
[]
null
[]
package com.FOEVERGOD73.Components; import com.FOEVERGOD73.Util.Input; public class Clickable extends GameComponent { private int x, y, width, height; private int mouseCode; public Clickable(String name, int x, int y, int width, int height, int mouseCode) { super(name); this.x = x; this.y = y; this.mouseCode = mouseCode; this.width = width; this.height = height; } public void tick() { if(Input.getInstance().mouseReleased(mouseCode)) if(Input.MousePos() != null) if(Input.MousePos().x > x && Input.MousePos().x < (x + width) && Input.MousePos().y > y && Input.MousePos().y < (y + height)) parent.callBack(name, Input.Mouse_Left_Release); } }
687
0.672489
0.666667
26
25.423077
29.139153
129
false
false
0
0
0
0
0
0
2.153846
false
false
10
f1f6d7263e33fd96bd3750e151b9b8687bf204b2
8,211,977,532,029
8e6245c3ccc36b4f7ca164b4f10899d6274426af
/src/main/java/StateProbability.java
632c1e6b156da4d8b139a23fa49607da72ce58dc
[]
no_license
tomyaacov/AI-exercise5
https://github.com/tomyaacov/AI-exercise5
9a5b9e9020a8db4ee98cf16629b1d5809c0099c8
ec9641b9137eeaa870c9bf6c6ce2d8d21b78de41
refs/heads/master
2020-04-16T13:37:13.403000
2019-01-15T17:01:28
2019-01-15T17:01:28
165,635,122
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import lombok.Getter; import lombok.Setter; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; public class StateProbability { @Getter @Setter private State state; @Getter @Setter private double probability; public StateProbability(State state, double probability) { this.state = state; this.probability = probability; } public double getValue(){ return state.getUtility()*probability; } public static void main(String[] args) { Map<String, Integer> peopleInVertex = new HashMap<>(); peopleInVertex.put("1", 5); peopleInVertex.put("2", 0); Map<String, Boolean> blockedEdge = new HashMap<>(); blockedEdge.put("1-2", true); blockedEdge.put("1-3", false); State s = new State("1",peopleInVertex, blockedEdge, 0, 10, 0); double p = 0.5; StateProbability sp = new StateProbability(s, p); System.out.println(sp.getValue()); } }
UTF-8
Java
1,022
java
StateProbability.java
Java
[]
null
[]
import lombok.Getter; import lombok.Setter; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; public class StateProbability { @Getter @Setter private State state; @Getter @Setter private double probability; public StateProbability(State state, double probability) { this.state = state; this.probability = probability; } public double getValue(){ return state.getUtility()*probability; } public static void main(String[] args) { Map<String, Integer> peopleInVertex = new HashMap<>(); peopleInVertex.put("1", 5); peopleInVertex.put("2", 0); Map<String, Boolean> blockedEdge = new HashMap<>(); blockedEdge.put("1-2", true); blockedEdge.put("1-3", false); State s = new State("1",peopleInVertex, blockedEdge, 0, 10, 0); double p = 0.5; StateProbability sp = new StateProbability(s, p); System.out.println(sp.getValue()); } }
1,022
0.638943
0.624266
38
25.894737
19.993143
71
false
false
0
0
0
0
0
0
0.894737
false
false
10
8d34bc595434e3441d975bb6f3cd7857eee35878
28,673,201,716,504
5a8e19995e187e5cbd0e3a39b34c9ad81f5efbd9
/_Engine Utils/src/engine/utils/MathHelper.java
73b5406b77149ec24df4c4d6969221b492c01848
[]
no_license
robinvd995/3D-Engine
https://github.com/robinvd995/3D-Engine
17b2e311fd7592ae8e0ddb8f4bbe210996a91e9c
3803dfdee368ef05e648d5ca9cb622024c5bc820
refs/heads/master
2021-01-10T04:24:08.718000
2016-03-18T16:44:19
2016-03-18T16:44:19
53,747,087
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package engine.utils; public class MathHelper { public static Matrix4f createTransformationMatrix(Vector3f position, float sx, float sy, float sz, Quaternion quat){ Matrix4f matrix = new Matrix4f(); matrix.setIdentity(); Matrix4f.translate(position, matrix, matrix); Matrix4f.mul(matrix, quat.toMatrix(), matrix); Matrix4f.scale(new Vector3f(sx, sy, sz), matrix, matrix); return matrix; } public static Matrix4f createTransformationMatrix(Vector3f position, Vector3f rot, float sx, float sy, float sz){ Matrix4f matrix = new Matrix4f(); matrix.setIdentity(); Matrix4f.translate(position, matrix, matrix); Matrix4f.rotate(rot.x, GlobalAxis.X.toVector(), matrix, matrix); Matrix4f.rotate(rot.y, GlobalAxis.Y.toVector(), matrix, matrix); Matrix4f.rotate(rot.z, GlobalAxis.Z.toVector(), matrix, matrix); Matrix4f.scale(new Vector3f(sx, sy, sz), matrix, matrix); return matrix; } public static Matrix4f createTransformationMatrix(Vector2f translation, Vector2f scale){ Matrix4f matrix = new Matrix4f(); matrix.setIdentity(); Matrix4f.translate(translation, matrix, matrix); Matrix4f.scale(new Vector3f(scale.x, scale.y, 1.0f), matrix, matrix); return matrix; } public static Matrix4f createViewMatrix(Vector3f position, Quaternion rotation){ Matrix4f m = new Matrix4f(); m.setIdentity(); Matrix4f.mul(m, rotation.toMatrix(), m); Vector3f cameraPos = position.copy(); Vector3f negativeCameraPos = new Vector3f(-cameraPos.x, -cameraPos.y, -cameraPos.z); Matrix4f.translate(negativeCameraPos, m, m); return m; } public static float clampf(float value, float min, float max){ if(value < min){ return min; } if(value > max){ return max; } return value; } public static double clamp(double value){ if(value < 0.0){ return 0.0; } if(value > 1.0){ return 1.0; } return value; } public static float lerp(float start, float end, float percentage){ return (start + percentage * (end - start)); } public static Vector3f multVector3f(Vector3f v1, float f){ return new Vector3f(v1.x * f, v1.y * f, v1.z * f); } public static Vector3f add(Vector3f v1, Vector3f v2){ return new Vector3f(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z); } public static float dist(Vector3f v1, Vector3f v2){ float dx = v2.x - v1.x; float dy = v2.y - v1.y; float dz = v2.z = v1.z; return (float) Math.sqrt(dx * dx + dy * dy + dz * dz); } public static Vector3f worldToScreenSpace(Vector3f position, Matrix4f viewMatrix, Matrix4f proMatrix){ Vector4f coords = new Vector4f(position.x, position.y, position.z, 1.0f); Matrix4f.transform(viewMatrix, coords, coords); Matrix4f.transform(proMatrix, coords, coords); Vector3f screenCoords = clipSpaceToScreenSpace(coords); return screenCoords; } private static Vector3f clipSpaceToScreenSpace(Vector4f coords){ if(coords.w < 0){ return null; } Vector3f screenCoords = new Vector3f(((coords.x) / coords.w) / 2f, 1 - (((coords.y / coords.w) + 1) / 2f), coords.z); return screenCoords; } }
UTF-8
Java
3,145
java
MathHelper.java
Java
[]
null
[]
package engine.utils; public class MathHelper { public static Matrix4f createTransformationMatrix(Vector3f position, float sx, float sy, float sz, Quaternion quat){ Matrix4f matrix = new Matrix4f(); matrix.setIdentity(); Matrix4f.translate(position, matrix, matrix); Matrix4f.mul(matrix, quat.toMatrix(), matrix); Matrix4f.scale(new Vector3f(sx, sy, sz), matrix, matrix); return matrix; } public static Matrix4f createTransformationMatrix(Vector3f position, Vector3f rot, float sx, float sy, float sz){ Matrix4f matrix = new Matrix4f(); matrix.setIdentity(); Matrix4f.translate(position, matrix, matrix); Matrix4f.rotate(rot.x, GlobalAxis.X.toVector(), matrix, matrix); Matrix4f.rotate(rot.y, GlobalAxis.Y.toVector(), matrix, matrix); Matrix4f.rotate(rot.z, GlobalAxis.Z.toVector(), matrix, matrix); Matrix4f.scale(new Vector3f(sx, sy, sz), matrix, matrix); return matrix; } public static Matrix4f createTransformationMatrix(Vector2f translation, Vector2f scale){ Matrix4f matrix = new Matrix4f(); matrix.setIdentity(); Matrix4f.translate(translation, matrix, matrix); Matrix4f.scale(new Vector3f(scale.x, scale.y, 1.0f), matrix, matrix); return matrix; } public static Matrix4f createViewMatrix(Vector3f position, Quaternion rotation){ Matrix4f m = new Matrix4f(); m.setIdentity(); Matrix4f.mul(m, rotation.toMatrix(), m); Vector3f cameraPos = position.copy(); Vector3f negativeCameraPos = new Vector3f(-cameraPos.x, -cameraPos.y, -cameraPos.z); Matrix4f.translate(negativeCameraPos, m, m); return m; } public static float clampf(float value, float min, float max){ if(value < min){ return min; } if(value > max){ return max; } return value; } public static double clamp(double value){ if(value < 0.0){ return 0.0; } if(value > 1.0){ return 1.0; } return value; } public static float lerp(float start, float end, float percentage){ return (start + percentage * (end - start)); } public static Vector3f multVector3f(Vector3f v1, float f){ return new Vector3f(v1.x * f, v1.y * f, v1.z * f); } public static Vector3f add(Vector3f v1, Vector3f v2){ return new Vector3f(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z); } public static float dist(Vector3f v1, Vector3f v2){ float dx = v2.x - v1.x; float dy = v2.y - v1.y; float dz = v2.z = v1.z; return (float) Math.sqrt(dx * dx + dy * dy + dz * dz); } public static Vector3f worldToScreenSpace(Vector3f position, Matrix4f viewMatrix, Matrix4f proMatrix){ Vector4f coords = new Vector4f(position.x, position.y, position.z, 1.0f); Matrix4f.transform(viewMatrix, coords, coords); Matrix4f.transform(proMatrix, coords, coords); Vector3f screenCoords = clipSpaceToScreenSpace(coords); return screenCoords; } private static Vector3f clipSpaceToScreenSpace(Vector4f coords){ if(coords.w < 0){ return null; } Vector3f screenCoords = new Vector3f(((coords.x) / coords.w) / 2f, 1 - (((coords.y / coords.w) + 1) / 2f), coords.z); return screenCoords; } }
3,145
0.683625
0.6531
97
30.42268
29.895638
119
false
false
0
0
0
0
0
0
2.773196
false
false
10
6512c435e064f174f895816c1ea24d1fc89dc18f
31,370,441,131,845
394dd417fe49f542fb7af20d67998f18a50d0d53
/pace-service/src/main/java/com/poweredbypace/pace/repository/TransactionLogEntryRepository.java
2895892d0c167aff917e9d682412d00934e191fe
[]
no_license
bellmit/backend
https://github.com/bellmit/backend
c72e32f002d237eed1d8f2a09da3f67bd860c1fa
769fc9630c09cea281fd958a42c1da907e1447c4
refs/heads/master
2023-04-14T05:07:15.642000
2021-04-20T02:57:06
2021-04-20T02:57:06
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.poweredbypace.pace.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import com.poweredbypace.pace.domain.order.Order; import com.poweredbypace.pace.domain.order.TransactionLogEntry; public interface TransactionLogEntryRepository extends JpaRepository<TransactionLogEntry, Long> { List<TransactionLogEntry> findByOrder(Order order); }
UTF-8
Java
399
java
TransactionLogEntryRepository.java
Java
[]
null
[]
package com.poweredbypace.pace.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import com.poweredbypace.pace.domain.order.Order; import com.poweredbypace.pace.domain.order.TransactionLogEntry; public interface TransactionLogEntryRepository extends JpaRepository<TransactionLogEntry, Long> { List<TransactionLogEntry> findByOrder(Order order); }
399
0.847118
0.847118
12
32.25
31.586191
97
false
false
0
0
0
0
0
0
0.666667
false
false
10
3d3c910650c11a38ee3edb5d24cd4641735a50fb
807,453,871,390
28725543f66badc90563a29f7cfe4879816e1ca9
/src/com/jacamars/dsp/rtb/commands/Echo.java
d98a4aa6321ab2df0f674c17b0bf30c133c44f5c
[ "Apache-2.0" ]
permissive
zorrofox/Newbidder
https://github.com/zorrofox/Newbidder
06e0f9c99a84c4173e260257528399c89b8bb5af
da7a61ba22c3985c7c72c4d1ddf617ca3be9c380
refs/heads/master
2023-08-15T22:23:16.590000
2021-09-17T17:14:55
2021-09-17T17:14:55
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jacamars.dsp.rtb.commands; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.fasterxml.jackson.core.JsonProcessingException; import com.hazelcast.client.config.ClientConfig; import com.hazelcast.config.Config; import com.hazelcast.nio.serialization.ClassDefinition; import com.hazelcast.nio.serialization.ClassDefinitionBuilder; import com.hazelcast.nio.serialization.Portable; import com.hazelcast.nio.serialization.PortableReader; import com.hazelcast.nio.serialization.PortableWriter; import com.jacamars.dsp.rtb.bidder.Controller; import com.jacamars.dsp.rtb.common.Configuration; import com.jacamars.dsp.rtb.probe.Probe; import com.jacamars.dsp.rtb.probe.Reason; import com.jacamars.dsp.rtb.shared.PortableJsonFactory; import com.jacamars.dsp.rtb.tools.DbTools; /** * This is the echo command and response format. It provides basic statistical info plus * all of the campaigns currently loaded in the system. * @author Ben M. Faul * */ public class Echo extends BasicCommand implements Portable { public static final int CLASS_ID = 2; /** The list of campaign objects, that are currently loaded in the systen */ public List<String> campaigns = new ArrayList();; /** The current setting of percentage */ public int percentage; /** Indicates whether the bidder is processing any bid requests */ public boolean stopped; /** the count of bid requests procesed */ public long request; /** The count of bids currently send */ public long bid; /** The count of no-bids current sent */ public long nobid; /** The number of win notifications */ public long win; /** The count of errors accessing the bidder */ public long error; /** Number of total requests */ public long handled; /** Number of unknown requests */ public long unknown; /** The current log level */ public int loglevel; /** The number of clicks */ public long clicks; /** The number of pixels */ public long pixels; /** the adpsend */ public double adspend; /** relative qps */ public double qps; /** avg xtime */ public List<Double> avgx = new ArrayList(); /** Fraud count */ public long fraud; /** Number of threads */ public List<Integer>threads = new ArrayList(); /** Percentage of memory used by the VM */ public List<String> memory = new ArrayList(); /** Percentage of disk free */ public List<String> freeDisk = new ArrayList(); /** Disk usage percentage */ public List<String> cpu = new ArrayList(); /** Summary stats by exchanges */ public List<Map>exchanges; /** Campaign/creative performance map */ public Probe probe; /** ip address */ public String ipaddress; /** is the leader */ public boolean leader; /** last write */ public long lastupdate; /** total http handled */ public long total; /** number of cores */ public int cores; /** number of campaigns */ public int ncampaigns; /** number of effective campaigns */ public int ecampaigns; /** no bid readon flag */ public boolean nobidreason; /** High severity events */ public List<Map<String,String>> events = new ArrayList(); public transient String json; /** * Register the portable hazelcast serializeable object. Call this before hazelcast is initialized! * @param config ClientConfig. The configuration for the user. */ public static void registerWithHazelCast(ClientConfig config) { config.getSerializationConfig().addPortableFactory(PortableJsonFactory.FACTORY_ID, new PortableJsonFactory()); ClassDefinitionBuilder portableEchoClassBuilder = new ClassDefinitionBuilder(PortableJsonFactory.FACTORY_ID, Echo.CLASS_ID); portableEchoClassBuilder.addUTFField("json"); ClassDefinition portableEchoClassDefinition = portableEchoClassBuilder.build(); config.getSerializationConfig().addClassDefinition(portableEchoClassDefinition); } /** * Register the portable hazelcast serializeable object. Call this before hazelcast is initialized! * @param config ClientConfig. The configuration for the member. */ public static void registerWithHazelCast(Config config) { config.getSerializationConfig().addPortableFactory(PortableJsonFactory.FACTORY_ID, new PortableJsonFactory()); ClassDefinitionBuilder portableEchoClassBuilder = new ClassDefinitionBuilder(PortableJsonFactory.FACTORY_ID, Echo.CLASS_ID); portableEchoClassBuilder.addUTFField("json"); ClassDefinition portableEchoClassDefinition = portableEchoClassBuilder.build(); config.getSerializationConfig().addClassDefinition(portableEchoClassDefinition); } // https://github.com/codeset-projects/portable-tricks/blob/master/src/test/java/codeset/portable/tips/Case2Test.java public Echo() { super(); cmd = Controller.ECHO; status = "ok"; } public Echo(String s) { super(s); cmd = Controller.ECHO; status = "ok"; } /** * Return a pretty printed JSON object * @return String. A pretty printed JSON string of this object */ public String toJson() { try { return DbTools.mapper.writer().withDefaultPrettyPrinter().writeValueAsString(this); } catch (JsonProcessingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public static void main(String [] args) { Echo e = new Echo(); System.out.println(e); } @Override public int getFactoryId() { return PortableJsonFactory.FACTORY_ID; } @Override public int getClassId() { return CLASS_ID; } @Override public void writePortable(PortableWriter writer) throws IOException { json = DbTools.mapper.writeValueAsString(this); writer.writeUTF("json",json); } @Override public void readPortable(PortableReader reader) throws IOException { json = reader.readUTF("json"); Echo e = DbTools.mapper.readValue(json, Echo.class); for (String c : e.campaigns) { campaigns.add(c); } for(Map<String,String> m : e.events) { events.add(m); } timestamp = e.timestamp; name = e.name; percentage = e.percentage; stopped = e.stopped; request = e.request; bid = e.bid; nobid = e.nobid; win = e.win; error = e.error; handled = e.handled; unknown = e.unknown; loglevel = e.loglevel; clicks = e.clicks; pixels = e.pixels; adspend = e.adspend; qps = e.qps; avgx = e.avgx; fraud = e.fraud; threads = e.threads; memory = e.memory; freeDisk = e.freeDisk; cpu = e.cpu; ipaddress = e.ipaddress; leader = e.leader; lastupdate = e.lastupdate; total = e.total; cores = e.cores; ncampaigns = e.ncampaigns; ecampaigns = e.ecampaigns; nobidreason = e.nobidreason; events = e.events; probe = e.probe; exchanges = e.exchanges; } }
UTF-8
Java
6,644
java
Echo.java
Java
[ { "context": "mpaigns currently loaded in the system.\n * @author Ben M. Faul\n *\n */\n\npublic class Echo extends BasicCommand im", "end": 1017, "score": 0.9997358322143555, "start": 1006, "tag": "NAME", "value": "Ben M. Faul" } ]
null
[]
package com.jacamars.dsp.rtb.commands; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.fasterxml.jackson.core.JsonProcessingException; import com.hazelcast.client.config.ClientConfig; import com.hazelcast.config.Config; import com.hazelcast.nio.serialization.ClassDefinition; import com.hazelcast.nio.serialization.ClassDefinitionBuilder; import com.hazelcast.nio.serialization.Portable; import com.hazelcast.nio.serialization.PortableReader; import com.hazelcast.nio.serialization.PortableWriter; import com.jacamars.dsp.rtb.bidder.Controller; import com.jacamars.dsp.rtb.common.Configuration; import com.jacamars.dsp.rtb.probe.Probe; import com.jacamars.dsp.rtb.probe.Reason; import com.jacamars.dsp.rtb.shared.PortableJsonFactory; import com.jacamars.dsp.rtb.tools.DbTools; /** * This is the echo command and response format. It provides basic statistical info plus * all of the campaigns currently loaded in the system. * @author <NAME> * */ public class Echo extends BasicCommand implements Portable { public static final int CLASS_ID = 2; /** The list of campaign objects, that are currently loaded in the systen */ public List<String> campaigns = new ArrayList();; /** The current setting of percentage */ public int percentage; /** Indicates whether the bidder is processing any bid requests */ public boolean stopped; /** the count of bid requests procesed */ public long request; /** The count of bids currently send */ public long bid; /** The count of no-bids current sent */ public long nobid; /** The number of win notifications */ public long win; /** The count of errors accessing the bidder */ public long error; /** Number of total requests */ public long handled; /** Number of unknown requests */ public long unknown; /** The current log level */ public int loglevel; /** The number of clicks */ public long clicks; /** The number of pixels */ public long pixels; /** the adpsend */ public double adspend; /** relative qps */ public double qps; /** avg xtime */ public List<Double> avgx = new ArrayList(); /** Fraud count */ public long fraud; /** Number of threads */ public List<Integer>threads = new ArrayList(); /** Percentage of memory used by the VM */ public List<String> memory = new ArrayList(); /** Percentage of disk free */ public List<String> freeDisk = new ArrayList(); /** Disk usage percentage */ public List<String> cpu = new ArrayList(); /** Summary stats by exchanges */ public List<Map>exchanges; /** Campaign/creative performance map */ public Probe probe; /** ip address */ public String ipaddress; /** is the leader */ public boolean leader; /** last write */ public long lastupdate; /** total http handled */ public long total; /** number of cores */ public int cores; /** number of campaigns */ public int ncampaigns; /** number of effective campaigns */ public int ecampaigns; /** no bid readon flag */ public boolean nobidreason; /** High severity events */ public List<Map<String,String>> events = new ArrayList(); public transient String json; /** * Register the portable hazelcast serializeable object. Call this before hazelcast is initialized! * @param config ClientConfig. The configuration for the user. */ public static void registerWithHazelCast(ClientConfig config) { config.getSerializationConfig().addPortableFactory(PortableJsonFactory.FACTORY_ID, new PortableJsonFactory()); ClassDefinitionBuilder portableEchoClassBuilder = new ClassDefinitionBuilder(PortableJsonFactory.FACTORY_ID, Echo.CLASS_ID); portableEchoClassBuilder.addUTFField("json"); ClassDefinition portableEchoClassDefinition = portableEchoClassBuilder.build(); config.getSerializationConfig().addClassDefinition(portableEchoClassDefinition); } /** * Register the portable hazelcast serializeable object. Call this before hazelcast is initialized! * @param config ClientConfig. The configuration for the member. */ public static void registerWithHazelCast(Config config) { config.getSerializationConfig().addPortableFactory(PortableJsonFactory.FACTORY_ID, new PortableJsonFactory()); ClassDefinitionBuilder portableEchoClassBuilder = new ClassDefinitionBuilder(PortableJsonFactory.FACTORY_ID, Echo.CLASS_ID); portableEchoClassBuilder.addUTFField("json"); ClassDefinition portableEchoClassDefinition = portableEchoClassBuilder.build(); config.getSerializationConfig().addClassDefinition(portableEchoClassDefinition); } // https://github.com/codeset-projects/portable-tricks/blob/master/src/test/java/codeset/portable/tips/Case2Test.java public Echo() { super(); cmd = Controller.ECHO; status = "ok"; } public Echo(String s) { super(s); cmd = Controller.ECHO; status = "ok"; } /** * Return a pretty printed JSON object * @return String. A pretty printed JSON string of this object */ public String toJson() { try { return DbTools.mapper.writer().withDefaultPrettyPrinter().writeValueAsString(this); } catch (JsonProcessingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public static void main(String [] args) { Echo e = new Echo(); System.out.println(e); } @Override public int getFactoryId() { return PortableJsonFactory.FACTORY_ID; } @Override public int getClassId() { return CLASS_ID; } @Override public void writePortable(PortableWriter writer) throws IOException { json = DbTools.mapper.writeValueAsString(this); writer.writeUTF("json",json); } @Override public void readPortable(PortableReader reader) throws IOException { json = reader.readUTF("json"); Echo e = DbTools.mapper.readValue(json, Echo.class); for (String c : e.campaigns) { campaigns.add(c); } for(Map<String,String> m : e.events) { events.add(m); } timestamp = e.timestamp; name = e.name; percentage = e.percentage; stopped = e.stopped; request = e.request; bid = e.bid; nobid = e.nobid; win = e.win; error = e.error; handled = e.handled; unknown = e.unknown; loglevel = e.loglevel; clicks = e.clicks; pixels = e.pixels; adspend = e.adspend; qps = e.qps; avgx = e.avgx; fraud = e.fraud; threads = e.threads; memory = e.memory; freeDisk = e.freeDisk; cpu = e.cpu; ipaddress = e.ipaddress; leader = e.leader; lastupdate = e.lastupdate; total = e.total; cores = e.cores; ncampaigns = e.ncampaigns; ecampaigns = e.ecampaigns; nobidreason = e.nobidreason; events = e.events; probe = e.probe; exchanges = e.exchanges; } }
6,639
0.729831
0.72953
224
28.660715
25.33016
132
false
false
0
0
0
0
64
0.009633
1.696429
false
false
10
b3d03f057d08ab64b7035b249615ca5c48af3ebd
3,264,175,167,148
6135157e66afb1a5cb5b99ea0695fee3e1f786c4
/ERP/src/erp/AdminNotice.java
52bee691b0d22b1933760cbb5afb7eba2902d40f
[]
no_license
naman-ajmera/College-ERP-using-Java-Swing
https://github.com/naman-ajmera/College-ERP-using-Java-Swing
6b270c8db183aa4ec5ddb341435b81ec6ae3478b
7e10ab546dc2c39f6c0093ab42494cc8f7e684cf
refs/heads/master
2020-03-25T05:12:25.565000
2018-08-03T14:20:23
2018-08-03T14:20:23
143,434,971
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package erp; import java.awt.Color; import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.text.SimpleDateFormat; import java.util.Calendar; import javax.swing.JOptionPane; /** * * @author VATSAL AJMERA */ public class AdminNotice extends javax.swing.JFrame { /** Creates new form AdminNotice */ public AdminNotice() { initComponents(); setLocationRelativeTo(null); jComboBox1.setSelectedItem(null); jComboBox2.setSelectedItem(null); getContentPane().setBackground(Color.LIGHT_GRAY); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jComboBox1 = new javax.swing.JComboBox<>(); jLabel3 = new javax.swing.JLabel(); jComboBox2 = new javax.swing.JComboBox<>(); jLabel4 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Admin Notice"); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N jLabel1.setText("Add Notice"); jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel2.setText("DEPTATMENT:"); jComboBox1.setBackground(new java.awt.Color(153, 153, 153)); jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "CIVIL", "MECH", "CSE", "IT", "ETC", "EEE" })); jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel3.setText("DESIGNATION:"); jComboBox2.setBackground(new java.awt.Color(153, 153, 153)); jComboBox2.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "HOD", "Asst. Professor", "Sr. Professor", "Professor" })); jComboBox2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBox2ActionPerformed(evt); } }); jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel4.setText("CONTENT:"); jTextArea1.setColumns(20); jTextArea1.setRows(5); jScrollPane1.setViewportView(jTextArea1); jButton1.setBackground(new java.awt.Color(153, 153, 153)); jButton1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jButton1.setText("VIEW ALL NOTICE"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setBackground(new java.awt.Color(153, 153, 153)); jButton2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/erp/images/Save-icon.png"))); // NOI18N jButton2.setText("SAVE NOTICE"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jButton3.setBackground(new java.awt.Color(153, 153, 153)); jButton3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jButton3.setText("BACK"); jButton3.setBorderPainted(false); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(165, 165, 165) .addComponent(jButton3)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(68, 68, 68) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(56, 56, 56) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 542, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 22, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(20, 20, 20) .addComponent(jButton3)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(52, 52, 52) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(30, 30, 30) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(22, 22, 22)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(277, Short.MAX_VALUE)) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 299, Short.MAX_VALUE))) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed try{ Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost:51586;database=bios1;user=sa;password=fastrack3"); PreparedStatement pst = con.prepareStatement("insert into AdminNotice(dept,desig,description,dateofpublish,timeofpublish) values (?,?,?,?,?)"); pst.setString(1, (String)(jComboBox1.getSelectedItem())); pst.setString(2, (String)(jComboBox2.getSelectedItem())); pst.setString(3, jTextArea1.getText()); Calendar cal = Calendar.getInstance(); cal.getTime(); SimpleDateFormat Time = new SimpleDateFormat("HH:mm:ss"); SimpleDateFormat Date = new SimpleDateFormat("yyyy/MM/dd"); pst.setString(4,Date.format(cal.getTime())); pst.setString(5,Time.format(cal.getTime())); int rs = pst.executeUpdate(); if(rs>0) { JOptionPane.showMessageDialog(null,"Notice Saved Successfully"); } con.close(); } catch(Exception e){ System.out.println(e); } }//GEN-LAST:event_jButton2ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed this.dispose(); java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new AdminNoticeForAdmin().setVisible(true); } }); }//GEN-LAST:event_jButton1ActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed this.setVisible(false); java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new AdminHomePage().setVisible(true); } }); }//GEN-LAST:event_jButton3ActionPerformed private void jComboBox2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox2ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jComboBox2ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(AdminNotice.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(AdminNotice.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(AdminNotice.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(AdminNotice.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new AdminNotice().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JComboBox<String> jComboBox1; private javax.swing.JComboBox<String> jComboBox2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea jTextArea1; // End of variables declaration//GEN-END:variables }
UTF-8
Java
14,753
java
AdminNotice.java
Java
[ { "context": "import javax.swing.JOptionPane;\n\n/**\n *\n * @author VATSAL AJMERA\n */\npublic class AdminNotice extends javax.swing.", "end": 465, "score": 0.9997203946113586, "start": 452, "tag": "NAME", "value": "VATSAL AJMERA" }, { "context": "//localhost:51586;database=bios1;user=sa;password=fastrack3\");\n PreparedStatement pst = con.prepar", "end": 10455, "score": 0.9983968734741211, "start": 10446, "tag": "PASSWORD", "value": "fastrack3" } ]
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 erp; import java.awt.Color; import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.text.SimpleDateFormat; import java.util.Calendar; import javax.swing.JOptionPane; /** * * @author <NAME> */ public class AdminNotice extends javax.swing.JFrame { /** Creates new form AdminNotice */ public AdminNotice() { initComponents(); setLocationRelativeTo(null); jComboBox1.setSelectedItem(null); jComboBox2.setSelectedItem(null); getContentPane().setBackground(Color.LIGHT_GRAY); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jComboBox1 = new javax.swing.JComboBox<>(); jLabel3 = new javax.swing.JLabel(); jComboBox2 = new javax.swing.JComboBox<>(); jLabel4 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Admin Notice"); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N jLabel1.setText("Add Notice"); jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel2.setText("DEPTATMENT:"); jComboBox1.setBackground(new java.awt.Color(153, 153, 153)); jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "CIVIL", "MECH", "CSE", "IT", "ETC", "EEE" })); jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel3.setText("DESIGNATION:"); jComboBox2.setBackground(new java.awt.Color(153, 153, 153)); jComboBox2.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "HOD", "Asst. Professor", "Sr. Professor", "Professor" })); jComboBox2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBox2ActionPerformed(evt); } }); jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel4.setText("CONTENT:"); jTextArea1.setColumns(20); jTextArea1.setRows(5); jScrollPane1.setViewportView(jTextArea1); jButton1.setBackground(new java.awt.Color(153, 153, 153)); jButton1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jButton1.setText("VIEW ALL NOTICE"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setBackground(new java.awt.Color(153, 153, 153)); jButton2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/erp/images/Save-icon.png"))); // NOI18N jButton2.setText("SAVE NOTICE"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jButton3.setBackground(new java.awt.Color(153, 153, 153)); jButton3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jButton3.setText("BACK"); jButton3.setBorderPainted(false); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(165, 165, 165) .addComponent(jButton3)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(68, 68, 68) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(56, 56, 56) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 542, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 22, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(20, 20, 20) .addComponent(jButton3)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(52, 52, 52) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(30, 30, 30) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(22, 22, 22)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(277, Short.MAX_VALUE)) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 299, Short.MAX_VALUE))) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed try{ Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost:51586;database=bios1;user=sa;password=<PASSWORD>"); PreparedStatement pst = con.prepareStatement("insert into AdminNotice(dept,desig,description,dateofpublish,timeofpublish) values (?,?,?,?,?)"); pst.setString(1, (String)(jComboBox1.getSelectedItem())); pst.setString(2, (String)(jComboBox2.getSelectedItem())); pst.setString(3, jTextArea1.getText()); Calendar cal = Calendar.getInstance(); cal.getTime(); SimpleDateFormat Time = new SimpleDateFormat("HH:mm:ss"); SimpleDateFormat Date = new SimpleDateFormat("yyyy/MM/dd"); pst.setString(4,Date.format(cal.getTime())); pst.setString(5,Time.format(cal.getTime())); int rs = pst.executeUpdate(); if(rs>0) { JOptionPane.showMessageDialog(null,"Notice Saved Successfully"); } con.close(); } catch(Exception e){ System.out.println(e); } }//GEN-LAST:event_jButton2ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed this.dispose(); java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new AdminNoticeForAdmin().setVisible(true); } }); }//GEN-LAST:event_jButton1ActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed this.setVisible(false); java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new AdminHomePage().setVisible(true); } }); }//GEN-LAST:event_jButton3ActionPerformed private void jComboBox2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox2ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jComboBox2ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(AdminNotice.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(AdminNotice.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(AdminNotice.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(AdminNotice.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new AdminNotice().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JComboBox<String> jComboBox1; private javax.swing.JComboBox<String> jComboBox2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea jTextArea1; // End of variables declaration//GEN-END:variables }
14,747
0.634447
0.614316
280
51.689285
40.442375
182
false
false
0
0
0
0
0
0
0.885714
false
false
10
e0b21f0333ef3312ea5a4f96682bd8dfe0f952c4
26,817,775,814,399
c1ab930305e651d0ab0262f1bccee1d4c8436375
/src/main/java/com/jobdiva/api/model/SocialNetwork.java
6e838674198a28ba1740957bbc201088712e3483
[]
no_license
omarkamoun1/SpringRestAPI
https://github.com/omarkamoun1/SpringRestAPI
ad2c0e846965b364f5067c7a229482b6ee5a8b3a
4a83b2f3dc097cc28eba2059873771679474f5d5
refs/heads/master
2023-04-30T08:47:37.804000
2021-05-20T10:33:11
2021-05-20T10:33:11
369,308,227
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jobdiva.api.model; @SuppressWarnings("serial") public class SocialNetwork implements java.io.Serializable { private Integer snid; private String snurl; private String snname; public Integer getSnid() { return snid; } public void setSnid(Integer snid) { this.snid = snid; } public String getSnurl() { return snurl; } public void setSnurl(String snurl) { this.snurl = snurl; } public String getSnname() { return snname; } public void setSnname(String snname) { this.snname = snname; } }
UTF-8
Java
572
java
SocialNetwork.java
Java
[]
null
[]
package com.jobdiva.api.model; @SuppressWarnings("serial") public class SocialNetwork implements java.io.Serializable { private Integer snid; private String snurl; private String snname; public Integer getSnid() { return snid; } public void setSnid(Integer snid) { this.snid = snid; } public String getSnurl() { return snurl; } public void setSnurl(String snurl) { this.snurl = snurl; } public String getSnname() { return snname; } public void setSnname(String snname) { this.snname = snname; } }
572
0.660839
0.660839
33
15.333333
15.010434
60
false
false
0
0
0
0
0
0
1.424242
false
false
10
e6e2a51bb59a17cfb9eaa3a91a5aae59f0672858
31,310,311,606,136
39e84d55b86fa644bd38059700658618c3fd3a5d
/src/ejercicios/Telemarketer.java
af2f71df3b43d26fe3be6b4ff6f87b9b8d358e54
[]
no_license
araimun/poo
https://github.com/araimun/poo
6a2db38f02b8c9603d33b14fe53f4b2ee71fb471
fb43b877b8eaadb8adc876e2048c4aa3268b27da
refs/heads/master
2021-01-20T08:03:07.103000
2020-10-20T02:42:24
2020-10-20T02:42:24
90,091,587
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ejercicios; public class Telemarketer extends OrderTaker { private int peopleHarassed; public void incrementPeopleHarassed() { peopleHarassed++; } public int getPeopleHarassed() { return peopleHarassed; } public double calculatePay() { double temp; //Telemarketer get 10 cents for every order they take //and 1 cent per person they harass (call) temp = getBasePay() / 52 + peopleHarassed * .01 + getOrdersTaken() * .1; return temp; } }//class //Ejercicio 24
UTF-8
Java
536
java
Telemarketer.java
Java
[]
null
[]
package ejercicios; public class Telemarketer extends OrderTaker { private int peopleHarassed; public void incrementPeopleHarassed() { peopleHarassed++; } public int getPeopleHarassed() { return peopleHarassed; } public double calculatePay() { double temp; //Telemarketer get 10 cents for every order they take //and 1 cent per person they harass (call) temp = getBasePay() / 52 + peopleHarassed * .01 + getOrdersTaken() * .1; return temp; } }//class //Ejercicio 24
536
0.662313
0.643657
17
30.588236
24.393969
80
false
false
0
0
0
0
0
0
0.411765
false
false
10
09aabccbb628a66329b9cad2b102ada4d09fbe63
25,769,803,794,994
9e851d8595d7239f69a79e1c93dc6cef87aae936
/src/third/GreekAlphabet.java
d5abfb3cbd2020fdbe4a921e2570da7f7fb21316
[]
no_license
bestAmy/test
https://github.com/bestAmy/test
11a0f4adedda6da61e5d4a66417bcd521d3e18a7
421206029643a2b629cf482051681b1159e64309
refs/heads/master
2020-12-03T21:18:23.927000
2020-01-03T02:11:22
2020-01-03T02:11:22
231,490,579
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package third; public class GreekAlphabet { public static void main(String[] args) { int startPosition = 0 , endPosition = 0; char cStart ='α' ,cEnd = 'ω'; startPosition = (int)cStart; endPosition = (int)cEnd; System.out.println("希腊字母\'α\'在unicode表中的顺序位置:"+(int)cStart); System.out.println("希腊字母表:"); for(int i=startPosition;i<=endPosition;i++){ char c='\0'; c=(char)i; System.out.print(" "+c); if((i-startPosition+1)%10==0){ System.out.println(""); } } } }
UTF-8
Java
650
java
GreekAlphabet.java
Java
[]
null
[]
package third; public class GreekAlphabet { public static void main(String[] args) { int startPosition = 0 , endPosition = 0; char cStart ='α' ,cEnd = 'ω'; startPosition = (int)cStart; endPosition = (int)cEnd; System.out.println("希腊字母\'α\'在unicode表中的顺序位置:"+(int)cStart); System.out.println("希腊字母表:"); for(int i=startPosition;i<=endPosition;i++){ char c='\0'; c=(char)i; System.out.print(" "+c); if((i-startPosition+1)%10==0){ System.out.println(""); } } } }
650
0.513957
0.502463
22
26.681818
18.902588
68
false
false
0
0
0
0
0
0
0.681818
false
false
10
6b2073f8f9e5e14f3940ee5ef8dd6bca6a2fa5ad
16,054,587,773,384
6f8564b6e54e83a4695b035b9c5c3aaa0dfede85
/app/src/main/java/com/vlasquez/zemogatechtest/ui/ScreenProvider.java
0da0fa6793aa9fbdd29af92afa8f8ec8bf303d2a
[]
no_license
vlasquez/ZemogaTechTest
https://github.com/vlasquez/ZemogaTechTest
1eddecf2b05660dd34609dff0cff9565696b36b9
40db70ae77e208fec38397b298036eb97d2c9d86
refs/heads/master
2020-04-30T11:03:17.741000
2019-03-28T19:16:04
2019-03-28T19:16:04
176,792,265
0
0
null
false
2019-03-28T18:47:04
2019-03-20T18:16:28
2019-03-26T16:50:28
2019-03-28T18:47:04
350
0
0
0
Java
false
null
package com.vlasquez.zemogatechtest.ui; import android.support.v4.app.Fragment; public interface ScreenProvider { Fragment initialScreen(); }
UTF-8
Java
147
java
ScreenProvider.java
Java
[ { "context": "package com.vlasquez.zemogatechtest.ui;\n\nimport android.support.v4.ap", "end": 19, "score": 0.5185197591781616, "start": 16, "tag": "USERNAME", "value": "que" } ]
null
[]
package com.vlasquez.zemogatechtest.ui; import android.support.v4.app.Fragment; public interface ScreenProvider { Fragment initialScreen(); }
147
0.795918
0.789116
8
17.375
17.485262
39
false
false
0
0
0
0
0
0
0.375
false
false
10
29945de730da46671731100e70c594d4b14a783c
2,705,829,420,761
ccaeddafb73e969c0c2b242dd9625f40a8dfd541
/src/com/d1/bean/BrandRck.java
dd50f383bf61d85caf2481df3b74a11d317e443a
[]
no_license
ACGT/d1
https://github.com/ACGT/d1
1f2e3e1759e34bfb1a730fda28ff90d3a4349531
c661e7c0b2ea1182105c9b155b1740515c6a2f37
refs/heads/master
2021-01-21T20:34:57.056000
2015-10-16T14:10:51
2015-10-16T14:10:51
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.d1.bean; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import com.d1.dbcache.core.BaseEntity; /** * @author Administrator * */ @Entity @Table(name="brandrck") public class BrandRck extends BaseEntity implements java.io.Serializable { private static final long serialVersionUID = 1L; @Id @Column(name="brandrck_id") private String id;//done private String brandrck_brand; private Long brandrck_count; private String brandrck_rackcode ; private Long brandrck_seq; private Long brandrck_southseq; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getBrandrck_brand() { return brandrck_brand; } public void setBrandrck_brand(String brandrck_brand) { this.brandrck_brand = brandrck_brand; } public Long getBrandrck_count() { return brandrck_count; } public void setBrandrck_count(Long brandrck_count) { this.brandrck_count = brandrck_count; } public String getBrandrck_rackcode() { return brandrck_rackcode; } public void setBrandrck_rackcode(String brandrck_rackcode) { this.brandrck_rackcode = brandrck_rackcode; } public Long getBrandrck_seq() { return brandrck_seq; } public void setBrandrck_seq(Long brandrck_seq) { this.brandrck_seq = brandrck_seq; } public Long getBrandrck_southseq() { return brandrck_southseq; } public void setBrandrck_southseq(Long brandrck_southseq) { this.brandrck_southseq = brandrck_southseq; } }
UTF-8
Java
1,532
java
BrandRck.java
Java
[ { "context": "rt com.d1.dbcache.core.BaseEntity;\n\n/**\n * @author Administrator\n *\n */\n@Entity\n@Table(name=\"brandrck\")\npublic cla", "end": 218, "score": 0.8886415958404541, "start": 205, "tag": "NAME", "value": "Administrator" } ]
null
[]
package com.d1.bean; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import com.d1.dbcache.core.BaseEntity; /** * @author Administrator * */ @Entity @Table(name="brandrck") public class BrandRck extends BaseEntity implements java.io.Serializable { private static final long serialVersionUID = 1L; @Id @Column(name="brandrck_id") private String id;//done private String brandrck_brand; private Long brandrck_count; private String brandrck_rackcode ; private Long brandrck_seq; private Long brandrck_southseq; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getBrandrck_brand() { return brandrck_brand; } public void setBrandrck_brand(String brandrck_brand) { this.brandrck_brand = brandrck_brand; } public Long getBrandrck_count() { return brandrck_count; } public void setBrandrck_count(Long brandrck_count) { this.brandrck_count = brandrck_count; } public String getBrandrck_rackcode() { return brandrck_rackcode; } public void setBrandrck_rackcode(String brandrck_rackcode) { this.brandrck_rackcode = brandrck_rackcode; } public Long getBrandrck_seq() { return brandrck_seq; } public void setBrandrck_seq(Long brandrck_seq) { this.brandrck_seq = brandrck_seq; } public Long getBrandrck_southseq() { return brandrck_southseq; } public void setBrandrck_southseq(Long brandrck_southseq) { this.brandrck_southseq = brandrck_southseq; } }
1,532
0.749347
0.747389
64
22.9375
18.767387
75
false
false
0
0
0
0
0
0
1.296875
false
false
10
a1056e087118b80c5a518e3df86b089001c7e14e
4,071,629,037,291
278a38e8dcb03cdb24ef158769dc59693a8c6e72
/wave/src/test/java/org/waveprotocol/wave/crypto/CertConstantUtil.java
d9802d9c36a2392af23d0d541c1a6879bca0ef96
[ "BSD-3-Clause", "Apache-2.0", "LicenseRef-scancode-generic-export-compliance" ]
permissive
SwellRT/swellrt
https://github.com/SwellRT/swellrt
b592f6486bd18cd54cc0b12563ad440399eec861
0b33f6d7fa933f2e180dc80d2beb6f6f2ff6eb54
refs/heads/master
2021-11-24T08:53:29.924000
2018-12-25T19:53:28
2018-12-25T19:53:28
15,933,766
89
11
Apache-2.0
false
2021-11-12T01:36:54
2014-01-15T11:52:21
2021-11-05T18:42:45
2018-12-25T20:06:02
233,181
215
31
55
Java
false
false
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.waveprotocol.wave.crypto; import java.security.GeneralSecurityException; import java.security.PrivateKey; import java.security.cert.X509Certificate; public class CertConstantUtil { public static final X509Certificate SERVER_PUB_CERT; public static final X509Certificate INTERMEDIATE_PUB_CERT; public static final X509Certificate CA_PUB_CERT; public static final PrivateKey SERVER_PRIV_KEY; public static final PrivateKey INTERMEDIATE_PRIV_KEY; public static final PrivateKey CA_PRIV_KEY; static { try { SERVER_PUB_CERT = CertUtil.getCertFromBytes(CertConstants.SERVER_PUB); INTERMEDIATE_PUB_CERT = CertUtil.getCertFromBytes(CertConstants.INTERMEDIATE_PUB); CA_PUB_CERT = CertUtil.getCertFromBytes(CertConstants.CA_PUB); SERVER_PRIV_KEY = CertUtil.getPrivateKeyFromBytes(CertConstants.SERVER_PRIV); INTERMEDIATE_PRIV_KEY = CertUtil.getPrivateKeyFromBytes(CertConstants.INTERMEDIATE_PRIV); CA_PRIV_KEY = CertUtil.getPrivateKeyFromBytes(CertConstants.CA_PRIV); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } } private CertConstantUtil() { } }
UTF-8
Java
1,967
java
CertConstantUtil.java
Java
[]
null
[]
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.waveprotocol.wave.crypto; import java.security.GeneralSecurityException; import java.security.PrivateKey; import java.security.cert.X509Certificate; public class CertConstantUtil { public static final X509Certificate SERVER_PUB_CERT; public static final X509Certificate INTERMEDIATE_PUB_CERT; public static final X509Certificate CA_PUB_CERT; public static final PrivateKey SERVER_PRIV_KEY; public static final PrivateKey INTERMEDIATE_PRIV_KEY; public static final PrivateKey CA_PRIV_KEY; static { try { SERVER_PUB_CERT = CertUtil.getCertFromBytes(CertConstants.SERVER_PUB); INTERMEDIATE_PUB_CERT = CertUtil.getCertFromBytes(CertConstants.INTERMEDIATE_PUB); CA_PUB_CERT = CertUtil.getCertFromBytes(CertConstants.CA_PUB); SERVER_PRIV_KEY = CertUtil.getPrivateKeyFromBytes(CertConstants.SERVER_PRIV); INTERMEDIATE_PRIV_KEY = CertUtil.getPrivateKeyFromBytes(CertConstants.INTERMEDIATE_PRIV); CA_PRIV_KEY = CertUtil.getPrivateKeyFromBytes(CertConstants.CA_PRIV); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } } private CertConstantUtil() { } }
1,967
0.763599
0.755465
51
37.568626
28.261562
95
false
false
0
0
0
0
0
0
0.431373
false
false
10
7881614a04f440c63ac042637de8e2742e008764
4,071,629,036,525
a91c0025313e75004780ec2bed2af66431516437
/src/main/java/com/eteach/eteach/api/rest/course/SectionController.java
c4550423a8050989baeed03e870fdae4d3e1a422
[]
no_license
bendary577/Eteach-Back-End
https://github.com/bendary577/Eteach-Back-End
aa966626e74aec5d704e6fee709cef724e512a89
9e18f33ffba9fff53017a474cd71071c73dc6e0b
refs/heads/main
2023-05-26T01:39:20.722000
2021-06-14T02:46:12
2021-06-14T02:46:12
339,892,816
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.eteach.eteach.api.rest.course; import com.eteach.eteach.exception.ResourceNotFoundException; import com.eteach.eteach.http.request.dataRequest.course.AddSectionRequest; import com.eteach.eteach.http.response.ApiResponse; import com.eteach.eteach.model.course.Course; import com.eteach.eteach.model.course.Section; import com.eteach.eteach.service.CourseService; import com.eteach.eteach.service.SectionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List; @RestController @RequestMapping(value ="/api/v1/sections", produces = "application/json;charset=UTF-8") public class SectionController { private final SectionService sectionService; private final CourseService courseService; @Autowired public SectionController(SectionService sectionService, CourseService courseService){ this.sectionService = sectionService; this.courseService = courseService; } //----------------------------- CREATE A NEW SECTION --------------------------------------------------- @PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_ADMINTRAINEE')") @PostMapping("/{courseId}") public ResponseEntity<?> postSection(@PathVariable Long courseId, @Valid @RequestBody AddSectionRequest addSectionRequest){ Course course = courseService.getCourse(courseId); Section section = new Section(); section.setTitle(addSectionRequest.getTitle()); course.getSections().add(section); section.setCourse(course); this.sectionService.saveSection(section); this.courseService.saveCourse(course); return ResponseEntity.ok(new ApiResponse(HttpStatus.OK, "section saved successfully")); } //------------------------------ GET ALL SECTIONS -------------------------------------------------- @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_ADMINTRAINEE','ROLE_STUDENT', 'ROLE_TEACHER')") @GetMapping("/{courseId}") public List<Section> getAllSections(@PathVariable Long courseId) { return sectionService.getAllSections(courseId); } //------------------------------ GET A SINGLE SECTION ------------------------------------------------ @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_ADMINTRAINEE','ROLE_STUDENT', 'ROLE_TEACHER')") @GetMapping("/{id}") public Section getSection(@PathVariable(value = "id") Long id) { return sectionService.getSection(id); } //------------------------------ UPDATE A SECTION ------------------------------------------------------ @PreAuthorize("hasRole('ROLE_TEACHER')") @PutMapping("/{id}") public Section updateSection(@PathVariable(value = "id") Long id, @Valid @RequestBody Section newSection) { Section oldSection = sectionService.getSection(id); if(oldSection == null){ throw new ResourceNotFoundException("Section", "id", id); } return sectionService.updateSection(oldSection, newSection); } //------------------------------ DELETE A SINGLE SECTION --------------------------------------------- @PreAuthorize("hasRole('ROLE_TEACHER')") @DeleteMapping("/{id}") public ResponseEntity<?> deleteSection(@PathVariable(value = "id") Long id) { Section section = sectionService.getSection(id); if(section == null){ throw new ResourceNotFoundException("Section", "id", id); } sectionService.deleteSection(section); return ResponseEntity.ok().build(); } }
UTF-8
Java
3,771
java
SectionController.java
Java
[]
null
[]
package com.eteach.eteach.api.rest.course; import com.eteach.eteach.exception.ResourceNotFoundException; import com.eteach.eteach.http.request.dataRequest.course.AddSectionRequest; import com.eteach.eteach.http.response.ApiResponse; import com.eteach.eteach.model.course.Course; import com.eteach.eteach.model.course.Section; import com.eteach.eteach.service.CourseService; import com.eteach.eteach.service.SectionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List; @RestController @RequestMapping(value ="/api/v1/sections", produces = "application/json;charset=UTF-8") public class SectionController { private final SectionService sectionService; private final CourseService courseService; @Autowired public SectionController(SectionService sectionService, CourseService courseService){ this.sectionService = sectionService; this.courseService = courseService; } //----------------------------- CREATE A NEW SECTION --------------------------------------------------- @PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_ADMINTRAINEE')") @PostMapping("/{courseId}") public ResponseEntity<?> postSection(@PathVariable Long courseId, @Valid @RequestBody AddSectionRequest addSectionRequest){ Course course = courseService.getCourse(courseId); Section section = new Section(); section.setTitle(addSectionRequest.getTitle()); course.getSections().add(section); section.setCourse(course); this.sectionService.saveSection(section); this.courseService.saveCourse(course); return ResponseEntity.ok(new ApiResponse(HttpStatus.OK, "section saved successfully")); } //------------------------------ GET ALL SECTIONS -------------------------------------------------- @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_ADMINTRAINEE','ROLE_STUDENT', 'ROLE_TEACHER')") @GetMapping("/{courseId}") public List<Section> getAllSections(@PathVariable Long courseId) { return sectionService.getAllSections(courseId); } //------------------------------ GET A SINGLE SECTION ------------------------------------------------ @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_ADMINTRAINEE','ROLE_STUDENT', 'ROLE_TEACHER')") @GetMapping("/{id}") public Section getSection(@PathVariable(value = "id") Long id) { return sectionService.getSection(id); } //------------------------------ UPDATE A SECTION ------------------------------------------------------ @PreAuthorize("hasRole('ROLE_TEACHER')") @PutMapping("/{id}") public Section updateSection(@PathVariable(value = "id") Long id, @Valid @RequestBody Section newSection) { Section oldSection = sectionService.getSection(id); if(oldSection == null){ throw new ResourceNotFoundException("Section", "id", id); } return sectionService.updateSection(oldSection, newSection); } //------------------------------ DELETE A SINGLE SECTION --------------------------------------------- @PreAuthorize("hasRole('ROLE_TEACHER')") @DeleteMapping("/{id}") public ResponseEntity<?> deleteSection(@PathVariable(value = "id") Long id) { Section section = sectionService.getSection(id); if(section == null){ throw new ResourceNotFoundException("Section", "id", id); } sectionService.deleteSection(section); return ResponseEntity.ok().build(); } }
3,771
0.638557
0.638027
84
43.892857
32.423542
127
false
false
0
0
0
0
0
0
0.642857
false
false
10
327af70665c28312638d12a607006d9adaf78084
14,379,550,545,685
0889671ed0a00995215e4c9b4643dd3e79d16368
/src/test/java/net/avensome/dev/parsing/parser/AbstractParserTest.java
4d64022c6b6dc4f1ce7e43409a6dd745f8464272
[ "MIT" ]
permissive
gronostajo/bbcode-strict-java
https://github.com/gronostajo/bbcode-strict-java
3672d304570f253258feb311a0bb390e8d1980cc
39c10089d4f165b71de2bc17f9bcd74cd986e23f
refs/heads/master
2017-10-18T06:17:14.041000
2016-10-28T12:59:40
2016-10-28T12:59:40
69,520,299
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.avensome.dev.parsing.parser; import net.avensome.dev.parsing.error.ParsingException; import net.avensome.dev.parsing.error.syntactic.SyntacticErrorException; import net.avensome.dev.parsing.error.syntactic.UnhandledTransitionException; import net.avensome.dev.parsing.lexer.Token; import net.avensome.dev.parsing.transitions.Transition; import org.junit.Assert; import org.junit.Test; import java.util.Set; import java.util.stream.Collectors; public class AbstractParserTest extends AbstractParser { private static final String STATE1 = "STATE1"; private static final String STATE2 = "STATE2"; private static final String STATE3 = "STATE3"; private static final String STATE4 = "STATE4"; private static final String STATE5 = "STATE5"; private String currentState = STATE1; public AbstractParserTest() { super(s -> tt -> { Set<String> expected = tt.stream() .filter(tpl -> !tpl.hasSpecialMeaning()) .map(tpl -> Character.toString(tpl.getToken())) .collect(Collectors.toSet()); if (expected.contains(".")) { return new Token("."); } else { throw new UnhandledTransitionException("whatever"); } }, STATE1, STATE4); addState(STATE1).addTransition('.', new Transition(STATE2) { @Override public void transition(String token) throws SyntacticErrorException { Assert.assertEquals(STATE1, currentState); currentState = STATE2; } }); addState(STATE3).addTransition('.', new Transition(STATE4) { @Override public void transition(String token) throws SyntacticErrorException { Assert.assertEquals(STATE3, currentState); currentState = STATE4; } }); addState(STATE2) .addTransition('.', new Transition(STATE3) { @Override public void transition(String token) throws SyntacticErrorException { Assert.assertEquals(STATE2, currentState); currentState = STATE3; } }) .addTransition(',', new Transition(STATE5) { @Override public void transition(String token) throws SyntacticErrorException { Assert.fail(); } }); } @Test public void testParserTransitions() throws ParsingException { parse("..."); Assert.assertEquals(currentState, STATE4); } @Test public void testUnknownTransitions() throws ParsingException { parse(".;."); Assert.assertEquals(currentState, STATE4); } }
UTF-8
Java
2,859
java
AbstractParserTest.java
Java
[]
null
[]
package net.avensome.dev.parsing.parser; import net.avensome.dev.parsing.error.ParsingException; import net.avensome.dev.parsing.error.syntactic.SyntacticErrorException; import net.avensome.dev.parsing.error.syntactic.UnhandledTransitionException; import net.avensome.dev.parsing.lexer.Token; import net.avensome.dev.parsing.transitions.Transition; import org.junit.Assert; import org.junit.Test; import java.util.Set; import java.util.stream.Collectors; public class AbstractParserTest extends AbstractParser { private static final String STATE1 = "STATE1"; private static final String STATE2 = "STATE2"; private static final String STATE3 = "STATE3"; private static final String STATE4 = "STATE4"; private static final String STATE5 = "STATE5"; private String currentState = STATE1; public AbstractParserTest() { super(s -> tt -> { Set<String> expected = tt.stream() .filter(tpl -> !tpl.hasSpecialMeaning()) .map(tpl -> Character.toString(tpl.getToken())) .collect(Collectors.toSet()); if (expected.contains(".")) { return new Token("."); } else { throw new UnhandledTransitionException("whatever"); } }, STATE1, STATE4); addState(STATE1).addTransition('.', new Transition(STATE2) { @Override public void transition(String token) throws SyntacticErrorException { Assert.assertEquals(STATE1, currentState); currentState = STATE2; } }); addState(STATE3).addTransition('.', new Transition(STATE4) { @Override public void transition(String token) throws SyntacticErrorException { Assert.assertEquals(STATE3, currentState); currentState = STATE4; } }); addState(STATE2) .addTransition('.', new Transition(STATE3) { @Override public void transition(String token) throws SyntacticErrorException { Assert.assertEquals(STATE2, currentState); currentState = STATE3; } }) .addTransition(',', new Transition(STATE5) { @Override public void transition(String token) throws SyntacticErrorException { Assert.fail(); } }); } @Test public void testParserTransitions() throws ParsingException { parse("..."); Assert.assertEquals(currentState, STATE4); } @Test public void testUnknownTransitions() throws ParsingException { parse(".;."); Assert.assertEquals(currentState, STATE4); } }
2,859
0.591466
0.581672
84
33.035713
25.654037
89
false
false
0
0
0
0
0
0
0.559524
false
false
10
fd1ea6930a5f07254b9a25dfd840e10747a2f872
7,834,020,404,535
f522f2322fd2c1b1ea71fb2beac1fe43855f7ebf
/src/netgen/Preprocessing/Components/RemoveDuplicates.java
0f56aeb2af4a43880259861ab9bcf3578519cd63
[]
no_license
zabbieru/semantic-network-generator
https://github.com/zabbieru/semantic-network-generator
ddb37550d155e7bc9ec4165ff91e8da184b937b4
d017a6ed659d38282b4806de10b3a44afc6dfd28
refs/heads/master
2021-01-23T03:43:09.248000
2015-09-12T00:25:23
2015-09-12T00:25:23
49,707,359
1
0
null
true
2016-01-15T08:47:51
2016-01-15T08:47:51
2015-09-12T00:29:42
2015-09-12T00:28:01
5,204
0
0
0
null
null
null
package netgen.Preprocessing.Components; import java.util.ArrayList; import java.util.HashSet; import netgen.Preprocessing.PreprocessingComponent; import netgen.Preprocessing.Token; public class RemoveDuplicates implements PreprocessingComponent<ArrayList<Token>> { private final ArrayList<Token> nonDuplicatesCorpus; public RemoveDuplicates(ArrayList<Token> inCorpus) { nonDuplicatesCorpus = removeDuplicates(inCorpus); } public ArrayList<Token> removeDuplicates(ArrayList<Token> tokenList) { HashSet<Token> tokenSet = new HashSet<>(); tokenSet.addAll(tokenList); tokenList = new ArrayList<>(); tokenList.addAll(tokenSet); return tokenList; } public String showRequiredTypes() { return "ArrayList<Token>"; } public ArrayList<Token> getProcessedCorpus() { return nonDuplicatesCorpus; } }
UTF-8
Java
873
java
RemoveDuplicates.java
Java
[]
null
[]
package netgen.Preprocessing.Components; import java.util.ArrayList; import java.util.HashSet; import netgen.Preprocessing.PreprocessingComponent; import netgen.Preprocessing.Token; public class RemoveDuplicates implements PreprocessingComponent<ArrayList<Token>> { private final ArrayList<Token> nonDuplicatesCorpus; public RemoveDuplicates(ArrayList<Token> inCorpus) { nonDuplicatesCorpus = removeDuplicates(inCorpus); } public ArrayList<Token> removeDuplicates(ArrayList<Token> tokenList) { HashSet<Token> tokenSet = new HashSet<>(); tokenSet.addAll(tokenList); tokenList = new ArrayList<>(); tokenList.addAll(tokenSet); return tokenList; } public String showRequiredTypes() { return "ArrayList<Token>"; } public ArrayList<Token> getProcessedCorpus() { return nonDuplicatesCorpus; } }
873
0.738832
0.738832
33
25.484848
23.395313
81
false
false
0
0
0
0
0
0
0.878788
false
false
10
740ac7d580845407a1af05d433f78ab19464b038
19,902,878,494,085
7ae054234faee61fff6a150ac42857863b372ee2
/main/java/com/ibtspl/foodmanagement/ThankActivity.java
326c1667402437a7cb5ea0d899d538c923581974
[]
no_license
sanghavi-valipireddy/travel-guide
https://github.com/sanghavi-valipireddy/travel-guide
ebca3c152af426a4e23d0f9e71afae162f0715e2
74511d6308b65048aa4ca76393b377a5482c9817
refs/heads/master
2021-01-19T11:46:10.537000
2017-02-17T12:16:08
2017-02-17T12:16:08
82,278,112
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ibtspl.foodmanagement; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import com.google.firebase.auth.FirebaseAuth; public class ThankActivity extends AppCompatActivity { private FirebaseAuth mAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_thank); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); mAuth = FirebaseAuth.getInstance(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.my_menu, menu); return super.onCreateOptionsMenu(menu); } /** * On selecting action bar icons * */ @Override public boolean onOptionsItemSelected(MenuItem item) { // Take appropriate action for each action item click switch (item.getItemId()) { case R.id.action_help: // help action OnHelp(); return true; case R.id.logout: // OnLogOut(); signOut(); // logout return true; default: return super.onOptionsItemSelected(item); } } /** * Launching new activity` * */ // private void OnLogOut() { // Intent i = new Intent(MenuActivity.this, LoginActivity.class); // startActivity(i); // } private void signOut() { mAuth.signOut(); Intent i = new Intent(this, LoginActivity.class); startActivity(i); } private void OnHelp() { Intent i = new Intent(this, HelpActivity.class); startActivity(i); } public void GivingCount (View view) { Intent intent = new Intent(this, Count.class); // EditText editText = (EditText) findViewById(R.id.edit_message); // String message = editText.getText().toString(); // intent.putExtra(EXTRA_MESSAGE, message); startActivity(intent); } }
UTF-8
Java
2,341
java
ThankActivity.java
Java
[]
null
[]
package com.ibtspl.foodmanagement; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import com.google.firebase.auth.FirebaseAuth; public class ThankActivity extends AppCompatActivity { private FirebaseAuth mAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_thank); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); mAuth = FirebaseAuth.getInstance(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.my_menu, menu); return super.onCreateOptionsMenu(menu); } /** * On selecting action bar icons * */ @Override public boolean onOptionsItemSelected(MenuItem item) { // Take appropriate action for each action item click switch (item.getItemId()) { case R.id.action_help: // help action OnHelp(); return true; case R.id.logout: // OnLogOut(); signOut(); // logout return true; default: return super.onOptionsItemSelected(item); } } /** * Launching new activity` * */ // private void OnLogOut() { // Intent i = new Intent(MenuActivity.this, LoginActivity.class); // startActivity(i); // } private void signOut() { mAuth.signOut(); Intent i = new Intent(this, LoginActivity.class); startActivity(i); } private void OnHelp() { Intent i = new Intent(this, HelpActivity.class); startActivity(i); } public void GivingCount (View view) { Intent intent = new Intent(this, Count.class); // EditText editText = (EditText) findViewById(R.id.edit_message); // String message = editText.getText().toString(); // intent.putExtra(EXTRA_MESSAGE, message); startActivity(intent); } }
2,341
0.618966
0.618112
91
24.725275
20.861692
73
false
false
0
0
0
0
0
0
0.472527
false
false
10
426d385f5bffa04449c342ba611926a95661e259
15,839,839,431,653
8cce3add5198fb7de7c5ea411a9d49c2550b09ac
/advertiser/src/main/java/com/juzuan/advertiser/rpts/service/TaobaoAuthorizeUserService.java
cebc8cfb08c1800282b664ab355cb80844a275e5
[]
no_license
daxiyang06/advertiser
https://github.com/daxiyang06/advertiser
5b732eacead101c608a1785994d3580758d5ea99
02af5f1a07f86773311e2a036c507fc61d8bfd85
refs/heads/master
2020-04-09T07:40:04.041000
2018-12-11T02:43:33
2018-12-11T02:43:33
160,160,634
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.juzuan.advertiser.rpts.service; import com.juzuan.advertiser.rpts.model.TaobaoAuthorizeUser; public interface TaobaoAuthorizeUserService { int deleteByPrimaryKey(Long id); int insert(TaobaoAuthorizeUser record); int insertSelective(TaobaoAuthorizeUser record); TaobaoAuthorizeUser selectByPrimaryKey(Long id); int updateByPrimaryKeySelective(TaobaoAuthorizeUser record); int updateByPrimaryKey(TaobaoAuthorizeUser record); }
UTF-8
Java
468
java
TaobaoAuthorizeUserService.java
Java
[]
null
[]
package com.juzuan.advertiser.rpts.service; import com.juzuan.advertiser.rpts.model.TaobaoAuthorizeUser; public interface TaobaoAuthorizeUserService { int deleteByPrimaryKey(Long id); int insert(TaobaoAuthorizeUser record); int insertSelective(TaobaoAuthorizeUser record); TaobaoAuthorizeUser selectByPrimaryKey(Long id); int updateByPrimaryKeySelective(TaobaoAuthorizeUser record); int updateByPrimaryKey(TaobaoAuthorizeUser record); }
468
0.809829
0.809829
17
26.529411
25.649487
64
false
false
0
0
0
0
0
0
0.470588
false
false
10