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
cd947ec172e5aca4857818a8593b74cb7c5cd423
23,141,283,851,645
ca84c8925d9eb4c6e0a3145a2422d56d8c0ade90
/src/main/java/org/hl7/cpcdsauthserver/RegisterEndpoint.java
9e5f2eaee461a6b6668974ddb4ab0bbd1816f553
[]
no_license
carin-alliance/cpcds-auth-server
https://github.com/carin-alliance/cpcds-auth-server
dc1b7ce7a1ac0e6cfe4dbffa31899cf4e5cf660c
6df3fa7bf081cec2f9c10968ed98885f4379d6c7
refs/heads/master
2021-02-18T08:46:39.829000
2020-11-19T15:20:32
2020-11-19T15:20:32
245,179,171
4
2
null
false
2020-09-07T02:28:08
2020-03-05T14:06:32
2020-08-17T10:24:43
2020-05-26T18:46:53
238
4
1
1
Java
false
false
package org.hl7.cpcdsauthserver; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonSyntaxException; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.text.StringEscapeUtils; import org.springframework.http.HttpEntity; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.crypto.bcrypt.BCrypt; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; @Controller @RequestMapping("/register") public class RegisterEndpoint { private static final Logger logger = ServerLogger.getLogger(); @RequestMapping(value = "/user", method = RequestMethod.POST, consumes = { "application/json" }) public ResponseEntity<String> RegisterUser(HttpServletRequest request, HttpEntity<String> entity) { logger.info("RegisterEndpoint::Register: /register/user"); logger.log(Level.FINE, StringEscapeUtils.escapeJava(entity.getBody())); try { Gson gson = new GsonBuilder().setPrettyPrinting().create(); User user = gson.fromJson(entity.getBody(), User.class); logger.log(Level.FINE, user.toString()); String hashedPassword = BCrypt.hashpw(user.getPassword(), BCrypt.gensalt()); User newUser = new User(user.getUsername(), hashedPassword, user.getPatientId()); if (App.getDB().write(newUser)) return new ResponseEntity<String>(gson.toJson(newUser.toMap()), HttpStatus.CREATED); else return new ResponseEntity<String>(HttpStatus.BAD_REQUEST); } catch (JsonSyntaxException e) { logger.log(Level.SEVERE, "RegisterEndpoint::RegisterUser:Unable to parse body", e); return new ResponseEntity<String>(HttpStatus.BAD_REQUEST); } } @RequestMapping(value = "/user", method = RequestMethod.GET) public String RegisterUserPage() { return "registerUser"; } @RequestMapping(value = "/client", method = RequestMethod.POST) public ResponseEntity<String> RegisterClient(HttpServletRequest request, HttpEntity<String> entity, @RequestParam(name = "redirect_uri") String redirectUri) { // Escape all the query parameters redirectUri = StringEscapeUtils.escapeJava(redirectUri); logger.info("RegisterEndpoint::Register: /register/client"); logger.log(Level.FINE, "RegisterClient:RedirectURI:" + redirectUri); Gson gson = new GsonBuilder().setPrettyPrinting().create(); String clientId = UUID.randomUUID().toString(); String clientSecret = RandomStringUtils.randomAlphanumeric(256); Client newClient = new Client(clientId, clientSecret, redirectUri); if (App.getDB().write(newClient)) return new ResponseEntity<String>(gson.toJson(newClient.toMap()), HttpStatus.CREATED); else return new ResponseEntity<String>(HttpStatus.BAD_REQUEST); } @RequestMapping(value = "/client", method = RequestMethod.GET) public String RegisterClientPage() { return "registerClient"; } }
UTF-8
Java
3,461
java
RegisterEndpoint.java
Java
[]
null
[]
package org.hl7.cpcdsauthserver; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonSyntaxException; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.text.StringEscapeUtils; import org.springframework.http.HttpEntity; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.crypto.bcrypt.BCrypt; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; @Controller @RequestMapping("/register") public class RegisterEndpoint { private static final Logger logger = ServerLogger.getLogger(); @RequestMapping(value = "/user", method = RequestMethod.POST, consumes = { "application/json" }) public ResponseEntity<String> RegisterUser(HttpServletRequest request, HttpEntity<String> entity) { logger.info("RegisterEndpoint::Register: /register/user"); logger.log(Level.FINE, StringEscapeUtils.escapeJava(entity.getBody())); try { Gson gson = new GsonBuilder().setPrettyPrinting().create(); User user = gson.fromJson(entity.getBody(), User.class); logger.log(Level.FINE, user.toString()); String hashedPassword = BCrypt.hashpw(user.getPassword(), BCrypt.gensalt()); User newUser = new User(user.getUsername(), hashedPassword, user.getPatientId()); if (App.getDB().write(newUser)) return new ResponseEntity<String>(gson.toJson(newUser.toMap()), HttpStatus.CREATED); else return new ResponseEntity<String>(HttpStatus.BAD_REQUEST); } catch (JsonSyntaxException e) { logger.log(Level.SEVERE, "RegisterEndpoint::RegisterUser:Unable to parse body", e); return new ResponseEntity<String>(HttpStatus.BAD_REQUEST); } } @RequestMapping(value = "/user", method = RequestMethod.GET) public String RegisterUserPage() { return "registerUser"; } @RequestMapping(value = "/client", method = RequestMethod.POST) public ResponseEntity<String> RegisterClient(HttpServletRequest request, HttpEntity<String> entity, @RequestParam(name = "redirect_uri") String redirectUri) { // Escape all the query parameters redirectUri = StringEscapeUtils.escapeJava(redirectUri); logger.info("RegisterEndpoint::Register: /register/client"); logger.log(Level.FINE, "RegisterClient:RedirectURI:" + redirectUri); Gson gson = new GsonBuilder().setPrettyPrinting().create(); String clientId = UUID.randomUUID().toString(); String clientSecret = RandomStringUtils.randomAlphanumeric(256); Client newClient = new Client(clientId, clientSecret, redirectUri); if (App.getDB().write(newClient)) return new ResponseEntity<String>(gson.toJson(newClient.toMap()), HttpStatus.CREATED); else return new ResponseEntity<String>(HttpStatus.BAD_REQUEST); } @RequestMapping(value = "/client", method = RequestMethod.GET) public String RegisterClientPage() { return "registerClient"; } }
3,461
0.713378
0.711933
85
39.729412
31.972557
103
false
false
0
0
0
0
0
0
0.729412
false
false
0
171420dcddfa0e1b244c925940c15eb42b2d8d5d
27,839,978,074,467
e1d2db9679f67f89cc8f983da8373f4ea6050720
/src/main/java/io/sampleprojects/spring/rbac/service/GroupUserDetailsService.java
56fd1ab6ef74333e3ed690250e5c26984fa28f2c
[]
no_license
krishnakrmahto97/spring-security-method-level-rbac
https://github.com/krishnakrmahto97/spring-security-method-level-rbac
78c293332420067c3643f43f9c6c579963d044a9
b04eec2208ef434763c2b6d589b48addffcc0b78
refs/heads/main
2023-09-01T05:56:42.634000
2021-10-22T06:43:40
2021-10-22T06:43:40
419,957,160
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package io.sampleprojects.spring.rbac.service; import static io.sampleprojects.spring.rbac.common.Constants.ADMIN_AUTHORIZED_TO_ADD_ROLES; import static io.sampleprojects.spring.rbac.common.Constants.DEFAULT_ROLE_USER; import static io.sampleprojects.spring.rbac.common.Constants.MODERATOR_AUTHORIZED_TO_ADD_ROLES; import static io.sampleprojects.spring.rbac.common.Constants.ROLE_ADMIN; import static io.sampleprojects.spring.rbac.common.Constants.ROLE_MODERATOR; import io.sampleprojects.spring.rbac.dto.AddUserRoleRequest; import io.sampleprojects.spring.rbac.entity.User; import io.sampleprojects.spring.rbac.repository.UserRepository; import java.security.Principal; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import javax.transaction.Transactional; import javax.xml.bind.ValidationException; import lombok.AllArgsConstructor; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; @Service @AllArgsConstructor public class GroupUserDetailsService implements UserDetailsService { private final UserRepository repository; private final BCryptPasswordEncoder passwordEncoder; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { return repository.findByUsername(username) .map(GroupUserDetails::new) .orElseThrow(() -> new UsernameNotFoundException(username + " not found")); } public void createUser(User user) { user.setRoles(DEFAULT_ROLE_USER); user.setPassword(passwordEncoder.encode(user.getPassword())); repository.save(user); } @Transactional public void addUserRoles(AddUserRoleRequest request, String username, Principal principal) throws ValidationException { List<String> loggedInUserRoles = getLoggedInUserRoles(principal); User userToBeUpdated = repository.findByUsername(username) .orElseThrow(() -> new UsernameNotFoundException("Requested user not found")); String newRole = request.getNewRole(); if (loggedInUserRoles.contains(ROLE_ADMIN) && ADMIN_AUTHORIZED_TO_ADD_ROLES.contains(newRole)) { userToBeUpdated.setRoles(userToBeUpdated.getRoles() + "," + newRole); } else if (loggedInUserRoles.contains(ROLE_MODERATOR) && MODERATOR_AUTHORIZED_TO_ADD_ROLES.contains(newRole)) { userToBeUpdated.setRoles(userToBeUpdated.getRoles() + "," + newRole); } else { throw new ValidationException("You cannot assign the role to the user."); } } private List<String> getLoggedInUserRoles(Principal principal) { User loggedInUser = repository.findByUsername(principal.getName()) .orElseThrow(() -> new RuntimeException("Invalid logged in user")); return Arrays.stream(loggedInUser.getRoles().split(",")).collect(Collectors.toList()); } }
UTF-8
Java
3,060
java
GroupUserDetailsService.java
Java
[]
null
[]
package io.sampleprojects.spring.rbac.service; import static io.sampleprojects.spring.rbac.common.Constants.ADMIN_AUTHORIZED_TO_ADD_ROLES; import static io.sampleprojects.spring.rbac.common.Constants.DEFAULT_ROLE_USER; import static io.sampleprojects.spring.rbac.common.Constants.MODERATOR_AUTHORIZED_TO_ADD_ROLES; import static io.sampleprojects.spring.rbac.common.Constants.ROLE_ADMIN; import static io.sampleprojects.spring.rbac.common.Constants.ROLE_MODERATOR; import io.sampleprojects.spring.rbac.dto.AddUserRoleRequest; import io.sampleprojects.spring.rbac.entity.User; import io.sampleprojects.spring.rbac.repository.UserRepository; import java.security.Principal; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import javax.transaction.Transactional; import javax.xml.bind.ValidationException; import lombok.AllArgsConstructor; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; @Service @AllArgsConstructor public class GroupUserDetailsService implements UserDetailsService { private final UserRepository repository; private final BCryptPasswordEncoder passwordEncoder; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { return repository.findByUsername(username) .map(GroupUserDetails::new) .orElseThrow(() -> new UsernameNotFoundException(username + " not found")); } public void createUser(User user) { user.setRoles(DEFAULT_ROLE_USER); user.setPassword(passwordEncoder.encode(user.getPassword())); repository.save(user); } @Transactional public void addUserRoles(AddUserRoleRequest request, String username, Principal principal) throws ValidationException { List<String> loggedInUserRoles = getLoggedInUserRoles(principal); User userToBeUpdated = repository.findByUsername(username) .orElseThrow(() -> new UsernameNotFoundException("Requested user not found")); String newRole = request.getNewRole(); if (loggedInUserRoles.contains(ROLE_ADMIN) && ADMIN_AUTHORIZED_TO_ADD_ROLES.contains(newRole)) { userToBeUpdated.setRoles(userToBeUpdated.getRoles() + "," + newRole); } else if (loggedInUserRoles.contains(ROLE_MODERATOR) && MODERATOR_AUTHORIZED_TO_ADD_ROLES.contains(newRole)) { userToBeUpdated.setRoles(userToBeUpdated.getRoles() + "," + newRole); } else { throw new ValidationException("You cannot assign the role to the user."); } } private List<String> getLoggedInUserRoles(Principal principal) { User loggedInUser = repository.findByUsername(principal.getName()) .orElseThrow(() -> new RuntimeException("Invalid logged in user")); return Arrays.stream(loggedInUser.getRoles().split(",")).collect(Collectors.toList()); } }
3,060
0.789216
0.789216
71
42.098591
33.330254
115
false
false
0
0
0
0
0
0
0.56338
false
false
0
a92e3ebe93134801bd6041debbe261691967874e
18,373,870,158,470
48b87ecd8b380c34646fc28cbfb5e38f0a34bcf7
/demo-spring-boot-event/src/main/java/com/fengwenyi/demospringbootevent/event/MyPublisher.java
2bba1fb687a4e29e66cbfae7b5d303c651ba9b45
[]
no_license
fengwenyi/springboot-demo
https://github.com/fengwenyi/springboot-demo
89783de556eb750a6a749e71bad8052346e26a15
2fdb4c8fb6d782adad7f4b7b31c1897126391b2d
refs/heads/main
2023-06-18T05:36:15.543000
2022-07-18T01:11:00
2022-07-18T01:11:00
365,941,274
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.fengwenyi.demospringbootevent.event; import com.fengwenyi.demospringbootevent.event.ExceptionEvent; import com.fengwenyi.demospringbootevent.event.UserLoginEvent; import com.fengwenyi.demospringbootevent.vo.request.UserLoginRequestVo; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; /** * @author <a href="https://www.fengwenyi.com">Erwin Feng</a> * @since 2021-08-18 */ @Component public class MyPublisher { private final ApplicationContext applicationContext; public MyPublisher(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } public void userLoginEvent(String username) { applicationContext.publishEvent(new UserLoginEvent(username)); } public void alarm(String msg) { applicationContext.publishEvent(new ExceptionEvent(msg)); } public void logout(String uid) { applicationContext.publishEvent(new UserLogoutEvent(uid)); } }
UTF-8
Java
1,015
java
MyPublisher.java
Java
[ { "context": "**\n * @author <a href=\"https://www.fengwenyi.com\">Erwin Feng</a>\n * @since 2021-08-18\n */\n@Component\npublic cl", "end": 414, "score": 0.9998663663864136, "start": 404, "tag": "NAME", "value": "Erwin Feng" } ]
null
[]
package com.fengwenyi.demospringbootevent.event; import com.fengwenyi.demospringbootevent.event.ExceptionEvent; import com.fengwenyi.demospringbootevent.event.UserLoginEvent; import com.fengwenyi.demospringbootevent.vo.request.UserLoginRequestVo; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; /** * @author <a href="https://www.fengwenyi.com"><NAME></a> * @since 2021-08-18 */ @Component public class MyPublisher { private final ApplicationContext applicationContext; public MyPublisher(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } public void userLoginEvent(String username) { applicationContext.publishEvent(new UserLoginEvent(username)); } public void alarm(String msg) { applicationContext.publishEvent(new ExceptionEvent(msg)); } public void logout(String uid) { applicationContext.publishEvent(new UserLogoutEvent(uid)); } }
1,011
0.768473
0.760591
33
29.757576
27.171766
71
false
false
0
0
0
0
0
0
0.333333
false
false
0
6210875aaba5d243c12197986de63467acf7b06a
4,509,715,666,831
7798846828ab786c02bff018d96143bb618dcac4
/app/src/main/java/com/example/mbarrben/rxjavasample/io/MovieAdapter.java
ee044f4dee699046d5b686207bf11387d86a13bd
[]
no_license
mbarrben/AndroidRxJavaSample
https://github.com/mbarrben/AndroidRxJavaSample
72f8cbf225bd72012110ae02302884f6be385b36
07a27c34d8ecd11575f42e40d8bf377e26356839
refs/heads/master
2020-07-08T08:36:02.981000
2014-11-28T23:39:12
2014-11-28T23:39:12
26,379,950
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.mbarrben.rxjavasample.io; import com.squareup.okhttp.OkHttpClient; import java.util.concurrent.TimeUnit; import retrofit.RestAdapter; import retrofit.client.OkClient; public class MovieAdapter { public static final String ENDPOINT = "http://www.myapifilms.com"; public MyApiFilmsService create() { OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(1, TimeUnit.MINUTES); client.setReadTimeout(2, TimeUnit.MINUTES); return new RestAdapter.Builder() .setEndpoint(ENDPOINT) .setClient(new OkClient(client)) .setLogLevel(RestAdapter.LogLevel.FULL) .build() .create(MyApiFilmsService.class); } }
UTF-8
Java
758
java
MovieAdapter.java
Java
[ { "context": "package com.example.mbarrben.rxjavasample.io;\n\nimport com.squareup.okhttp.OkHt", "end": 28, "score": 0.9918369650840759, "start": 20, "tag": "USERNAME", "value": "mbarrben" } ]
null
[]
package com.example.mbarrben.rxjavasample.io; import com.squareup.okhttp.OkHttpClient; import java.util.concurrent.TimeUnit; import retrofit.RestAdapter; import retrofit.client.OkClient; public class MovieAdapter { public static final String ENDPOINT = "http://www.myapifilms.com"; public MyApiFilmsService create() { OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(1, TimeUnit.MINUTES); client.setReadTimeout(2, TimeUnit.MINUTES); return new RestAdapter.Builder() .setEndpoint(ENDPOINT) .setClient(new OkClient(client)) .setLogLevel(RestAdapter.LogLevel.FULL) .build() .create(MyApiFilmsService.class); } }
758
0.671504
0.668865
26
28.153847
22.046616
70
false
false
0
0
0
0
0
0
0.461538
false
false
0
77b688441fafe35f9227eb4a75dbdd716b87423f
4,733,053,962,391
f3ed53704451a762efb292ea78a0082deb834186
/demo/src/main/java/demo/javafx_samples/src/3DViewer/src/main/java/com/javafx/experiments/jfx3dviewer/AutoScalingGroup.java
5cf6fb9633cb84fad020a158ed260df1c4c242b7
[ "BSD-3-Clause" ]
permissive
kongzhidea/jdk-source
https://github.com/kongzhidea/jdk-source
8811c193b29cc638737079fb86585124a7780118
edd6501bb03f6cc5dcc5c19d8de16bd7f9702afe
refs/heads/master
2020-04-01T10:53:47.271000
2018-10-15T16:15:12
2018-10-15T16:15:12
153,136,405
2
0
null
true
2018-10-15T15:21:34
2018-10-15T15:21:34
2018-10-15T02:33:27
2018-02-05T03:43:29
109,719
0
0
0
null
false
null
package demo.javafx_samples.src.3DViewer.src.main.java.com.javafx.experiments.jfx3dviewer; /* * Copyright (c) 2010, 2014, Oracle and/or its affiliates. * All rights reserved. Use is subject to license terms. * * This file is available and licensed under the following license: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - 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. * - Neither the name of Oracle Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * 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 * OWNER 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. */ import java.util.List; import javafx.beans.property.SimpleBooleanProperty; import javafx.geometry.Bounds; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.transform.Scale; import javafx.scene.transform.Translate; /** * A Group that auto scales its self to fit its content in a given size box. */ public class AutoScalingGroup extends Group { private double size; private double twoSize; private boolean autoScale = false; private Translate translate = new Translate(0,0,0); private Scale scale = new Scale(1,1,1,0,0,0); private SimpleBooleanProperty enabled = new SimpleBooleanProperty(false) { @Override protected void invalidated() { if (get()) { getTransforms().setAll(scale, translate); } else { getTransforms().clear(); } } }; /** * Create AutoScalingGroup * * @param size half of width/height/depth of box to fit content into */ public AutoScalingGroup(double size) { this.size = size; this.twoSize = size * 2; getTransforms().addAll(scale,translate); } /** * Get is auto scaling enabled * * @return true if auto scaling is enabled */ public boolean isEnabled() { return enabled.get(); } /** * Get enabled property * * @return enabled property */ public SimpleBooleanProperty enabledProperty() { return enabled; } /** * Set is auto scaling enabled * * @param enabled true if auto scaling is enabled */ public void setEnabled(boolean enabled) { this.enabled.set(enabled); } @Override protected void layoutChildren() { if (autoScale) { List<Node> children = getChildren(); double minX = Double.MAX_VALUE, minY = Double.MAX_VALUE, minZ = Double.MAX_VALUE; double maxX = Double.MIN_VALUE, maxY = Double.MIN_VALUE, maxZ = Double.MIN_VALUE; boolean first = true; for (int i=0, max=children.size(); i<max; i++) { final Node node = children.get(i); if (node.isVisible()) { Bounds bounds = node.getBoundsInLocal(); // if the bounds of the child are invalid, we don't want // to use those in the remaining computations. if (bounds.isEmpty()) continue; if (first) { minX = bounds.getMinX(); minY = bounds.getMinY(); minZ = bounds.getMinZ(); maxX = bounds.getMaxX(); maxY = bounds.getMaxY(); maxZ = bounds.getMaxZ(); first = false; } else { minX = Math.min(bounds.getMinX(), minX); minY = Math.min(bounds.getMinY(), minY); minZ = Math.min(bounds.getMinZ(), minZ); maxX = Math.max(bounds.getMaxX(), maxX); maxY = Math.max(bounds.getMaxY(), maxY); maxZ = Math.max(bounds.getMaxZ(), maxZ); } } } final double w = maxX-minX; final double h = maxY-minY; final double d = maxZ-minZ; final double centerX = minX + (w/2); final double centerY = minY + (h/2); final double centerZ = minZ + (d/2); double scaleX = twoSize/w; double scaleY = twoSize/h; double scaleZ = twoSize/d; double scale = Math.min(scaleX, Math.min(scaleY,scaleZ)); this.scale.setX(scale); this.scale.setY(scale); this.scale.setZ(scale); this.translate.setX(-centerX); this.translate.setY(-centerY); } } }
UTF-8
Java
5,759
java
AutoScalingGroup.java
Java
[]
null
[]
package demo.javafx_samples.src.3DViewer.src.main.java.com.javafx.experiments.jfx3dviewer; /* * Copyright (c) 2010, 2014, Oracle and/or its affiliates. * All rights reserved. Use is subject to license terms. * * This file is available and licensed under the following license: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - 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. * - Neither the name of Oracle Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * 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 * OWNER 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. */ import java.util.List; import javafx.beans.property.SimpleBooleanProperty; import javafx.geometry.Bounds; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.transform.Scale; import javafx.scene.transform.Translate; /** * A Group that auto scales its self to fit its content in a given size box. */ public class AutoScalingGroup extends Group { private double size; private double twoSize; private boolean autoScale = false; private Translate translate = new Translate(0,0,0); private Scale scale = new Scale(1,1,1,0,0,0); private SimpleBooleanProperty enabled = new SimpleBooleanProperty(false) { @Override protected void invalidated() { if (get()) { getTransforms().setAll(scale, translate); } else { getTransforms().clear(); } } }; /** * Create AutoScalingGroup * * @param size half of width/height/depth of box to fit content into */ public AutoScalingGroup(double size) { this.size = size; this.twoSize = size * 2; getTransforms().addAll(scale,translate); } /** * Get is auto scaling enabled * * @return true if auto scaling is enabled */ public boolean isEnabled() { return enabled.get(); } /** * Get enabled property * * @return enabled property */ public SimpleBooleanProperty enabledProperty() { return enabled; } /** * Set is auto scaling enabled * * @param enabled true if auto scaling is enabled */ public void setEnabled(boolean enabled) { this.enabled.set(enabled); } @Override protected void layoutChildren() { if (autoScale) { List<Node> children = getChildren(); double minX = Double.MAX_VALUE, minY = Double.MAX_VALUE, minZ = Double.MAX_VALUE; double maxX = Double.MIN_VALUE, maxY = Double.MIN_VALUE, maxZ = Double.MIN_VALUE; boolean first = true; for (int i=0, max=children.size(); i<max; i++) { final Node node = children.get(i); if (node.isVisible()) { Bounds bounds = node.getBoundsInLocal(); // if the bounds of the child are invalid, we don't want // to use those in the remaining computations. if (bounds.isEmpty()) continue; if (first) { minX = bounds.getMinX(); minY = bounds.getMinY(); minZ = bounds.getMinZ(); maxX = bounds.getMaxX(); maxY = bounds.getMaxY(); maxZ = bounds.getMaxZ(); first = false; } else { minX = Math.min(bounds.getMinX(), minX); minY = Math.min(bounds.getMinY(), minY); minZ = Math.min(bounds.getMinZ(), minZ); maxX = Math.max(bounds.getMaxX(), maxX); maxY = Math.max(bounds.getMaxY(), maxY); maxZ = Math.max(bounds.getMaxZ(), maxZ); } } } final double w = maxX-minX; final double h = maxY-minY; final double d = maxZ-minZ; final double centerX = minX + (w/2); final double centerY = minY + (h/2); final double centerZ = minZ + (d/2); double scaleX = twoSize/w; double scaleY = twoSize/h; double scaleZ = twoSize/d; double scale = Math.min(scaleX, Math.min(scaleY,scaleZ)); this.scale.setX(scale); this.scale.setY(scale); this.scale.setZ(scale); this.translate.setX(-centerX); this.translate.setY(-centerY); } } }
5,759
0.603403
0.599236
152
36.888157
25.84049
93
false
false
0
0
0
0
0
0
0.697368
false
false
0
f9e86a6074bb6ef0b23b54aeabd52fcb4f703c30
1,494,648,675,668
ae87ed1e88a93090833531aa65129e4c128d5e1f
/commons-hbase/src/test/java/com/navercorp/pinpoint/common/hbase/HbaseTemplate2IT.java
f6964765a1565dd003b8a7a4bd2ee84ce33c566a
[ "DOC", "LicenseRef-scancode-free-unknown", "CC0-1.0", "OFL-1.1", "GPL-1.0-or-later", "CC-PDDC", "GPL-2.0-only", "Apache-2.0", "LicenseRef-scancode-public-domain", "CC-BY-3.0", "LicenseRef-scancode-unknown-license-reference", "MITNFA", "MIT", "CC-BY-4.0", "OFL-1.0" ]
permissive
pinpoint-apm/pinpoint
https://github.com/pinpoint-apm/pinpoint
f008775040cd8e07219a8b6695f30afbfd324d38
2eaa751235a2599771c7da8af8f66b1f0b285897
refs/heads/master
2023-08-21T12:53:56.344000
2023-08-16T07:33:32
2023-08-21T09:12:56
25,459,400
2,475
691
Apache-2.0
false
2023-09-14T09:34:33
2014-10-20T09:27:22
2023-09-14T08:09:19
2023-09-14T07:43:10
249,323
12,961
3,746
406
Java
false
false
/* * Copyright 2014 NAVER Corp. * * 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.navercorp.pinpoint.common.hbase; import com.navercorp.pinpoint.common.util.PropertyUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.TableNotFoundException; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.apache.hadoop.hbase.client.RetriesExhaustedWithDetailsException; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Properties; /** * @author emeroad * @author minwoo.jung */ @Disabled public class HbaseTemplate2IT { private static Connection connection; private static HbaseTemplate2 hbaseTemplate2; @BeforeAll public static void beforeClass() throws IOException { Properties properties = PropertyUtils.loadPropertyFromClassPath("test-hbase.properties"); Configuration cfg = HBaseConfiguration.create(); cfg.set("hbase.zookeeper.quorum", properties.getProperty("hbase.client.host")); cfg.set("hbase.zookeeper.property.clientPort", properties.getProperty("hbase.client.port")); connection = ConnectionFactory.createConnection(cfg); hbaseTemplate2 = new HbaseTemplate2(); hbaseTemplate2.setConfiguration(cfg); hbaseTemplate2.setTableFactory(new HbaseTableFactory(connection)); hbaseTemplate2.afterPropertiesSet(); } @AfterAll public static void afterClass() throws Exception { if (hbaseTemplate2 != null) { hbaseTemplate2.destroy(); } if (connection != null) { connection.close(); } } @Test public void notExist() { try { hbaseTemplate2.put(TableName.valueOf("NOT_EXIST"), new byte[]{0, 0, 0}, "familyName".getBytes(), "columnName".getBytes(), new byte[]{0, 0, 0}); Assertions.fail("exceptions"); } catch (HbaseSystemException e) { RetriesExhaustedWithDetailsException exception = (RetriesExhaustedWithDetailsException) (e.getCause()); if (!(exception.getCause(0) instanceof TableNotFoundException)) { Assertions.fail("unexpected exception :" + e.getCause()); } } } }
UTF-8
Java
3,133
java
HbaseTemplate2IT.java
Java
[ { "context": ";\r\nimport java.util.Properties;\r\n\r\n/**\r\n * @author emeroad\r\n * @author minwoo.jung\r\n */\r\n\r\n@Disabled\r\npublic", "end": 1386, "score": 0.9475786089897156, "start": 1379, "tag": "USERNAME", "value": "emeroad" }, { "context": "Properties;\r\n\r\n/**\r\n * @author emeroad\r\n * @author minwoo.jung\r\n */\r\n\r\n@Disabled\r\npublic class HbaseTemplate2IT ", "end": 1410, "score": 0.9390736818313599, "start": 1399, "tag": "NAME", "value": "minwoo.jung" } ]
null
[]
/* * Copyright 2014 NAVER Corp. * * 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.navercorp.pinpoint.common.hbase; import com.navercorp.pinpoint.common.util.PropertyUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.TableNotFoundException; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.apache.hadoop.hbase.client.RetriesExhaustedWithDetailsException; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Properties; /** * @author emeroad * @author minwoo.jung */ @Disabled public class HbaseTemplate2IT { private static Connection connection; private static HbaseTemplate2 hbaseTemplate2; @BeforeAll public static void beforeClass() throws IOException { Properties properties = PropertyUtils.loadPropertyFromClassPath("test-hbase.properties"); Configuration cfg = HBaseConfiguration.create(); cfg.set("hbase.zookeeper.quorum", properties.getProperty("hbase.client.host")); cfg.set("hbase.zookeeper.property.clientPort", properties.getProperty("hbase.client.port")); connection = ConnectionFactory.createConnection(cfg); hbaseTemplate2 = new HbaseTemplate2(); hbaseTemplate2.setConfiguration(cfg); hbaseTemplate2.setTableFactory(new HbaseTableFactory(connection)); hbaseTemplate2.afterPropertiesSet(); } @AfterAll public static void afterClass() throws Exception { if (hbaseTemplate2 != null) { hbaseTemplate2.destroy(); } if (connection != null) { connection.close(); } } @Test public void notExist() { try { hbaseTemplate2.put(TableName.valueOf("NOT_EXIST"), new byte[]{0, 0, 0}, "familyName".getBytes(), "columnName".getBytes(), new byte[]{0, 0, 0}); Assertions.fail("exceptions"); } catch (HbaseSystemException e) { RetriesExhaustedWithDetailsException exception = (RetriesExhaustedWithDetailsException) (e.getCause()); if (!(exception.getCause(0) instanceof TableNotFoundException)) { Assertions.fail("unexpected exception :" + e.getCause()); } } } }
3,133
0.694861
0.686562
84
35.297619
30.959951
155
false
false
0
0
0
0
0
0
0.571429
false
false
0
53a4ec5cc4c5a0213777422c16b6cb96a16bd5c6
4,415,226,418,849
89452c6d9123ab3a7e6509e8702bf930a08ce7a8
/src/me/chagnwei/leetcode/firstMissingPositive/Solution.java
87f8ab5bd3e952e42b4717963d57d5d70a52b7a6
[]
no_license
cw1997/LeetCode
https://github.com/cw1997/LeetCode
f5fd38061272616e6f862405d32f0a0007f0d5d3
6623f7c1331adb1be6783b2a1c89eca090c59eeb
refs/heads/master
2023-02-10T14:45:16.030000
2021-01-03T07:32:39
2021-01-03T07:32:39
293,904,654
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package me.chagnwei.leetcode.firstMissingPositive; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * @author cw1997 <867597730@qq.com> * @file null.java * @date 2020/9/10 20:19 * @description */ public class Solution { public static void main(String[] args) { int[] ints1 = {1,2,0}; System.out.println(new Solution().firstMissingPositive(ints1)); int[] ints2 = {3,4,-1,1}; System.out.println(new Solution().firstMissingPositive(ints2)); int[] ints3 = {7,8,9,11,12}; System.out.println(new Solution().firstMissingPositive(ints3)); } public int firstMissingPositive(int[] nums) { Set<Integer> set = new HashSet<>(); int max = Integer.MIN_VALUE; for (int num : nums) { set.add(num); if (num > 0) { max = Math.max(max, num); } } int i = 1; while (i <= max) { if (!set.contains(i)) { return i; } ++i; } return i; } }
UTF-8
Java
1,081
java
Solution.java
Java
[ { "context": "til.HashSet;\nimport java.util.Set;\n\n/**\n * @author cw1997 <867597730@qq.com>\n * @file null.java\n * @date 20", "end": 147, "score": 0.9996584057807922, "start": 141, "tag": "USERNAME", "value": "cw1997" }, { "context": "et;\nimport java.util.Set;\n\n/**\n * @author cw1997 <867597730@qq.com>\n * @file null.java\n * @date 2020/9/10 20:19\n * @", "end": 165, "score": 0.9999070763587952, "start": 149, "tag": "EMAIL", "value": "867597730@qq.com" } ]
null
[]
package me.chagnwei.leetcode.firstMissingPositive; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * @author cw1997 <<EMAIL>> * @file null.java * @date 2020/9/10 20:19 * @description */ public class Solution { public static void main(String[] args) { int[] ints1 = {1,2,0}; System.out.println(new Solution().firstMissingPositive(ints1)); int[] ints2 = {3,4,-1,1}; System.out.println(new Solution().firstMissingPositive(ints2)); int[] ints3 = {7,8,9,11,12}; System.out.println(new Solution().firstMissingPositive(ints3)); } public int firstMissingPositive(int[] nums) { Set<Integer> set = new HashSet<>(); int max = Integer.MIN_VALUE; for (int num : nums) { set.add(num); if (num > 0) { max = Math.max(max, num); } } int i = 1; while (i <= max) { if (!set.contains(i)) { return i; } ++i; } return i; } }
1,072
0.533765
0.491212
41
25.365854
18.771744
71
false
false
0
0
0
0
0
0
0.682927
false
false
0
538d529694846ecbcb85eec961afe142a59efbe8
22,737,556,897,217
0dc045da32b0ae67bb966724fe0d734be4c38be4
/่ฎพ่ฎกๆจกๅผ/StrategyPattern/src/TestDuck.java
fa5843a46ee9f476a15478a697137583cff66a8b
[]
no_license
zhishou001/MyLearn
https://github.com/zhishou001/MyLearn
5baef82ff964ea77fe182934a38080e305346c80
68762436c906281090b75bb2d3a37d5349890559
refs/heads/master
2022-04-19T21:29:59.869000
2020-03-12T16:42:54
2020-03-12T16:42:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class TestDuck { public static void main(String[] args) { Duck aduck = new OneDuck(); //ๆœ€ๅˆ็Šถๆ€ aduck.display(); System.out.println("ๆˆ‘ๆ˜ฏไธ€ๅช้ธญๅญ๏ผŒไธ€ๅผ€ๅง‹ๆˆ‘ๆ˜ฏไผš้ฃž็š„๏ผ"); aduck.performFly(); System.out.println("ๆˆ‘ไนŸๆ˜ฏไผšๅซ็š„๏ผ"); aduck.performQuack(); //ๅŠจๆ€่ฎพๅฎš่กŒไธบ๏ผŒไฝฟ้ธญๅญไธไผš้ฃž System.out.println("ๆœ‰ไธ€ๅคฉ๏ผŒๆˆ‘็š„็ฟ…่†€ๆŠ˜ๆ–ญไบ†๏ผŒๆˆ‘ไธไผš้ฃžไบ†๏ผ"); aduck.setFlyBehavior(new FlyNoWay()); aduck.performFly(); } }
GB18030
Java
503
java
TestDuck.java
Java
[]
null
[]
public class TestDuck { public static void main(String[] args) { Duck aduck = new OneDuck(); //ๆœ€ๅˆ็Šถๆ€ aduck.display(); System.out.println("ๆˆ‘ๆ˜ฏไธ€ๅช้ธญๅญ๏ผŒไธ€ๅผ€ๅง‹ๆˆ‘ๆ˜ฏไผš้ฃž็š„๏ผ"); aduck.performFly(); System.out.println("ๆˆ‘ไนŸๆ˜ฏไผšๅซ็š„๏ผ"); aduck.performQuack(); //ๅŠจๆ€่ฎพๅฎš่กŒไธบ๏ผŒไฝฟ้ธญๅญไธไผš้ฃž System.out.println("ๆœ‰ไธ€ๅคฉ๏ผŒๆˆ‘็š„็ฟ…่†€ๆŠ˜ๆ–ญไบ†๏ผŒๆˆ‘ไธไผš้ฃžไบ†๏ผ"); aduck.setFlyBehavior(new FlyNoWay()); aduck.performFly(); } }
503
0.661499
0.661499
20
18.299999
15.056892
43
false
false
0
0
0
0
0
0
2
false
false
0
18ca6187eb4882bd1ed3478c0e542742190265fe
16,295,105,933,574
00c449a76e19c51b01ad9a6fca18c08fe5db1927
/src/main/java/leetcode/easy/cells_with_odd_values_in_a_matrix/Solution.java
329225effce8575760fc937120aa236e2d632858
[]
no_license
ddojai/problem-solving
https://github.com/ddojai/problem-solving
9eec9abd56fe34db386c2b0ae8d4c6722a4d6115
aa75376d11665f09ef818006b4ee3f1d2d19a815
refs/heads/master
2023-04-06T10:14:18.165000
2023-03-29T14:00:38
2023-03-29T14:00:38
141,455,490
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package leetcode.easy.cells_with_odd_values_in_a_matrix; /** * https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/ * 1252. Cells with Odd Values in a Matrix */ public class Solution { public int oddCells(int n, int m, int[][] indices) { int[][] cells = new int[n][m]; for (int i = 0; i < indices.length; i++) { int row = indices[i][0]; int column = indices[i][1]; for (int ri = 0; ri < n; ri++) { cells[ri][column]++; } for (int ci = 0; ci < m; ci++) { cells[row][ci]++; } } int oddCount = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (cells[i][j] % 2 != 0) { oddCount++; } } } return oddCount; } }
UTF-8
Java
885
java
Solution.java
Java
[]
null
[]
package leetcode.easy.cells_with_odd_values_in_a_matrix; /** * https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/ * 1252. Cells with Odd Values in a Matrix */ public class Solution { public int oddCells(int n, int m, int[][] indices) { int[][] cells = new int[n][m]; for (int i = 0; i < indices.length; i++) { int row = indices[i][0]; int column = indices[i][1]; for (int ri = 0; ri < n; ri++) { cells[ri][column]++; } for (int ci = 0; ci < m; ci++) { cells[row][ci]++; } } int oddCount = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (cells[i][j] % 2 != 0) { oddCount++; } } } return oddCount; } }
885
0.420339
0.40452
34
25.029411
19.429337
67
false
false
0
0
0
0
0
0
0.617647
false
false
0
c6d4e14d52cbb61dd7289f24415d216d46074ed6
16,295,105,936,743
3a0510dbe95b9b5d47fd24f6b4813381532a9b5d
/Java_Projects/AutoChoiceNew_bk/src/main/java/gov/gsa/fas/AutoChoice/DTO/GroupDunsDealerFranCompositePK.java
e67cccf955d70895f30ef432953f713f02f28c90
[]
no_license
prem1982/Lockh
https://github.com/prem1982/Lockh
7a7ed9005fe689f2bbe43b2eafa8dd07221e2d00
12bd08228760039da39f713a25468c75ab1399f6
refs/heads/master
2020-03-28T15:08:27.187000
2018-09-13T00:48:06
2018-09-13T00:48:06
148,560,262
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package gov.gsa.fas.AutoChoice.DTO; /** * @author Arnel Macatula * */ /** * @author ArnelPMacatula * */ import java.io.Serializable; public class GroupDunsDealerFranCompositePK implements Serializable { protected int groupDUNS = 0; protected String dealerCode = ""; protected String Fran_Code = ""; public int getGroupDUNS() { return groupDUNS; } public void setGroupDUNS(int groupDUNS) { this.groupDUNS = groupDUNS; } public String getDealerCode() { return dealerCode; } public void setDealerCode(String dealerCode) { this.dealerCode = dealerCode; } public String getFran_Code() { return Fran_Code; } public void setFran_Code(String fran_Code) { Fran_Code = fran_Code; } }
UTF-8
Java
773
java
GroupDunsDealerFranCompositePK.java
Java
[ { "context": "e gov.gsa.fas.AutoChoice.DTO;\r\n\r\n\r\n/**\r\n * @author Arnel Macatula\r\n *\r\n */\r\n\r\n\r\n/**\r\n * @author ArnelPMacatula\r\n *\r", "end": 86, "score": 0.9998739361763, "start": 72, "tag": "NAME", "value": "Arnel Macatula" }, { "context": "uthor Arnel Macatula\r\n *\r\n */\r\n\r\n\r\n/**\r\n * @author ArnelPMacatula\r\n *\r\n */\r\nimport java.io.Serializable", "end": 119, "score": 0.8115335702896118, "start": 117, "tag": "NAME", "value": "Ar" }, { "context": "or Arnel Macatula\r\n *\r\n */\r\n\r\n\r\n/**\r\n * @author ArnelPMacatula\r\n *\r\n */\r\nimport java.io.Serializable;\r\n\r\n", "end": 124, "score": 0.8991731405258179, "start": 119, "tag": "USERNAME", "value": "nelPM" }, { "context": "nel Macatula\r\n *\r\n */\r\n\r\n\r\n/**\r\n * @author ArnelPMacatula\r\n *\r\n */\r\nimport java.io.Serializable;\r\n\r\npublic ", "end": 131, "score": 0.8307300209999084, "start": 124, "tag": "NAME", "value": "acatula" } ]
null
[]
/** * */ package gov.gsa.fas.AutoChoice.DTO; /** * @author <NAME> * */ /** * @author ArnelPMacatula * */ import java.io.Serializable; public class GroupDunsDealerFranCompositePK implements Serializable { protected int groupDUNS = 0; protected String dealerCode = ""; protected String Fran_Code = ""; public int getGroupDUNS() { return groupDUNS; } public void setGroupDUNS(int groupDUNS) { this.groupDUNS = groupDUNS; } public String getDealerCode() { return dealerCode; } public void setDealerCode(String dealerCode) { this.dealerCode = dealerCode; } public String getFran_Code() { return Fran_Code; } public void setFran_Code(String fran_Code) { Fran_Code = fran_Code; } }
765
0.658473
0.65718
43
15.930233
17.091267
69
false
false
0
0
0
0
0
0
0.930233
false
false
0
c00bc4dbc92738fa2b7bf413df8dbb7c816049b4
27,659,589,388,565
464b4a5e90db70c1a5cd1cfe9999ed52b5a0f5c1
/jinternals-event-bus-rabbitmq-configuration/src/main/java/com/jinternals/event/bus/rabbitmq/configuration/RabbitmqBrokerConfiguration.java
d2384889449d421eccdc47a034aa7b9d975d0253
[]
no_license
jinternals/jinternals-event-bus
https://github.com/jinternals/jinternals-event-bus
f5b53c1ea22fe6fcfad9d3cf0070cab42bceb1e7
9737196dda66183a3d638a0a68239873cbeb83d3
refs/heads/master
2020-04-23T02:40:31.188000
2019-05-04T14:01:55
2019-05-04T14:01:55
170,853,718
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jinternals.event.bus.rabbitmq.configuration; import com.jinternals.event.bus.rabbitmq.properties.RabbitmqEventBusProperties; import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; import org.springframework.amqp.rabbit.transaction.RabbitTransactionManager; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.amqp.rabbit.connection.ConnectionFactory; import java.util.Objects; import static java.util.Objects.nonNull; @Configuration public class RabbitmqBrokerConfiguration { @ConditionalOnProperty(prefix = "event.bus.rabbitmq.consumer", name = "enabled", havingValue = "true", matchIfMissing = true) @Bean("rabbitmqTransactionManager") public PlatformTransactionManager rabbitmqTransactionManager( @Qualifier("rabbitmqCachingConnectionFactory") ConnectionFactory cachingConnectionFactory) { RabbitTransactionManager transactionManager = new RabbitTransactionManager(); transactionManager.setConnectionFactory(cachingConnectionFactory); return transactionManager; } @Bean("rabbitmqCachingConnectionFactory") public ConnectionFactory rabbitmqCachingConnectionFactory( RabbitmqEventBusProperties rabbitmqEventBusProperties, @Value("${spring.application.name}")String name) { CachingConnectionFactory connectionFactory= new CachingConnectionFactory(); connectionFactory.setUri(rabbitmqEventBusProperties.getBroker().getUrl()); connectionFactory.setUsername(rabbitmqEventBusProperties.getBroker().getUserName()); connectionFactory.setPassword(rabbitmqEventBusProperties.getBroker().getPassword()); if(nonNull(name)) { connectionFactory.setConnectionNameStrategy(conn ->name); } return connectionFactory; } }
UTF-8
Java
2,157
java
RabbitmqBrokerConfiguration.java
Java
[]
null
[]
package com.jinternals.event.bus.rabbitmq.configuration; import com.jinternals.event.bus.rabbitmq.properties.RabbitmqEventBusProperties; import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; import org.springframework.amqp.rabbit.transaction.RabbitTransactionManager; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.amqp.rabbit.connection.ConnectionFactory; import java.util.Objects; import static java.util.Objects.nonNull; @Configuration public class RabbitmqBrokerConfiguration { @ConditionalOnProperty(prefix = "event.bus.rabbitmq.consumer", name = "enabled", havingValue = "true", matchIfMissing = true) @Bean("rabbitmqTransactionManager") public PlatformTransactionManager rabbitmqTransactionManager( @Qualifier("rabbitmqCachingConnectionFactory") ConnectionFactory cachingConnectionFactory) { RabbitTransactionManager transactionManager = new RabbitTransactionManager(); transactionManager.setConnectionFactory(cachingConnectionFactory); return transactionManager; } @Bean("rabbitmqCachingConnectionFactory") public ConnectionFactory rabbitmqCachingConnectionFactory( RabbitmqEventBusProperties rabbitmqEventBusProperties, @Value("${spring.application.name}")String name) { CachingConnectionFactory connectionFactory= new CachingConnectionFactory(); connectionFactory.setUri(rabbitmqEventBusProperties.getBroker().getUrl()); connectionFactory.setUsername(rabbitmqEventBusProperties.getBroker().getUserName()); connectionFactory.setPassword(rabbitmqEventBusProperties.getBroker().getPassword()); if(nonNull(name)) { connectionFactory.setConnectionNameStrategy(conn ->name); } return connectionFactory; } }
2,157
0.800185
0.800185
48
43.9375
36.690941
129
false
false
0
0
0
0
0
0
0.541667
false
false
0
f3b65d2aa1b2f055fad921abb93cde332554fd24
20,675,972,620,331
52b28c9be89de5e2c6df3a6389648af1524c0ea1
/ide/org.eclipse.edt.ide.core/src/org/eclipse/edt/ide/core/internal/bindings/WorkspaceImportContainer.java
2c59795fddf1788b6656a37ae45aea526994bbdd
[]
no_license
eclipse/edt
https://github.com/eclipse/edt
3b033c4a5e4bf765a4c236649598c722be35d070
f99c34a72e3e3a6c0672cdb65086393112915087
refs/heads/master
2020-11-10T03:31:32.992000
2013-01-17T21:03:47
2013-01-17T21:03:47
5,970,664
2
3
null
null
null
null
null
null
null
null
null
null
null
null
null
/******************************************************************************* * Copyright ยฉ 2000, 2013 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.edt.ide.core.internal.bindings; /** * @author svihovec * * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. * To enable and disable the creation of type comments go to * Window>Preferences>Java>Code Generation. */ public class WorkspaceImportContainer extends AbstractImportContainer { public static final String DEFAULT_FOLDER_NAME = ""; //$NON-NLS-1$ /** * Constructor for WorkspaceImportContainer. * @param importStatement */ public WorkspaceImportContainer(String importStatement) { super(importStatement); } /** * @see com.ibm.etools.edt.common.internal.bindings.AbstractImportContainer#getDefaultFolderName() */ public String getDefaultFolderName() { return DEFAULT_FOLDER_NAME; } }
UTF-8
Java
1,346
java
WorkspaceImportContainer.java
Java
[ { "context": ".edt.ide.core.internal.bindings;\n\n\n\n/**\n * @author svihovec\n *\n * To change this generated comment edit the t", "end": 616, "score": 0.9978632926940918, "start": 608, "tag": "USERNAME", "value": "svihovec" } ]
null
[]
/******************************************************************************* * Copyright ยฉ 2000, 2013 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.edt.ide.core.internal.bindings; /** * @author svihovec * * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. * To enable and disable the creation of type comments go to * Window>Preferences>Java>Code Generation. */ public class WorkspaceImportContainer extends AbstractImportContainer { public static final String DEFAULT_FOLDER_NAME = ""; //$NON-NLS-1$ /** * Constructor for WorkspaceImportContainer. * @param importStatement */ public WorkspaceImportContainer(String importStatement) { super(importStatement); } /** * @see com.ibm.etools.edt.common.internal.bindings.AbstractImportContainer#getDefaultFolderName() */ public String getDefaultFolderName() { return DEFAULT_FOLDER_NAME; } }
1,346
0.665428
0.655762
43
30.27907
29.917969
99
false
false
0
0
0
0
0
0
0.511628
false
false
0
fce02ca6cc2bfcb863e3b1d56cbc5b900166ef3d
27,444,841,038,259
6dc1f8bbcd361aa35d8661badfcd8e26c6224593
/codigo-fonte/servico/src/main/java/br/med/maisvida/repository/EspecialidadeRepository.java
24bf4bf5dc78dc0eabf687887100d83f870a6524
[]
no_license
ygordanniel/maisvida
https://github.com/ygordanniel/maisvida
e2f9bf656c12a9b1c3e48581f9d570d16c146e9d
ae7134e795853c166c89a76577fbc7f3ad7909f8
refs/heads/master
2021-05-11T14:42:01.050000
2018-01-18T15:36:03
2018-01-18T15:36:03
117,708,803
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.med.maisvida.repository; import br.med.maisvida.model.Especialidade; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.stereotype.Repository; @Repository public interface EspecialidadeRepository extends JpaRepository<Especialidade, Long> , JpaSpecificationExecutor<Especialidade> { }
UTF-8
Java
409
java
EspecialidadeRepository.java
Java
[]
null
[]
package br.med.maisvida.repository; import br.med.maisvida.model.Especialidade; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.stereotype.Repository; @Repository public interface EspecialidadeRepository extends JpaRepository<Especialidade, Long> , JpaSpecificationExecutor<Especialidade> { }
409
0.860636
0.860636
10
39.900002
38.35479
127
false
false
0
0
0
0
0
0
0.7
false
false
0
e16a9f73b5f53f83634579cd62667e15c85a4a17
25,108,378,873,592
6782b0132e9c43d9013c182d2fea68dff6957000
/Acme-Chorbies/src/main/java/domain/Chorbi.java
eb303b04bbe9ca93b7ca33be7a62dc0304cdaa10
[]
no_license
josprigal/D-T2017-3
https://github.com/josprigal/D-T2017-3
50bb7c8a9a025c01c63d09827a8b2d3e011c5cde
d7ebc7deaf727cfb39eb97009a7ff2028d1b634c
refs/heads/master
2021-01-18T17:03:54.848000
2017-05-09T15:52:37
2017-05-09T15:52:37
86,785,790
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package domain; import java.util.Collection; import java.util.Date; import java.util.List; import javax.persistence.Access; import javax.persistence.AccessType; import javax.persistence.Entity; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotBlank; import org.hibernate.validator.constraints.URL; import org.joda.time.LocalDate; import org.joda.time.Period; import org.joda.time.PeriodType; import org.springframework.format.annotation.DateTimeFormat; @Entity @Access(AccessType.PROPERTY) public class Chorbi extends CreditCardUser { public enum Gender { MALE, FEMALE; @Override public String toString() { return super.toString(); } } public enum Relationship { ACTIVITIES, FRIENDSHIP, LOVE; @Override public String toString() { return super.toString(); } } public Chorbi() { super(); // TODO Auto-generated constructor stub this.banned = false; } private String description; private Date birth; private boolean banned; private String picture; private Relationship relationship; private Gender gender; private Integer age; private Collection<Likes> userLikedYou; private Collection<Likes> likedUsers; @NotNull public String getDescription() { return this.description; } public void setDescription(final String description) { this.description = description; } @NotNull @Temporal(TemporalType.TIMESTAMP) @DateTimeFormat(pattern = "dd/MM/yyyy") public Date getBirth() { return this.birth; } public void setBirth(final Date birth) { this.birth = birth; this.age = this.calculateAge(); } @NotBlank @URL public String getPicture() { return this.picture; } public void setPicture(final String picture) { this.picture = picture; } @NotNull public Relationship getRelationship() { return this.relationship; } public void setRelationship(final Relationship relationship) { this.relationship = relationship; } @NotNull public Gender getGender() { return this.gender; } public void setGender(final Gender gender) { this.gender = gender; } @NotNull public boolean isBanned() { return this.banned; } public void setBanned(final boolean banned) { this.banned = banned; } private Coordinates coordinates; private SearchTemplate searchTemplate; @OneToOne public Coordinates getCoordinates() { return this.coordinates; } public void setCoordinates(final Coordinates coordinates) { this.coordinates = coordinates; } @OneToOne public SearchTemplate getSearchTemplate() { return this.searchTemplate; } public void setSearchTemplate(final SearchTemplate searchTemplate) { this.searchTemplate = searchTemplate; } public Integer getAge() { return this.age; } public void setAge(final Integer age) { this.age = age; } public Integer calculateAge() { final LocalDate birthdate = new LocalDate(this.birth); //Birth date final LocalDate now = new LocalDate(); //Today's date final Period period = new Period(birthdate, now, PeriodType.yearMonthDay()); //Now access the values as below return period.getYears(); } @OneToMany(mappedBy = "recipent") public Collection<Likes> getUserLikedYou() { return this.userLikedYou; } public void setUserLikedYou(final Collection<Likes> userLikedYou) { this.userLikedYou = userLikedYou; } @OneToMany(mappedBy = "sender") public Collection<Likes> getLikedUsers() { return this.likedUsers; } public void setLikedUsers(final Collection<Likes> likedUsers) { this.likedUsers = likedUsers; } private List<Event> events; @ManyToMany(mappedBy = "chorbies") public List<Event> getEvents() { return this.events; } public void setEvents(final List<Event> events) { this.events = events; } }
UTF-8
Java
3,982
java
Chorbi.java
Java
[ { "context": "edYou = userLikedYou;\n\t}\n\n\t@OneToMany(mappedBy = \"sender\")\n\tpublic Collection<Likes> getLikedUsers() {\n\t\tr", "end": 3593, "score": 0.5679565668106079, "start": 3587, "tag": "USERNAME", "value": "sender" }, { "context": "te List<Event>\tevents;\n\n\n\t@ManyToMany(mappedBy = \"chorbies\")\n\tpublic List<Event> getEvents() {\n\t\treturn this", "end": 3838, "score": 0.999146044254303, "start": 3830, "tag": "USERNAME", "value": "chorbies" } ]
null
[]
package domain; import java.util.Collection; import java.util.Date; import java.util.List; import javax.persistence.Access; import javax.persistence.AccessType; import javax.persistence.Entity; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotBlank; import org.hibernate.validator.constraints.URL; import org.joda.time.LocalDate; import org.joda.time.Period; import org.joda.time.PeriodType; import org.springframework.format.annotation.DateTimeFormat; @Entity @Access(AccessType.PROPERTY) public class Chorbi extends CreditCardUser { public enum Gender { MALE, FEMALE; @Override public String toString() { return super.toString(); } } public enum Relationship { ACTIVITIES, FRIENDSHIP, LOVE; @Override public String toString() { return super.toString(); } } public Chorbi() { super(); // TODO Auto-generated constructor stub this.banned = false; } private String description; private Date birth; private boolean banned; private String picture; private Relationship relationship; private Gender gender; private Integer age; private Collection<Likes> userLikedYou; private Collection<Likes> likedUsers; @NotNull public String getDescription() { return this.description; } public void setDescription(final String description) { this.description = description; } @NotNull @Temporal(TemporalType.TIMESTAMP) @DateTimeFormat(pattern = "dd/MM/yyyy") public Date getBirth() { return this.birth; } public void setBirth(final Date birth) { this.birth = birth; this.age = this.calculateAge(); } @NotBlank @URL public String getPicture() { return this.picture; } public void setPicture(final String picture) { this.picture = picture; } @NotNull public Relationship getRelationship() { return this.relationship; } public void setRelationship(final Relationship relationship) { this.relationship = relationship; } @NotNull public Gender getGender() { return this.gender; } public void setGender(final Gender gender) { this.gender = gender; } @NotNull public boolean isBanned() { return this.banned; } public void setBanned(final boolean banned) { this.banned = banned; } private Coordinates coordinates; private SearchTemplate searchTemplate; @OneToOne public Coordinates getCoordinates() { return this.coordinates; } public void setCoordinates(final Coordinates coordinates) { this.coordinates = coordinates; } @OneToOne public SearchTemplate getSearchTemplate() { return this.searchTemplate; } public void setSearchTemplate(final SearchTemplate searchTemplate) { this.searchTemplate = searchTemplate; } public Integer getAge() { return this.age; } public void setAge(final Integer age) { this.age = age; } public Integer calculateAge() { final LocalDate birthdate = new LocalDate(this.birth); //Birth date final LocalDate now = new LocalDate(); //Today's date final Period period = new Period(birthdate, now, PeriodType.yearMonthDay()); //Now access the values as below return period.getYears(); } @OneToMany(mappedBy = "recipent") public Collection<Likes> getUserLikedYou() { return this.userLikedYou; } public void setUserLikedYou(final Collection<Likes> userLikedYou) { this.userLikedYou = userLikedYou; } @OneToMany(mappedBy = "sender") public Collection<Likes> getLikedUsers() { return this.likedUsers; } public void setLikedUsers(final Collection<Likes> likedUsers) { this.likedUsers = likedUsers; } private List<Event> events; @ManyToMany(mappedBy = "chorbies") public List<Event> getEvents() { return this.events; } public void setEvents(final List<Event> events) { this.events = events; } }
3,982
0.739076
0.739076
199
19.005026
19.07312
78
false
false
0
0
0
0
0
0
1.371859
false
false
0
af2d75a473677f36d61d732fe32d01961e503079
32,555,852,131,088
e287354499368b8c38a67c74d63d27ac3aa9f0eb
/MaxOccurringChar.java
11fcefd1d83f0a555560a5cc639e37df95013345
[]
no_license
dhanashreepande/String-Programs
https://github.com/dhanashreepande/String-Programs
0839930b350aa4ccc2580cb50eaf1ba859b7c705
0515404b2ef0371c73f113bf64b2afbf93b2a3aa
refs/heads/main
2023-03-21T09:47:58.004000
2021-03-14T09:24:54
2021-03-14T09:24:54
343,164,383
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//Write a program to find the maximum occurring character in a string. package stringpractice; public class MaxOccurringChar { public static void main(String[] args) { String s = "fchgfghcfdgdgfcfgcfc"; char c[] = s.toCharArray(); int n=0; char ch = ' '; for(int i = 0;i<c.length;i++) { int cnt = 1; for(int j = i+1;j<c.length;j++) { if(c[i] == c[j]) { cnt++; } } if(n<cnt) { n = cnt; ch = c[i]; } } System.out.println(ch+" max "+n); } }
UTF-8
Java
539
java
MaxOccurringChar.java
Java
[]
null
[]
//Write a program to find the maximum occurring character in a string. package stringpractice; public class MaxOccurringChar { public static void main(String[] args) { String s = "fchgfghcfdgdgfcfgcfc"; char c[] = s.toCharArray(); int n=0; char ch = ' '; for(int i = 0;i<c.length;i++) { int cnt = 1; for(int j = i+1;j<c.length;j++) { if(c[i] == c[j]) { cnt++; } } if(n<cnt) { n = cnt; ch = c[i]; } } System.out.println(ch+" max "+n); } }
539
0.512059
0.504638
32
14.90625
15.782426
70
false
false
0
0
0
0
0
0
2.53125
false
false
0
3444cc572e4eae2e694fa4f14f241e1d063af942
22,402,549,422,045
04e6f5fe32f9b78edb3ce38076952b3b91cfc76c
/If3.java
cb039a67bf39eb237a6c162b740dd74cc7548a2d
[]
no_license
ohkkkkk/Java
https://github.com/ohkkkkk/Java
e2e59bfe26b59c35fe282c06194227f0848209cc
b5f0d1c3c62012c77512630878617491db273543
refs/heads/master
2023-03-20T23:05:00.560000
2021-02-25T14:44:32
2021-02-25T14:44:32
335,271,382
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package test; /* * if่ฏญๅฅๆ ผๅผ3 * if๏ผˆๅ…ณ็ณป่กจ่พพๅผ๏ผ‰{ * ่ฏญๅฅไฝ“1; * }else if๏ผˆๅ…ณ็ณป่กจ่พพๅผ2๏ผ‰{ * ่ฏญๅฅไฝ“2; * } * ...... * else{ * ่ฏญๅฅไฝ“n + 1; * } * ๆ‰ง่กŒๆต็จ‹๏ผš * 1.่ฎก็ฎ—ๅ…ณ็ณป่กจ่พพๅผ1็š„ๅ€ผ * 2.ๅ€ผไธบtrueๆ‰ง่กŒ่ฏญๅฅไฝ“1๏ผŒๅ€ผไธบfalse่ฎก็ฎ—ๅ…ณ็ณป่กจ่พพๅผ2็š„ๅ€ผ * 3.ๅ€ผไธบtrueๆ‰ง่กŒ่ฏญๅฅไฝ“2๏ผŒๅ€ผไธบfalse่ฎก็ฎ—ๅ…ณ็ณป่กจ่พพๅผ3็š„ๅ€ผ * 4...... * 5.ๅฆ‚ๆžœๆฒกๆœ‰ไปปไฝ•ๅ…ณ็ณป่กจ่พพๅผๅ€ผไธบtrue๏ผŒๅฐฑๆ‰ง่กŒ่ฏญๅฅไฝ“n+1 */ import java.util.Scanner; public class If3 { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("-----start-----"); Scanner sc = new Scanner(System.in); System.out.println("Please enter a weekday(1-7):"); int week = sc.nextInt(); if(week == 1) { System.out.println("Monday"); }else if(week == 2) { System.out.println("Tuesday"); }else if(week == 3) { System.out.println("Wednesday"); }else if(week == 4) { System.out.println("Thursday"); }else if(week == 5) { System.out.println("Friday"); }else if(week == 6) { System.out.println("Saturday"); }else if(week == 7) { System.out.println("Sunday"); } System.out.println("-----end-----"); } }
GB18030
Java
1,219
java
If3.java
Java
[]
null
[]
package test; /* * if่ฏญๅฅๆ ผๅผ3 * if๏ผˆๅ…ณ็ณป่กจ่พพๅผ๏ผ‰{ * ่ฏญๅฅไฝ“1; * }else if๏ผˆๅ…ณ็ณป่กจ่พพๅผ2๏ผ‰{ * ่ฏญๅฅไฝ“2; * } * ...... * else{ * ่ฏญๅฅไฝ“n + 1; * } * ๆ‰ง่กŒๆต็จ‹๏ผš * 1.่ฎก็ฎ—ๅ…ณ็ณป่กจ่พพๅผ1็š„ๅ€ผ * 2.ๅ€ผไธบtrueๆ‰ง่กŒ่ฏญๅฅไฝ“1๏ผŒๅ€ผไธบfalse่ฎก็ฎ—ๅ…ณ็ณป่กจ่พพๅผ2็š„ๅ€ผ * 3.ๅ€ผไธบtrueๆ‰ง่กŒ่ฏญๅฅไฝ“2๏ผŒๅ€ผไธบfalse่ฎก็ฎ—ๅ…ณ็ณป่กจ่พพๅผ3็š„ๅ€ผ * 4...... * 5.ๅฆ‚ๆžœๆฒกๆœ‰ไปปไฝ•ๅ…ณ็ณป่กจ่พพๅผๅ€ผไธบtrue๏ผŒๅฐฑๆ‰ง่กŒ่ฏญๅฅไฝ“n+1 */ import java.util.Scanner; public class If3 { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("-----start-----"); Scanner sc = new Scanner(System.in); System.out.println("Please enter a weekday(1-7):"); int week = sc.nextInt(); if(week == 1) { System.out.println("Monday"); }else if(week == 2) { System.out.println("Tuesday"); }else if(week == 3) { System.out.println("Wednesday"); }else if(week == 4) { System.out.println("Thursday"); }else if(week == 5) { System.out.println("Friday"); }else if(week == 6) { System.out.println("Saturday"); }else if(week == 7) { System.out.println("Sunday"); } System.out.println("-----end-----"); } }
1,219
0.590597
0.565132
52
18.634615
14.084947
53
false
false
0
0
0
0
0
0
1.538462
false
false
0
ec3523b8c601d1a23d0d940216e6c6f9acd7845c
35,579,509,132,864
1001b40792b6748e643dcf7fe93db1926109792e
/app/src/main/java/com/icon/bluetooth/CommunicationThread.java
724fb04e05af7b82312060f9d5ba3c1b1f473722
[]
no_license
gee12/BluetoothApp
https://github.com/gee12/BluetoothApp
f71ba5b84b43abe5265ad093f43e8c1a028291f4
20ebabbf4f02a1c120b7526a078ea3b42bb446c9
refs/heads/master
2021-01-10T11:18:49.239000
2015-10-29T15:24:23
2015-10-29T15:24:23
43,936,213
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.icon.bluetooth; import android.bluetooth.BluetoothSocket; import android.util.Log; import com.icon.agnks.Bluetooth; import com.icon.agnks.Logger; import com.icon.utils.Utils; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; public class CommunicationThread extends Thread implements Communicator { public interface CommunicationListener { void onMessage(byte[] bytes); void onResponceTimeElapsed(); } private final BluetoothSocket socket; private final InputStream inputStream; private final OutputStream outputStream; private final CommunicationListener listener; public CommunicationThread(BluetoothSocket socket, CommunicationListener listener) { this.socket = socket; this.listener = listener; InputStream tmpIn = null; OutputStream tmpOut = null; try { tmpIn = socket.getInputStream(); tmpOut = socket.getOutputStream(); } catch (IOException ex) { Logger.add("CommunicationThread: Create InputStream,OutputStream", ex); } inputStream = tmpIn; outputStream = tmpOut; } @Override public void listenMessage() { if (listener == null) { Logger.add("CommunicationThread: CommunicationListener object is null", Log.ERROR, true); return; } byte[] buffer = new byte[1024]; int bytes; int responceMsec = Bluetooth.MaxTimeout; long startTime = System.currentTimeMillis(); while (startTime + responceMsec > System.currentTimeMillis()) { try { if (inputStream.available() != 0) { // read responce bytes = inputStream.read(buffer); Logger.add("CommunicationThread: Read " + bytes + " bytes", Log.DEBUG); listener.onMessage(Arrays.copyOfRange(buffer, 0, bytes)); return; } } catch (IOException ex) { Logger.add("CommunicationThread: Run the communicator", ex); break; } } // listener.onResponceTimeElapsed(); Logger.add("CommunicationThread: Responce time " + responceMsec + " (msec) elapsed", Log.DEBUG); } public void write(byte[] bytes) { try { Logger.add("CommunicationThread: Write: [" + Utils.toString(bytes, ",", Utils.RADIX_HEX) + "]", Log.DEBUG); outputStream.write(bytes); } catch (IOException ex) { Logger.add("CommunicationThread: Write to OutputStream", ex); } } @Override public void writeAndListenResponce(byte[] bytes) { try { Logger.add("CommunicationThread: Write: [" + Utils.toString(bytes, ",", Utils.RADIX_HEX) + "]", Log.DEBUG); outputStream.write(bytes); new Thread(new Runnable() { @Override public void run() { Logger.add("CommunicationThread: listenMessage()", Log.DEBUG); listenMessage(); } }).start(); } catch (IOException ex) { Logger.add("CommunicationThread: writeAndListenResponce()", ex); } } @Override public void stopCommunication() { try { socket.close(); } catch (IOException ex) { Logger.add("CommunicationThread: Close BluetoothSocket", ex); } } }
UTF-8
Java
3,558
java
CommunicationThread.java
Java
[]
null
[]
package com.icon.bluetooth; import android.bluetooth.BluetoothSocket; import android.util.Log; import com.icon.agnks.Bluetooth; import com.icon.agnks.Logger; import com.icon.utils.Utils; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; public class CommunicationThread extends Thread implements Communicator { public interface CommunicationListener { void onMessage(byte[] bytes); void onResponceTimeElapsed(); } private final BluetoothSocket socket; private final InputStream inputStream; private final OutputStream outputStream; private final CommunicationListener listener; public CommunicationThread(BluetoothSocket socket, CommunicationListener listener) { this.socket = socket; this.listener = listener; InputStream tmpIn = null; OutputStream tmpOut = null; try { tmpIn = socket.getInputStream(); tmpOut = socket.getOutputStream(); } catch (IOException ex) { Logger.add("CommunicationThread: Create InputStream,OutputStream", ex); } inputStream = tmpIn; outputStream = tmpOut; } @Override public void listenMessage() { if (listener == null) { Logger.add("CommunicationThread: CommunicationListener object is null", Log.ERROR, true); return; } byte[] buffer = new byte[1024]; int bytes; int responceMsec = Bluetooth.MaxTimeout; long startTime = System.currentTimeMillis(); while (startTime + responceMsec > System.currentTimeMillis()) { try { if (inputStream.available() != 0) { // read responce bytes = inputStream.read(buffer); Logger.add("CommunicationThread: Read " + bytes + " bytes", Log.DEBUG); listener.onMessage(Arrays.copyOfRange(buffer, 0, bytes)); return; } } catch (IOException ex) { Logger.add("CommunicationThread: Run the communicator", ex); break; } } // listener.onResponceTimeElapsed(); Logger.add("CommunicationThread: Responce time " + responceMsec + " (msec) elapsed", Log.DEBUG); } public void write(byte[] bytes) { try { Logger.add("CommunicationThread: Write: [" + Utils.toString(bytes, ",", Utils.RADIX_HEX) + "]", Log.DEBUG); outputStream.write(bytes); } catch (IOException ex) { Logger.add("CommunicationThread: Write to OutputStream", ex); } } @Override public void writeAndListenResponce(byte[] bytes) { try { Logger.add("CommunicationThread: Write: [" + Utils.toString(bytes, ",", Utils.RADIX_HEX) + "]", Log.DEBUG); outputStream.write(bytes); new Thread(new Runnable() { @Override public void run() { Logger.add("CommunicationThread: listenMessage()", Log.DEBUG); listenMessage(); } }).start(); } catch (IOException ex) { Logger.add("CommunicationThread: writeAndListenResponce()", ex); } } @Override public void stopCommunication() { try { socket.close(); } catch (IOException ex) { Logger.add("CommunicationThread: Close BluetoothSocket", ex); } } }
3,558
0.588252
0.586565
111
31.063063
27.447666
119
false
false
0
0
0
0
0
0
0.648649
false
false
0
20024ed8ed6c3a8c324798cda9c8cab9388dd2c8
5,660,766,943,766
97b534f96b0b076299a8e9ac1f41db189c60ac24
/src/chapter2/designpattern/abstractfactory/IEat.java
8e89d8a0485ae0a124ac15a35ec7e4ee1b009f13
[]
no_license
yichuancq/Java8_learning
https://github.com/yichuancq/Java8_learning
9a936111686187b2f452c7f2ad9e52f11f188443
ed791f43d0f1b0835529ded25a66d5b21d1b08c0
refs/heads/master
2020-09-21T18:49:33.138000
2020-04-05T04:16:08
2020-04-05T04:16:08
224,889,263
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package chapter2.designpattern.abstractfactory; /** * ๅƒ็š„ๆŽฅๅฃ */ public interface IEat { void eat(); }
UTF-8
Java
116
java
IEat.java
Java
[]
null
[]
package chapter2.designpattern.abstractfactory; /** * ๅƒ็š„ๆŽฅๅฃ */ public interface IEat { void eat(); }
116
0.675926
0.666667
9
11
14.689377
47
false
false
0
0
0
0
0
0
0.222222
false
false
0
351f588eb4aa1e439a017573a57418921c1a308f
12,094,627,953,598
2e53de3077b9411bb8a92188c5ac507e060be42f
/src/main/java/com/tenjava/entries/MarianDCrafter/t2/util/ConfirmDialogInventory.java
75c5e493f0a3ca8331c14dbb274a7ba2a03a9ede
[]
no_license
tenjava/MarianDCrafter-t2
https://github.com/tenjava/MarianDCrafter-t2
a82b7e809b3032ac937f58043cc720d1574ffb7a
f1260859ec621cb7b8f016156be6b069d0d6c4a6
refs/heads/master
2021-01-22T11:07:01.223000
2014-07-12T18:59:41
2014-07-12T18:59:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tenjava.entries.MarianDCrafter.t2.util; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.player.PlayerKickEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.inventory.Inventory; /** * Represents an inventory where the user can click on YES or NO. * If he clicks on YES, the given Runnable will be executed. */ public abstract class ConfirmDialogInventory implements Listener { private final static int SLOT_YES = 11, SLOT_NO = 15; private Runnable onYes; private Inventory inventory; private Player player; /** * Initializes the ConfirmDialogInventory with the player, the 'onYes' Runnable and the name of the inventory. * The name of the inventory is usually a question like 'Destroy Bag?' * @param player the player * @param onYes the runnable which will be executed if the player clicks on 'YES' * @param name the name or question of this view */ public ConfirmDialogInventory(Player player, Runnable onYes, String name) { this.onYes = onYes; this.player = player; inventory = Bukkit.createInventory(player, 27, name); inventory.setItem(SLOT_YES, ItemStackUtils.itemStack(Material.WOOL, 1, (short) 5, "ยงaยงlYES")); inventory.setItem(SLOT_NO, ItemStackUtils.itemStack(Material.WOOL, 1, (short) 14, "ยงcยงlNO")); player.openInventory(inventory); } /** * Called when a player closes the inventory. * Used to unregister this listener from the list, if it was the right player. */ @EventHandler public void onInventoryClose(InventoryCloseEvent event) { if (event.getPlayer() == player) HandlerList.unregisterAll(this); } /** * Called when a player quits the game. * Used to unregister this listener from the list, if it was the right player. */ @EventHandler public void onLeave(PlayerQuitEvent event) { if (event.getPlayer() == player) HandlerList.unregisterAll(this); } /** * Called when a player is kicked from the server. * Used to unregister this listener from the list, if it was the right player. */ @EventHandler public void onKick(PlayerKickEvent event) { if (event.getPlayer() == player) HandlerList.unregisterAll(this); } /** * Called when a player clicks in his inventory * Used to call the 'onYes' Runnable, if the player has clicked on 'YES'. * Also unregister this listener, if the player has clicked on 'YES' or 'NO' and closes this inventory. */ @EventHandler public void onClick(InventoryClickEvent event) { if (event.getWhoClicked() != player || event.getSlot() != event.getRawSlot()) return; event.setCancelled(true); if(event.getSlot() == SLOT_YES) { HandlerList.unregisterAll(this); player.closeInventory(); onYes.run(); } else if(event.getSlot() == SLOT_NO) { HandlerList.unregisterAll(this); player.closeInventory(); } } }
UTF-8
Java
3,423
java
ConfirmDialogInventory.java
Java
[]
null
[]
package com.tenjava.entries.MarianDCrafter.t2.util; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.player.PlayerKickEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.inventory.Inventory; /** * Represents an inventory where the user can click on YES or NO. * If he clicks on YES, the given Runnable will be executed. */ public abstract class ConfirmDialogInventory implements Listener { private final static int SLOT_YES = 11, SLOT_NO = 15; private Runnable onYes; private Inventory inventory; private Player player; /** * Initializes the ConfirmDialogInventory with the player, the 'onYes' Runnable and the name of the inventory. * The name of the inventory is usually a question like 'Destroy Bag?' * @param player the player * @param onYes the runnable which will be executed if the player clicks on 'YES' * @param name the name or question of this view */ public ConfirmDialogInventory(Player player, Runnable onYes, String name) { this.onYes = onYes; this.player = player; inventory = Bukkit.createInventory(player, 27, name); inventory.setItem(SLOT_YES, ItemStackUtils.itemStack(Material.WOOL, 1, (short) 5, "ยงaยงlYES")); inventory.setItem(SLOT_NO, ItemStackUtils.itemStack(Material.WOOL, 1, (short) 14, "ยงcยงlNO")); player.openInventory(inventory); } /** * Called when a player closes the inventory. * Used to unregister this listener from the list, if it was the right player. */ @EventHandler public void onInventoryClose(InventoryCloseEvent event) { if (event.getPlayer() == player) HandlerList.unregisterAll(this); } /** * Called when a player quits the game. * Used to unregister this listener from the list, if it was the right player. */ @EventHandler public void onLeave(PlayerQuitEvent event) { if (event.getPlayer() == player) HandlerList.unregisterAll(this); } /** * Called when a player is kicked from the server. * Used to unregister this listener from the list, if it was the right player. */ @EventHandler public void onKick(PlayerKickEvent event) { if (event.getPlayer() == player) HandlerList.unregisterAll(this); } /** * Called when a player clicks in his inventory * Used to call the 'onYes' Runnable, if the player has clicked on 'YES'. * Also unregister this listener, if the player has clicked on 'YES' or 'NO' and closes this inventory. */ @EventHandler public void onClick(InventoryClickEvent event) { if (event.getWhoClicked() != player || event.getSlot() != event.getRawSlot()) return; event.setCancelled(true); if(event.getSlot() == SLOT_YES) { HandlerList.unregisterAll(this); player.closeInventory(); onYes.run(); } else if(event.getSlot() == SLOT_NO) { HandlerList.unregisterAll(this); player.closeInventory(); } } }
3,423
0.665399
0.661889
98
33.887756
27.816044
114
false
false
0
0
0
0
0
0
0.55102
false
false
0
a919f73da7c1941787f2eeaaa512dcb1822658ac
7,138,235,695,957
7333cdaa2bd3980d4f82fbb4e0570967d516472f
/core/src/main/java/zm/gov/moh/core/repository/database/entity/domain/PatientIdentifierType.java
78b6ecd816ceb902cb2e8894f84db4c33792fc87
[]
no_license
k9uma/smartcerv
https://github.com/k9uma/smartcerv
55b2bb703b0a61b9caa680a7f6cce5401a46e79b
11ed0343b297e890d80add49969957d2c13636b5
refs/heads/master
2020-08-23T01:57:01.836000
2019-06-03T12:32:25
2019-06-03T12:32:25
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package zm.gov.moh.core.repository.database.entity.domain; import androidx.room.*; import org.threeten.bp.LocalDateTime; @Entity(tableName = "patient_identifier_type") public class PatientIdentifierType { @PrimaryKey public Long patient_identifier_type_id; public String name; public String description; public String format; public short check_digit; public Long creator; public LocalDateTime date_created; public short required; public String format_description; public String validator; public String location_behavior; public short retired; public Long retired_by; public LocalDateTime date_retired; public String retired_reason; public String uuid; public String uniqueness_behavior; public LocalDateTime date_changed; public Long changed_by; }
UTF-8
Java
833
java
PatientIdentifierType.java
Java
[]
null
[]
package zm.gov.moh.core.repository.database.entity.domain; import androidx.room.*; import org.threeten.bp.LocalDateTime; @Entity(tableName = "patient_identifier_type") public class PatientIdentifierType { @PrimaryKey public Long patient_identifier_type_id; public String name; public String description; public String format; public short check_digit; public Long creator; public LocalDateTime date_created; public short required; public String format_description; public String validator; public String location_behavior; public short retired; public Long retired_by; public LocalDateTime date_retired; public String retired_reason; public String uuid; public String uniqueness_behavior; public LocalDateTime date_changed; public Long changed_by; }
833
0.743097
0.743097
29
27.724138
13.811281
58
false
false
0
0
0
0
0
0
0.758621
false
false
0
f48edad3be9ba14e2458750e1f162f3451a2811b
1,254,130,511,820
351c9510f759fb639f34eedab80c5bd39ffbac59
/SeleniumBasedTests/src/test/java/tests/pages/TestGoogleSearch.java
fc4a68b3ddb89320cc498a8180a8a9dea92d3dfc
[]
no_license
Sharin/server-api-tests
https://github.com/Sharin/server-api-tests
c006212569931122d4decfd95fccdc724d7b81c1
3f91e187e2a09163a61715b3d7521f732d8d59d5
refs/heads/master
2022-12-29T21:33:24.698000
2020-05-18T07:00:56
2020-05-18T07:00:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tests.pages; import org.openqa.selenium.WebDriver; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import pages.GoogleSearchPage; import java.util.concurrent.TimeUnit; public class TestGoogleSearch { WebDriver driver; @BeforeTest public void setup(){ // TODO change the driver to be a one selected from a configuration file driver = new HtmlUnitDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.get(GoogleSearchPage.GOOGLE_ADDRESS); } /** * Test */ @Test(priority=0) public void test_Search_Key_Word(){ GoogleSearchPage gsp = new GoogleSearchPage(this.driver); gsp.searchGoogle("facebook logout"); // Check the title of the page System.out.println("Page title is: " + driver.getTitle()); String result = gsp.getFirstResult(); System.out.println("Result was : " + result); driver.quit(); } }
UTF-8
Java
1,052
java
TestGoogleSearch.java
Java
[]
null
[]
package tests.pages; import org.openqa.selenium.WebDriver; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import pages.GoogleSearchPage; import java.util.concurrent.TimeUnit; public class TestGoogleSearch { WebDriver driver; @BeforeTest public void setup(){ // TODO change the driver to be a one selected from a configuration file driver = new HtmlUnitDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.get(GoogleSearchPage.GOOGLE_ADDRESS); } /** * Test */ @Test(priority=0) public void test_Search_Key_Word(){ GoogleSearchPage gsp = new GoogleSearchPage(this.driver); gsp.searchGoogle("facebook logout"); // Check the title of the page System.out.println("Page title is: " + driver.getTitle()); String result = gsp.getFirstResult(); System.out.println("Result was : " + result); driver.quit(); } }
1,052
0.673954
0.671103
39
25.97436
23.026726
80
false
false
0
0
0
0
0
0
0.461538
false
false
0
cea6cc5c4428c33a5084ec7feece740898ffc71c
3,229,815,462,413
11691fa120cabc67e246d59944585bf9006f3a32
/Proy2_pizza/src/java/ServiciosDB/ServicioDBUsuario.java
f1c27b5339268489a71a23844faf872f3d21efc9
[]
no_license
hostname2/Proy_pizza
https://github.com/hostname2/Proy_pizza
a703884c06af4a31e3ba8cba61fe5c3abe30412b
39c18d26cc6e1522392ac92054a62a34214071af
refs/heads/master
2022-11-08T15:21:48.897000
2020-06-27T22:05:36
2020-06-27T22:05:36
274,290,709
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 ServiciosDB; import Datos.BaseDatos; import Model.Cliente; import Model.Usuario; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; /** * * @author sebas */ public class ServicioDBUsuario { public Usuario obtenerUsuariobyUser(String user) { Usuario r = null; try (Connection cnx = obtenerConexion(); PreparedStatement stm = cnx.prepareStatement(CMD_RECUPERAR_BY_USER);) { stm.clearParameters(); stm.setString(1, user); try (ResultSet rs = stm.executeQuery()) { if (rs.next()) { r = new Usuario( user, rs.getString("clave"), rs.getShort("tipo") ); } } } catch (IOException | ClassNotFoundException | IllegalAccessException | InstantiationException | SQLException ex) { System.err.printf("Excepciรณn: '%s'%n", ex.getMessage()); } return r; } public void agregarUser(Usuario u) { try (Connection cnx = obtenerConexion(); PreparedStatement stm = cnx.prepareStatement(CMD_INSERTAR)) { stm.clearParameters(); stm.setString(1, u.getIdUsuario()); stm.setString(2, u.getClave()); stm.setInt(3, u.getTipo()); if (stm.executeUpdate() != 1) { throw new Exception("Error no determinado"); } } catch (Exception ex) { System.err.printf("Excepciรณn: '%s'%n", ex.getMessage()); } } public void actualizarUser(Usuario u) { try (Connection cnx = obtenerConexion(); PreparedStatement stm = cnx.prepareStatement(CMD_ACTUALIZAR)) { stm.clearParameters(); stm.setString(1, u.getClave()); stm.setString(2, u.getIdUsuario()); if (stm.executeUpdate() != 1) { throw new Exception("Error no determinado"); } } catch (Exception ex) { System.err.printf("Excepciรณn: '%s'%n", ex.getMessage()); } } public Connection obtenerConexion() throws ClassNotFoundException, IllegalAccessException, InstantiationException, IOException, SQLException { BaseDatos bd = BaseDatos.obtenerInstancia(); Properties cfg = bd.obtenerConfiguracion(); Connection cnx = bd.obtenerConexion( cfg.getProperty("database"), cfg.getProperty("user"), cfg.getProperty("password") ); return cnx; } private static final String CMD_ACTUALIZAR = "UPDATE Cliente SET clave=? where idUsuario=?; "; private static final String CMD_INSERTAR = "INSERT INTO Usuario " + "(idUsuario, clave, tipo) " + "VALUES(?, ?, ?); "; private static final String CMD_RECUPERAR_BY_USER = "SELECT clave, tipo FROM Usuario where idUsuario =?; "; }
UTF-8
Java
3,460
java
ServicioDBUsuario.java
Java
[ { "context": "n;\nimport java.util.Properties;\n\n/**\n *\n * @author sebas\n */\npublic class ServicioDBUsuario {\n \n ", "end": 476, "score": 0.9996151924133301, "start": 471, "tag": "USERNAME", "value": "sebas" } ]
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 ServiciosDB; import Datos.BaseDatos; import Model.Cliente; import Model.Usuario; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; /** * * @author sebas */ public class ServicioDBUsuario { public Usuario obtenerUsuariobyUser(String user) { Usuario r = null; try (Connection cnx = obtenerConexion(); PreparedStatement stm = cnx.prepareStatement(CMD_RECUPERAR_BY_USER);) { stm.clearParameters(); stm.setString(1, user); try (ResultSet rs = stm.executeQuery()) { if (rs.next()) { r = new Usuario( user, rs.getString("clave"), rs.getShort("tipo") ); } } } catch (IOException | ClassNotFoundException | IllegalAccessException | InstantiationException | SQLException ex) { System.err.printf("Excepciรณn: '%s'%n", ex.getMessage()); } return r; } public void agregarUser(Usuario u) { try (Connection cnx = obtenerConexion(); PreparedStatement stm = cnx.prepareStatement(CMD_INSERTAR)) { stm.clearParameters(); stm.setString(1, u.getIdUsuario()); stm.setString(2, u.getClave()); stm.setInt(3, u.getTipo()); if (stm.executeUpdate() != 1) { throw new Exception("Error no determinado"); } } catch (Exception ex) { System.err.printf("Excepciรณn: '%s'%n", ex.getMessage()); } } public void actualizarUser(Usuario u) { try (Connection cnx = obtenerConexion(); PreparedStatement stm = cnx.prepareStatement(CMD_ACTUALIZAR)) { stm.clearParameters(); stm.setString(1, u.getClave()); stm.setString(2, u.getIdUsuario()); if (stm.executeUpdate() != 1) { throw new Exception("Error no determinado"); } } catch (Exception ex) { System.err.printf("Excepciรณn: '%s'%n", ex.getMessage()); } } public Connection obtenerConexion() throws ClassNotFoundException, IllegalAccessException, InstantiationException, IOException, SQLException { BaseDatos bd = BaseDatos.obtenerInstancia(); Properties cfg = bd.obtenerConfiguracion(); Connection cnx = bd.obtenerConexion( cfg.getProperty("database"), cfg.getProperty("user"), cfg.getProperty("password") ); return cnx; } private static final String CMD_ACTUALIZAR = "UPDATE Cliente SET clave=? where idUsuario=?; "; private static final String CMD_INSERTAR = "INSERT INTO Usuario " + "(idUsuario, clave, tipo) " + "VALUES(?, ?, ?); "; private static final String CMD_RECUPERAR_BY_USER = "SELECT clave, tipo FROM Usuario where idUsuario =?; "; }
3,460
0.554527
0.552213
110
30.427273
21.765886
87
false
false
0
0
0
0
0
0
0.636364
false
false
0
c5e4f62925b76de91cf0ed1d8d13696032d424aa
7,524,782,758,336
17ffcfac1a8a5bdf814e4ab5cefd530183ae7d2a
/Main.java
8836475299e14be6f52dd35ca0228e5368033022
[]
no_license
DevStephi/Ejercicio5_BootCamp
https://github.com/DevStephi/Ejercicio5_BootCamp
7c5918495375bff65c4e632fcbbd8a0dac34ae49
bf0747d742f2a441e125ac0b3daaa1d481e57642
refs/heads/main
2023-09-06T01:12:06.168000
2021-11-06T12:28:18
2021-11-06T12:28:18
425,238,161
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Clases; public class Main { static CocheCRUD cocheCRUD = new CocheCRUDImpl(); public static void main(String[] args) { CocheCRUDImpl bmw = new CocheCRUDImpl("BMW", "Serie 1"); CocheCRUDImpl audi = new CocheCRUDImpl("Audi", "TT"); cocheCRUD.save(bmw); cocheCRUD.save(audi); cocheCRUD.findAll(); // cocheCRUD.save(new CocheCRUDImpl()); // cocheCRUD.delete(new CocheCRUDImpl()); cocheCRUD.delete(audi); System.out.println(bmw); System.out.println(audi); } }
UTF-8
Java
561
java
Main.java
Java
[]
null
[]
package Clases; public class Main { static CocheCRUD cocheCRUD = new CocheCRUDImpl(); public static void main(String[] args) { CocheCRUDImpl bmw = new CocheCRUDImpl("BMW", "Serie 1"); CocheCRUDImpl audi = new CocheCRUDImpl("Audi", "TT"); cocheCRUD.save(bmw); cocheCRUD.save(audi); cocheCRUD.findAll(); // cocheCRUD.save(new CocheCRUDImpl()); // cocheCRUD.delete(new CocheCRUDImpl()); cocheCRUD.delete(audi); System.out.println(bmw); System.out.println(audi); } }
561
0.614973
0.613191
24
22.375
21.468605
64
false
false
0
0
0
0
0
0
0.583333
false
false
0
3152d87ef19d8b862b18882914a36374f344189d
17,772,574,719,032
2ca4232facc84e7b4e996d80ddb88ce8beaa66d3
/Samples2/localisation/src/main/java/com/example/localisation/MainActivity.java
b25082ac637d172fb2825cad306ca925a5ebc253
[]
no_license
ticou973/ChatApp
https://github.com/ticou973/ChatApp
b6b5c2a57b5bae6e2acda52c9bc9cfda65859ea8
ae743f8b656247f36204c9e4606d71ce629eecdd
refs/heads/master
2021-01-25T13:23:52.987000
2018-03-13T14:14:50
2018-03-13T14:14:50
123,564,245
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.localisation; import android.Manifest; import android.annotation.SuppressLint; import android.content.Context; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { //Dans le manifest les permissions ont รฉtรฉ rรฉalisรฉes //On peut aussi mettre au lieu de juste la localisation mettre un ProximityAlert public static final int MY_PERMISSIONS_REQUEST_LOCATION=0; public LocationManager locationManager; public TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv=findViewById(R.id.tv); // Acquire a reference to the system Location Manager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); // Register the listener with the Location Manager to receive location updates //Pour faire la demande de permissions avec onrequest, une boite de dialogue s'ouvre. if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details // Should we show an explanation? if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { // Show an explanation to the user *asynchronously* -- don't block // this thread waiting for the user's response! After the user // sees the explanation, try again to request the permission. Toast.makeText(this, "Pour la bonne cause", Toast.LENGTH_SHORT).show(); } else { // No explanation needed, we can request the permission. ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION); // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an // app-defined int constant. The callback method gets the // result of the request. } Toast.makeText(this, "coucou", Toast.LENGTH_SHORT).show(); return; } locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); String locationProvider = LocationManager.GPS_PROVIDER; // Or use LocationManager.GPS_PROVIDER Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider); tv.setText(lastKnownLocation.toString()); Toast.makeText(this, lastKnownLocation.toString(), Toast.LENGTH_LONG).show(); } @SuppressLint("MissingPermission") @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case MY_PERMISSIONS_REQUEST_LOCATION: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission was granted, yay! Do the // contacts-related task you need to do. locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); String locationProvider = LocationManager.NETWORK_PROVIDER; // Or use LocationManager.GPS_PROVIDER Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider); Toast.makeText(this, lastKnownLocation.toString(), Toast.LENGTH_LONG).show(); } else { // permission denied, boo! Disable the // functionality that depends on this permission. Toast.makeText(this, "Mince alors...", Toast.LENGTH_SHORT).show(); } return; } // other 'case' lines to check for other // permissions this app might request. } } // Define a listener that responds to location updates LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { // Called when a new location is found by the network location provider. //makeUseOfNewLocation(location); } public void onStatusChanged(String provider, int status, Bundle extras) { } public void onProviderEnabled(String provider) { } public void onProviderDisabled(String provider) { } }; /*Intent intent = new Intent(this, AlertReceiver.class); PendingIntent pending = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); // On ajoute une alerte de proximitรฉ si on s'approche ou s'รฉloigne du bรขtiment de Simple IT locationManager.addProximityAlert(48.872808, 2.33517, 150, -1, pending); public class AlertReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // Vaudra true par dรฉfaut si on ne trouve pas l'extra boolรฉen dont la clรฉ est LocationManager.KEY_PROXIMITY_ENTERING bool entrer = booleanValue(intent.getBooleanExtra(LocationManager.KEY_PROXIMITY_ENTERING, true)); } } */ }
UTF-8
Java
6,538
java
MainActivity.java
Java
[ { "context": "ssion.\n\n Toast.makeText(this, \"Mince alors...\", Toast.LENGTH_SHORT).show();\n ", "end": 5051, "score": 0.974073052406311, "start": 5040, "tag": "NAME", "value": "Mince alors" } ]
null
[]
package com.example.localisation; import android.Manifest; import android.annotation.SuppressLint; import android.content.Context; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { //Dans le manifest les permissions ont รฉtรฉ rรฉalisรฉes //On peut aussi mettre au lieu de juste la localisation mettre un ProximityAlert public static final int MY_PERMISSIONS_REQUEST_LOCATION=0; public LocationManager locationManager; public TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv=findViewById(R.id.tv); // Acquire a reference to the system Location Manager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); // Register the listener with the Location Manager to receive location updates //Pour faire la demande de permissions avec onrequest, une boite de dialogue s'ouvre. if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details // Should we show an explanation? if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { // Show an explanation to the user *asynchronously* -- don't block // this thread waiting for the user's response! After the user // sees the explanation, try again to request the permission. Toast.makeText(this, "Pour la bonne cause", Toast.LENGTH_SHORT).show(); } else { // No explanation needed, we can request the permission. ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION); // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an // app-defined int constant. The callback method gets the // result of the request. } Toast.makeText(this, "coucou", Toast.LENGTH_SHORT).show(); return; } locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); String locationProvider = LocationManager.GPS_PROVIDER; // Or use LocationManager.GPS_PROVIDER Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider); tv.setText(lastKnownLocation.toString()); Toast.makeText(this, lastKnownLocation.toString(), Toast.LENGTH_LONG).show(); } @SuppressLint("MissingPermission") @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case MY_PERMISSIONS_REQUEST_LOCATION: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission was granted, yay! Do the // contacts-related task you need to do. locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); String locationProvider = LocationManager.NETWORK_PROVIDER; // Or use LocationManager.GPS_PROVIDER Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider); Toast.makeText(this, lastKnownLocation.toString(), Toast.LENGTH_LONG).show(); } else { // permission denied, boo! Disable the // functionality that depends on this permission. Toast.makeText(this, "<NAME>...", Toast.LENGTH_SHORT).show(); } return; } // other 'case' lines to check for other // permissions this app might request. } } // Define a listener that responds to location updates LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { // Called when a new location is found by the network location provider. //makeUseOfNewLocation(location); } public void onStatusChanged(String provider, int status, Bundle extras) { } public void onProviderEnabled(String provider) { } public void onProviderDisabled(String provider) { } }; /*Intent intent = new Intent(this, AlertReceiver.class); PendingIntent pending = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); // On ajoute une alerte de proximitรฉ si on s'approche ou s'รฉloigne du bรขtiment de Simple IT locationManager.addProximityAlert(48.872808, 2.33517, 150, -1, pending); public class AlertReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // Vaudra true par dรฉfaut si on ne trouve pas l'extra boolรฉen dont la clรฉ est LocationManager.KEY_PROXIMITY_ENTERING bool entrer = booleanValue(intent.getBooleanExtra(LocationManager.KEY_PROXIMITY_ENTERING, true)); } } */ }
6,533
0.665594
0.661305
178
35.674156
38.559532
259
false
false
0
0
0
0
0
0
0.5
false
false
0
893b17276640f8622635fb0b6f2c92d73b85ad6a
7,971,459,360,741
6910be4694559cc412ff0e9c0caffd1ce52e8c29
/src/org/glen_h/games/wolfnsheep/PlayerMode.java
496b4ba6be16dcdb9d4050db953b542ee0c92fe4
[]
no_license
glen3b/wolf-n-sheep
https://github.com/glen3b/wolf-n-sheep
6eef07de1dcb85acb0c8a6763656af932a634574
1a9083d90c67db18cd5c196006493aea7437a623
refs/heads/master
2021-01-23T13:22:45.916000
2013-01-05T21:25:17
2013-01-05T21:25:17
32,426,086
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.glen_h.games.wolfnsheep; /** * An enum representing the game type: <i>SINGLEPLAYER</i> (One player), <i>MULTIPLAYER</i> (Multiple players), <i>MULTIPLAYER_2P</i> (2 players), <i>MULTIPLAYER_3P</i> (3 players), or <i>MULTIPLAYER_4P</i> (4 players). * It is preferred to be as specific as possible (Example: If there are going to be 3 players, use <i>MULTIPLAYER_3P</i>, not <i>MULTIPLAYER</i>. * In this case, "players" mean human players. */ public enum PlayerMode { SINGLEPLAYER, MULTIPLAYER, MULTIPLAYER_2P, MULTIPLAYER_3P, MULTIPLAYER_4P }
UTF-8
Java
562
java
PlayerMode.java
Java
[]
null
[]
package org.glen_h.games.wolfnsheep; /** * An enum representing the game type: <i>SINGLEPLAYER</i> (One player), <i>MULTIPLAYER</i> (Multiple players), <i>MULTIPLAYER_2P</i> (2 players), <i>MULTIPLAYER_3P</i> (3 players), or <i>MULTIPLAYER_4P</i> (4 players). * It is preferred to be as specific as possible (Example: If there are going to be 3 players, use <i>MULTIPLAYER_3P</i>, not <i>MULTIPLAYER</i>. * In this case, "players" mean human players. */ public enum PlayerMode { SINGLEPLAYER, MULTIPLAYER, MULTIPLAYER_2P, MULTIPLAYER_3P, MULTIPLAYER_4P }
562
0.713523
0.69395
10
55.200001
69.388474
219
false
false
0
0
0
0
0
0
1.4
false
false
0
8a92744804da388abc340e6ddb60d8bcdfed832b
22,686,017,307,190
4b3ea7b75dca7f3a172ce0a9b61277fb315bdc09
/src/main/java/leetcode/Test0120_Triangle.java
069675e4ae0be3fb94aff308a47faaca8cbcf905
[]
no_license
wwnhahaxiao/leetcodetest
https://github.com/wwnhahaxiao/leetcodetest
894a54ab7d561a6bb2e8888a1ac7e98eade67609
8a8f75add372974bfae39d7c01fa254d91b3d4f9
refs/heads/master
2023-06-18T03:26:24.099000
2021-07-12T05:35:42
2021-07-12T05:35:42
226,481,085
0
0
null
false
2020-10-13T20:22:37
2019-12-07T08:42:45
2020-10-12T01:45:50
2020-10-13T20:22:35
325
0
0
1
Java
false
false
package leetcode; import org.junit.Test; import java.util.ArrayList; import java.util.List; //Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. // For example, given the following triangle // [ // [2], // [3,4], // [6,5,7], // [4,1,8,3] // ] // The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). // Note: // Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle. public class Test0120_Triangle { private int minimumTotal(List<List<Integer>> triangle) { if (triangle == null || triangle.size() == 0) { return 0; } int[] dp = new int[triangle.size() + 1]; for (int i = triangle.size() - 1; i >= 0; i--) { List<Integer> row = triangle.get(i); for (int j = 0; j < row.size(); j++) { dp[j] = Math.min(dp[j], dp[j + 1]) + row.get(j); } } return dp[0]; } @Test public void test() { List<List<Integer>> triangle = build(2, null, 3, 4, null, 6, 5, 7, null, 4, 1, 8, 3, null); int step = minimumTotal(triangle); System.out.println(step); } private List<List<Integer>> build(Integer... values) { List<List<Integer>> result = new ArrayList<>(); List<Integer> row = new ArrayList<>(); for (Integer v : values) { if (v == null) { result.add(row); row = new ArrayList<>(); } else { row.add(v); } } return result; } }
UTF-8
Java
1,730
java
Test0120_Triangle.java
Java
[]
null
[]
package leetcode; import org.junit.Test; import java.util.ArrayList; import java.util.List; //Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. // For example, given the following triangle // [ // [2], // [3,4], // [6,5,7], // [4,1,8,3] // ] // The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). // Note: // Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle. public class Test0120_Triangle { private int minimumTotal(List<List<Integer>> triangle) { if (triangle == null || triangle.size() == 0) { return 0; } int[] dp = new int[triangle.size() + 1]; for (int i = triangle.size() - 1; i >= 0; i--) { List<Integer> row = triangle.get(i); for (int j = 0; j < row.size(); j++) { dp[j] = Math.min(dp[j], dp[j + 1]) + row.get(j); } } return dp[0]; } @Test public void test() { List<List<Integer>> triangle = build(2, null, 3, 4, null, 6, 5, 7, null, 4, 1, 8, 3, null); int step = minimumTotal(triangle); System.out.println(step); } private List<List<Integer>> build(Integer... values) { List<List<Integer>> result = new ArrayList<>(); List<Integer> row = new ArrayList<>(); for (Integer v : values) { if (v == null) { result.add(row); row = new ArrayList<>(); } else { row.add(v); } } return result; } }
1,730
0.507514
0.484393
55
30.454546
29.034662
130
false
false
0
0
0
0
0
0
0.927273
false
false
0
111146ea756eac8d141538f7a7f55acfb9172c15
16,157,666,967,553
d65ea34643d033a832a2e53e03c15c2e949090cf
/OvertredingGenerator/src/be/kdg/se3/penaltygenerator/model/EmissionPenalty.java
a8ab3d57c618b47fa8860fe3396a74097a0775d9
[]
no_license
samvanderroost/BoeteBerekening
https://github.com/samvanderroost/BoeteBerekening
19ac5418de66e6864a5f12788b54fe0a81f037c4
9a33dd8d57b1c4f27e0ccd68df61a46c747204a1
refs/heads/master
2018-12-29T05:52:15.515000
2017-07-20T10:03:01
2017-07-20T10:03:01
95,593,055
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package be.kdg.se3.penaltygenerator.model; import java.util.Date; /** * Created by sam on 28/06/2017. */ public class EmissionPenalty extends Penalty { private int minEuroNorm; private int euroNorm; public Date getTimestamp() { return super.getTimestamp(); } public void setTimestamp(Date timestamp) { super.setTimestamp(timestamp); } public String getLicencePlate() { return super.getLicencePlate(); } public void setLicencePlate(String licencePlate) { super.setLicencePlate(licencePlate); } public String getStreetName() { return super.getStreetName(); } public void setStreetName(String streetName) { super.setStreetName(streetName); } public String getCity() { return super.getCity(); } public void setCity(String city) { super.setCity(city); } public int getMinEuroNorm() { return minEuroNorm; } public void setMinEuroNorm(int minEuroNorm) { this.minEuroNorm = minEuroNorm; } public int getEuroNorm() { return euroNorm; } public void setEuroNorm(int euroNorm) { this.euroNorm = euroNorm; } @Override public String toString() { return String.format("Licenceplate; %s\n" + "city: %s\ns" + "address: %s\n" + "minimal emission norm: %d\n" + "emission norm: %d\n" + "time: %S\n", getLicencePlate(), getCity(), getStreetName(), minEuroNorm, euroNorm, getTimestamp().toString()); } }
UTF-8
Java
1,963
java
EmissionPenalty.java
Java
[ { "context": ".model;\n\nimport java.util.Date;\n\n/**\n * Created by sam on 28/06/2017.\n */\npublic class EmissionPenalty e", "end": 89, "score": 0.9506399631500244, "start": 86, "tag": "USERNAME", "value": "sam" } ]
null
[]
package be.kdg.se3.penaltygenerator.model; import java.util.Date; /** * Created by sam on 28/06/2017. */ public class EmissionPenalty extends Penalty { private int minEuroNorm; private int euroNorm; public Date getTimestamp() { return super.getTimestamp(); } public void setTimestamp(Date timestamp) { super.setTimestamp(timestamp); } public String getLicencePlate() { return super.getLicencePlate(); } public void setLicencePlate(String licencePlate) { super.setLicencePlate(licencePlate); } public String getStreetName() { return super.getStreetName(); } public void setStreetName(String streetName) { super.setStreetName(streetName); } public String getCity() { return super.getCity(); } public void setCity(String city) { super.setCity(city); } public int getMinEuroNorm() { return minEuroNorm; } public void setMinEuroNorm(int minEuroNorm) { this.minEuroNorm = minEuroNorm; } public int getEuroNorm() { return euroNorm; } public void setEuroNorm(int euroNorm) { this.euroNorm = euroNorm; } @Override public String toString() { return String.format("Licenceplate; %s\n" + "city: %s\ns" + "address: %s\n" + "minimal emission norm: %d\n" + "emission norm: %d\n" + "time: %S\n", getLicencePlate(), getCity(), getStreetName(), minEuroNorm, euroNorm, getTimestamp().toString()); } }
1,963
0.492104
0.487519
75
25.173334
21.574907
71
false
false
0
0
0
0
0
0
0.32
false
false
0
5672ee3937d46e448441910be4eb810efdbb0042
16,157,666,968,818
0cd5570693a2151480954ba102bbcdf599007177
/src/edu/mcckc/gui/FrameApp.java
cc3654a932ac611db1f9d2df08f1ea5472cb18e6
[]
no_license
tiunicorn1/CS222-final
https://github.com/tiunicorn1/CS222-final
127d21444815fc1e6734332a749c10ac7efc8f1b
73178a9ddd581630438e2abe5b7bd286c39ab860
refs/heads/master
2021-01-01T06:23:15.273000
2017-05-16T02:26:49
2017-05-16T02:26:49
97,418,643
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.mcckc.gui; import javax.swing.*; /** * Created by rharris on 5/1/2017. */ public class FrameApp extends JFrame { private PanelApp pnlApp; public FrameApp() { pnlApp = new PanelApp(); add(pnlApp); } }
UTF-8
Java
249
java
FrameApp.java
Java
[ { "context": "ckc.gui;\n\nimport javax.swing.*;\n\n/**\n * Created by rharris on 5/1/2017.\n */\npublic class FrameApp extends JF", "end": 72, "score": 0.9988723993301392, "start": 65, "tag": "USERNAME", "value": "rharris" } ]
null
[]
package edu.mcckc.gui; import javax.swing.*; /** * Created by rharris on 5/1/2017. */ public class FrameApp extends JFrame { private PanelApp pnlApp; public FrameApp() { pnlApp = new PanelApp(); add(pnlApp); } }
249
0.606426
0.582329
17
13.647058
13.128062
36
false
false
0
0
0
0
0
0
0.294118
false
false
0
aae487afb83e44be0c0603b72ad8956c6b35f359
30,932,354,525,462
0634a0110c89d386d20fd33c26e19d846b9ee7cd
/yun-video-monitor/admin-center/src/main/java/com/hlcy/yun/admincenter/modules/device/listener/DeviceEventHandler.java
8630c0a324f10ae812a5f9891cfe3babf0c60558
[]
no_license
cckmit/yun
https://github.com/cckmit/yun
0d1c5d104a78bddef0590c14990f4a52cd994cf9
3031ee54f79455813fb8f15d82495db893b02f9a
refs/heads/master
2023-03-31T00:18:53.219000
2021-04-01T04:51:28
2021-04-01T04:51:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hlcy.yun.admincenter.modules.device.listener; import com.hlcy.yun.admincenter.modules.device.listener.event.KeepaliveEvent; import com.hlcy.yun.admincenter.modules.device.listener.event.LogoutEvent; import com.hlcy.yun.admincenter.modules.device.listener.event.RegisterEvent; public interface DeviceEventHandler { /** * ๅค„็†่ฎพๅค‡ๆณจๅ†Œไบ‹ไปถ * * @param event register event */ void handleRegisterEvent(RegisterEvent event); /** * ๅค„็†่ฎพๅค‡ๆณจ้”€ไบ‹ไปถ * * @param event logout event */ void handleLogoutEvent(LogoutEvent event); /** * ๅค„็†่ฎพๅค‡ๅฟƒ่ทณไบ‹ไปถ * * @param event Keepalive event */ void handleKeepaliveEvent(KeepaliveEvent event); }
UTF-8
Java
754
java
DeviceEventHandler.java
Java
[]
null
[]
package com.hlcy.yun.admincenter.modules.device.listener; import com.hlcy.yun.admincenter.modules.device.listener.event.KeepaliveEvent; import com.hlcy.yun.admincenter.modules.device.listener.event.LogoutEvent; import com.hlcy.yun.admincenter.modules.device.listener.event.RegisterEvent; public interface DeviceEventHandler { /** * ๅค„็†่ฎพๅค‡ๆณจๅ†Œไบ‹ไปถ * * @param event register event */ void handleRegisterEvent(RegisterEvent event); /** * ๅค„็†่ฎพๅค‡ๆณจ้”€ไบ‹ไปถ * * @param event logout event */ void handleLogoutEvent(LogoutEvent event); /** * ๅค„็†่ฎพๅค‡ๅฟƒ่ทณไบ‹ไปถ * * @param event Keepalive event */ void handleKeepaliveEvent(KeepaliveEvent event); }
754
0.696884
0.696884
30
22.533333
24.74501
77
false
false
0
0
0
0
0
0
0.233333
false
false
0
a55c706785a236fa2b381babd13a1f71bda16956
128,849,078,374
9e2dafc441eb471c4b5bcfaa72c283fd021f93b6
/app/src/main/java/com/misura/dontforget/MainActivity.java
53692a51fded69ae6ca9d14af72f8ce95084ea32
[]
no_license
kmisura/DontForget
https://github.com/kmisura/DontForget
f96a911001281d09d4bcaf9c9b4438e5a8b7f31a
910de61763a4558dd4cc7a791c0cd3803257f270
refs/heads/master
2021-01-18T20:31:46.934000
2016-04-05T20:57:37
2016-04-05T20:57:37
55,533,374
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.misura.dontforget; import android.app.LoaderManager; import android.content.CursorLoader; import android.content.Intent; import android.content.Loader; import android.database.Cursor; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import com.misura.dontforget.create.AddReminderActivity; public class MainActivity extends AppCompatActivity implements View.OnClickListener, LoaderManager.LoaderCallbacks<Cursor> { static final int COL_ID = 0; static final int COL_TITLE = 1; static final int COL_DESCRIPTION = 2; static final int COL_REMAINING_TIME = 3; static final int COL_LOCATION_NAME = 4; private static final int REMINDERS_LOADER = 0; private static final String[] REMINDERS_LIST_COLUMNS = new String[]{ RemindersContract.ReminderEntry._ID, RemindersContract.ReminderEntry.COLUMN_TITLE, RemindersContract.ReminderEntry.COLUMN_DESCRIPTION, RemindersContract.ReminderEntry.COLUMN_TIME, RemindersContract.ReminderEntry.COLUMN_LOCATION_NAME }; private FloatingActionButton mAddReminderButton; private ReminderListAdapter mListAdapter; private RecyclerView mRecyclerView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setTitle(R.string.main_activity_title); setSupportActionBar(toolbar); mAddReminderButton = (FloatingActionButton) findViewById(R.id.fab); assert mAddReminderButton != null; mAddReminderButton.setOnClickListener(this); mListAdapter = new ReminderListAdapter(this, null); mRecyclerView = (RecyclerView) findViewById(R.id.content_main_rv_remider_list); mRecyclerView.setAdapter(mListAdapter); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); getLoaderManager().initLoader(REMINDERS_LOADER, null, this); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onClick(View v) { Intent addReminderIntent = new Intent(this, AddReminderActivity.class); startActivity(addReminderIntent); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { return new CursorLoader( this, RemindersContract.ReminderEntry.CONTENT_URI, REMINDERS_LIST_COLUMNS, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { mListAdapter.swapCursor(data); } @Override public void onLoaderReset(Loader<Cursor> loader) { mListAdapter.swapCursor(null); } }
UTF-8
Java
3,802
java
MainActivity.java
Java
[]
null
[]
package com.misura.dontforget; import android.app.LoaderManager; import android.content.CursorLoader; import android.content.Intent; import android.content.Loader; import android.database.Cursor; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import com.misura.dontforget.create.AddReminderActivity; public class MainActivity extends AppCompatActivity implements View.OnClickListener, LoaderManager.LoaderCallbacks<Cursor> { static final int COL_ID = 0; static final int COL_TITLE = 1; static final int COL_DESCRIPTION = 2; static final int COL_REMAINING_TIME = 3; static final int COL_LOCATION_NAME = 4; private static final int REMINDERS_LOADER = 0; private static final String[] REMINDERS_LIST_COLUMNS = new String[]{ RemindersContract.ReminderEntry._ID, RemindersContract.ReminderEntry.COLUMN_TITLE, RemindersContract.ReminderEntry.COLUMN_DESCRIPTION, RemindersContract.ReminderEntry.COLUMN_TIME, RemindersContract.ReminderEntry.COLUMN_LOCATION_NAME }; private FloatingActionButton mAddReminderButton; private ReminderListAdapter mListAdapter; private RecyclerView mRecyclerView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setTitle(R.string.main_activity_title); setSupportActionBar(toolbar); mAddReminderButton = (FloatingActionButton) findViewById(R.id.fab); assert mAddReminderButton != null; mAddReminderButton.setOnClickListener(this); mListAdapter = new ReminderListAdapter(this, null); mRecyclerView = (RecyclerView) findViewById(R.id.content_main_rv_remider_list); mRecyclerView.setAdapter(mListAdapter); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); getLoaderManager().initLoader(REMINDERS_LOADER, null, this); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onClick(View v) { Intent addReminderIntent = new Intent(this, AddReminderActivity.class); startActivity(addReminderIntent); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { return new CursorLoader( this, RemindersContract.ReminderEntry.CONTENT_URI, REMINDERS_LIST_COLUMNS, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { mListAdapter.swapCursor(data); } @Override public void onLoaderReset(Loader<Cursor> loader) { mListAdapter.swapCursor(null); } }
3,802
0.701736
0.699106
106
34.867924
25.309061
124
false
false
0
0
0
0
0
0
0.641509
false
false
0
dd52253fa8691d83627e0030f308626f103546de
14,869,176,821,375
cb16ee2988c7531e23f163bd701edffe1a041cc7
/com/swapnil/java/practice/random/TwoNumSum.java
cc3158377db608476e9921b3bd3519d2aca6dcd9
[]
no_license
Swapnil-ingle/Java-Practice-Programs
https://github.com/Swapnil-ingle/Java-Practice-Programs
94906d39cea93e737b1eb11f1219229f25448c4e
bb85856de142de058e4c82f7dff005a92df7af90
refs/heads/master
2022-08-11T20:36:35.380000
2022-06-26T07:00:57
2022-06-26T07:00:57
156,978,381
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.swapnil.java.practice.random; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.stream.Collectors; public class TwoNumSum { /** * Problem Statement: * Given an array ex: [1, 6, 9] and a target number ex: 10. * Find if there is a pair which sums up to the target. * Catch: Restrict the complexity to BigO(n) * @param args */ public static void main(String[] args) { Scanner sc = null; int target = getTargetInt(sc); try { sc = initScanner(sc); // Get input Array Integer[] inputArray = getInputArray(sc); // Get index of the numbers if sum exists int[] finalIdx = getTwoNumSum(inputArray, target); // Display value displayResultingIndexes(target, finalIdx); } catch (Exception e) { System.out.println("Error while running: " + e); } finally { sc.close(); } } private static int getTargetInt(Scanner sc) { System.out.println("Enter the target number"); return sc.nextInt(); } private static Scanner initScanner(Scanner sc) { return new Scanner(System.in); } private static Integer[] getInputArray(Scanner sc) { System.out.println("Enter the input array..."); String[] input = sc.nextLine().split(" "); return Arrays.stream(input) .map(Integer::valueOf) .collect(Collectors.toList()) .toArray(new Integer[input.length]); } private static int[] getTwoNumSum(Integer[] input, int target) { // Make a hash table of the input num --> index Map<Integer, Integer> inputHashMap = convertToHashMap(input); /** Algorithm -- * 0. Iterate input array * 1. Check if diff(input[i], target) exists in inputHashMap<> * and counterpart's index != current index (This would cause the * program to consider the same index twice) * 2. If yes --> return [i, inputHashMap.get(diff(input[i],target))] */ for (int i = 0; i < input.length; i++) { if (inputHashMap.containsKey(diff(input[i],target)) && (inputHashMap.get(diff(input[i],target)) != i)) { return new int[] {i, inputHashMap.get(diff(input[i],target))}; } } return null; } private static Map<Integer, Integer> convertToHashMap(Integer[] input) { Map<Integer, Integer> inputHashMap = new HashMap<>(); for (int i = 0; i < input.length; i++) { inputHashMap.put(input[i], i); } return inputHashMap; } private static Integer diff(Integer currInt, int targetInt) { if (currInt > targetInt) { return (currInt - targetInt); } return (targetInt - currInt); } private static void displayResultingIndexes(int target, int[] finalIdx) { if (finalIdx != null) { System.out.println(finalIdx[0] + " , " + finalIdx[1]); } else { System.out.println("No two integer exists who's sum is: " + target); } } }
UTF-8
Java
2,822
java
TwoNumSum.java
Java
[]
null
[]
package com.swapnil.java.practice.random; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.stream.Collectors; public class TwoNumSum { /** * Problem Statement: * Given an array ex: [1, 6, 9] and a target number ex: 10. * Find if there is a pair which sums up to the target. * Catch: Restrict the complexity to BigO(n) * @param args */ public static void main(String[] args) { Scanner sc = null; int target = getTargetInt(sc); try { sc = initScanner(sc); // Get input Array Integer[] inputArray = getInputArray(sc); // Get index of the numbers if sum exists int[] finalIdx = getTwoNumSum(inputArray, target); // Display value displayResultingIndexes(target, finalIdx); } catch (Exception e) { System.out.println("Error while running: " + e); } finally { sc.close(); } } private static int getTargetInt(Scanner sc) { System.out.println("Enter the target number"); return sc.nextInt(); } private static Scanner initScanner(Scanner sc) { return new Scanner(System.in); } private static Integer[] getInputArray(Scanner sc) { System.out.println("Enter the input array..."); String[] input = sc.nextLine().split(" "); return Arrays.stream(input) .map(Integer::valueOf) .collect(Collectors.toList()) .toArray(new Integer[input.length]); } private static int[] getTwoNumSum(Integer[] input, int target) { // Make a hash table of the input num --> index Map<Integer, Integer> inputHashMap = convertToHashMap(input); /** Algorithm -- * 0. Iterate input array * 1. Check if diff(input[i], target) exists in inputHashMap<> * and counterpart's index != current index (This would cause the * program to consider the same index twice) * 2. If yes --> return [i, inputHashMap.get(diff(input[i],target))] */ for (int i = 0; i < input.length; i++) { if (inputHashMap.containsKey(diff(input[i],target)) && (inputHashMap.get(diff(input[i],target)) != i)) { return new int[] {i, inputHashMap.get(diff(input[i],target))}; } } return null; } private static Map<Integer, Integer> convertToHashMap(Integer[] input) { Map<Integer, Integer> inputHashMap = new HashMap<>(); for (int i = 0; i < input.length; i++) { inputHashMap.put(input[i], i); } return inputHashMap; } private static Integer diff(Integer currInt, int targetInt) { if (currInt > targetInt) { return (currInt - targetInt); } return (targetInt - currInt); } private static void displayResultingIndexes(int target, int[] finalIdx) { if (finalIdx != null) { System.out.println(finalIdx[0] + " , " + finalIdx[1]); } else { System.out.println("No two integer exists who's sum is: " + target); } } }
2,822
0.66017
0.655918
104
26.134615
22.883509
74
false
false
0
0
0
0
0
0
2.278846
false
false
0
cf9fec912c73f1fac08f766784c57e4fc285e396
22,093,311,813,836
0c68287f79454e993e467a327c2270112cb4bb67
/src/Game.java
4f02ab898e6d6936b119a60890578af7c5879b43
[]
no_license
Christian2019/IA_knn
https://github.com/Christian2019/IA_knn
aff31024768184f96d363022c3774f197efe6329
00e152d71af4781b4f371fb2545345f41312a13b
refs/heads/master
2022-11-06T16:54:57.646000
2020-06-19T20:25:35
2020-06-19T20:25:35
273,580,359
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Random; public class Game { public static ArrayList<Petala> petalas; static ArrayList<Petala> treino; static ArrayList<Petala> teste_resposta; static ArrayList<Petala> teste; static ArrayList<ArrayList<Type_Distance>> distancias; static int k=5; public static void main(String[] args) { petalas = new ArrayList<Petala>(); treino = new ArrayList<Petala>(); teste_resposta = new ArrayList<Petala>(); teste = new ArrayList<Petala>(); distancias = new ArrayList<ArrayList<Type_Distance>>(); Random random = new Random(); Leitura.load(); // System.out.println(petalas); for (int i = 0; i < 40; i++) { int v = random.nextInt(petalas.size()); treino.add(petalas.get(v)); petalas.remove(v); } // System.out.println(treino); for (int i = 0; i < 30; i++) { int v = random.nextInt(petalas.size()); Petala p = new Petala(petalas.get(i).sepal_length,petalas.get(i).sepal_width , petalas.get(i).petal_length, petalas.get(i).petal_width, petalas.get(i).petal_class); Petala p2= new Petala(petalas.get(i).sepal_length,petalas.get(i).sepal_width , petalas.get(i).petal_length, petalas.get(i).petal_width, petalas.get(i).petal_class); teste_resposta.add(p); teste.add(p2); petalas.remove(v); } // System.out.println(teste); for (int i = 0; i < teste.size(); i++) { teste.get(i).petal_class = null; } // System.out.println(teste); // k-NN for (int i = 0; i < teste.size(); i++) { ArrayList<Type_Distance> d = new ArrayList<Type_Distance>(); for (int j = 0; j < treino.size(); j++) { // 1-teste 2-treino double v1 = teste.get(i).sepal_length; double v2 = treino.get(j).sepal_length; double x1 = teste.get(i).sepal_width; double x2 = treino.get(j).sepal_width; double y1 = teste.get(i).petal_length; double y2 = treino.get(j).petal_length; double z1 = teste.get(i).petal_width; double z2 = treino.get(j).petal_width; double cateto1 = v1 - v2; double cateto2 = x1 - x2; double cateto3 = y1 - y2; double cateto4 = z1 - z2; double distancia = Math .sqrt((cateto1 * cateto1) + (cateto2 * cateto2) + (cateto3 * cateto3) + (cateto4 * cateto4)); Type_Distance td = new Type_Distance(treino.get(j).petal_class,distancia); d.add(td); } distancias.add(d); } for (int i = 0; i < distancias.size(); i++) { depth(distancias.get(i)); } /* for (int i = 0; i < distancias.size(); i++) { System.out.println("Teste "+i); for (int j=0;j<distancias.get(i).size();j++) { System.out.println(distancias.get(i).get(j)); } } */ ArrayList<String> resultado = new ArrayList<String>(); for (int i=0;i<distancias.size();i++) { int setosa=0; int versicolor=0; int virginica=0; String resposta="empate"; for (int j=0;j<k;j++) { if (distancias.get(i).get(j).type.equals("Iris-versicolor")) { versicolor++; } if (distancias.get(i).get(j).type.equals("Iris-virginica")) { virginica++; } if (distancias.get(i).get(j).type.equals("Iris-setosa")) { setosa++; } } if (setosa>=versicolor&&setosa>=virginica) { resposta = "Iris-setosa"; }else if (versicolor>=setosa&&versicolor>=virginica) { resposta = "Iris-versicolor"; }else if (virginica>=setosa&&virginica>=versicolor) { resposta = "Iris-virginica"; } resultado.add(resposta); } int acertos=0; for (int i=0;i<teste_resposta.size();i++) { System.out.println("Teste "+i+" Tipo: "+teste_resposta.get(i).petal_class+" Resultado: "+resultado.get(i)); if (teste_resposta.get(i).petal_class.equals(resultado.get(i))) { System.out.println("Correto"); acertos++; }else { System.out.println("Errado"); } } System.out.println("Total de acertos: "+acertos+"/"+teste_resposta.size()); } public static void depth(ArrayList<Type_Distance> a) { // Crescente // Collections.sort(a, listSorter); // Decrescente Collections.sort(a, listSorter.reversed()); } public static Comparator<Type_Distance> listSorter = new Comparator<Type_Distance>() { @Override public int compare(Type_Distance n0, Type_Distance n1) { if (n1.distance < n0.distance) { return -1; } if (n1.distance > n0.distance) { return +1; } return 0; } }; }
UTF-8
Java
4,361
java
Game.java
Java
[]
null
[]
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Random; public class Game { public static ArrayList<Petala> petalas; static ArrayList<Petala> treino; static ArrayList<Petala> teste_resposta; static ArrayList<Petala> teste; static ArrayList<ArrayList<Type_Distance>> distancias; static int k=5; public static void main(String[] args) { petalas = new ArrayList<Petala>(); treino = new ArrayList<Petala>(); teste_resposta = new ArrayList<Petala>(); teste = new ArrayList<Petala>(); distancias = new ArrayList<ArrayList<Type_Distance>>(); Random random = new Random(); Leitura.load(); // System.out.println(petalas); for (int i = 0; i < 40; i++) { int v = random.nextInt(petalas.size()); treino.add(petalas.get(v)); petalas.remove(v); } // System.out.println(treino); for (int i = 0; i < 30; i++) { int v = random.nextInt(petalas.size()); Petala p = new Petala(petalas.get(i).sepal_length,petalas.get(i).sepal_width , petalas.get(i).petal_length, petalas.get(i).petal_width, petalas.get(i).petal_class); Petala p2= new Petala(petalas.get(i).sepal_length,petalas.get(i).sepal_width , petalas.get(i).petal_length, petalas.get(i).petal_width, petalas.get(i).petal_class); teste_resposta.add(p); teste.add(p2); petalas.remove(v); } // System.out.println(teste); for (int i = 0; i < teste.size(); i++) { teste.get(i).petal_class = null; } // System.out.println(teste); // k-NN for (int i = 0; i < teste.size(); i++) { ArrayList<Type_Distance> d = new ArrayList<Type_Distance>(); for (int j = 0; j < treino.size(); j++) { // 1-teste 2-treino double v1 = teste.get(i).sepal_length; double v2 = treino.get(j).sepal_length; double x1 = teste.get(i).sepal_width; double x2 = treino.get(j).sepal_width; double y1 = teste.get(i).petal_length; double y2 = treino.get(j).petal_length; double z1 = teste.get(i).petal_width; double z2 = treino.get(j).petal_width; double cateto1 = v1 - v2; double cateto2 = x1 - x2; double cateto3 = y1 - y2; double cateto4 = z1 - z2; double distancia = Math .sqrt((cateto1 * cateto1) + (cateto2 * cateto2) + (cateto3 * cateto3) + (cateto4 * cateto4)); Type_Distance td = new Type_Distance(treino.get(j).petal_class,distancia); d.add(td); } distancias.add(d); } for (int i = 0; i < distancias.size(); i++) { depth(distancias.get(i)); } /* for (int i = 0; i < distancias.size(); i++) { System.out.println("Teste "+i); for (int j=0;j<distancias.get(i).size();j++) { System.out.println(distancias.get(i).get(j)); } } */ ArrayList<String> resultado = new ArrayList<String>(); for (int i=0;i<distancias.size();i++) { int setosa=0; int versicolor=0; int virginica=0; String resposta="empate"; for (int j=0;j<k;j++) { if (distancias.get(i).get(j).type.equals("Iris-versicolor")) { versicolor++; } if (distancias.get(i).get(j).type.equals("Iris-virginica")) { virginica++; } if (distancias.get(i).get(j).type.equals("Iris-setosa")) { setosa++; } } if (setosa>=versicolor&&setosa>=virginica) { resposta = "Iris-setosa"; }else if (versicolor>=setosa&&versicolor>=virginica) { resposta = "Iris-versicolor"; }else if (virginica>=setosa&&virginica>=versicolor) { resposta = "Iris-virginica"; } resultado.add(resposta); } int acertos=0; for (int i=0;i<teste_resposta.size();i++) { System.out.println("Teste "+i+" Tipo: "+teste_resposta.get(i).petal_class+" Resultado: "+resultado.get(i)); if (teste_resposta.get(i).petal_class.equals(resultado.get(i))) { System.out.println("Correto"); acertos++; }else { System.out.println("Errado"); } } System.out.println("Total de acertos: "+acertos+"/"+teste_resposta.size()); } public static void depth(ArrayList<Type_Distance> a) { // Crescente // Collections.sort(a, listSorter); // Decrescente Collections.sort(a, listSorter.reversed()); } public static Comparator<Type_Distance> listSorter = new Comparator<Type_Distance>() { @Override public int compare(Type_Distance n0, Type_Distance n1) { if (n1.distance < n0.distance) { return -1; } if (n1.distance > n0.distance) { return +1; } return 0; } }; }
4,361
0.638844
0.624857
157
26.777071
27.249636
167
false
false
0
0
0
0
0
0
2.828026
false
false
0
8793039690bf764b08b71948bb26a65d2e6c51ff
34,110,630,301,182
3fba58335e52e6d039bef5c8203c4a54cb2d0746
/ssh-dlxm/src/com/maben/dlxm/service/impl/ElecApplicationTemplateServiceImpl.java
f40ca0638d98ca785315ff1bd31f9ed736136d94
[]
no_license
Maben-jm/ssh-dlxm
https://github.com/Maben-jm/ssh-dlxm
95c679b627406f06cf87a62806e6bacf8619e5a6
f4b2c2ef720a77fee3d52b2cb755ec0961f0fb09
refs/heads/main
2023-03-11T21:38:19.177000
2021-03-01T13:30:08
2021-03-01T13:30:08
338,476,819
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.maben.dlxm.service.impl; import com.maben.dlxm.dao.ElecApplicationTemplateDao; import com.maben.dlxm.domain.ElecApplicationTemplate; import com.maben.dlxm.service.ElecApplicationTemplateService; import com.maben.dlxm.util.FileUploadUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.List; @Service(value = ElecApplicationTemplateService.SERVICE_NAME) @Transactional(readOnly = true) public class ElecApplicationTemplateServiceImpl implements ElecApplicationTemplateService { @Resource(name = ElecApplicationTemplateDao.SERVICE_NAME) private ElecApplicationTemplateDao elecApplicationTemplateDao; /** * ่Žทๅ–ๆ‰€ๆœ‰็š„ๆจกๆฟ * @return List<ElecApplicationTemplate> */ @Override public List<ElecApplicationTemplate> findApplicationTemplateList() { final List<ElecApplicationTemplate> list = elecApplicationTemplateDao.findCollectionByConditionNoPage("", null, null); return list; } /** * ไฟๅญ˜ๆจกๆฟๆ–นๆณ• * @param elecApplicationTemplate elecApplicationTemplate */ @Override @Transactional(readOnly = false,isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED) public void saveElecApplicationTemplate(ElecApplicationTemplate elecApplicationTemplate) { // 1:่Žทๅ–ไธŠไผ ็š„fileๆ–‡ไปถ final File upload = elecApplicationTemplate.getUpload(); // 2๏ผšๅฐ†ๆ–‡ไปถไธŠไผ ๅˆฐๆŒ‡ๅฎš็›ฎๅฝ•ไธ‹๏ผŒๅนถ่ฟ”ๅ›žpath final String path = FileUploadUtils.fileReturnPath(upload); // 3๏ผšๅฐ†่ทฏๅพ„ไฟๅญ˜ๅˆฐๆจกๆฟ็ฑปไธญ elecApplicationTemplate.setPath(path); elecApplicationTemplateDao.save(elecApplicationTemplate); } /** * ้€š่ฟ‡id่Žทๅ–ๅ”ฏไธ€ๆจกๆฟ * @param elecApplicationTemplate elecApplicationTemplate * @return */ @Override public ElecApplicationTemplate findApplicationTemlateByID(ElecApplicationTemplate elecApplicationTemplate) { return elecApplicationTemplateDao.findObjectById(elecApplicationTemplate.getId()); } /** * ๆ›ดๆ–ฐๆจกๆฟไฟกๆฏ * @param elecApplicationTemplate elecApplicationTemplate */ @Override @Transactional(readOnly = false,isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED) public void updateApplicationTemplate(ElecApplicationTemplate elecApplicationTemplate) { //่Žทๅ–ไธŠไผ ็š„ๆ–‡ไปถupload๏ผŒ็”จๆฅๅˆคๆ–ญๆ˜ฏๅฆไธŠไผ ไบ†ๆ–ฐ็š„้™„ไปถ File file = elecApplicationTemplate.getUpload(); //ๆญคๆ—ถ่ฏดๆ˜ŽไธŠไผ ไบ†ๆ–ฐ็š„้™„ไปถ if(file!=null){ //่Žทๅ–้กต้ขไธญ้š่—ๅŸŸ็š„ๅ€ผpath่ทฏๅพ„๏ผŒไฝฟ็”จpath่ทฏๅพ„ๅˆ ้™คไน‹ๅ‰็š„้™„ไปถ String path = elecApplicationTemplate.getPath(); File oldFile = new File(path); if(oldFile.exists()){ //ๅˆ ้™คไน‹ๅ‰้™„ไปถ oldFile.delete(); } //ไธŠไผ ๆ–ฐ็š„้™„ไปถ๏ผŒ่ฟ”ๅ›ž่ทฏๅพ„path String newPath = FileUploadUtils.fileReturnPath(file); //็ป„็ป‡POๅฏน่ฑก๏ผŒๆ‰ง่กŒupdateๆ“ไฝœ elecApplicationTemplate.setPath(newPath); } elecApplicationTemplateDao.update(elecApplicationTemplate); } /** * ๅˆ ้™คๆจกๆฟไฟกๆฏ * @param elecApplicationTemplate elecApplicationTemplate */ @Override @Transactional(readOnly = false,isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED) public void deleteApplicationTemplate(ElecApplicationTemplate elecApplicationTemplate) { //่Žทๅ–็”ณ่ฏทๆจกๆฟ็š„ไธป้”ฎID Long id = elecApplicationTemplate.getId(); //ไฝฟ็”จID๏ผŒ่Žทๅ–็”ณ่ฏทๆจกๆฟ็š„่ฏฆ็ป†ไฟกๆฏ๏ผŒไปŽ่€Œ่Žทๅ–่ทฏๅพ„path๏ผŒไฝฟ็”จpathๅˆ ้™คไน‹ๅ‰ไธŠไผ ็š„้™„ไปถ ElecApplicationTemplate applicationTemplate = elecApplicationTemplateDao.findObjectById(id); String path = applicationTemplate.getPath();//่ทฏๅพ„path File oldFile = new File(path); if(oldFile.exists()){ //ๅˆ ้™คไน‹ๅ‰็š„้™„ไปถ oldFile.delete(); } //ไฝฟ็”จID๏ผŒๅˆ ้™คๆ•ฐๆฎๅบ“็š„ๆ•ฐๆฎ elecApplicationTemplateDao.deleteObjectByIds(id); } /** * ไธ‹่ฝฝๆจกๆฟ * @param elecApplicationTemplate elecApplicationTemplate * @return inputstream */ @Override public InputStream findInputStreamWithFile(ElecApplicationTemplate elecApplicationTemplate) { //่Žทๅ–็”ณ่ฏทๆจกๆฟ็š„ID Long id = elecApplicationTemplate.getId(); //ไฝฟ็”จ็”ณ่ฏทๆจกๆฟID๏ผŒๆŸฅ่ฏข็”ณ่ฏทๆจกๆฟ็š„่ฏฆ็ป†ไฟกๆฏ๏ผŒไปŽ่€Œ่Žทๅ–่ทฏๅพ„path ElecApplicationTemplate applicationTemplate = elecApplicationTemplateDao.findObjectById(id); //่Žทๅ–ๆจกๆฟ็š„ๅ็งฐ String name = applicationTemplate.getName(); //ๅค„็†ไธญๆ–‡ๅœจxmlไธญ็š„ๆ˜พ็คบ๏ผŒไฝฟ็”จUTF-8่ฟ›่กŒ็ผ–็  try { //name = URLEncoder.encode(name, "UTF-8"); name = new String(name.getBytes("gbk"),"iso-8859-1"); } catch (Exception e1) { e1.printStackTrace(); } //ๅฐ†ๆจกๆฟๅ็งฐๆ”พ็ฝฎๅˆฐๆ ˆ้กถ๏ผŒ็”จไบŽๅœจstruts.xmlๆ–‡ไปถไธญ<param name="contentDisposition">attachment;filename="${name}.doc"</param>ๆ˜พ็คบ elecApplicationTemplate.setName(name); //่ทฏๅพ„path String path = applicationTemplate.getPath(); //ไฝฟ็”จ่ทฏๅพ„path่Žทๅ–uploadๆ–‡ไปถๅคนไธ‹่ต„ๆบๆ–‡ไปถ๏ผŒ่ฝฌๆขๆˆInputStream่พ“ๅ…ฅๆตๅฏน่ฑก File file = new File(path); InputStream inputStream = null; try { inputStream = new FileInputStream(file); } catch (Exception e) { throw new RuntimeException(); } return inputStream; } }
UTF-8
Java
5,949
java
ElecApplicationTemplateServiceImpl.java
Java
[]
null
[]
package com.maben.dlxm.service.impl; import com.maben.dlxm.dao.ElecApplicationTemplateDao; import com.maben.dlxm.domain.ElecApplicationTemplate; import com.maben.dlxm.service.ElecApplicationTemplateService; import com.maben.dlxm.util.FileUploadUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.List; @Service(value = ElecApplicationTemplateService.SERVICE_NAME) @Transactional(readOnly = true) public class ElecApplicationTemplateServiceImpl implements ElecApplicationTemplateService { @Resource(name = ElecApplicationTemplateDao.SERVICE_NAME) private ElecApplicationTemplateDao elecApplicationTemplateDao; /** * ่Žทๅ–ๆ‰€ๆœ‰็š„ๆจกๆฟ * @return List<ElecApplicationTemplate> */ @Override public List<ElecApplicationTemplate> findApplicationTemplateList() { final List<ElecApplicationTemplate> list = elecApplicationTemplateDao.findCollectionByConditionNoPage("", null, null); return list; } /** * ไฟๅญ˜ๆจกๆฟๆ–นๆณ• * @param elecApplicationTemplate elecApplicationTemplate */ @Override @Transactional(readOnly = false,isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED) public void saveElecApplicationTemplate(ElecApplicationTemplate elecApplicationTemplate) { // 1:่Žทๅ–ไธŠไผ ็š„fileๆ–‡ไปถ final File upload = elecApplicationTemplate.getUpload(); // 2๏ผšๅฐ†ๆ–‡ไปถไธŠไผ ๅˆฐๆŒ‡ๅฎš็›ฎๅฝ•ไธ‹๏ผŒๅนถ่ฟ”ๅ›žpath final String path = FileUploadUtils.fileReturnPath(upload); // 3๏ผšๅฐ†่ทฏๅพ„ไฟๅญ˜ๅˆฐๆจกๆฟ็ฑปไธญ elecApplicationTemplate.setPath(path); elecApplicationTemplateDao.save(elecApplicationTemplate); } /** * ้€š่ฟ‡id่Žทๅ–ๅ”ฏไธ€ๆจกๆฟ * @param elecApplicationTemplate elecApplicationTemplate * @return */ @Override public ElecApplicationTemplate findApplicationTemlateByID(ElecApplicationTemplate elecApplicationTemplate) { return elecApplicationTemplateDao.findObjectById(elecApplicationTemplate.getId()); } /** * ๆ›ดๆ–ฐๆจกๆฟไฟกๆฏ * @param elecApplicationTemplate elecApplicationTemplate */ @Override @Transactional(readOnly = false,isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED) public void updateApplicationTemplate(ElecApplicationTemplate elecApplicationTemplate) { //่Žทๅ–ไธŠไผ ็š„ๆ–‡ไปถupload๏ผŒ็”จๆฅๅˆคๆ–ญๆ˜ฏๅฆไธŠไผ ไบ†ๆ–ฐ็š„้™„ไปถ File file = elecApplicationTemplate.getUpload(); //ๆญคๆ—ถ่ฏดๆ˜ŽไธŠไผ ไบ†ๆ–ฐ็š„้™„ไปถ if(file!=null){ //่Žทๅ–้กต้ขไธญ้š่—ๅŸŸ็š„ๅ€ผpath่ทฏๅพ„๏ผŒไฝฟ็”จpath่ทฏๅพ„ๅˆ ้™คไน‹ๅ‰็š„้™„ไปถ String path = elecApplicationTemplate.getPath(); File oldFile = new File(path); if(oldFile.exists()){ //ๅˆ ้™คไน‹ๅ‰้™„ไปถ oldFile.delete(); } //ไธŠไผ ๆ–ฐ็š„้™„ไปถ๏ผŒ่ฟ”ๅ›ž่ทฏๅพ„path String newPath = FileUploadUtils.fileReturnPath(file); //็ป„็ป‡POๅฏน่ฑก๏ผŒๆ‰ง่กŒupdateๆ“ไฝœ elecApplicationTemplate.setPath(newPath); } elecApplicationTemplateDao.update(elecApplicationTemplate); } /** * ๅˆ ้™คๆจกๆฟไฟกๆฏ * @param elecApplicationTemplate elecApplicationTemplate */ @Override @Transactional(readOnly = false,isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED) public void deleteApplicationTemplate(ElecApplicationTemplate elecApplicationTemplate) { //่Žทๅ–็”ณ่ฏทๆจกๆฟ็š„ไธป้”ฎID Long id = elecApplicationTemplate.getId(); //ไฝฟ็”จID๏ผŒ่Žทๅ–็”ณ่ฏทๆจกๆฟ็š„่ฏฆ็ป†ไฟกๆฏ๏ผŒไปŽ่€Œ่Žทๅ–่ทฏๅพ„path๏ผŒไฝฟ็”จpathๅˆ ้™คไน‹ๅ‰ไธŠไผ ็š„้™„ไปถ ElecApplicationTemplate applicationTemplate = elecApplicationTemplateDao.findObjectById(id); String path = applicationTemplate.getPath();//่ทฏๅพ„path File oldFile = new File(path); if(oldFile.exists()){ //ๅˆ ้™คไน‹ๅ‰็š„้™„ไปถ oldFile.delete(); } //ไฝฟ็”จID๏ผŒๅˆ ้™คๆ•ฐๆฎๅบ“็š„ๆ•ฐๆฎ elecApplicationTemplateDao.deleteObjectByIds(id); } /** * ไธ‹่ฝฝๆจกๆฟ * @param elecApplicationTemplate elecApplicationTemplate * @return inputstream */ @Override public InputStream findInputStreamWithFile(ElecApplicationTemplate elecApplicationTemplate) { //่Žทๅ–็”ณ่ฏทๆจกๆฟ็š„ID Long id = elecApplicationTemplate.getId(); //ไฝฟ็”จ็”ณ่ฏทๆจกๆฟID๏ผŒๆŸฅ่ฏข็”ณ่ฏทๆจกๆฟ็š„่ฏฆ็ป†ไฟกๆฏ๏ผŒไปŽ่€Œ่Žทๅ–่ทฏๅพ„path ElecApplicationTemplate applicationTemplate = elecApplicationTemplateDao.findObjectById(id); //่Žทๅ–ๆจกๆฟ็š„ๅ็งฐ String name = applicationTemplate.getName(); //ๅค„็†ไธญๆ–‡ๅœจxmlไธญ็š„ๆ˜พ็คบ๏ผŒไฝฟ็”จUTF-8่ฟ›่กŒ็ผ–็  try { //name = URLEncoder.encode(name, "UTF-8"); name = new String(name.getBytes("gbk"),"iso-8859-1"); } catch (Exception e1) { e1.printStackTrace(); } //ๅฐ†ๆจกๆฟๅ็งฐๆ”พ็ฝฎๅˆฐๆ ˆ้กถ๏ผŒ็”จไบŽๅœจstruts.xmlๆ–‡ไปถไธญ<param name="contentDisposition">attachment;filename="${name}.doc"</param>ๆ˜พ็คบ elecApplicationTemplate.setName(name); //่ทฏๅพ„path String path = applicationTemplate.getPath(); //ไฝฟ็”จ่ทฏๅพ„path่Žทๅ–uploadๆ–‡ไปถๅคนไธ‹่ต„ๆบๆ–‡ไปถ๏ผŒ่ฝฌๆขๆˆInputStream่พ“ๅ…ฅๆตๅฏน่ฑก File file = new File(path); InputStream inputStream = null; try { inputStream = new FileInputStream(file); } catch (Exception e) { throw new RuntimeException(); } return inputStream; } }
5,949
0.699305
0.697049
141
36.737587
29.633614
126
false
false
0
0
0
0
0
0
0.41844
false
false
0
f022b6ead2d6c868a204c6517eb3bad1cc146164
9,199,820,003,869
33b00fab8a2ccc1b2d1746d9107c2941b18c71bd
/BaiTap/BaitapTuan6/Bai5Tuan6/app/src/main/java/com/example/bai5tuan6/MainActivity.java
2cd3ee913ca3cea61ec65de0d9209378807a1f71
[]
no_license
lhtrung307/AndroidProgramming
https://github.com/lhtrung307/AndroidProgramming
7b59f4bed201b608fb053e1d241eb0b65efd4ef0
7962d783701176ee4a4a55feb794056913fe0de2
refs/heads/master
2020-04-29T06:31:06.544000
2019-05-26T18:42:45
2019-05-26T18:42:45
175,918,389
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.bai5tuan6; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { Button btnSave; EditText txtName, txtPhone; ListView lvListContact; ArrayList<Contact> arrContact = new ArrayList<Contact>(); ArrayAdapter<Contact> arrayListview = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getWidgetsControl(); addEventsForFormWidgets(); } private void getWidgetsControl() { txtName = findViewById(R.id.txtName); txtPhone = findViewById(R.id.txtPhone); btnSave = findViewById(R.id.btnSave); lvListContact = findViewById(R.id.lvContact); // arrayListview = new ArrayAdapter<Contact>(this, android.R.layout.simple_list_item_1, arrContact); lvListContact.setAdapter(arrayListview); } private boolean isDuplicate(String name, String phone) { if (arrContact.size() > 0) { for (Contact c1 : arrContact) { if (c1.getName().trim().equalsIgnoreCase(name) && c1.getPhone_number().equals(phone)) return true; } return false; } return true; } private void Add_Contact() { Contact c = new Contact(txtName.getText().toString(), txtPhone.getText().toString()); // c.setName(txtName.getText().toString()); // c.setPhone_number(txtPhone.getText().toString()); arrContact.add(c); txtName.setText(""); txtPhone.setText(""); txtName.requestFocus(); } private void addEventsForFormWidgets() { btnSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (txtName.getText().toString().equals("")) { Toast.makeText(MainActivity.this, "Name is not allowed empty!", Toast.LENGTH_LONG).show(); return; } else if (txtPhone.getText().toString().equals("")) { Toast.makeText(MainActivity.this, "Phone is not allowed empty!", Toast.LENGTH_LONG).show(); return; } Add_Contact(); arrayListview.notifyDataSetChanged(); } }); } }
UTF-8
Java
2,705
java
MainActivity.java
Java
[ { "context": "package com.example.bai5tuan6;\n\nimport android.support.v7.app.AppCompatActivity", "end": 29, "score": 0.7807362675666809, "start": 22, "tag": "USERNAME", "value": "i5tuan6" } ]
null
[]
package com.example.bai5tuan6; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { Button btnSave; EditText txtName, txtPhone; ListView lvListContact; ArrayList<Contact> arrContact = new ArrayList<Contact>(); ArrayAdapter<Contact> arrayListview = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getWidgetsControl(); addEventsForFormWidgets(); } private void getWidgetsControl() { txtName = findViewById(R.id.txtName); txtPhone = findViewById(R.id.txtPhone); btnSave = findViewById(R.id.btnSave); lvListContact = findViewById(R.id.lvContact); // arrayListview = new ArrayAdapter<Contact>(this, android.R.layout.simple_list_item_1, arrContact); lvListContact.setAdapter(arrayListview); } private boolean isDuplicate(String name, String phone) { if (arrContact.size() > 0) { for (Contact c1 : arrContact) { if (c1.getName().trim().equalsIgnoreCase(name) && c1.getPhone_number().equals(phone)) return true; } return false; } return true; } private void Add_Contact() { Contact c = new Contact(txtName.getText().toString(), txtPhone.getText().toString()); // c.setName(txtName.getText().toString()); // c.setPhone_number(txtPhone.getText().toString()); arrContact.add(c); txtName.setText(""); txtPhone.setText(""); txtName.requestFocus(); } private void addEventsForFormWidgets() { btnSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (txtName.getText().toString().equals("")) { Toast.makeText(MainActivity.this, "Name is not allowed empty!", Toast.LENGTH_LONG).show(); return; } else if (txtPhone.getText().toString().equals("")) { Toast.makeText(MainActivity.this, "Phone is not allowed empty!", Toast.LENGTH_LONG).show(); return; } Add_Contact(); arrayListview.notifyDataSetChanged(); } }); } }
2,705
0.613309
0.610351
79
33.240505
24.646469
111
false
false
0
0
0
0
0
0
0.658228
false
false
0
f490882bafa5c8b374a11d2fe28cb49101e470d9
33,414,845,629,058
4bb614a06718efe738373ce2cdf7466c90245dd1
/app/src/main/java/pirala/herokuapp/com/dialogs/BookingDialog.java
27b979299cfb7be6e19fa851da57894b27ba5e3f
[]
no_license
Gvetri/PiralaAndroid
https://github.com/Gvetri/PiralaAndroid
36cf929ac069ad49c0d4fc1663544ebbf6b7e91a
b0b937dd3cd8ef34e7dd65d535e1d8d66bae0999
refs/heads/master
2020-04-06T06:53:33.978000
2016-09-06T17:14:33
2016-09-06T17:14:33
62,278,656
0
0
null
false
2016-09-06T17:14:33
2016-06-30T04:12:31
2016-06-30T04:15:27
2016-09-06T17:14:33
1,037
0
0
0
Java
null
null
package pirala.herokuapp.com.dialogs; import android.app.Dialog; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.DialogFragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; import pirala.herokuapp.com.R; import pirala.herokuapp.com.model.Booking; /** * Created by giuseppe on 22/07/16. */ public class BookingDialog extends DialogFragment { private static final String URL = "https://pirala.herokuapp.com/api/v1/bookings/"; private static final String TAG = "BookingDialog"; private static final String MY_PREFS_NAME = "USERINFO"; private RequestQueue requestQueue; public BookingDialog(){ } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.dialog_booking,container,false); TextView hotel_name = (TextView) view.findViewById(R.id.hotel_name); TextView booking_in = (TextView) view.findViewById(R.id.booking_in); TextView booking_out = (TextView) view.findViewById(R.id.booking_out); TextView created_at = (TextView) view.findViewById(R.id.created_at); TextView status = (TextView) view.findViewById(R.id.status); Button delete_booking = (Button) view.findViewById(R.id.button); ImageView back_nav = (ImageView) view.findViewById(R.id.back_nav); final Booking booking = getArguments().getParcelable("booking"); requestQueue = Volley.newRequestQueue(getContext()); if (booking == null) { Toast.makeText(getActivity(), "Ha ocurrido un error cargando la informacion de la reserva", Toast.LENGTH_SHORT).show(); } else{ try { hotel_name.setText(booking.getHotel_name()); booking_in.setText(booking.getDate_in()); booking_out.setText(booking.getDate_out()); String created_at_string = truncateDate(booking.getCreated_at()); //Truncate shows only the first 10 char of the date created_at.setText(created_at_string); String status_string = booleanToString(booking.getStatus()); status.setText(status_string); back_nav.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getDialog().dismiss(); } }); delete_booking.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EliminarBooking(booking); } }); } catch (Exception e) { e.printStackTrace(); } } return view; } private String truncateDate(String date) { String s; if (date.equals("No disponible")) { s = date; } else { s = date.substring(0,10); } return s; } private void EliminarBooking(Booking booking) { String url = URL+ booking.getId()+ ".json"; Log.i(TAG,url); JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.DELETE, url, null, new Response.Listener<JSONObject>(){ @Override public void onResponse(JSONObject response) { Log.i(TAG,"Response: "+ response.toString()); try { if(response.getString("code").equals("0")){ Toast.makeText(getActivity(), "La reserva ha sido eliminada", Toast.LENGTH_SHORT).show(); getDialog().dismiss(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); Toast.makeText(getActivity(), "Ha ocurrido un error eliminando la reserva", Toast.LENGTH_SHORT).show(); } }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); String email_string = getEmailCredential(); String token_string = getTokenCredential(); Log.i(TAG,"EMAIL Y TOKEN : "+email_string + token_string); headers.put("Content-Type", "application/json; charset=utf-8"); headers.put("Accept","application/json"); headers.put("X-User-Email",email_string); headers.put("X-User-Token",token_string); return headers; } }; requestQueue.add(jsonObjectRequest); } private String getTokenCredential() { String s; SharedPreferences sharedPreferences = getActivity().getSharedPreferences(MY_PREFS_NAME, Context.MODE_PRIVATE); s = sharedPreferences.getString("token", null); return s; } private String getEmailCredential() { String s; SharedPreferences sharedPreferences = getActivity().getSharedPreferences(MY_PREFS_NAME, Context.MODE_PRIVATE); s = sharedPreferences.getString("email", null); return s; } private String booleanToString(Boolean status) { String s; if (status){ s = "Activa"; } else { s = "Suspendida"; } return s; } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Dialog dialog = super.onCreateDialog(savedInstanceState); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); return dialog; } public static BookingDialog newInstance(Booking booking){ BookingDialog f = new BookingDialog(); Bundle args = new Bundle(); args.putParcelable("booking",booking); f.setArguments(args); return f; } @Override public void onResume() { // Get existing layout params for the window ViewGroup.LayoutParams params = getDialog().getWindow().getAttributes(); // Assign window properties to fill the parent params.width = WindowManager.LayoutParams.MATCH_PARENT; params.height = WindowManager.LayoutParams.MATCH_PARENT; getDialog().getWindow().setAttributes((android.view.WindowManager.LayoutParams) params); // Call super onResume after sizing super.onResume(); } }
UTF-8
Java
7,723
java
BookingDialog.java
Java
[ { "context": "la.herokuapp.com.model.Booking;\n\n/**\n * Created by giuseppe on 22/07/16.\n */\npublic class BookingDialog exten", "end": 1169, "score": 0.9995948076248169, "start": 1161, "tag": "USERNAME", "value": "giuseppe" } ]
null
[]
package pirala.herokuapp.com.dialogs; import android.app.Dialog; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.DialogFragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; import pirala.herokuapp.com.R; import pirala.herokuapp.com.model.Booking; /** * Created by giuseppe on 22/07/16. */ public class BookingDialog extends DialogFragment { private static final String URL = "https://pirala.herokuapp.com/api/v1/bookings/"; private static final String TAG = "BookingDialog"; private static final String MY_PREFS_NAME = "USERINFO"; private RequestQueue requestQueue; public BookingDialog(){ } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.dialog_booking,container,false); TextView hotel_name = (TextView) view.findViewById(R.id.hotel_name); TextView booking_in = (TextView) view.findViewById(R.id.booking_in); TextView booking_out = (TextView) view.findViewById(R.id.booking_out); TextView created_at = (TextView) view.findViewById(R.id.created_at); TextView status = (TextView) view.findViewById(R.id.status); Button delete_booking = (Button) view.findViewById(R.id.button); ImageView back_nav = (ImageView) view.findViewById(R.id.back_nav); final Booking booking = getArguments().getParcelable("booking"); requestQueue = Volley.newRequestQueue(getContext()); if (booking == null) { Toast.makeText(getActivity(), "Ha ocurrido un error cargando la informacion de la reserva", Toast.LENGTH_SHORT).show(); } else{ try { hotel_name.setText(booking.getHotel_name()); booking_in.setText(booking.getDate_in()); booking_out.setText(booking.getDate_out()); String created_at_string = truncateDate(booking.getCreated_at()); //Truncate shows only the first 10 char of the date created_at.setText(created_at_string); String status_string = booleanToString(booking.getStatus()); status.setText(status_string); back_nav.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getDialog().dismiss(); } }); delete_booking.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EliminarBooking(booking); } }); } catch (Exception e) { e.printStackTrace(); } } return view; } private String truncateDate(String date) { String s; if (date.equals("No disponible")) { s = date; } else { s = date.substring(0,10); } return s; } private void EliminarBooking(Booking booking) { String url = URL+ booking.getId()+ ".json"; Log.i(TAG,url); JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.DELETE, url, null, new Response.Listener<JSONObject>(){ @Override public void onResponse(JSONObject response) { Log.i(TAG,"Response: "+ response.toString()); try { if(response.getString("code").equals("0")){ Toast.makeText(getActivity(), "La reserva ha sido eliminada", Toast.LENGTH_SHORT).show(); getDialog().dismiss(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); Toast.makeText(getActivity(), "Ha ocurrido un error eliminando la reserva", Toast.LENGTH_SHORT).show(); } }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); String email_string = getEmailCredential(); String token_string = getTokenCredential(); Log.i(TAG,"EMAIL Y TOKEN : "+email_string + token_string); headers.put("Content-Type", "application/json; charset=utf-8"); headers.put("Accept","application/json"); headers.put("X-User-Email",email_string); headers.put("X-User-Token",token_string); return headers; } }; requestQueue.add(jsonObjectRequest); } private String getTokenCredential() { String s; SharedPreferences sharedPreferences = getActivity().getSharedPreferences(MY_PREFS_NAME, Context.MODE_PRIVATE); s = sharedPreferences.getString("token", null); return s; } private String getEmailCredential() { String s; SharedPreferences sharedPreferences = getActivity().getSharedPreferences(MY_PREFS_NAME, Context.MODE_PRIVATE); s = sharedPreferences.getString("email", null); return s; } private String booleanToString(Boolean status) { String s; if (status){ s = "Activa"; } else { s = "Suspendida"; } return s; } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Dialog dialog = super.onCreateDialog(savedInstanceState); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); return dialog; } public static BookingDialog newInstance(Booking booking){ BookingDialog f = new BookingDialog(); Bundle args = new Bundle(); args.putParcelable("booking",booking); f.setArguments(args); return f; } @Override public void onResume() { // Get existing layout params for the window ViewGroup.LayoutParams params = getDialog().getWindow().getAttributes(); // Assign window properties to fill the parent params.width = WindowManager.LayoutParams.MATCH_PARENT; params.height = WindowManager.LayoutParams.MATCH_PARENT; getDialog().getWindow().setAttributes((android.view.WindowManager.LayoutParams) params); // Call super onResume after sizing super.onResume(); } }
7,723
0.612715
0.610773
219
34.264839
28.891439
131
false
false
0
0
0
0
0
0
0.643836
false
false
0
abd888bc341ebf29f89de3434203b6c941156e07
24,653,112,344,272
a156346a45943ccd9085e81b2c5d6bec71352890
/dependency-watcher-server/src/main/java/com/nuance/mobility/dependencywatcher/data/DependencyRepository.java
ce499184058cf6c342cf80f87c1c3530ec6636a0
[]
no_license
lumeche/dependency-watcher
https://github.com/lumeche/dependency-watcher
5a04800001f431bce02a30f4b99b3a14c1f2d8ec
f1b5019a2561d9f444270d691ca741b6e35327a3
refs/heads/master
2020-12-03T03:46:01.579000
2017-07-13T14:50:13
2017-07-13T14:50:13
95,770,902
0
2
null
false
2017-07-12T14:53:44
2017-06-29T11:29:21
2017-06-29T17:37:07
2017-07-12T14:53:43
107
0
1
1
Java
null
null
package com.nuance.mobility.dependencywatcher.data; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.function.Predicate; import org.apache.commons.collections.ListUtils; import org.springframework.stereotype.Component; import com.nuance.mobility.dependencywatcher.artifact.Artifact; //TODO: Make sure that this class is thread safe @Component public class DependencyRepository { private ConcurrentMap<Artifact, List<Artifact>> repository; public DependencyRepository(){ repository=new ConcurrentHashMap<Artifact,List<Artifact>>(); } public List<Artifact> getArtifactDependencies(Artifact artifact){ return new ArrayList<Artifact>(repository.getOrDefault(artifact, ListUtils.EMPTY_LIST)); } public void updateDependency(Artifact artifact,List<Artifact> dependencies){ repository.put(artifact, new ArrayList<Artifact>(dependencies)); } public List<Artifact> getArtifactsThatDependsOn(final Artifact dependency){ Object[] ret = repository.entrySet().parallelStream().filter(new Predicate<Map.Entry<Artifact, List<Artifact>>>() { @Override public boolean test(Map.Entry<Artifact, List<Artifact>> t) { return t.getValue().contains(dependency); } }).map(e-> e.getKey()).toArray(); ArrayList<Artifact> dependencies = new ArrayList<Artifact>(); for (int i = 0; i < ret.length; i++) { dependencies.add((Artifact)ret[i]); } return dependencies; } }
UTF-8
Java
1,531
java
DependencyRepository.java
Java
[]
null
[]
package com.nuance.mobility.dependencywatcher.data; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.function.Predicate; import org.apache.commons.collections.ListUtils; import org.springframework.stereotype.Component; import com.nuance.mobility.dependencywatcher.artifact.Artifact; //TODO: Make sure that this class is thread safe @Component public class DependencyRepository { private ConcurrentMap<Artifact, List<Artifact>> repository; public DependencyRepository(){ repository=new ConcurrentHashMap<Artifact,List<Artifact>>(); } public List<Artifact> getArtifactDependencies(Artifact artifact){ return new ArrayList<Artifact>(repository.getOrDefault(artifact, ListUtils.EMPTY_LIST)); } public void updateDependency(Artifact artifact,List<Artifact> dependencies){ repository.put(artifact, new ArrayList<Artifact>(dependencies)); } public List<Artifact> getArtifactsThatDependsOn(final Artifact dependency){ Object[] ret = repository.entrySet().parallelStream().filter(new Predicate<Map.Entry<Artifact, List<Artifact>>>() { @Override public boolean test(Map.Entry<Artifact, List<Artifact>> t) { return t.getValue().contains(dependency); } }).map(e-> e.getKey()).toArray(); ArrayList<Artifact> dependencies = new ArrayList<Artifact>(); for (int i = 0; i < ret.length; i++) { dependencies.add((Artifact)ret[i]); } return dependencies; } }
1,531
0.768779
0.768125
48
30.895834
29.348652
117
false
false
0
0
0
0
0
0
1.625
false
false
0
f27e75f5967613d38a07c8960828411b0f28a3c9
36,524,401,913,565
8054a1f10869b2326552ebc5f994a861a678bdd0
/src/test/java/com/practicalunittesting/chp06/collections/TDDNarrowingTest.java
4d1a9b72ece40a47ec2ea3afa59d59de154c076e
[]
no_license
melmoutaoukil/Projet1
https://github.com/melmoutaoukil/Projet1
e5bf1af4c6c74c8c912e2566afd73b901c4a9662
2d0e2d7f92a3903ca628bf2794bff90e87519294
refs/heads/master
2020-09-30T14:18:24.087000
2016-09-16T14:29:53
2016-09-16T14:29:53
67,812,246
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.practicalunittesting.chp06.collections; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.*; /** * Practical Unit Testing with JUnit and Mockito - source code for examples. * Visit http://practicalunittesting.com for more information. * * @author Tomek Kaczanowski */ public class TDDNarrowingTest { class User { private List<String> phones = new ArrayList<String>(); public List<String> getPhones() { return phones; } public void addPhone(String s) { phones.add(s); } } private User user = new User(); @Test public void newUserHasNoPhone() { assertNotNull(user.getPhones()); assertTrue(user.getPhones().isEmpty()); } @Test public void shouldReturnAllPhonesOfUser() { user.addPhone("123 456 789"); List<String> phones = user.getPhones(); assertNotNull(phones); assertFalse(phones.isEmpty()); assertEquals(1, phones.size()); assertTrue(phones.contains("123 456 789")); } }
UTF-8
Java
996
java
TDDNarrowingTest.java
Java
[ { "context": "nittesting.com for more information.\n *\n * @author Tomek Kaczanowski\n */\npublic class TDDNarrowingTest {\n\n\tclass User ", "end": 339, "score": 0.9996668696403503, "start": 322, "tag": "NAME", "value": "Tomek Kaczanowski" } ]
null
[]
package com.practicalunittesting.chp06.collections; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.*; /** * Practical Unit Testing with JUnit and Mockito - source code for examples. * Visit http://practicalunittesting.com for more information. * * @author <NAME> */ public class TDDNarrowingTest { class User { private List<String> phones = new ArrayList<String>(); public List<String> getPhones() { return phones; } public void addPhone(String s) { phones.add(s); } } private User user = new User(); @Test public void newUserHasNoPhone() { assertNotNull(user.getPhones()); assertTrue(user.getPhones().isEmpty()); } @Test public void shouldReturnAllPhonesOfUser() { user.addPhone("123 456 789"); List<String> phones = user.getPhones(); assertNotNull(phones); assertFalse(phones.isEmpty()); assertEquals(1, phones.size()); assertTrue(phones.contains("123 456 789")); } }
985
0.713855
0.692771
48
19.75
19.75211
76
false
false
0
0
0
0
0
0
1.229167
false
false
0
26866e4638793af14c0c1e5ebcd4cb9d0ee5f940
4,844,723,138,952
3303ad8d14ae930027927152452ae90ad92a6c74
/prodcons/NewsProducer.java
66ea0829eb0a3da382b2d44a1da0cca378a1aa1e
[]
no_license
cmcwerner/creolJava
https://github.com/cmcwerner/creolJava
9e3550ebdf31465f799b7069f79da130f5a1806b
42b63c9aa598c1277eba192bb0469144767d0adc
refs/heads/master
2021-01-17T13:42:39.701000
2016-07-25T21:47:13
2016-07-25T21:47:13
25,713,133
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import creol.*; import java.util.*; public class NewsProducer extends CreolObject{ private ArrayList<News> requests = new ArrayList<News>(); public void add(News ns) { requests.add(ns); } public News getNews() { while (requests.size() <= 0) creolAwait(); News firstNews = requests.remove(0); return firstNews; } }
UTF-8
Java
345
java
NewsProducer.java
Java
[]
null
[]
import creol.*; import java.util.*; public class NewsProducer extends CreolObject{ private ArrayList<News> requests = new ArrayList<News>(); public void add(News ns) { requests.add(ns); } public News getNews() { while (requests.size() <= 0) creolAwait(); News firstNews = requests.remove(0); return firstNews; } }
345
0.666667
0.66087
15
21.933332
18.25182
59
false
false
0
0
0
0
0
0
0.466667
false
false
0
3ebf4a0fce68f4993650281c930e71b6f424a289
6,734,508,785,698
cdd9ef22064ee3939001c06de23f44b2ae9cc042
/src/main/java/org/example/data/Account.java
12cfb5054ff95ea7f090969c74abf5baa10cf607
[]
no_license
NPEKL/sync2obj
https://github.com/NPEKL/sync2obj
371173501a491c27a68561a0337d72492530602c
0f28d99c20a13300141487ff56227cac5ebd7d20
refs/heads/main
2023-07-02T04:22:15.627000
2021-07-30T06:41:59
2021-07-30T06:41:59
390,877,367
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.example.data; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class Account { private volatile Long moneyAccount; private final String name; private final Lock lock; public Account(String name, long startMoney) { this.name = name; this.lock = new ReentrantLock(false); this.moneyAccount = startMoney; } public void add(long money) { this.moneyAccount += money; } public boolean minus(long money) { if (this.moneyAccount - money >= 0) { this.moneyAccount -= money; return true; } else { return false; } } public void lock() { lock.lock(); } public void unlock() { lock.unlock(); } public String getName() { return name; } public Long getMoneyAccount() { return moneyAccount; } @Override public String toString() { return "Account{" + "moneyAccount=" + moneyAccount + ", name='" + name + '}'; } }
UTF-8
Java
1,126
java
Account.java
Java
[]
null
[]
package org.example.data; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class Account { private volatile Long moneyAccount; private final String name; private final Lock lock; public Account(String name, long startMoney) { this.name = name; this.lock = new ReentrantLock(false); this.moneyAccount = startMoney; } public void add(long money) { this.moneyAccount += money; } public boolean minus(long money) { if (this.moneyAccount - money >= 0) { this.moneyAccount -= money; return true; } else { return false; } } public void lock() { lock.lock(); } public void unlock() { lock.unlock(); } public String getName() { return name; } public Long getMoneyAccount() { return moneyAccount; } @Override public String toString() { return "Account{" + "moneyAccount=" + moneyAccount + ", name='" + name + '}'; } }
1,126
0.554174
0.553286
54
19.851852
15.91925
50
false
false
0
0
0
0
0
0
0.37037
false
false
0
f3a5760d1889fcab1806ba7b0c3d44c44640e62d
33,998,961,159,933
fd6e29bdcba924f00674e6ef374eda836cdc5c30
/Programiranje1/Izpit/Grafika/Pravokotniki.java
a9a51712f73aaf3cd9ac4dbaf903133eb6098724
[ "MIT" ]
permissive
RokKos/FRI_Programiranje
https://github.com/RokKos/FRI_Programiranje
58ee8826631ffaf36360fac8d46fec7635321eaf
d1b0c73585af049be9283447039f5f3e3fa4bdd9
refs/heads/master
2021-06-16T08:25:24.079000
2019-12-20T14:36:12
2019-12-20T14:36:12
74,551,325
5
12
MIT
false
2021-06-11T17:58:10
2016-11-23T07:26:30
2020-07-29T07:54:38
2021-06-11T17:58:10
229,300
4
5
2
HTML
false
false
// Samo oznacevanje g.setColor(Color.BLACK); g.drawString("(0,0)",7,10); g.drawString("(0,hp)",7,ri(hp-10)); g.drawString("(wp,0)",ri(wp)-40,10); g.drawString("(wp,hp)",ri(wp)-50,ri(hp)-10); g.drawString("x", ri(wp / 2), 10); g.drawString("y", 0, ri(hp / 2)); // Risanje pravokotnikov int levoZgorajX = 50; int levoZgorajY = 100; int dolzina = 75; int visina = 200; // Zaznamek za levi zgornji kot g.drawString(String.format("(%d,%d)",levoZgorajX, levoZgorajY),levoZgorajX,levoZgorajY); g.drawRect(levoZgorajX, levoZgorajY, dolzina, visina); // Zaznamek za levi zgornji kot g.drawString(String.format("(%d,%d)",levoZgorajX * 2, levoZgorajY * 2),levoZgorajX * 2,levoZgorajY * 2); g.setColor(Color.BLUE); g.fillRect(levoZgorajX * 2, levoZgorajY * 2, dolzina * 2, visina * 2);
UTF-8
Java
775
java
Pravokotniki.java
Java
[]
null
[]
// Samo oznacevanje g.setColor(Color.BLACK); g.drawString("(0,0)",7,10); g.drawString("(0,hp)",7,ri(hp-10)); g.drawString("(wp,0)",ri(wp)-40,10); g.drawString("(wp,hp)",ri(wp)-50,ri(hp)-10); g.drawString("x", ri(wp / 2), 10); g.drawString("y", 0, ri(hp / 2)); // Risanje pravokotnikov int levoZgorajX = 50; int levoZgorajY = 100; int dolzina = 75; int visina = 200; // Zaznamek za levi zgornji kot g.drawString(String.format("(%d,%d)",levoZgorajX, levoZgorajY),levoZgorajX,levoZgorajY); g.drawRect(levoZgorajX, levoZgorajY, dolzina, visina); // Zaznamek za levi zgornji kot g.drawString(String.format("(%d,%d)",levoZgorajX * 2, levoZgorajY * 2),levoZgorajX * 2,levoZgorajY * 2); g.setColor(Color.BLUE); g.fillRect(levoZgorajX * 2, levoZgorajY * 2, dolzina * 2, visina * 2);
775
0.689032
0.636129
21
35.904762
24.104742
104
false
false
0
0
0
0
0
0
2.285714
false
false
0
0c2bf04af6a1733eabae3dd1b8de5bb8b7de73b5
31,267,361,973,056
2bf30c31677494a379831352befde4a5e3d8ed19
/exportLibraries/scaleio/src/main/java/com/emc/storageos/scaleio/api/ScaleIOVersionCommand.java
58b7d6e11aeac369240e2aa3cf9aff4f2efc39fb
[]
no_license
dennywangdengyu/coprhd-controller
https://github.com/dennywangdengyu/coprhd-controller
fed783054a4970c5f891e83d696a4e1e8364c424
116c905ae2728131e19631844eecf49566e46db9
refs/heads/master
2020-12-30T22:43:41.462000
2015-07-23T18:09:30
2015-07-23T18:09:30
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright 2015 EMC Corporation * All Rights Reserved */ /* * Copyright (c) 2014 EMC Corporation * * All Rights Reserved * * This software contains the intellectual property of EMC Corporation * or is licensed to EMC Corporation from third parties. Use of this * software and the intellectual property contained therein is expressly * limited to the terms and conditions of the License Agreement under which * it is provided by or on behalf of EMC. */ package com.emc.storageos.scaleio.api; import java.util.List; import java.util.Stack; public class ScaleIOVersionCommand extends AbstractScaleIOQueryCommand<ScaleIOVersionResult> { public static final String VERSION_STRING = "VersionString"; // Examples: // EMC ScaleIO Version: R1_30.17.1 // ScaleIO ECS Version: R1_21.0.20 private final static ParsePattern[] PARSING_CONFIG = new ParsePattern[]{ new ParsePattern(".*?\\s+Version:\\s+\\w{1}(.*)", VERSION_STRING), }; public ScaleIOVersionCommand() { addArgument("--version"); } @Override ParsePattern[] getOutputPatternSpecification() { return PARSING_CONFIG.clone(); //No need to check not null condition here } @Override void beforeProcessing() { results = new ScaleIOVersionResult(); } @Override void processMatch(ParsePattern spec, List<String> capturedStrings) { results.setVersion(capturedStrings.get(0)); } }
UTF-8
Java
1,463
java
ScaleIOVersionCommand.java
Java
[]
null
[]
/* * Copyright 2015 EMC Corporation * All Rights Reserved */ /* * Copyright (c) 2014 EMC Corporation * * All Rights Reserved * * This software contains the intellectual property of EMC Corporation * or is licensed to EMC Corporation from third parties. Use of this * software and the intellectual property contained therein is expressly * limited to the terms and conditions of the License Agreement under which * it is provided by or on behalf of EMC. */ package com.emc.storageos.scaleio.api; import java.util.List; import java.util.Stack; public class ScaleIOVersionCommand extends AbstractScaleIOQueryCommand<ScaleIOVersionResult> { public static final String VERSION_STRING = "VersionString"; // Examples: // EMC ScaleIO Version: R1_30.17.1 // ScaleIO ECS Version: R1_21.0.20 private final static ParsePattern[] PARSING_CONFIG = new ParsePattern[]{ new ParsePattern(".*?\\s+Version:\\s+\\w{1}(.*)", VERSION_STRING), }; public ScaleIOVersionCommand() { addArgument("--version"); } @Override ParsePattern[] getOutputPatternSpecification() { return PARSING_CONFIG.clone(); //No need to check not null condition here } @Override void beforeProcessing() { results = new ScaleIOVersionResult(); } @Override void processMatch(ParsePattern spec, List<String> capturedStrings) { results.setVersion(capturedStrings.get(0)); } }
1,463
0.696514
0.681476
52
27.134615
28.070673
94
false
false
0
0
0
0
0
0
0.230769
false
false
0
8efd39f369a58726094e54a01e60254eb2976cbe
37,830,071,957,662
ea5f76a6c722fd38005cfb0c256bb3b4b2649d6e
/rockframework-core/src/main/java/br/net/woodstock/rockframework/xml/dom/DocumentWrapper.java
a78506f0de1e619e4bfc001136adb72c27a08d07
[]
no_license
flaviooo/rockframework
https://github.com/flaviooo/rockframework
fbf867c623cebb0062167c93b5972eb8d99af327
8c3c18c587e2131dd8f84c804b845f91a7c296be
refs/heads/master
2018-01-09T05:38:04.037000
2012-08-31T20:41:47
2012-08-31T20:41:47
46,314,145
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * This file is part of rockframework. * * rockframework is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * rockframework is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>;. */ package br.net.woodstock.rockframework.xml.dom; import java.io.Serializable; import org.w3c.dom.Attr; import org.w3c.dom.CDATASection; import org.w3c.dom.Comment; import org.w3c.dom.DOMConfiguration; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; import org.w3c.dom.DocumentFragment; import org.w3c.dom.DocumentType; import org.w3c.dom.Element; import org.w3c.dom.EntityReference; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.ProcessingInstruction; import org.w3c.dom.Text; import org.w3c.dom.UserDataHandler; abstract class DocumentWrapper implements Cloneable, Comparable<Document>, Document, Serializable { private static final long serialVersionUID = 2580717334916435297L; private Document document; @Override public abstract int compareTo(Document o); public Document getDocument() { return this.document; } public void setDocument(final Document document) { this.document = document; } @Override public DocumentType getDoctype() { return this.document.getDoctype(); } @Override public DOMImplementation getImplementation() { return this.document.getImplementation(); } @Override public Element getDocumentElement() { return this.document.getDocumentElement(); } @Override public Element createElement(final String tagName) { return this.document.createElement(tagName); } @Override public DocumentFragment createDocumentFragment() { return this.document.createDocumentFragment(); } @Override public Text createTextNode(final String data) { return this.document.createTextNode(data); } @Override public Comment createComment(final String data) { return this.document.createComment(data); } @Override public CDATASection createCDATASection(final String data) { return this.document.createCDATASection(data); } @Override public ProcessingInstruction createProcessingInstruction(final String target, final String data) { return this.document.createProcessingInstruction(target, data); } @Override public Attr createAttribute(final String name) { return this.document.createAttribute(name); } @Override public EntityReference createEntityReference(final String name) { return this.document.createEntityReference(name); } @Override public NodeList getElementsByTagName(final String tagname) { return this.document.getElementsByTagName(tagname); } @Override public Node importNode(final Node importedNode, final boolean deep) { return this.document.importNode(importedNode, deep); } @Override public Element createElementNS(final String namespaceURI, final String qualifiedName) { return this.document.createElementNS(namespaceURI, qualifiedName); } @Override public Attr createAttributeNS(final String namespaceURI, final String qualifiedName) { return this.document.createAttributeNS(namespaceURI, qualifiedName); } @Override public NodeList getElementsByTagNameNS(final String namespaceURI, final String localName) { return this.document.getElementsByTagNameNS(namespaceURI, localName); } @Override public Element getElementById(final String elementId) { return this.document.getElementById(elementId); } @Override public String getInputEncoding() { return this.document.getInputEncoding(); } @Override public String getXmlEncoding() { return this.document.getXmlEncoding(); } @Override public boolean getXmlStandalone() { return this.document.getXmlStandalone(); } @Override public void setXmlStandalone(final boolean xmlStandalone) { this.document.setXmlStandalone(xmlStandalone); } @Override public String getXmlVersion() { return this.document.getXmlVersion(); } @Override public void setXmlVersion(final String xmlVersion) { this.document.setXmlVersion(xmlVersion); } @Override public boolean getStrictErrorChecking() { return this.document.getStrictErrorChecking(); } @Override public void setStrictErrorChecking(final boolean strictErrorChecking) { this.document.setStrictErrorChecking(strictErrorChecking); } @Override public String getDocumentURI() { return this.document.getDocumentURI(); } @Override public void setDocumentURI(final String documentURI) { this.document.setDocumentURI(documentURI); } @Override public Node adoptNode(final Node source) { return this.document.adoptNode(source); } @Override public DOMConfiguration getDomConfig() { return this.document.getDomConfig(); } @Override public void normalizeDocument() { this.document.normalizeDocument(); } @Override public Node renameNode(final Node n, final String namespaceURI, final String qualifiedName) { return this.document.renameNode(n, namespaceURI, qualifiedName); } @Override public String getNodeName() { return this.document.getNodeName(); } @Override public String getNodeValue() { return this.document.getNodeValue(); } @Override public void setNodeValue(final String nodeValue) { this.document.setNodeValue(nodeValue); } @Override public short getNodeType() { return this.document.getNodeType(); } @Override public Node getParentNode() { return this.document.getParentNode(); } @Override public NodeList getChildNodes() { return this.document.getChildNodes(); } @Override public Node getFirstChild() { return this.document.getFirstChild(); } @Override public Node getLastChild() { return this.document.getLastChild(); } @Override public Node getPreviousSibling() { return this.document.getPreviousSibling(); } @Override public Node getNextSibling() { return this.document.getNextSibling(); } @Override public NamedNodeMap getAttributes() { return this.document.getAttributes(); } @Override public Document getOwnerDocument() { return this.document.getOwnerDocument(); } @Override public Node insertBefore(final Node newChild, final Node refChild) { return this.document.insertBefore(newChild, refChild); } @Override public Node replaceChild(final Node newChild, final Node oldChild) { return this.document.replaceChild(newChild, oldChild); } @Override public Node removeChild(final Node oldChild) { return this.document.removeChild(oldChild); } @Override public Node appendChild(final Node newChild) { return this.document.appendChild(newChild); } @Override public boolean hasChildNodes() { return this.document.hasChildNodes(); } @Override public Node cloneNode(final boolean deep) { return this.document.cloneNode(deep); } @Override public void normalize() { this.document.normalize(); } @Override public boolean isSupported(final String feature, final String version) { return this.document.isSupported(feature, version); } @Override public String getNamespaceURI() { return this.document.getNamespaceURI(); } @Override public String getPrefix() { return this.document.getPrefix(); } @Override public void setPrefix(final String prefix) { this.document.setPrefix(prefix); } @Override public String getLocalName() { return this.document.getLocalName(); } @Override public boolean hasAttributes() { return this.document.hasAttributes(); } @Override public String getBaseURI() { return this.document.getBaseURI(); } @Override public short compareDocumentPosition(final Node other) { return this.document.compareDocumentPosition(other); } @Override public String getTextContent() { return this.document.getTextContent(); } @Override public void setTextContent(final String textContent) { this.document.setTextContent(textContent); } @Override public boolean isSameNode(final Node other) { return this.document.isSameNode(other); } @Override public String lookupPrefix(final String namespaceURI) { return this.document.lookupPrefix(namespaceURI); } @Override public boolean isDefaultNamespace(final String namespaceURI) { return this.document.isDefaultNamespace(namespaceURI); } @Override public String lookupNamespaceURI(final String prefix) { return this.document.lookupNamespaceURI(prefix); } @Override public boolean isEqualNode(final Node arg) { return this.document.isEqualNode(arg); } @Override public Object getFeature(final String feature, final String version) { return this.document.getFeature(feature, version); } @Override public Object setUserData(final String key, final Object data, final UserDataHandler handler) { return this.document.setUserData(key, data, handler); } @Override public Object getUserData(final String key) { return this.document.getUserData(key); } }
UTF-8
Java
9,287
java
DocumentWrapper.java
Java
[]
null
[]
/* * This file is part of rockframework. * * rockframework is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * rockframework is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>;. */ package br.net.woodstock.rockframework.xml.dom; import java.io.Serializable; import org.w3c.dom.Attr; import org.w3c.dom.CDATASection; import org.w3c.dom.Comment; import org.w3c.dom.DOMConfiguration; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; import org.w3c.dom.DocumentFragment; import org.w3c.dom.DocumentType; import org.w3c.dom.Element; import org.w3c.dom.EntityReference; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.ProcessingInstruction; import org.w3c.dom.Text; import org.w3c.dom.UserDataHandler; abstract class DocumentWrapper implements Cloneable, Comparable<Document>, Document, Serializable { private static final long serialVersionUID = 2580717334916435297L; private Document document; @Override public abstract int compareTo(Document o); public Document getDocument() { return this.document; } public void setDocument(final Document document) { this.document = document; } @Override public DocumentType getDoctype() { return this.document.getDoctype(); } @Override public DOMImplementation getImplementation() { return this.document.getImplementation(); } @Override public Element getDocumentElement() { return this.document.getDocumentElement(); } @Override public Element createElement(final String tagName) { return this.document.createElement(tagName); } @Override public DocumentFragment createDocumentFragment() { return this.document.createDocumentFragment(); } @Override public Text createTextNode(final String data) { return this.document.createTextNode(data); } @Override public Comment createComment(final String data) { return this.document.createComment(data); } @Override public CDATASection createCDATASection(final String data) { return this.document.createCDATASection(data); } @Override public ProcessingInstruction createProcessingInstruction(final String target, final String data) { return this.document.createProcessingInstruction(target, data); } @Override public Attr createAttribute(final String name) { return this.document.createAttribute(name); } @Override public EntityReference createEntityReference(final String name) { return this.document.createEntityReference(name); } @Override public NodeList getElementsByTagName(final String tagname) { return this.document.getElementsByTagName(tagname); } @Override public Node importNode(final Node importedNode, final boolean deep) { return this.document.importNode(importedNode, deep); } @Override public Element createElementNS(final String namespaceURI, final String qualifiedName) { return this.document.createElementNS(namespaceURI, qualifiedName); } @Override public Attr createAttributeNS(final String namespaceURI, final String qualifiedName) { return this.document.createAttributeNS(namespaceURI, qualifiedName); } @Override public NodeList getElementsByTagNameNS(final String namespaceURI, final String localName) { return this.document.getElementsByTagNameNS(namespaceURI, localName); } @Override public Element getElementById(final String elementId) { return this.document.getElementById(elementId); } @Override public String getInputEncoding() { return this.document.getInputEncoding(); } @Override public String getXmlEncoding() { return this.document.getXmlEncoding(); } @Override public boolean getXmlStandalone() { return this.document.getXmlStandalone(); } @Override public void setXmlStandalone(final boolean xmlStandalone) { this.document.setXmlStandalone(xmlStandalone); } @Override public String getXmlVersion() { return this.document.getXmlVersion(); } @Override public void setXmlVersion(final String xmlVersion) { this.document.setXmlVersion(xmlVersion); } @Override public boolean getStrictErrorChecking() { return this.document.getStrictErrorChecking(); } @Override public void setStrictErrorChecking(final boolean strictErrorChecking) { this.document.setStrictErrorChecking(strictErrorChecking); } @Override public String getDocumentURI() { return this.document.getDocumentURI(); } @Override public void setDocumentURI(final String documentURI) { this.document.setDocumentURI(documentURI); } @Override public Node adoptNode(final Node source) { return this.document.adoptNode(source); } @Override public DOMConfiguration getDomConfig() { return this.document.getDomConfig(); } @Override public void normalizeDocument() { this.document.normalizeDocument(); } @Override public Node renameNode(final Node n, final String namespaceURI, final String qualifiedName) { return this.document.renameNode(n, namespaceURI, qualifiedName); } @Override public String getNodeName() { return this.document.getNodeName(); } @Override public String getNodeValue() { return this.document.getNodeValue(); } @Override public void setNodeValue(final String nodeValue) { this.document.setNodeValue(nodeValue); } @Override public short getNodeType() { return this.document.getNodeType(); } @Override public Node getParentNode() { return this.document.getParentNode(); } @Override public NodeList getChildNodes() { return this.document.getChildNodes(); } @Override public Node getFirstChild() { return this.document.getFirstChild(); } @Override public Node getLastChild() { return this.document.getLastChild(); } @Override public Node getPreviousSibling() { return this.document.getPreviousSibling(); } @Override public Node getNextSibling() { return this.document.getNextSibling(); } @Override public NamedNodeMap getAttributes() { return this.document.getAttributes(); } @Override public Document getOwnerDocument() { return this.document.getOwnerDocument(); } @Override public Node insertBefore(final Node newChild, final Node refChild) { return this.document.insertBefore(newChild, refChild); } @Override public Node replaceChild(final Node newChild, final Node oldChild) { return this.document.replaceChild(newChild, oldChild); } @Override public Node removeChild(final Node oldChild) { return this.document.removeChild(oldChild); } @Override public Node appendChild(final Node newChild) { return this.document.appendChild(newChild); } @Override public boolean hasChildNodes() { return this.document.hasChildNodes(); } @Override public Node cloneNode(final boolean deep) { return this.document.cloneNode(deep); } @Override public void normalize() { this.document.normalize(); } @Override public boolean isSupported(final String feature, final String version) { return this.document.isSupported(feature, version); } @Override public String getNamespaceURI() { return this.document.getNamespaceURI(); } @Override public String getPrefix() { return this.document.getPrefix(); } @Override public void setPrefix(final String prefix) { this.document.setPrefix(prefix); } @Override public String getLocalName() { return this.document.getLocalName(); } @Override public boolean hasAttributes() { return this.document.hasAttributes(); } @Override public String getBaseURI() { return this.document.getBaseURI(); } @Override public short compareDocumentPosition(final Node other) { return this.document.compareDocumentPosition(other); } @Override public String getTextContent() { return this.document.getTextContent(); } @Override public void setTextContent(final String textContent) { this.document.setTextContent(textContent); } @Override public boolean isSameNode(final Node other) { return this.document.isSameNode(other); } @Override public String lookupPrefix(final String namespaceURI) { return this.document.lookupPrefix(namespaceURI); } @Override public boolean isDefaultNamespace(final String namespaceURI) { return this.document.isDefaultNamespace(namespaceURI); } @Override public String lookupNamespaceURI(final String prefix) { return this.document.lookupNamespaceURI(prefix); } @Override public boolean isEqualNode(final Node arg) { return this.document.isEqualNode(arg); } @Override public Object getFeature(final String feature, final String version) { return this.document.getFeature(feature, version); } @Override public Object setUserData(final String key, final Object data, final UserDataHandler handler) { return this.document.setUserData(key, data, handler); } @Override public Object getUserData(final String key) { return this.document.getUserData(key); } }
9,287
0.767524
0.763648
395
22.511393
23.8211
99
false
false
0
0
0
0
0
0
1.225316
false
false
0
032c70347e4bfc5527822f733d3f533bcb173f0b
31,241,592,115,552
21d4306dd14692b5ba833599dd725ff20b5bf75a
/Lab5/Lab_XML/Lab_XML/src/main/java/ru/ansmirnov/rsatu/java/lab/lab_xml/FacilityNavigator.java
fe30b55347b4c8357be5caebf5a7140be6c49c27
[]
no_license
ansmirnov-rsatu/java-labs
https://github.com/ansmirnov-rsatu/java-labs
7c6c542e82612fd31c31dcecb16b75aa3d011033
20ddc7db6d8bb85cdb7c8ea39c15b372b6a94536
refs/heads/master
2019-07-10T11:24:06.924000
2017-05-15T11:00:53
2017-05-15T11:00:53
91,327,826
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.ansmirnov.rsatu.java.lab.lab_xml; import java.util.List; import java.util.Scanner; import ru.rsatu.xml.Facility; import ru.rsatu.xml.University; /** * * @author Andrey Smirnov <mail@ansmirnov.ru> */ public class FacilityNavigator { private Scanner in = new Scanner(System.in); private University university; private Facility facility; public FacilityNavigator(University university, Facility facility) { this.university = university; this.facility = facility; } public boolean printChilds() { if (facility.getChairs().isEmpty()) { System.out.println(String.format("ะคะฐะบัƒะปัŒั‚ะตั‚ %s ะฟัƒัั‚.", facility.getName())); return false; } System.out.println(String.format("ะคะฐะบัƒะปัŒั‚ะตั‚ %s ัะพะดะตั€ะถะธั‚ ัะปะตะดัƒัŽั‰ะธะต ะบะฐั„ะตะดั€ั‹: ", facility.getName())); List<Facility.Chair> chairs = facility.getChairs(); for (int i = 0; i < chairs.size(); i++) { System.out.println(String.format("%d\t%s", i, chairs.get(i).getName())); } return true; } public void createChair() { System.out.print("ะ’ะฒะตะดะธั‚ะต ะฝะฐะทะฒะฐะฝะธะต ะบะฐั„ะตะดั€ั‹: "); String name = in.nextLine().trim(); Facility.Chair chair = new Facility.Chair(); chair.setName(name); facility.getChairs().add(chair); } public void editChair() { if (!printChilds()) { return; } System.out.print("ะ’ะฒะตะดะธั‚ะต ะฝะพะผะตั€ ะบะฐั„ะตะดั€ั‹ ะดะปั ั€ะตะดะฐะบั‚ะธั€ะพะฒะฐะฝะธั: "); try { int x = Integer.parseInt(in.nextLine().trim()); new ChairNavigator(university, facility, facility.getChairs().get(x)).run(); } catch (Exception Ex) { System.out.println("ะะตั‚ ั‚ะฐะบะพะน ะบะฐั„ะตะดั€ั‹"); } } public void deleteFacility() { university.getFacilities().remove(facility); } private boolean operate(String cmd) { switch (cmd) { case "p": printChilds(); break; case "a": createChair(); break; case "e": editChair(); break; case "d": deleteFacility(); return false; case "q": return false; default: System.out.println("ะะตะฒะตั€ะฝะฐั ะบะพะผะฐะฝะดะฐ"); } return true; } public void run() { String cmd; do { System.out.println(String.format("\nะ ะตะดะฐะบั‚ะธั€ะพะฒะฐะฝะธะต ั„ะฐะบัƒะปัŒั‚ะตั‚ะฐ %s.", facility.getName())); System.out.print("ะ’ะพะทะผะพะถะฝั‹ะต ะบะพะผะฐะฝะดั‹: \n" + "p\tะ’ั‹ะฒะตัั‚ะธ ัะพะดะตั€ะถะธะผะพะต ะพะฑัŠะตะบั‚ะฐ\n" + "a\tะ”ะพะฑะฐะฒะธั‚ัŒ ะบะฐั„ะตะดั€ัƒ\n" + "e\tะŸะตั€ะตะนั‚ะธ ะบ ั€ะตะดะฐะบั‚ะธั€ะพะฒะฐะฝะธัŽ ะบะฐั„ะตะดั€ั‹\n" + "d\tะฃะดะฐะปะธั‚ัŒ ั„ะฐะบัƒะปัŒั‚ะตั‚ ะธ ะฒะตั€ะฝัƒั‚ัŒัั ะบ ั€ะตะดะฐะบั‚ะธั€ะพะฒะฐะฝะธัŽ ัƒะฝะธะฒะตั€ัะธั‚ะตั‚ะฐ\n" + "q\tะ’ะตั€ะฝัƒั‚ัŒัั ะบ ั€ะตะดะฐะบั‚ะธั€ะพะฒะฐะฝะธัŽ ัƒะฝะธะฒะตั€ัะธั‚ะตั‚ะฐ\n" + "ะ’ะฒะตะดะธั‚ะต ะบะพะผะฐะฝะดัƒ: "); cmd = in.nextLine().trim(); if (!operate(cmd)) { break; } } while (true); } }
UTF-8
Java
3,463
java
FacilityNavigator.java
Java
[ { "context": "import ru.rsatu.xml.University;\n\n/**\n *\n * @author Andrey Smirnov <mail@ansmirnov.ru>\n */\npublic class FacilityNavi", "end": 190, "score": 0.9998780488967896, "start": 176, "tag": "NAME", "value": "Andrey Smirnov" }, { "context": "ml.University;\n\n/**\n *\n * @author Andrey Smirnov <mail@ansmirnov.ru>\n */\npublic class FacilityNavigator {\n\n privat", "end": 209, "score": 0.9999309182167053, "start": 192, "tag": "EMAIL", "value": "mail@ansmirnov.ru" } ]
null
[]
package ru.ansmirnov.rsatu.java.lab.lab_xml; import java.util.List; import java.util.Scanner; import ru.rsatu.xml.Facility; import ru.rsatu.xml.University; /** * * @author <NAME> <<EMAIL>> */ public class FacilityNavigator { private Scanner in = new Scanner(System.in); private University university; private Facility facility; public FacilityNavigator(University university, Facility facility) { this.university = university; this.facility = facility; } public boolean printChilds() { if (facility.getChairs().isEmpty()) { System.out.println(String.format("ะคะฐะบัƒะปัŒั‚ะตั‚ %s ะฟัƒัั‚.", facility.getName())); return false; } System.out.println(String.format("ะคะฐะบัƒะปัŒั‚ะตั‚ %s ัะพะดะตั€ะถะธั‚ ัะปะตะดัƒัŽั‰ะธะต ะบะฐั„ะตะดั€ั‹: ", facility.getName())); List<Facility.Chair> chairs = facility.getChairs(); for (int i = 0; i < chairs.size(); i++) { System.out.println(String.format("%d\t%s", i, chairs.get(i).getName())); } return true; } public void createChair() { System.out.print("ะ’ะฒะตะดะธั‚ะต ะฝะฐะทะฒะฐะฝะธะต ะบะฐั„ะตะดั€ั‹: "); String name = in.nextLine().trim(); Facility.Chair chair = new Facility.Chair(); chair.setName(name); facility.getChairs().add(chair); } public void editChair() { if (!printChilds()) { return; } System.out.print("ะ’ะฒะตะดะธั‚ะต ะฝะพะผะตั€ ะบะฐั„ะตะดั€ั‹ ะดะปั ั€ะตะดะฐะบั‚ะธั€ะพะฒะฐะฝะธั: "); try { int x = Integer.parseInt(in.nextLine().trim()); new ChairNavigator(university, facility, facility.getChairs().get(x)).run(); } catch (Exception Ex) { System.out.println("ะะตั‚ ั‚ะฐะบะพะน ะบะฐั„ะตะดั€ั‹"); } } public void deleteFacility() { university.getFacilities().remove(facility); } private boolean operate(String cmd) { switch (cmd) { case "p": printChilds(); break; case "a": createChair(); break; case "e": editChair(); break; case "d": deleteFacility(); return false; case "q": return false; default: System.out.println("ะะตะฒะตั€ะฝะฐั ะบะพะผะฐะฝะดะฐ"); } return true; } public void run() { String cmd; do { System.out.println(String.format("\nะ ะตะดะฐะบั‚ะธั€ะพะฒะฐะฝะธะต ั„ะฐะบัƒะปัŒั‚ะตั‚ะฐ %s.", facility.getName())); System.out.print("ะ’ะพะทะผะพะถะฝั‹ะต ะบะพะผะฐะฝะดั‹: \n" + "p\tะ’ั‹ะฒะตัั‚ะธ ัะพะดะตั€ะถะธะผะพะต ะพะฑัŠะตะบั‚ะฐ\n" + "a\tะ”ะพะฑะฐะฒะธั‚ัŒ ะบะฐั„ะตะดั€ัƒ\n" + "e\tะŸะตั€ะตะนั‚ะธ ะบ ั€ะตะดะฐะบั‚ะธั€ะพะฒะฐะฝะธัŽ ะบะฐั„ะตะดั€ั‹\n" + "d\tะฃะดะฐะปะธั‚ัŒ ั„ะฐะบัƒะปัŒั‚ะตั‚ ะธ ะฒะตั€ะฝัƒั‚ัŒัั ะบ ั€ะตะดะฐะบั‚ะธั€ะพะฒะฐะฝะธัŽ ัƒะฝะธะฒะตั€ัะธั‚ะตั‚ะฐ\n" + "q\tะ’ะตั€ะฝัƒั‚ัŒัั ะบ ั€ะตะดะฐะบั‚ะธั€ะพะฒะฐะฝะธัŽ ัƒะฝะธะฒะตั€ัะธั‚ะตั‚ะฐ\n" + "ะ’ะฒะตะดะธั‚ะต ะบะพะผะฐะฝะดัƒ: "); cmd = in.nextLine().trim(); if (!operate(cmd)) { break; } } while (true); } }
3,445
0.539448
0.539128
101
29.871286
24.246532
107
false
false
0
0
0
0
0
0
0.534653
false
false
0
434f7c1438edde11fadb510c2949fb65459d5c3d
32,169,305,053,471
dcf5d58c28f4c31f39dda524595a81ea7f4934bd
/src/main/java/cn/design/demo/proxy/OrderService.java
358bebb377ae2f7efce9152f1f1c8be1a569115a
[]
no_license
qybmsnl/java-design
https://github.com/qybmsnl/java-design
ea49335daef3d22ccadf596b5b4a76451cc3162f
8ddf398582c6d893be24647afaabb3ce43e21d1e
refs/heads/master
2022-12-03T19:51:34.992000
2020-08-17T12:06:23
2020-08-17T12:06:23
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.design.demo.proxy; /** * @author zhangkun * @create 2020-07-30 3:01 PM * @desc **/ public interface OrderService { void order(); }
UTF-8
Java
154
java
OrderService.java
Java
[ { "context": "package cn.design.demo.proxy;\n\n/**\n * @author zhangkun\n * @create 2020-07-30 3:01 PM\n * @desc\n **/\n\npubl", "end": 54, "score": 0.9973723888397217, "start": 46, "tag": "USERNAME", "value": "zhangkun" } ]
null
[]
package cn.design.demo.proxy; /** * @author zhangkun * @create 2020-07-30 3:01 PM * @desc **/ public interface OrderService { void order(); }
154
0.62987
0.558442
13
10.846154
11.941177
31
false
false
0
0
0
0
0
0
0.153846
false
false
10
b35c705ccb273a777432294ad33c32588da6201e
17,635,135,725,598
5f8fe9b7ec03e2074d302513d9c0e2df5baa949f
/src/main/java/uk/ac/ucl/jsh/core/Pipeline.java
1fbea5a5508f7061d4906904b20653833d536ab6
[]
no_license
yifanzhang13/JSH_Bash-like-shell-in-Java
https://github.com/yifanzhang13/JSH_Bash-like-shell-in-Java
6c6976457fe85db8078e7022a18073efe93cd31f
fcd287868c69e4b3200b8271b5a0767ef2373f27
refs/heads/master
2023-04-18T16:28:46.480000
2020-12-03T03:38:50
2020-12-03T03:38:50
268,225,626
0
0
null
false
2021-04-26T20:30:12
2020-05-31T06:51:56
2020-12-03T03:38:53
2021-04-26T20:30:12
107
0
0
2
Java
false
false
package uk.ac.ucl.jsh.core; import uk.ac.ucl.jsh.app.App; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; public class Pipeline implements IPipeline { private List<App> apps; private ExecutorService executorService = ExecutorFactory.getExecutorService(); public Pipeline() { apps = new ArrayList<>(); } @Override public void run() throws RuntimeException { for (App app : apps) { Future future = executorService.submit(app); try { future.get(); } catch (Exception e) { throw new PanicPipeLineException(""); } } } @Override public void append(App app, String[] args) throws Exception { if (app.getInputStream() == null) { InputStream inputStream; if (apps.size() == 0) { inputStream = System.in; } else { inputStream = new PipedInputStream((PipedOutputStream) apps.get(apps.size() - 1).getOutputStream()); } app.setInputStream(inputStream); } if (app.getOutputStream() == null) { app.setOutputStream(new PipedOutputStream()); } app.setArgs(args); apps.add(app); } @Override public void setOutputStream(OutputStream outputStream) { App app = apps.get(apps.size() - 1); if (!app.isOutputStreamLock()) { apps.get(apps.size() - 1).setOutputStream(outputStream); } } @Override public void lockEnd() { apps.get(apps.size() - 1).disallowCloseOut(); } }
UTF-8
Java
1,724
java
Pipeline.java
Java
[]
null
[]
package uk.ac.ucl.jsh.core; import uk.ac.ucl.jsh.app.App; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; public class Pipeline implements IPipeline { private List<App> apps; private ExecutorService executorService = ExecutorFactory.getExecutorService(); public Pipeline() { apps = new ArrayList<>(); } @Override public void run() throws RuntimeException { for (App app : apps) { Future future = executorService.submit(app); try { future.get(); } catch (Exception e) { throw new PanicPipeLineException(""); } } } @Override public void append(App app, String[] args) throws Exception { if (app.getInputStream() == null) { InputStream inputStream; if (apps.size() == 0) { inputStream = System.in; } else { inputStream = new PipedInputStream((PipedOutputStream) apps.get(apps.size() - 1).getOutputStream()); } app.setInputStream(inputStream); } if (app.getOutputStream() == null) { app.setOutputStream(new PipedOutputStream()); } app.setArgs(args); apps.add(app); } @Override public void setOutputStream(OutputStream outputStream) { App app = apps.get(apps.size() - 1); if (!app.isOutputStreamLock()) { apps.get(apps.size() - 1).setOutputStream(outputStream); } } @Override public void lockEnd() { apps.get(apps.size() - 1).disallowCloseOut(); } }
1,724
0.578886
0.575986
66
25.121212
23.438194
116
false
false
0
0
0
0
0
0
0.363636
false
false
10
18fd9c115a39a35f84d7592e7b055df003052a2f
20,925,080,729,961
17fce2b6786c91533635a1850cc51d5eb1307825
/shop-admin/src/main/java/com/fh/shop/admin/controller/user/UserController.java
47e137340b62f07f17f8c15674432c6ba76e1e5e
[]
no_license
ggh666666/public
https://github.com/ggh666666/public
c9a96c7979dbebdbdbad6ab9d1b1cd3209330289
ff49251bfdc0ec4dae2294b58cb476399719d75f
refs/heads/master
2022-12-27T08:15:40.884000
2019-11-01T00:32:00
2019-11-01T00:32:00
218,882,519
0
0
null
false
2022-12-16T11:09:30
2019-11-01T00:15:12
2019-11-01T00:41:26
2022-12-16T11:09:27
70,214
0
0
32
JavaScript
false
false
package com.fh.shop.admin.controller.user; import com.alibaba.fastjson.JSON; import com.baomidou.mybatisplus.extension.api.R; import com.fh.shop.admin.biz.user.IUserService; import com.fh.shop.admin.biz.wealth.IWealthService; import com.fh.shop.admin.common.DataTableResult; import com.fh.shop.admin.common.Log; import com.fh.shop.admin.common.ResponseEnum; import com.fh.shop.admin.common.ServerResponse; import com.fh.shop.admin.param.user.UserPasswordParam; import com.fh.shop.admin.param.user.UserSearchParam; import com.fh.shop.admin.po.user.User; import com.fh.shop.admin.po.wealth.Wealth; import com.fh.shop.admin.util.*; import com.fh.shop.admin.vo.user.UserVo; import com.itextpdf.text.DocumentException; import freemarker.template.TemplateException; import org.apache.commons.lang3.StringUtils; import org.apache.poi.xssf.usermodel.*; 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 org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.*; @Controller @RequestMapping(value = "/user") public class UserController { @Autowired private HttpServletResponse response; @Resource(name = "userService") private IUserService userService; @Resource(name = "wealthService") private IWealthService wealthService; @Autowired private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class); /** * ็™ปๅฝ• * * @param user * @param request * @return */ @RequestMapping(value = "/login") @ResponseBody public ServerResponse login(User user, HttpServletRequest request) throws Exception { String code = request.getParameter("code"); if (StringUtils.isEmpty(code)) return ServerResponse.error(ResponseEnum.CODE_IS_NULL); //้ชŒ่ฏ้ชŒ่ฏ็  String sessionId = DistributedSession.getSessionId(request, response); String code2 = RedisUtil.get(KeyUtil.buildCodeKey(sessionId)); if (!code.equalsIgnoreCase(code2)) { return ServerResponse.error(ResponseEnum.CODE_IS_ERROR); } String userName = user.getUserName(); String password = user.getPassword(); //ๅˆคๆ–ญ็”จๆˆทๅ’Œๅฏ†็ ไธ่ƒฝไธบ็ฉบ if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) { return ServerResponse.error(ResponseEnum.USERNAME_PASSWORD_IS_EMPTY); } //้ชŒ่ฏ็”จๆˆทๅ User userDb = userService.findUserByUserName(userName); if (userDb == null) { return ServerResponse.error(ResponseEnum.USERNAME_IS_ERROR); } //ๅˆคๆ–ญ้”ๅฎš็Šถๆ€ String lastErrorDate = DateUtil.date2str(userDb.getLastErrorTime(), DateUtil.Y_M_D); String today = DateUtil.date2str(new Date(), DateUtil.Y_M_D); if (userDb.getLockState() == ResponseEnum.USER_IS_LOCK.getCode()) { if (!lastErrorDate.equals(today)) {//ๅฆ‚ๆžœๆœ€ๅŽ่พ“้”™ๆ—ฅๆœŸไธๆ˜ฏไปŠๅคฉๅˆ™่งฃ้”็”จๆˆท userDb.setErrors(0); userService.updateLockInfo(0, 0, userDb.getId()); } else return ServerResponse.error(ResponseEnum.USER_IS_LOCK); } else { //ๅฆ‚ๆžœ้”™่ฏฏๆฌกๆ•ฐไธไธบ0 //ๅนถไธ”ๆœ€ๅŽ่พ“้”™ๆ—ฅๆœŸไธๆ˜ฏไปŠๅคฉ ่ฏดๆ˜Žไน‹ๅ‰ๅฏ†็ ่พ“้”™่ฟ‡ ๆ›ดๆ–ฐ้”ๅฎšไฟกๆฏ if (userDb.getErrors() != 0 && !lastErrorDate.equals(today)) { userDb.setErrors(0); userService.updateLockInfo(0, 0, userDb.getId()); } } //้ชŒ่ฏๅฏ†็  if (!Md5Util.salt_md5_2(password, userDb.getSalt()).equals(userDb.getPassword())) { int errors = userDb.getErrors();//ๅฏ†็ ้”™่ฏฏๆฌกๆ•ฐ errors++;//ๅฏ†็ ้”™่ฏฏๆฌกๆ•ฐ+1 int lockState = 0; if (errors >= SystemConst.IF_ERRORS_LOCK)//ๅฆ‚ๆžœๅฏ†็ ้”™่ฏฏๆฌกๆ•ฐๅคงไบŽ็ญ‰ไบŽ้œ€้”ๅฎš็š„ๆฌกๆ•ฐๅˆ™้”ๅฎš็”จๆˆท { lockState = ResponseEnum.USER_IS_LOCK.getCode(); //็ป™็”จๆˆทๅ‘้‚ฎไปถๆ็คบ็”จๆˆท่ขซ้”ๅฎš EmailUtil.sendEmail(userDb.getEmail()); } //ๆ›ดๆ–ฐ้”ๅฎšไฟกๆฏ userService.updateLockInfo(errors, lockState, userDb.getId()); return ServerResponse.error(ResponseEnum.PASSWORD_IS_ERROR); } //็™ป้™†ๆˆๅŠŸ ๆ›ดๆ–ฐ้”ๅฎšไฟกๆฏ //ๅฆ‚ๆžœ้”™่ฏฏๆฌกๆ•ฐไธไธบ0 ่ฏดๆ˜Žไน‹ๅ‰ๅฏ†็ ่พ“้”™่ฟ‡ ๆ›ดๆ–ฐ้”ๅฎšไฟกๆฏ if (userDb.getErrors() != 0) userService.updateLockInfo(0, 0, userDb.getId()); //็™ปๅฝ•ๆˆๅŠŸๅŽ ่ฎฐๅฝ•ไปŠๅคฉ็™ปๅฝ•ๆฌกๆ•ฐ ๅนถ ๆ›ดๆ–ฐๆœ€ๅŽ็™ปๅฝ•ๆ—ถ้—ด Integer todayLogins = userDb.getTodayLogins(); String lastLoginDate = DateUtil.date2str(userDb.getLastLoginTime(), DateUtil.Y_M_D);//ไธŠๆฌก็™ปๅฝ•ๆ—ฅๆœŸ String todayDate = DateUtil.date2str(new Date(), DateUtil.Y_M_D);//ไปŠๅคฉ็š„ๆ—ฅๆœŸ if (lastLoginDate.equals(todayDate)) {//ๅฆ‚ๆžœไธŠๆฌก็™ปๅฝ•ๆ—ฅๆœŸๆ˜ฏไปŠๅคฉๅฐฑๆŠŠไปŠๅคฉ็™ปๅฝ•ๆฌกๆ•ฐ+1 todayLogins++; userDb.setTodayLogins(todayLogins); userService.updateLoginInfo(todayLogins, userDb.getId());//ๆ›ดๆ–ฐ็™ปๅฝ•ไฟกๆฏ } else {//ๅฆ‚ๆžœไธๆ˜ฏไปŠๅคฉๅˆ™ๆŠŠๆฌกๆ•ฐ่ฎพไธบ1 todayLogins = 1; userDb.setTodayLogins(todayLogins); userService.updateLoginInfo(todayLogins, userDb.getId());//ๆ›ดๆ–ฐ็™ปๅฝ•ไฟกๆฏ } //็™ปๅฝ•ๆˆๅŠŸ userDb.setPassword(null);//ไธๆŠŠๅฏ†็ ๅญ˜ๅˆฐsession // request.getSession().setAttribute(SystemConst.CURR_USER, userDb); //ๅˆ†ๅธƒๅผsession cookie + redis String userDbJson = JSON.toJSONString(userDb); RedisUtil.setEx(KeyUtil.buildCurrUserKey(sessionId), userDbJson, SystemConst.EXPIRE); // request.getSession().setAttribute("lastLoginTime", DateUtil.date2str(userDb.getLastLoginTime(), DateUtil.FULL_YEAR)); //ๅˆ†ๅธƒๅผsession cookie + redis RedisUtil.setEx(KeyUtil.buildLastLoginTimeKey(sessionId), DateUtil.date2str(userDb.getLastLoginTime(), DateUtil.FULL_YEAR), SystemConst.EXPIRE); //ๅฐ†ๅฝ“ๅ‰็”จๆˆท็š„่ต„ๆบไฟกๆฏๆ”พๅ…ฅsession ็”จไบŽ้‡ๅค่Žทๅ– ๅ‡ๅฐ‘ๆ•ฐๆฎๅบ“ๅŽ‹ๅŠ› //ๆ นๆฎ็”จๆˆทไฟกๆฏๆŸฅ่ฏข็›ธๅ…ณ่œๅ• List<Wealth> wealths = userService.getMenu(userDb.getId()); // request.getSession().setAttribute(SystemConst.CURR_USER_MENU_INFO, wealths); //ๅˆ†ๅธƒๅผsession cookie + redis RedisUtil.setEx(KeyUtil.buildCurrUserMenuInfoKey(sessionId), JSON.toJSONString(wealths), SystemConst.EXPIRE); //ๅฐ†ๆ‰€ๆœ‰่ต„ๆบไฟกๆฏๆ”พๅ…ฅๅˆฐsessionไธญ List<Wealth> wealthList = wealthService.findAllList(); // request.getSession().setAttribute(SystemConst.MENU_ALL_INFO, wealthList); //ๅˆ†ๅธƒๅผsession cookie + redis RedisUtil.setEx(KeyUtil.buildMenuAllInfo(sessionId), JSON.toJSONString(wealthList), SystemConst.EXPIRE); //ๅฐ†ๅฝ“ๅ‰็”จๆˆท็š„่ต„ๆบurlๆ”พๅ…ฅsession ็”จไบŽๆ‹ฆๆˆชๅ™จๅˆคๆ–ญ List<String> menuUrls = userService.getMenuUrls(userDb.getId()); // request.getSession().setAttribute(SystemConst.CURR_USER_MENU_URLS, menuUrls); //ๅˆ†ๅธƒๅผsession cookie + redis RedisUtil.setEx(KeyUtil.buildCurrUserMenuUrls(sessionId), StringUtils.join(menuUrls, ","), SystemConst.EXPIRE); //็™ปๅฝ•ๆˆๅŠŸๅŽๅˆ ้™คredisไธญ็š„้ชŒ่ฏ็  RedisUtil.del(KeyUtil.buildCodeKey(sessionId)); //ๆ‰“ๅฐๆ—ฅๅฟ— LOGGER.info(ServerResponse.printLog(this.getClass(), Thread.currentThread().getStackTrace()[1].getMethodName())); return ServerResponse.success(); } /** * ่Žทๅ–็™ปๅฝ•ไฟกๆฏ * * @param request * @return */ @RequestMapping(value = "/loginInfo") @ResponseBody public ServerResponse loginInfo(HttpServletRequest request) { //ๅˆ†ๅธƒๅผsession cookie + redis String sessionId = DistributedSession.getSessionId(request, response); String userJson = RedisUtil.get(KeyUtil.buildCurrUserKey(sessionId)); User user = JSON.parseObject(userJson, User.class); String lastLoginTime = RedisUtil.get(KeyUtil.buildLastLoginTimeKey(sessionId)); Map<String, Object> map = new HashMap<>(); map.put("user", user); map.put("lastLoginTime", lastLoginTime); return ServerResponse.success(map); } /** * ๅˆคๆ–ญ็”จๆˆทๅ”ฏไธ€ * * @param userName * @return */ @RequestMapping(value = "/userUnique") @ResponseBody public String userUnique(String userName) { User user = userService.findUserByUserName(userName); if (user == null) return "{ \"valid\": true }"; else return "{ \"valid\": false }"; } /** * ่Žทๅ–่œๅ• * * @param request * @return */ @RequestMapping(value = "/getMenu") @ResponseBody public ServerResponse getMenu(HttpServletRequest request) { //ไปŽsessionๅ–ๅ‡บ่ต„ๆบไฟกๆฏ // List<Wealth> wealths = (List<Wealth>) request.getSession().getAttribute(SystemConst.CURR_USER_MENU_INFO); //ๅˆ†ๅธƒๅผsession cookie + redis String sessionId = DistributedSession.getSessionId(request, response); String wealthsJson = RedisUtil.get(KeyUtil.buildCurrUserMenuInfoKey(sessionId)); List<Wealth> wealths = JSON.parseArray(wealthsJson, Wealth.class); return ServerResponse.success(wealths); } /** * ๆณจ้”€ * * @param request * @return */ @RequestMapping(value = "/logout") //@ResponseBody // public ServerResponse logout(HttpServletRequest request){ public String logout(HttpServletRequest request) { // request.getSession().invalidate();//ไฝฟsessionๅคฑๆ•ˆ ๅคฑๆ•ˆ็š„ๅŒๆ—ถๆต่งˆๅ™จไผš็ซ‹ๅˆปๅˆ›ๅปบๆ–ฐ็š„session //ๅˆ†ๅธƒๅผsession cookie + redis ๆธ…็ฉบ String sessionId = DistributedSession.getSessionId(request, response); DistributedSession.invalidate(sessionId);//ๆ นๆฎsessionId ๆธ…็ฉบsessionๆ•ฐๆฎ // return ServerResponse.success(); //ๆ‰“ๅฐๆ—ฅๅฟ— LOGGER.info(ServerResponse.printLog(this.getClass(), Thread.currentThread().getStackTrace()[1].getMethodName())); return "redirect:/"; } /** * ๅฏผๅ‡บexcel * * @param userSearchParam * @param response */ @RequestMapping(value = "/exportExcel") public void exportExcel(UserSearchParam userSearchParam, HttpServletResponse response) { //ๆŸฅ่ฏข็”จๆˆทๅˆ—่กจ List<UserVo> list = userService.list(userSearchParam); String[] headers = new String[]{"ๅบๅท", "็”จๆˆทๅ", "็œŸๅฎžๅง“ๅ", "ๅนด้พ„", "่–ช่ต„", "ๅ…ฅ่Œๆ—ถ้—ด", "็”ต่ฏ", "้‚ฎ็ฎฑ", "่ง’่‰ฒ", "ๅœฐๅŒบ"}; String[] props = new String[]{"id", "userName", "realName", "age", "pay", "entryTime", "phone", "email", "roleNames", "areaInfo"}; XSSFWorkbook xssfw = ExcelUtil.buildWorkbook(list, "็”จๆˆทๅˆ—่กจ", headers, props, UserVo.class); //ๆž„ๅปบWorkbook // XSSFWorkbook xssfw = userService.buildWorkbook(userSearchParam); //ๅฏผๅ‡บ FileUtil.excelDownload(xssfw, response); } /** * ๅฏผๅ‡บpdf * * @param userSearchParam * @param response */ @RequestMapping(value = "/exportPdf") public void exportPdf(UserSearchParam userSearchParam, HttpServletRequest request, HttpServletResponse response) throws IOException, DocumentException { //ๆž„ๅปบไธ€ไธชๅญ—่Š‚ๆตๆ•ฐ็ป„ ByteArrayOutputStream byo = userService.buildPdfOS(userSearchParam); PDFFileUtil.pdfDownload(response, byo); } /** * ๅฏผๅ‡บword * * @param userSearchParam * @param response */ @RequestMapping(value = "/exportWord") public void exportWord(UserSearchParam userSearchParam, HttpServletRequest request, HttpServletResponse response) throws IOException, TemplateException { File file = userService.buildWordFile(userSearchParam); // ่ฐƒ็”จไธ‹่ฝฝๆ–นๆณ• FileUtil.downloadFile(request, response, file.getPath(), file.getName()); //ๅˆ ้™คๅžƒๅœพๆ–‡ไปถ file.delete(); } /** * ๅŽปๆทปๅŠ ้กต้ข * * @return */ @RequestMapping(value = "/toAdd") public String toAdd() { return "user/add"; } /** * ๆทปๅŠ  * * @param user * @return */ @Log("ๆทปๅŠ ็”จๆˆท") @RequestMapping(value = "/add") public String add(User user) { userService.add(user); //ๆ‰“ๅฐๆ—ฅๅฟ— LOGGER.info(ServerResponse.printLog(this.getClass(), Thread.currentThread().getStackTrace()[1].getMethodName())); return "redirect:/user/list.jhtml"; } /** * ajaxๆทปๅŠ  * * @param user * @return */ @RequestMapping(value = "/addAjax") @ResponseBody @Log("ๆทปๅŠ ็”จๆˆท") public String addAjax(User user) { userService.add(user); //ๆ‰“ๅฐๆ—ฅๅฟ— LOGGER.info(ServerResponse.printLog(this.getClass(), Thread.currentThread().getStackTrace()[1].getMethodName())); return "1"; } /** * ๅŽปๅˆ—่กจๅฑ•็คบ้กต้ข * * @return */ @RequestMapping(value = "/toList") public String toList() { return "user/list"; } /** * ๆŸฅ่ฏขlistๆ•ฐๆฎ * * @return */ @RequestMapping(value = "/list") @ResponseBody //public Map list(UserSearchParam userSearchParam, @RequestParam("ids[]")ArrayList<Long> ids){ // public Map list(UserSearchParam userSearchParam) { // public DataTableResult list(UserSearchParam userSearchParam) { public ServerResponse list(UserSearchParam userSearchParam) { Map<String, Object> map = new HashMap<>(); Long recordsTotal = userService.getRecordsTotal(userSearchParam); List<UserVo> list = userService.getList(userSearchParam); // map.put("draw", userSearchParam.getDraw()); // map.put("recordsTotal", recordsTotal); // map.put("recordsFiltered", recordsTotal); // map.put("data", list); DataTableResult dataTableResult = new DataTableResult(userSearchParam.getDraw(), recordsTotal, recordsTotal, list); return ServerResponse.success(dataTableResult); // return map; } /** * ๅˆ ้™ค * * @param id * @return */ @RequestMapping(value = "delete") @ResponseBody @Log("ๅˆ ้™ค็”จๆˆท") public ServerResponse delete(Long id) { userService.delete(id); //ๆ‰“ๅฐๆ—ฅๅฟ— LOGGER.info(ServerResponse.printLog(this.getClass(), Thread.currentThread().getStackTrace()[1].getMethodName())); return ServerResponse.success(); } /** * ่งฃ้”็”จๆˆท * * @param id * @return */ @RequestMapping(value = "/unlockUser") @ResponseBody public ServerResponse unlockUser(Long id) { userService.updateLockInfo(0, 0, id); return ServerResponse.success(); } /** * ๅŽปไฟฎๆ”นๅฏ†็ ้กต้ข * * @return */ @RequestMapping("/toUpdatePassword") public String toUpdatePassword() { return "/user/password"; } /** * ไฟฎๆ”นๅฏ†็  * * @param userPasswordParam * @return */ @RequestMapping("/updatePassword") @ResponseBody @Log("ไฟฎๆ”นๅฏ†็ ") public ServerResponse updatePassword(UserPasswordParam userPasswordParam) { return userService.updatePassword(userPasswordParam); } /** * ้‡็ฝฎๅฏ†็  * * @param id * @return */ @RequestMapping(value = "/resetPassword") @ResponseBody public ServerResponse resetPassword(Long id) throws Exception { UserVo user = userService.findUser(id); if (user == null) return ServerResponse.error(ResponseEnum.USER_NOT_EXIST); String newPassword = userService.resetPassword(id); //ๅ‘้€้‚ฎไปถ EmailUtil.sendEmail(user.getEmail(), "ๆ–ฐๅฏ†็ ไธบ:" + newPassword); return ServerResponse.success(); } /** * ๅฟ˜่ฎฐๅฏ†็  * * @param email * @return * @throws Exception */ @RequestMapping(value = "/forgetPassword") @ResponseBody public ServerResponse forgetPassword(String email) throws Exception { User user = userService.findUserByEmail(email); if (user == null) { return ServerResponse.error(ResponseEnum.EMAIL_IS_ERROR); } //้‡็ฝฎๅฏ†็  String newPassword = userService.resetPassword(user.getId()); //ๅ‘้€้‚ฎไปถ EmailUtil.sendEmail(user.getEmail(), "ๆ–ฐๅฏ†็ ไธบ:" + newPassword); return ServerResponse.success(); } /** * ๅ›žๆ˜พ * * @param id * @return */ @RequestMapping(value = "findUser") @ResponseBody public ServerResponse findUser(Long id) { "".indexOf(1); //Map map = new HashMap(); UserVo user = userService.findUser(id); return ServerResponse.success(user); // map.put("code",1200); // map.put("msg","ๅ›žๆ˜พๆˆๅŠŸ"); // map.put("data",user); } /** * ajaxไฟฎๆ”น * * @param user * @return */ @RequestMapping(value = "updateAjax") @ResponseBody @Log("ไฟฎๆ”น็”จๆˆท") public ServerResponse updateAjax(User user) { userService.update(user); //ๆ‰“ๅฐๆ—ฅๅฟ— LOGGER.info(ServerResponse.printLog(this.getClass(), Thread.currentThread().getStackTrace()[1].getMethodName())); return ServerResponse.success(user); } /** * ๆ‰น้‡ๅˆ ้™ค * * @param ids */ @RequestMapping(value = "/batchDelete") @ResponseBody public void batchDelete(@RequestParam(value = "ids[]") Long[] ids) { userService.batchDelete(ids); //ๆ‰“ๅฐๆ—ฅๅฟ— LOGGER.info(ServerResponse.printLog(this.getClass(), Thread.currentThread().getStackTrace()[1].getMethodName())); } }
UTF-8
Java
18,368
java
UserController.java
Java
[ { "context": "\n }\n\n String userName = user.getUserName();\n String password = user.getPassword();\n", "end": 2557, "score": 0.7234539985656738, "start": 2553, "tag": "USERNAME", "value": "Name" }, { "context": "me = user.getUserName();\n String password = user.getPassword();\n //ๅˆคๆ–ญ็”จๆˆทๅ’Œๅฏ†็ ไธ่ƒฝไธบ็ฉบ\n if (", "end": 2591, "score": 0.8435457348823547, "start": 2587, "tag": "PASSWORD", "value": "user" }, { "context": "ser.getUserName();\n String password = user.getPassword();\n //ๅˆคๆ–ญ็”จๆˆทๅ’Œๅฏ†็ ไธ่ƒฝไธบ็ฉบ\n if (StringUtils.", "end": 2603, "score": 0.9034051895141602, "start": 2592, "tag": "PASSWORD", "value": "getPassword" }, { "context": " }\n //็™ปๅฝ•ๆˆๅŠŸ\n userDb.setPassword(null);//ไธๆŠŠๅฏ†็ ๅญ˜ๅˆฐsession\n// request.getSession().s", "end": 5364, "score": 0.9422311782836914, "start": 5360, "tag": "PASSWORD", "value": "null" }, { "context": "\n }\n\n /**\n * ๅˆคๆ–ญ็”จๆˆทๅ”ฏไธ€\n *\n * @param userName\n * @return\n */\n @RequestMapping(value ", "end": 8089, "score": 0.9886152744293213, "start": 8081, "tag": "USERNAME", "value": "userName" }, { "context": ");\n String[] headers = new String[]{\"ๅบๅท\", \"็”จๆˆทๅ\", \"็œŸๅฎžๅง“ๅ\", \"ๅนด้พ„\", \"่–ช่ต„\", \"ๅ…ฅ่Œๆ—ถ้—ด\", \"็”ต่ฏ\", \"้‚ฎ็ฎฑ\", \"่ง’่‰ฒ\", \"", "end": 10188, "score": 0.7866045236587524, "start": 10185, "tag": "USERNAME", "value": "็”จๆˆทๅ" }, { "context": "ๅŒบ\"};\n String[] props = new String[]{\"id\", \"userName\", \"realName\", \"age\", \"pay\", \"entryTime\", \"phone\",", "end": 10297, "score": 0.9933678507804871, "start": 10289, "tag": "USERNAME", "value": "userName" }, { "context": " String[] props = new String[]{\"id\", \"userName\", \"realName\", \"age\", \"pay\", \"entryTime\", \"phone\", \"email\"", "end": 10305, "score": 0.7604652643203735, "start": 10301, "tag": "NAME", "value": "real" }, { "context": "ing[] props = new String[]{\"id\", \"userName\", \"realName\", \"age\", \"pay\", \"entryTime\", \"phone\", \"email\", \"r", "end": 10309, "score": 0.35466697812080383, "start": 10305, "tag": "USERNAME", "value": "Name" } ]
null
[]
package com.fh.shop.admin.controller.user; import com.alibaba.fastjson.JSON; import com.baomidou.mybatisplus.extension.api.R; import com.fh.shop.admin.biz.user.IUserService; import com.fh.shop.admin.biz.wealth.IWealthService; import com.fh.shop.admin.common.DataTableResult; import com.fh.shop.admin.common.Log; import com.fh.shop.admin.common.ResponseEnum; import com.fh.shop.admin.common.ServerResponse; import com.fh.shop.admin.param.user.UserPasswordParam; import com.fh.shop.admin.param.user.UserSearchParam; import com.fh.shop.admin.po.user.User; import com.fh.shop.admin.po.wealth.Wealth; import com.fh.shop.admin.util.*; import com.fh.shop.admin.vo.user.UserVo; import com.itextpdf.text.DocumentException; import freemarker.template.TemplateException; import org.apache.commons.lang3.StringUtils; import org.apache.poi.xssf.usermodel.*; 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 org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.*; @Controller @RequestMapping(value = "/user") public class UserController { @Autowired private HttpServletResponse response; @Resource(name = "userService") private IUserService userService; @Resource(name = "wealthService") private IWealthService wealthService; @Autowired private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class); /** * ็™ปๅฝ• * * @param user * @param request * @return */ @RequestMapping(value = "/login") @ResponseBody public ServerResponse login(User user, HttpServletRequest request) throws Exception { String code = request.getParameter("code"); if (StringUtils.isEmpty(code)) return ServerResponse.error(ResponseEnum.CODE_IS_NULL); //้ชŒ่ฏ้ชŒ่ฏ็  String sessionId = DistributedSession.getSessionId(request, response); String code2 = RedisUtil.get(KeyUtil.buildCodeKey(sessionId)); if (!code.equalsIgnoreCase(code2)) { return ServerResponse.error(ResponseEnum.CODE_IS_ERROR); } String userName = user.getUserName(); String password = <PASSWORD>.<PASSWORD>(); //ๅˆคๆ–ญ็”จๆˆทๅ’Œๅฏ†็ ไธ่ƒฝไธบ็ฉบ if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) { return ServerResponse.error(ResponseEnum.USERNAME_PASSWORD_IS_EMPTY); } //้ชŒ่ฏ็”จๆˆทๅ User userDb = userService.findUserByUserName(userName); if (userDb == null) { return ServerResponse.error(ResponseEnum.USERNAME_IS_ERROR); } //ๅˆคๆ–ญ้”ๅฎš็Šถๆ€ String lastErrorDate = DateUtil.date2str(userDb.getLastErrorTime(), DateUtil.Y_M_D); String today = DateUtil.date2str(new Date(), DateUtil.Y_M_D); if (userDb.getLockState() == ResponseEnum.USER_IS_LOCK.getCode()) { if (!lastErrorDate.equals(today)) {//ๅฆ‚ๆžœๆœ€ๅŽ่พ“้”™ๆ—ฅๆœŸไธๆ˜ฏไปŠๅคฉๅˆ™่งฃ้”็”จๆˆท userDb.setErrors(0); userService.updateLockInfo(0, 0, userDb.getId()); } else return ServerResponse.error(ResponseEnum.USER_IS_LOCK); } else { //ๅฆ‚ๆžœ้”™่ฏฏๆฌกๆ•ฐไธไธบ0 //ๅนถไธ”ๆœ€ๅŽ่พ“้”™ๆ—ฅๆœŸไธๆ˜ฏไปŠๅคฉ ่ฏดๆ˜Žไน‹ๅ‰ๅฏ†็ ่พ“้”™่ฟ‡ ๆ›ดๆ–ฐ้”ๅฎšไฟกๆฏ if (userDb.getErrors() != 0 && !lastErrorDate.equals(today)) { userDb.setErrors(0); userService.updateLockInfo(0, 0, userDb.getId()); } } //้ชŒ่ฏๅฏ†็  if (!Md5Util.salt_md5_2(password, userDb.getSalt()).equals(userDb.getPassword())) { int errors = userDb.getErrors();//ๅฏ†็ ้”™่ฏฏๆฌกๆ•ฐ errors++;//ๅฏ†็ ้”™่ฏฏๆฌกๆ•ฐ+1 int lockState = 0; if (errors >= SystemConst.IF_ERRORS_LOCK)//ๅฆ‚ๆžœๅฏ†็ ้”™่ฏฏๆฌกๆ•ฐๅคงไบŽ็ญ‰ไบŽ้œ€้”ๅฎš็š„ๆฌกๆ•ฐๅˆ™้”ๅฎš็”จๆˆท { lockState = ResponseEnum.USER_IS_LOCK.getCode(); //็ป™็”จๆˆทๅ‘้‚ฎไปถๆ็คบ็”จๆˆท่ขซ้”ๅฎš EmailUtil.sendEmail(userDb.getEmail()); } //ๆ›ดๆ–ฐ้”ๅฎšไฟกๆฏ userService.updateLockInfo(errors, lockState, userDb.getId()); return ServerResponse.error(ResponseEnum.PASSWORD_IS_ERROR); } //็™ป้™†ๆˆๅŠŸ ๆ›ดๆ–ฐ้”ๅฎšไฟกๆฏ //ๅฆ‚ๆžœ้”™่ฏฏๆฌกๆ•ฐไธไธบ0 ่ฏดๆ˜Žไน‹ๅ‰ๅฏ†็ ่พ“้”™่ฟ‡ ๆ›ดๆ–ฐ้”ๅฎšไฟกๆฏ if (userDb.getErrors() != 0) userService.updateLockInfo(0, 0, userDb.getId()); //็™ปๅฝ•ๆˆๅŠŸๅŽ ่ฎฐๅฝ•ไปŠๅคฉ็™ปๅฝ•ๆฌกๆ•ฐ ๅนถ ๆ›ดๆ–ฐๆœ€ๅŽ็™ปๅฝ•ๆ—ถ้—ด Integer todayLogins = userDb.getTodayLogins(); String lastLoginDate = DateUtil.date2str(userDb.getLastLoginTime(), DateUtil.Y_M_D);//ไธŠๆฌก็™ปๅฝ•ๆ—ฅๆœŸ String todayDate = DateUtil.date2str(new Date(), DateUtil.Y_M_D);//ไปŠๅคฉ็š„ๆ—ฅๆœŸ if (lastLoginDate.equals(todayDate)) {//ๅฆ‚ๆžœไธŠๆฌก็™ปๅฝ•ๆ—ฅๆœŸๆ˜ฏไปŠๅคฉๅฐฑๆŠŠไปŠๅคฉ็™ปๅฝ•ๆฌกๆ•ฐ+1 todayLogins++; userDb.setTodayLogins(todayLogins); userService.updateLoginInfo(todayLogins, userDb.getId());//ๆ›ดๆ–ฐ็™ปๅฝ•ไฟกๆฏ } else {//ๅฆ‚ๆžœไธๆ˜ฏไปŠๅคฉๅˆ™ๆŠŠๆฌกๆ•ฐ่ฎพไธบ1 todayLogins = 1; userDb.setTodayLogins(todayLogins); userService.updateLoginInfo(todayLogins, userDb.getId());//ๆ›ดๆ–ฐ็™ปๅฝ•ไฟกๆฏ } //็™ปๅฝ•ๆˆๅŠŸ userDb.setPassword(<PASSWORD>);//ไธๆŠŠๅฏ†็ ๅญ˜ๅˆฐsession // request.getSession().setAttribute(SystemConst.CURR_USER, userDb); //ๅˆ†ๅธƒๅผsession cookie + redis String userDbJson = JSON.toJSONString(userDb); RedisUtil.setEx(KeyUtil.buildCurrUserKey(sessionId), userDbJson, SystemConst.EXPIRE); // request.getSession().setAttribute("lastLoginTime", DateUtil.date2str(userDb.getLastLoginTime(), DateUtil.FULL_YEAR)); //ๅˆ†ๅธƒๅผsession cookie + redis RedisUtil.setEx(KeyUtil.buildLastLoginTimeKey(sessionId), DateUtil.date2str(userDb.getLastLoginTime(), DateUtil.FULL_YEAR), SystemConst.EXPIRE); //ๅฐ†ๅฝ“ๅ‰็”จๆˆท็š„่ต„ๆบไฟกๆฏๆ”พๅ…ฅsession ็”จไบŽ้‡ๅค่Žทๅ– ๅ‡ๅฐ‘ๆ•ฐๆฎๅบ“ๅŽ‹ๅŠ› //ๆ นๆฎ็”จๆˆทไฟกๆฏๆŸฅ่ฏข็›ธๅ…ณ่œๅ• List<Wealth> wealths = userService.getMenu(userDb.getId()); // request.getSession().setAttribute(SystemConst.CURR_USER_MENU_INFO, wealths); //ๅˆ†ๅธƒๅผsession cookie + redis RedisUtil.setEx(KeyUtil.buildCurrUserMenuInfoKey(sessionId), JSON.toJSONString(wealths), SystemConst.EXPIRE); //ๅฐ†ๆ‰€ๆœ‰่ต„ๆบไฟกๆฏๆ”พๅ…ฅๅˆฐsessionไธญ List<Wealth> wealthList = wealthService.findAllList(); // request.getSession().setAttribute(SystemConst.MENU_ALL_INFO, wealthList); //ๅˆ†ๅธƒๅผsession cookie + redis RedisUtil.setEx(KeyUtil.buildMenuAllInfo(sessionId), JSON.toJSONString(wealthList), SystemConst.EXPIRE); //ๅฐ†ๅฝ“ๅ‰็”จๆˆท็š„่ต„ๆบurlๆ”พๅ…ฅsession ็”จไบŽๆ‹ฆๆˆชๅ™จๅˆคๆ–ญ List<String> menuUrls = userService.getMenuUrls(userDb.getId()); // request.getSession().setAttribute(SystemConst.CURR_USER_MENU_URLS, menuUrls); //ๅˆ†ๅธƒๅผsession cookie + redis RedisUtil.setEx(KeyUtil.buildCurrUserMenuUrls(sessionId), StringUtils.join(menuUrls, ","), SystemConst.EXPIRE); //็™ปๅฝ•ๆˆๅŠŸๅŽๅˆ ้™คredisไธญ็š„้ชŒ่ฏ็  RedisUtil.del(KeyUtil.buildCodeKey(sessionId)); //ๆ‰“ๅฐๆ—ฅๅฟ— LOGGER.info(ServerResponse.printLog(this.getClass(), Thread.currentThread().getStackTrace()[1].getMethodName())); return ServerResponse.success(); } /** * ่Žทๅ–็™ปๅฝ•ไฟกๆฏ * * @param request * @return */ @RequestMapping(value = "/loginInfo") @ResponseBody public ServerResponse loginInfo(HttpServletRequest request) { //ๅˆ†ๅธƒๅผsession cookie + redis String sessionId = DistributedSession.getSessionId(request, response); String userJson = RedisUtil.get(KeyUtil.buildCurrUserKey(sessionId)); User user = JSON.parseObject(userJson, User.class); String lastLoginTime = RedisUtil.get(KeyUtil.buildLastLoginTimeKey(sessionId)); Map<String, Object> map = new HashMap<>(); map.put("user", user); map.put("lastLoginTime", lastLoginTime); return ServerResponse.success(map); } /** * ๅˆคๆ–ญ็”จๆˆทๅ”ฏไธ€ * * @param userName * @return */ @RequestMapping(value = "/userUnique") @ResponseBody public String userUnique(String userName) { User user = userService.findUserByUserName(userName); if (user == null) return "{ \"valid\": true }"; else return "{ \"valid\": false }"; } /** * ่Žทๅ–่œๅ• * * @param request * @return */ @RequestMapping(value = "/getMenu") @ResponseBody public ServerResponse getMenu(HttpServletRequest request) { //ไปŽsessionๅ–ๅ‡บ่ต„ๆบไฟกๆฏ // List<Wealth> wealths = (List<Wealth>) request.getSession().getAttribute(SystemConst.CURR_USER_MENU_INFO); //ๅˆ†ๅธƒๅผsession cookie + redis String sessionId = DistributedSession.getSessionId(request, response); String wealthsJson = RedisUtil.get(KeyUtil.buildCurrUserMenuInfoKey(sessionId)); List<Wealth> wealths = JSON.parseArray(wealthsJson, Wealth.class); return ServerResponse.success(wealths); } /** * ๆณจ้”€ * * @param request * @return */ @RequestMapping(value = "/logout") //@ResponseBody // public ServerResponse logout(HttpServletRequest request){ public String logout(HttpServletRequest request) { // request.getSession().invalidate();//ไฝฟsessionๅคฑๆ•ˆ ๅคฑๆ•ˆ็š„ๅŒๆ—ถๆต่งˆๅ™จไผš็ซ‹ๅˆปๅˆ›ๅปบๆ–ฐ็š„session //ๅˆ†ๅธƒๅผsession cookie + redis ๆธ…็ฉบ String sessionId = DistributedSession.getSessionId(request, response); DistributedSession.invalidate(sessionId);//ๆ นๆฎsessionId ๆธ…็ฉบsessionๆ•ฐๆฎ // return ServerResponse.success(); //ๆ‰“ๅฐๆ—ฅๅฟ— LOGGER.info(ServerResponse.printLog(this.getClass(), Thread.currentThread().getStackTrace()[1].getMethodName())); return "redirect:/"; } /** * ๅฏผๅ‡บexcel * * @param userSearchParam * @param response */ @RequestMapping(value = "/exportExcel") public void exportExcel(UserSearchParam userSearchParam, HttpServletResponse response) { //ๆŸฅ่ฏข็”จๆˆทๅˆ—่กจ List<UserVo> list = userService.list(userSearchParam); String[] headers = new String[]{"ๅบๅท", "็”จๆˆทๅ", "็œŸๅฎžๅง“ๅ", "ๅนด้พ„", "่–ช่ต„", "ๅ…ฅ่Œๆ—ถ้—ด", "็”ต่ฏ", "้‚ฎ็ฎฑ", "่ง’่‰ฒ", "ๅœฐๅŒบ"}; String[] props = new String[]{"id", "userName", "realName", "age", "pay", "entryTime", "phone", "email", "roleNames", "areaInfo"}; XSSFWorkbook xssfw = ExcelUtil.buildWorkbook(list, "็”จๆˆทๅˆ—่กจ", headers, props, UserVo.class); //ๆž„ๅปบWorkbook // XSSFWorkbook xssfw = userService.buildWorkbook(userSearchParam); //ๅฏผๅ‡บ FileUtil.excelDownload(xssfw, response); } /** * ๅฏผๅ‡บpdf * * @param userSearchParam * @param response */ @RequestMapping(value = "/exportPdf") public void exportPdf(UserSearchParam userSearchParam, HttpServletRequest request, HttpServletResponse response) throws IOException, DocumentException { //ๆž„ๅปบไธ€ไธชๅญ—่Š‚ๆตๆ•ฐ็ป„ ByteArrayOutputStream byo = userService.buildPdfOS(userSearchParam); PDFFileUtil.pdfDownload(response, byo); } /** * ๅฏผๅ‡บword * * @param userSearchParam * @param response */ @RequestMapping(value = "/exportWord") public void exportWord(UserSearchParam userSearchParam, HttpServletRequest request, HttpServletResponse response) throws IOException, TemplateException { File file = userService.buildWordFile(userSearchParam); // ่ฐƒ็”จไธ‹่ฝฝๆ–นๆณ• FileUtil.downloadFile(request, response, file.getPath(), file.getName()); //ๅˆ ้™คๅžƒๅœพๆ–‡ไปถ file.delete(); } /** * ๅŽปๆทปๅŠ ้กต้ข * * @return */ @RequestMapping(value = "/toAdd") public String toAdd() { return "user/add"; } /** * ๆทปๅŠ  * * @param user * @return */ @Log("ๆทปๅŠ ็”จๆˆท") @RequestMapping(value = "/add") public String add(User user) { userService.add(user); //ๆ‰“ๅฐๆ—ฅๅฟ— LOGGER.info(ServerResponse.printLog(this.getClass(), Thread.currentThread().getStackTrace()[1].getMethodName())); return "redirect:/user/list.jhtml"; } /** * ajaxๆทปๅŠ  * * @param user * @return */ @RequestMapping(value = "/addAjax") @ResponseBody @Log("ๆทปๅŠ ็”จๆˆท") public String addAjax(User user) { userService.add(user); //ๆ‰“ๅฐๆ—ฅๅฟ— LOGGER.info(ServerResponse.printLog(this.getClass(), Thread.currentThread().getStackTrace()[1].getMethodName())); return "1"; } /** * ๅŽปๅˆ—่กจๅฑ•็คบ้กต้ข * * @return */ @RequestMapping(value = "/toList") public String toList() { return "user/list"; } /** * ๆŸฅ่ฏขlistๆ•ฐๆฎ * * @return */ @RequestMapping(value = "/list") @ResponseBody //public Map list(UserSearchParam userSearchParam, @RequestParam("ids[]")ArrayList<Long> ids){ // public Map list(UserSearchParam userSearchParam) { // public DataTableResult list(UserSearchParam userSearchParam) { public ServerResponse list(UserSearchParam userSearchParam) { Map<String, Object> map = new HashMap<>(); Long recordsTotal = userService.getRecordsTotal(userSearchParam); List<UserVo> list = userService.getList(userSearchParam); // map.put("draw", userSearchParam.getDraw()); // map.put("recordsTotal", recordsTotal); // map.put("recordsFiltered", recordsTotal); // map.put("data", list); DataTableResult dataTableResult = new DataTableResult(userSearchParam.getDraw(), recordsTotal, recordsTotal, list); return ServerResponse.success(dataTableResult); // return map; } /** * ๅˆ ้™ค * * @param id * @return */ @RequestMapping(value = "delete") @ResponseBody @Log("ๅˆ ้™ค็”จๆˆท") public ServerResponse delete(Long id) { userService.delete(id); //ๆ‰“ๅฐๆ—ฅๅฟ— LOGGER.info(ServerResponse.printLog(this.getClass(), Thread.currentThread().getStackTrace()[1].getMethodName())); return ServerResponse.success(); } /** * ่งฃ้”็”จๆˆท * * @param id * @return */ @RequestMapping(value = "/unlockUser") @ResponseBody public ServerResponse unlockUser(Long id) { userService.updateLockInfo(0, 0, id); return ServerResponse.success(); } /** * ๅŽปไฟฎๆ”นๅฏ†็ ้กต้ข * * @return */ @RequestMapping("/toUpdatePassword") public String toUpdatePassword() { return "/user/password"; } /** * ไฟฎๆ”นๅฏ†็  * * @param userPasswordParam * @return */ @RequestMapping("/updatePassword") @ResponseBody @Log("ไฟฎๆ”นๅฏ†็ ") public ServerResponse updatePassword(UserPasswordParam userPasswordParam) { return userService.updatePassword(userPasswordParam); } /** * ้‡็ฝฎๅฏ†็  * * @param id * @return */ @RequestMapping(value = "/resetPassword") @ResponseBody public ServerResponse resetPassword(Long id) throws Exception { UserVo user = userService.findUser(id); if (user == null) return ServerResponse.error(ResponseEnum.USER_NOT_EXIST); String newPassword = userService.resetPassword(id); //ๅ‘้€้‚ฎไปถ EmailUtil.sendEmail(user.getEmail(), "ๆ–ฐๅฏ†็ ไธบ:" + newPassword); return ServerResponse.success(); } /** * ๅฟ˜่ฎฐๅฏ†็  * * @param email * @return * @throws Exception */ @RequestMapping(value = "/forgetPassword") @ResponseBody public ServerResponse forgetPassword(String email) throws Exception { User user = userService.findUserByEmail(email); if (user == null) { return ServerResponse.error(ResponseEnum.EMAIL_IS_ERROR); } //้‡็ฝฎๅฏ†็  String newPassword = userService.resetPassword(user.getId()); //ๅ‘้€้‚ฎไปถ EmailUtil.sendEmail(user.getEmail(), "ๆ–ฐๅฏ†็ ไธบ:" + newPassword); return ServerResponse.success(); } /** * ๅ›žๆ˜พ * * @param id * @return */ @RequestMapping(value = "findUser") @ResponseBody public ServerResponse findUser(Long id) { "".indexOf(1); //Map map = new HashMap(); UserVo user = userService.findUser(id); return ServerResponse.success(user); // map.put("code",1200); // map.put("msg","ๅ›žๆ˜พๆˆๅŠŸ"); // map.put("data",user); } /** * ajaxไฟฎๆ”น * * @param user * @return */ @RequestMapping(value = "updateAjax") @ResponseBody @Log("ไฟฎๆ”น็”จๆˆท") public ServerResponse updateAjax(User user) { userService.update(user); //ๆ‰“ๅฐๆ—ฅๅฟ— LOGGER.info(ServerResponse.printLog(this.getClass(), Thread.currentThread().getStackTrace()[1].getMethodName())); return ServerResponse.success(user); } /** * ๆ‰น้‡ๅˆ ้™ค * * @param ids */ @RequestMapping(value = "/batchDelete") @ResponseBody public void batchDelete(@RequestParam(value = "ids[]") Long[] ids) { userService.batchDelete(ids); //ๆ‰“ๅฐๆ—ฅๅฟ— LOGGER.info(ServerResponse.printLog(this.getClass(), Thread.currentThread().getStackTrace()[1].getMethodName())); } }
18,379
0.638646
0.635966
520
32.011539
30.204683
157
false
false
0
0
0
0
0
0
0.523077
false
false
10
caa686eb9fa44d31919b638cf3dbef5da8b45c84
20,925,080,733,248
14d0ab5f8fb94b0188f8bac8c757c28230401559
/blue-beast/src/beast/dr/inferencexml/convergence/BlueBeastLoggerParser.java
6bcc95a7d76232d276a0ed7bb2a116cfd417e09a
[]
no_license
sibonli/blue-beast
https://github.com/sibonli/blue-beast
dcb73f746726d857ce41c237f080c95e24080da6
e6975be4943a6f42eb41b2d5bb02170815fd99bd
refs/heads/master
2016-09-02T05:55:10.916000
2013-08-16T00:04:47
2013-08-16T00:04:47
33,784,468
3
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * BlueBeastLoggerParser.java * * Copyright (C) 2002-2009 Alexei Drummond and Andrew Rambaut * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * BEAST is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package beast.dr.inferencexml.convergence; import bb.loggers.BlueBeastLogger; import dr.app.beast.BeastVersion; import dr.inference.loggers.*; import dr.math.MathUtils; import dr.util.Identifiable; import dr.util.Property; import dr.xml.*; import java.io.PrintWriter; import java.util.Date; /** * @author Wai Lok Li */ public class BlueBeastLoggerParser extends AbstractXMLObjectParser { public static final String LOG = "blueBeastLog"; public static final String ECHO = "echo"; public static final String ECHO_EVERY = "echoEvery"; public static final String TITLE = "title"; // public static final String FILE_NAME = FileHelpers.FILE_NAME; public static final String FORMAT = "format"; public static final String TAB = "tab"; public static final String HTML = "html"; public static final String PRETTY = "pretty"; // public static final String INITIAL_CHECK_INTERVAL = "initalLogInterval"; public static final String LOG_EVERY = "logEvery"; // public static final String ALLOW_OVERWRITE_LOG = "overwrite"; public static final String COLUMNS = "columns"; public static final String COLUMN = "column"; public static final String LABEL = "label"; public static final String SIGNIFICANT_FIGURES = "sf"; public static final String DECIMAL_PLACES = "dp"; public static final String WIDTH = "width"; public String getParserName() { return LOG; } /** * @return an object based on the XML element it was passed. */ public Object parseXMLObject(XMLObject xo) throws XMLParseException { // You must say how often you want to log final int logEvery = xo.getIntegerAttribute(LOG_EVERY); // And also how often you want to check the logged values // int initialLogInterval = 1000; // if (xo.hasAttribute(INITIAL_CHECK_INTERVAL)) { // initialLogInterval = xo.getIntegerAttribute(INITIAL_CHECK_INTERVAL); // System.out.println("Starting log interval: " + initialLogInterval); // } final PrintWriter pw = getLogFile(xo, getParserName()); final LogFormatter formatter = new TabDelimitedFormatter(pw); boolean performanceReport = false; // added a performance measurement delay to avoid the full evaluation period. //final BlueBeastLogger logger = new BlueBeastLogger(formatter, logEvery, initialLogInterval, performanceReport, 10000); final BlueBeastLogger logger = new BlueBeastLogger(formatter, logEvery, performanceReport, 10000); if (xo.hasAttribute(TITLE)) { logger.setTitle(xo.getStringAttribute(TITLE)); } else { final BeastVersion version = new BeastVersion(); final String title = "BEAST " + version.getVersionString() + ", " + version.getBuildString() + "\n" + "Generated " + (new Date()).toString() + " [seed=" + MathUtils.getSeed() + "]"; logger.setTitle(title); } for (int i = 0; i < xo.getChildCount(); i++) { final Object child = xo.getChild(i); // if (child instanceof Columns) { // // logger.addColumns(((Columns) child).getColumns()); // // } else if (child instanceof Loggable) { logger.add((Loggable) child); } else if (child instanceof Identifiable) { throw new RuntimeException("Inputted an Identifiable to the logger, not valid in BlueBeast"); // logger.addColumn(new LogColumn.Default(((Identifiable) child).getId(), child)); } else if (child instanceof Property) { throw new RuntimeException("Inputted a Property to the logger, not valid in BlueBeast"); // logger.addColumn(new LogColumn.Default(((Property) child).getAttributeName(), child)); } else { throw new RuntimeException("Inputted a wrong object type to the logger, not valid in BlueBeast"); // logger.addColumn(new LogColumn.Default(child.getClass().toString(), child)); } } return logger; } public static PrintWriter getLogFile(XMLObject xo, String parserName) throws XMLParseException { return XMLParser.getFilePrintWriter(xo, parserName); } //************************************************************************ // AbstractXMLObjectParser implementation //************************************************************************ public XMLSyntaxRule[] getSyntaxRules() { return rules; } private final XMLSyntaxRule[] rules = { // AttributeRule.newIntegerRule(INITIAL_CHECK_INTERVAL, true), AttributeRule.newIntegerRule(LOG_EVERY), new StringAttributeRule(TITLE, "The title of the log", true), new OrRule( new XMLSyntaxRule[]{ //new ElementRule(Columns.class, 1, Integer.MAX_VALUE), new ElementRule(Loggable.class, 1, Integer.MAX_VALUE), new ElementRule(Object.class, 1, Integer.MAX_VALUE) } ) }; public String getParserDescription() { return "Logs one or more items at a given frequency to the screen or to a file"; } public Class getReturnType() { return BlueBeastLogger.class; } }
UTF-8
Java
6,421
java
BlueBeastLoggerParser.java
Java
[ { "context": "BeastLoggerParser.java\n*\n* Copyright (C) 2002-2009 Alexei Drummond and Andrew Rambaut\n*\n* This file is part of BEAST", "end": 75, "score": 0.9998302459716797, "start": 60, "tag": "NAME", "value": "Alexei Drummond" }, { "context": "va\n*\n* Copyright (C) 2002-2009 Alexei Drummond and Andrew Rambaut\n*\n* This file is part of BEAST.\n* See the NOTICE ", "end": 94, "score": 0.9998399615287781, "start": 80, "tag": "NAME", "value": "Andrew Rambaut" }, { "context": "PrintWriter;\nimport java.util.Date;\n\n/**\n* @author Wai Lok Li\n*/\npublic class BlueBeastLoggerParser extends Abs", "end": 1277, "score": 0.9997137188911438, "start": 1267, "tag": "NAME", "value": "Wai Lok Li" } ]
null
[]
/* * BlueBeastLoggerParser.java * * Copyright (C) 2002-2009 <NAME> and <NAME> * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * BEAST is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package beast.dr.inferencexml.convergence; import bb.loggers.BlueBeastLogger; import dr.app.beast.BeastVersion; import dr.inference.loggers.*; import dr.math.MathUtils; import dr.util.Identifiable; import dr.util.Property; import dr.xml.*; import java.io.PrintWriter; import java.util.Date; /** * @author <NAME> */ public class BlueBeastLoggerParser extends AbstractXMLObjectParser { public static final String LOG = "blueBeastLog"; public static final String ECHO = "echo"; public static final String ECHO_EVERY = "echoEvery"; public static final String TITLE = "title"; // public static final String FILE_NAME = FileHelpers.FILE_NAME; public static final String FORMAT = "format"; public static final String TAB = "tab"; public static final String HTML = "html"; public static final String PRETTY = "pretty"; // public static final String INITIAL_CHECK_INTERVAL = "initalLogInterval"; public static final String LOG_EVERY = "logEvery"; // public static final String ALLOW_OVERWRITE_LOG = "overwrite"; public static final String COLUMNS = "columns"; public static final String COLUMN = "column"; public static final String LABEL = "label"; public static final String SIGNIFICANT_FIGURES = "sf"; public static final String DECIMAL_PLACES = "dp"; public static final String WIDTH = "width"; public String getParserName() { return LOG; } /** * @return an object based on the XML element it was passed. */ public Object parseXMLObject(XMLObject xo) throws XMLParseException { // You must say how often you want to log final int logEvery = xo.getIntegerAttribute(LOG_EVERY); // And also how often you want to check the logged values // int initialLogInterval = 1000; // if (xo.hasAttribute(INITIAL_CHECK_INTERVAL)) { // initialLogInterval = xo.getIntegerAttribute(INITIAL_CHECK_INTERVAL); // System.out.println("Starting log interval: " + initialLogInterval); // } final PrintWriter pw = getLogFile(xo, getParserName()); final LogFormatter formatter = new TabDelimitedFormatter(pw); boolean performanceReport = false; // added a performance measurement delay to avoid the full evaluation period. //final BlueBeastLogger logger = new BlueBeastLogger(formatter, logEvery, initialLogInterval, performanceReport, 10000); final BlueBeastLogger logger = new BlueBeastLogger(formatter, logEvery, performanceReport, 10000); if (xo.hasAttribute(TITLE)) { logger.setTitle(xo.getStringAttribute(TITLE)); } else { final BeastVersion version = new BeastVersion(); final String title = "BEAST " + version.getVersionString() + ", " + version.getBuildString() + "\n" + "Generated " + (new Date()).toString() + " [seed=" + MathUtils.getSeed() + "]"; logger.setTitle(title); } for (int i = 0; i < xo.getChildCount(); i++) { final Object child = xo.getChild(i); // if (child instanceof Columns) { // // logger.addColumns(((Columns) child).getColumns()); // // } else if (child instanceof Loggable) { logger.add((Loggable) child); } else if (child instanceof Identifiable) { throw new RuntimeException("Inputted an Identifiable to the logger, not valid in BlueBeast"); // logger.addColumn(new LogColumn.Default(((Identifiable) child).getId(), child)); } else if (child instanceof Property) { throw new RuntimeException("Inputted a Property to the logger, not valid in BlueBeast"); // logger.addColumn(new LogColumn.Default(((Property) child).getAttributeName(), child)); } else { throw new RuntimeException("Inputted a wrong object type to the logger, not valid in BlueBeast"); // logger.addColumn(new LogColumn.Default(child.getClass().toString(), child)); } } return logger; } public static PrintWriter getLogFile(XMLObject xo, String parserName) throws XMLParseException { return XMLParser.getFilePrintWriter(xo, parserName); } //************************************************************************ // AbstractXMLObjectParser implementation //************************************************************************ public XMLSyntaxRule[] getSyntaxRules() { return rules; } private final XMLSyntaxRule[] rules = { // AttributeRule.newIntegerRule(INITIAL_CHECK_INTERVAL, true), AttributeRule.newIntegerRule(LOG_EVERY), new StringAttributeRule(TITLE, "The title of the log", true), new OrRule( new XMLSyntaxRule[]{ //new ElementRule(Columns.class, 1, Integer.MAX_VALUE), new ElementRule(Loggable.class, 1, Integer.MAX_VALUE), new ElementRule(Object.class, 1, Integer.MAX_VALUE) } ) }; public String getParserDescription() { return "Logs one or more items at a given frequency to the screen or to a file"; } public Class getReturnType() { return BlueBeastLogger.class; } }
6,400
0.637595
0.631677
168
37.214287
31.480747
128
false
false
0
0
0
0
0
0
0.607143
false
false
10
89a6993f758dbc17d585bb614abe878eb70baaf6
8,186,207,700,066
fa5a1c62310c364fa66b3b65521ce0dfb0bbcf1f
/app/android/Sensorama/app/src/main/java/com/barvoy/sensorama/Sensorama.java
0c0ce1e975dc824669af2e1220a5e0309597b2ff
[ "BSD-2-Clause" ]
permissive
wkoszek/sensorama
https://github.com/wkoszek/sensorama
688887199997896d60e521178dfb34c0b6d04939
c2ddf06bd0aba49d267f204ce35a5d7b851c5fed
refs/heads/master
2020-12-02T15:07:13.294000
2016-02-17T09:17:38
2016-02-17T09:17:38
39,643,194
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// Copyright (c) 2015, Wojciech Adam Koszek <wojciech@koszek.com> // All rights reserved. package com.barvoy.sensorama; import android.app.Activity; import java.io.BufferedWriter; import java.io.IOException; import java.util.*; public class Sensorama { SRAccel accel; SRBattery battery; SRGyro gyro; SRGravity gravity; SRStepCounter stepCounter; SREnviron environ; List<SRDataPointList> points; boolean enabled; public Sensorama(Activity activity) { points = new ArrayList<SRDataPointList>(); accel = new SRAccel(activity); gyro = new SRGyro(activity); gravity = new SRGravity(activity); stepCounter = new SRStepCounter(activity); environ = new SREnviron(activity); battery = new SRBattery(); } public void capture() { SRDataPointList list = new SRDataPointList(); accel.capture(list); gyro.capture(list); gravity.capture(list); stepCounter.capture(list); environ.capture(list); battery.capture(list); points.add(list); } public void dumpPoints(BufferedWriter fo) throws IOException { boolean isFirst = true; for (SRDataPointList list : points) { fo.write(" " + (isFirst ? " " : ",") + "{"); list.dump(fo); fo.write(" }\n"); isFirst = false; } points = new ArrayList<SRDataPointList>(); } public boolean isEnabled() { return enabled; } public void enable(boolean _enabled) { enabled = _enabled; } }
UTF-8
Java
1,622
java
Sensorama.java
Java
[ { "context": "// Copyright (c) 2015, Wojciech Adam Koszek <wojciech@koszek.com>\n// All rights reserved.\n\npa", "end": 43, "score": 0.9998614192008972, "start": 23, "tag": "NAME", "value": "Wojciech Adam Koszek" }, { "context": "// Copyright (c) 2015, Wojciech Adam Koszek <wojciech@koszek.com>\n// All rights reserved.\n\npackage com.barvoy.sens", "end": 64, "score": 0.9999321699142456, "start": 45, "tag": "EMAIL", "value": "wojciech@koszek.com" } ]
null
[]
// Copyright (c) 2015, <NAME> <<EMAIL>> // All rights reserved. package com.barvoy.sensorama; import android.app.Activity; import java.io.BufferedWriter; import java.io.IOException; import java.util.*; public class Sensorama { SRAccel accel; SRBattery battery; SRGyro gyro; SRGravity gravity; SRStepCounter stepCounter; SREnviron environ; List<SRDataPointList> points; boolean enabled; public Sensorama(Activity activity) { points = new ArrayList<SRDataPointList>(); accel = new SRAccel(activity); gyro = new SRGyro(activity); gravity = new SRGravity(activity); stepCounter = new SRStepCounter(activity); environ = new SREnviron(activity); battery = new SRBattery(); } public void capture() { SRDataPointList list = new SRDataPointList(); accel.capture(list); gyro.capture(list); gravity.capture(list); stepCounter.capture(list); environ.capture(list); battery.capture(list); points.add(list); } public void dumpPoints(BufferedWriter fo) throws IOException { boolean isFirst = true; for (SRDataPointList list : points) { fo.write(" " + (isFirst ? " " : ",") + "{"); list.dump(fo); fo.write(" }\n"); isFirst = false; } points = new ArrayList<SRDataPointList>(); } public boolean isEnabled() { return enabled; } public void enable(boolean _enabled) { enabled = _enabled; } }
1,596
0.601726
0.59926
68
22.852942
17.779917
66
false
false
0
0
0
0
0
0
0.558824
false
false
10
1f4b94dfcf6a46b6130a9989ebda2a48063e1676
15,590,731,330,135
aafd0979aa68e830ec90eb3502e7ce8dfce6c028
/app/src/main/java/com/cgwx/yyfwptz/lixiang/AQBP/di/components/VCodeComponent.java
6656fec72b216d615573c6d2c50cbdb30d7d2290
[]
no_license
lixxxiang/AQBP
https://github.com/lixxxiang/AQBP
23a8355ce3ad51fc6d818a494e72ae38b880553f
7b51126f687e5e75bcb6f5567c6fb4b72fdfe791
refs/heads/master
2021-01-22T21:07:24.997000
2017-08-18T06:36:32
2017-08-18T06:36:32
100,681,133
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cgwx.yyfwptz.lixiang.AQBP.di.components; import com.cgwx.yyfwptz.lixiang.AQBP.di.modules.VCodeModule; import com.cgwx.yyfwptz.lixiang.AQBP.view.activity.VCodeActivity; import dagger.Component; /** * Created by yyfwptz on 2017/8/8. */ @Component(modules = VCodeModule.class) public interface VCodeComponent { void inject(VCodeActivity activity); }
UTF-8
Java
369
java
VCodeComponent.java
Java
[ { "context": "vity;\n\nimport dagger.Component;\n\n/**\n * Created by yyfwptz on 2017/8/8.\n */\n\n@Component(modules = VCodeModul", "end": 233, "score": 0.9996992349624634, "start": 226, "tag": "USERNAME", "value": "yyfwptz" } ]
null
[]
package com.cgwx.yyfwptz.lixiang.AQBP.di.components; import com.cgwx.yyfwptz.lixiang.AQBP.di.modules.VCodeModule; import com.cgwx.yyfwptz.lixiang.AQBP.view.activity.VCodeActivity; import dagger.Component; /** * Created by yyfwptz on 2017/8/8. */ @Component(modules = VCodeModule.class) public interface VCodeComponent { void inject(VCodeActivity activity); }
369
0.780488
0.764228
15
23.6
23.28891
65
false
false
0
0
0
0
0
0
0.333333
false
false
10
22834e32b2a9d6f6da198adfe59025807551e5ed
2,087,354,155,388
0a8b68908ef457f8b0c0ab18c1ec1b57b32e03e1
/creditEcoSystem/kernel/credit-third-interface/src/main/java/com/ctc/credit/bairong/service/CreditBrLocationEntiryService.java
2253c0c63f1abe6e61c3d3e0efc25b988c06ed1b
[]
no_license
gspandy/c.r.e.d.it
https://github.com/gspandy/c.r.e.d.it
68f33b347a4bd1cb6e110bf3123fb2674a4ad900
8095962d0f4b4443c884ef4a318f9d1aa818e0dc
refs/heads/master
2023-08-09T15:41:15.738000
2015-08-07T06:10:12
2015-08-07T06:10:12
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ctc.credit.bairong.service; import com.ctc.credit.bairong.api.dto.location.LocationDto; import com.ctc.credit.bairong.model.CreditBrLocationEntiry; import com.ctc.credit.kernel.base.GenericService; public interface CreditBrLocationEntiryService extends GenericService <CreditBrLocationEntiry, String>{ /** * ็™พ่ž๏ผšไฟๅญ˜ไฝ็ฝฎไฟกๆฏๆ ธๆŸฅไฟกๆฏ * @param internetDto */ public void saveLocationInfo(LocationDto locationDto); }
UTF-8
Java
452
java
CreditBrLocationEntiryService.java
Java
[]
null
[]
package com.ctc.credit.bairong.service; import com.ctc.credit.bairong.api.dto.location.LocationDto; import com.ctc.credit.bairong.model.CreditBrLocationEntiry; import com.ctc.credit.kernel.base.GenericService; public interface CreditBrLocationEntiryService extends GenericService <CreditBrLocationEntiry, String>{ /** * ็™พ่ž๏ผšไฟๅญ˜ไฝ็ฝฎไฟกๆฏๆ ธๆŸฅไฟกๆฏ * @param internetDto */ public void saveLocationInfo(LocationDto locationDto); }
452
0.812207
0.812207
14
29.428572
30.705315
103
false
false
0
0
0
0
0
0
0.785714
false
false
10
c1732f9368a0ed1d6de9af26d4cbe9b174456e10
4,346,506,959,218
8bf4fe9cd3fe399f3440c2a09a26db615d312dab
/java8/src/main/java/com/xmw/java8/Demo.java
69952e149096c795101100c4cff9f27b5a185a80
[]
no_license
xmw9160/base-code
https://github.com/xmw9160/base-code
9ffef91d1d015d08b7ebcf3e760cd9f3985d3bb0
df4f519ae2b8b0797ee0a428f6f747908d68946f
refs/heads/master
2020-04-01T18:07:40.455000
2019-03-10T05:10:45
2019-03-10T05:10:45
153,473,079
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xmw.java8; /** * @author mingwei.xia * @date 2018/8/24 9:56 * @since V1.0 */ public class Demo { public static void main(String[] args) { // Proxy.newProxyInstance() // byte[] bytes = new byte[100 * 1024 * 1024]; // System.out.println(Objects.equals(null, null)); int a = Integer.MAX_VALUE; int b = 5; if (a < 5 - b) { System.out.println(a + b); } } }
UTF-8
Java
444
java
Demo.java
Java
[ { "context": "package com.xmw.java8;\n\n/**\n * @author mingwei.xia\n * @date 2018/8/24 9:56\n * @since V1.0\n */", "end": 43, "score": 0.7515642642974854, "start": 39, "tag": "NAME", "value": "ming" }, { "context": "package com.xmw.java8;\n\n/**\n * @author mingwei.xia\n * @date 2018/8/24 9:56\n * @since V1.0\n */\npublic", "end": 50, "score": 0.5877172350883484, "start": 43, "tag": "USERNAME", "value": "wei.xia" } ]
null
[]
package com.xmw.java8; /** * @author mingwei.xia * @date 2018/8/24 9:56 * @since V1.0 */ public class Demo { public static void main(String[] args) { // Proxy.newProxyInstance() // byte[] bytes = new byte[100 * 1024 * 1024]; // System.out.println(Objects.equals(null, null)); int a = Integer.MAX_VALUE; int b = 5; if (a < 5 - b) { System.out.println(a + b); } } }
444
0.524775
0.466216
21
20.142857
17.332287
57
false
false
0
0
0
0
0
0
0.333333
false
false
10
654869382047868392a0b2d08c6a00c0338f4a8f
32,255,204,423,010
3fc098fda87b2faae000a150faa1a18c8c8b89d0
/SamuliLehtonen_ArthurXavier_COMP304_Sec003_Lab4/app/src/main/java/com/example/samulilehtonen_arthurxavier_comp304_sec003_lab4/Nurse.java
df34ee63b50a469038443214468f2030b30ac8db
[]
no_license
Cendukka/MobileApplicationAssignments4-6
https://github.com/Cendukka/MobileApplicationAssignments4-6
f87661a44b770751b121e0b78da0eaac3508be9c
d84511540c0b5f039688649ae15b270894c1eb2c
refs/heads/master
2021-02-16T15:59:40.697000
2020-04-10T18:36:00
2020-04-10T18:36:00
245,021,704
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.samulilehtonen_arthurxavier_comp304_sec003_lab4; /* * Created an entity of Nurse * * */ import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.PrimaryKey; @Entity public class Nurse { @PrimaryKey @ColumnInfo(name = "nurse_id") private int id; private String first_name; private String last_name; private String department; private String password; //Getters and Setters public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirst_name() { return first_name; } public void setFirst_name(String first_name) { this.first_name = first_name; } public String getLast_name() { return last_name; } public void setLast_name(String last_name) { this.last_name = last_name; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public String getPassword() { return password; } public void setPassword(String password){ this.password = password; } }
UTF-8
Java
1,210
java
Nurse.java
Java
[ { "context": "package com.example.samulilehtonen_arthurxavier_comp304_sec003_lab4;\n\n/*\n * Created ", "end": 34, "score": 0.8501558303833008, "start": 20, "tag": "USERNAME", "value": "samulilehtonen" }, { "context": "package com.example.samulilehtonen_arthurxavier_comp304_sec003_lab4;\n\n/*\n * Created an en", "end": 39, "score": 0.6945365071296692, "start": 35, "tag": "USERNAME", "value": "arth" }, { "context": "mp304_sec003_lab4;\n\n/*\n * Created an entity of Nurse\n *\n * */\n\nimport androidx.room.ColumnInfo;\nimport", "end": 102, "score": 0.37209567427635193, "start": 100, "tag": "USERNAME", "value": "se" } ]
null
[]
package com.example.samulilehtonen_arthurxavier_comp304_sec003_lab4; /* * Created an entity of Nurse * * */ import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.PrimaryKey; @Entity public class Nurse { @PrimaryKey @ColumnInfo(name = "nurse_id") private int id; private String first_name; private String last_name; private String department; private String password; //Getters and Setters public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirst_name() { return first_name; } public void setFirst_name(String first_name) { this.first_name = first_name; } public String getLast_name() { return last_name; } public void setLast_name(String last_name) { this.last_name = last_name; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public String getPassword() { return password; } public void setPassword(String password){ this.password = password; } }
1,210
0.633884
0.628099
58
19.879311
16.521749
68
false
false
0
0
0
0
0
0
0.327586
false
false
10
793a31933dbb4ec9e6c167ebf79fe898bbcb8661
31,164,282,711,872
e7ca3a996490d264bbf7e10818558e8249956eda
/aliyun-java-sdk-emr/src/main/java/com/aliyuncs/emr/model/v20160408/ListClusterForAdminRequest.java
88e57ad28893fe52d719895d46f02213e2b4ed0b
[ "Apache-2.0" ]
permissive
AndyYHL/aliyun-openapi-java-sdk
https://github.com/AndyYHL/aliyun-openapi-java-sdk
6f0e73f11f040568fa03294de2bf9a1796767996
15927689c66962bdcabef0b9fc54a919d4d6c494
refs/heads/master
2020-03-26T23:18:49.532000
2018-08-21T04:12:23
2018-08-21T04:12:23
145,530,169
1
0
null
true
2018-08-21T08:14:14
2018-08-21T08:14:13
2018-08-21T07:37:26
2018-08-21T04:12:29
10,055
0
0
0
null
false
null
/* * 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.aliyuncs.emr.model.v20160408; import com.aliyuncs.RpcAcsRequest; import java.util.List; /** * @author auto create * @version */ public class ListClusterForAdminRequest extends RpcAcsRequest<ListClusterForAdminResponse> { public ListClusterForAdminRequest() { super("Emr", "2016-04-08", "ListClusterForAdmin"); } private Long resourceOwnerId; private List<String> statusLists; private String fuzzyName; private String userId; private Integer pageNumber; private List<Long> ecmClusterIdLists; private List<String> clusterIdLists; private List<String> payTypeLists; private String name; private Integer pageSize; private String emrVersion; private Boolean resize; private List<String> clusterTypeLists; public Long getResourceOwnerId() { return this.resourceOwnerId; } public void setResourceOwnerId(Long resourceOwnerId) { this.resourceOwnerId = resourceOwnerId; if(resourceOwnerId != null){ putQueryParameter("ResourceOwnerId", resourceOwnerId.toString()); } } public List<String> getStatusLists() { return this.statusLists; } public void setStatusLists(List<String> statusLists) { this.statusLists = statusLists; if (statusLists != null) { for (int i = 0; i < statusLists.size(); i++) { putQueryParameter("StatusList." + (i + 1) , statusLists.get(i)); } } } public String getFuzzyName() { return this.fuzzyName; } public void setFuzzyName(String fuzzyName) { this.fuzzyName = fuzzyName; if(fuzzyName != null){ putQueryParameter("FuzzyName", fuzzyName); } } public String getUserId() { return this.userId; } public void setUserId(String userId) { this.userId = userId; if(userId != null){ putQueryParameter("UserId", userId); } } public Integer getPageNumber() { return this.pageNumber; } public void setPageNumber(Integer pageNumber) { this.pageNumber = pageNumber; if(pageNumber != null){ putQueryParameter("PageNumber", pageNumber.toString()); } } public List<Long> getEcmClusterIdLists() { return this.ecmClusterIdLists; } public void setEcmClusterIdLists(List<Long> ecmClusterIdLists) { this.ecmClusterIdLists = ecmClusterIdLists; if (ecmClusterIdLists != null) { for (int i = 0; i < ecmClusterIdLists.size(); i++) { putQueryParameter("EcmClusterIdList." + (i + 1) , ecmClusterIdLists.get(i)); } } } public List<String> getClusterIdLists() { return this.clusterIdLists; } public void setClusterIdLists(List<String> clusterIdLists) { this.clusterIdLists = clusterIdLists; if (clusterIdLists != null) { for (int i = 0; i < clusterIdLists.size(); i++) { putQueryParameter("ClusterIdList." + (i + 1) , clusterIdLists.get(i)); } } } public List<String> getPayTypeLists() { return this.payTypeLists; } public void setPayTypeLists(List<String> payTypeLists) { this.payTypeLists = payTypeLists; if (payTypeLists != null) { for (int i = 0; i < payTypeLists.size(); i++) { putQueryParameter("PayTypeList." + (i + 1) , payTypeLists.get(i)); } } } public String getName() { return this.name; } public void setName(String name) { this.name = name; if(name != null){ putQueryParameter("Name", name); } } public Integer getPageSize() { return this.pageSize; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; if(pageSize != null){ putQueryParameter("PageSize", pageSize.toString()); } } public String getEmrVersion() { return this.emrVersion; } public void setEmrVersion(String emrVersion) { this.emrVersion = emrVersion; if(emrVersion != null){ putQueryParameter("EmrVersion", emrVersion); } } public Boolean getResize() { return this.resize; } public void setResize(Boolean resize) { this.resize = resize; if(resize != null){ putQueryParameter("Resize", resize.toString()); } } public List<String> getClusterTypeLists() { return this.clusterTypeLists; } public void setClusterTypeLists(List<String> clusterTypeLists) { this.clusterTypeLists = clusterTypeLists; if (clusterTypeLists != null) { for (int i = 0; i < clusterTypeLists.size(); i++) { putQueryParameter("ClusterTypeList." + (i + 1) , clusterTypeLists.get(i)); } } } @Override public Class<ListClusterForAdminResponse> getResponseClass() { return ListClusterForAdminResponse.class; } }
UTF-8
Java
5,103
java
ListClusterForAdminRequest.java
Java
[]
null
[]
/* * 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.aliyuncs.emr.model.v20160408; import com.aliyuncs.RpcAcsRequest; import java.util.List; /** * @author auto create * @version */ public class ListClusterForAdminRequest extends RpcAcsRequest<ListClusterForAdminResponse> { public ListClusterForAdminRequest() { super("Emr", "2016-04-08", "ListClusterForAdmin"); } private Long resourceOwnerId; private List<String> statusLists; private String fuzzyName; private String userId; private Integer pageNumber; private List<Long> ecmClusterIdLists; private List<String> clusterIdLists; private List<String> payTypeLists; private String name; private Integer pageSize; private String emrVersion; private Boolean resize; private List<String> clusterTypeLists; public Long getResourceOwnerId() { return this.resourceOwnerId; } public void setResourceOwnerId(Long resourceOwnerId) { this.resourceOwnerId = resourceOwnerId; if(resourceOwnerId != null){ putQueryParameter("ResourceOwnerId", resourceOwnerId.toString()); } } public List<String> getStatusLists() { return this.statusLists; } public void setStatusLists(List<String> statusLists) { this.statusLists = statusLists; if (statusLists != null) { for (int i = 0; i < statusLists.size(); i++) { putQueryParameter("StatusList." + (i + 1) , statusLists.get(i)); } } } public String getFuzzyName() { return this.fuzzyName; } public void setFuzzyName(String fuzzyName) { this.fuzzyName = fuzzyName; if(fuzzyName != null){ putQueryParameter("FuzzyName", fuzzyName); } } public String getUserId() { return this.userId; } public void setUserId(String userId) { this.userId = userId; if(userId != null){ putQueryParameter("UserId", userId); } } public Integer getPageNumber() { return this.pageNumber; } public void setPageNumber(Integer pageNumber) { this.pageNumber = pageNumber; if(pageNumber != null){ putQueryParameter("PageNumber", pageNumber.toString()); } } public List<Long> getEcmClusterIdLists() { return this.ecmClusterIdLists; } public void setEcmClusterIdLists(List<Long> ecmClusterIdLists) { this.ecmClusterIdLists = ecmClusterIdLists; if (ecmClusterIdLists != null) { for (int i = 0; i < ecmClusterIdLists.size(); i++) { putQueryParameter("EcmClusterIdList." + (i + 1) , ecmClusterIdLists.get(i)); } } } public List<String> getClusterIdLists() { return this.clusterIdLists; } public void setClusterIdLists(List<String> clusterIdLists) { this.clusterIdLists = clusterIdLists; if (clusterIdLists != null) { for (int i = 0; i < clusterIdLists.size(); i++) { putQueryParameter("ClusterIdList." + (i + 1) , clusterIdLists.get(i)); } } } public List<String> getPayTypeLists() { return this.payTypeLists; } public void setPayTypeLists(List<String> payTypeLists) { this.payTypeLists = payTypeLists; if (payTypeLists != null) { for (int i = 0; i < payTypeLists.size(); i++) { putQueryParameter("PayTypeList." + (i + 1) , payTypeLists.get(i)); } } } public String getName() { return this.name; } public void setName(String name) { this.name = name; if(name != null){ putQueryParameter("Name", name); } } public Integer getPageSize() { return this.pageSize; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; if(pageSize != null){ putQueryParameter("PageSize", pageSize.toString()); } } public String getEmrVersion() { return this.emrVersion; } public void setEmrVersion(String emrVersion) { this.emrVersion = emrVersion; if(emrVersion != null){ putQueryParameter("EmrVersion", emrVersion); } } public Boolean getResize() { return this.resize; } public void setResize(Boolean resize) { this.resize = resize; if(resize != null){ putQueryParameter("Resize", resize.toString()); } } public List<String> getClusterTypeLists() { return this.clusterTypeLists; } public void setClusterTypeLists(List<String> clusterTypeLists) { this.clusterTypeLists = clusterTypeLists; if (clusterTypeLists != null) { for (int i = 0; i < clusterTypeLists.size(); i++) { putQueryParameter("ClusterTypeList." + (i + 1) , clusterTypeLists.get(i)); } } } @Override public Class<ListClusterForAdminResponse> getResponseClass() { return ListClusterForAdminResponse.class; } }
5,103
0.685675
0.679796
214
22.079439
22.571346
92
false
false
0
0
0
0
0
0
1.635514
false
false
10
c24d5e7bb9a56d1b066e9f97a5a48ca79f2715f3
21,912,923,166,028
31fabaf273f37d1ca7c57d2d53b230a8236082bb
/src/main/java/com/lzhenxing/javascaffold/javabase/monitor/cpu/CpuHighFromIO.java
e447bc33a8c3c7931ebfc8c69d22efc0ae1a7c28
[]
no_license
lzx2011/java-scaffold
https://github.com/lzx2011/java-scaffold
8210811b21730f51a0280f4917fd0859c1b6a192
7ff7266179068502bb9229eca42111dc41e57555
refs/heads/master
2021-06-13T18:40:21.611000
2019-10-02T17:48:37
2019-10-02T17:48:37
84,739,117
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lzhenxing.javascaffold.javabase.monitor.cpu; import org.apache.commons.lang3.StringUtils; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; /** * ClassName: CpuHighFromIO <br/> * Function: <br/> * * @author gary.liu * @date 2017/8/27 */ public class CpuHighFromIO { public static void main(String[] args) throws Exception { final String tudou = "http://v.youku.com/v_playlist/f17170661o1p9.html"; URL url = new URL(tudou); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); try { InputStream in = conn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8")); StringBuilder buf = new StringBuilder(); String line = null; while ((line = br.readLine()) != null) { if (StringUtils.isNotEmpty(buf.toString())) { buf.append("\r\n"); } buf.append(line); } //do something with 'buf' } finally { conn.disconnect(); } } }
UTF-8
Java
1,233
java
CpuHighFromIO.java
Java
[ { "context": "uHighFromIO <br/>\n * Function: <br/>\n *\n * @author gary.liu\n * @date 2017/8/27\n */\npublic class CpuHighFromIO", "end": 333, "score": 0.9992095232009888, "start": 325, "tag": "NAME", "value": "gary.liu" } ]
null
[]
package com.lzhenxing.javascaffold.javabase.monitor.cpu; import org.apache.commons.lang3.StringUtils; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; /** * ClassName: CpuHighFromIO <br/> * Function: <br/> * * @author gary.liu * @date 2017/8/27 */ public class CpuHighFromIO { public static void main(String[] args) throws Exception { final String tudou = "http://v.youku.com/v_playlist/f17170661o1p9.html"; URL url = new URL(tudou); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); try { InputStream in = conn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8")); StringBuilder buf = new StringBuilder(); String line = null; while ((line = br.readLine()) != null) { if (StringUtils.isNotEmpty(buf.toString())) { buf.append("\r\n"); } buf.append(line); } //do something with 'buf' } finally { conn.disconnect(); } } }
1,233
0.596107
0.580697
44
27.022728
23.144299
87
false
false
0
0
0
0
0
0
0.431818
false
false
10
8b9c9cc8138fe516dff7691adff0c6b123d1f2b8
10,024,453,671,399
eb4af41bc83ad0a5ed270bc478d23dd9fcdff41c
/src/main/java/org/leiqiao/ideares/sc/FilePropPair.java
d00625e7eba052fbd85783d773e2a77a8b2d524d
[]
no_license
leiqiao0/IDEA-SC-Res
https://github.com/leiqiao0/IDEA-SC-Res
ffa63c951739ed8eabc9c3c3d6b6a5dbe33292b5
93dcba862ae62fcc6c62e784b96ce30983bb3283
refs/heads/master
2017-04-21T17:01:37.908000
2017-02-10T10:38:31
2017-02-10T10:38:31
81,060,552
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.leiqiao.ideares.sc; import java.util.Properties; public class FilePropPair { private String filename; private Properties properties; public FilePropPair(String filename, Properties properties) { this.filename = filename; this.properties = properties; } public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } public Properties getProperties() { return properties; } public void setProperties(Properties properties) { this.properties = properties; } }
UTF-8
Java
637
java
FilePropPair.java
Java
[]
null
[]
package org.leiqiao.ideares.sc; import java.util.Properties; public class FilePropPair { private String filename; private Properties properties; public FilePropPair(String filename, Properties properties) { this.filename = filename; this.properties = properties; } public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } public Properties getProperties() { return properties; } public void setProperties(Properties properties) { this.properties = properties; } }
637
0.660911
0.660911
36
16.694445
18.664909
65
false
false
0
0
0
0
0
0
0.305556
false
false
10
0d955c1fee03b5d0c15cdddaf5d1b3dc14dc4f77
28,810,640,636,123
03f49cdab6f1bbb3ddaee5e64a19b820b51567f5
/src/main/java/com/zb/dto/UserDto.java
3059154174be7e9ebcb2532d582c228cb4b6e1fd
[]
no_license
ZhengBing520/zhengb
https://github.com/ZhengBing520/zhengb
88118dd9ba71919549b2125f9e97d7368ede53f3
2e39d74762e1b7f09071841b27633ae47e858494
refs/heads/master
2021-04-26T04:21:45.252000
2020-03-19T12:26:44
2020-03-19T12:26:44
106,996,735
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zb.dto; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; /** * Created by bzheng on 2019/1/27. */ public class UserDto extends BaseDto { @ApiModelProperty("็”จๆˆทๅ") @NotEmpty(message = "็”จๆˆทๅไธ่ƒฝไธบ็ฉบ") private String username; @ApiModelProperty("ๅฏ†็ ") @NotEmpty(message = "ๅฏ†็ ไธ่ƒฝไธบ็ฉบ") private String password; @ApiModelProperty("็”จๆˆท็ฑปๅž‹๏ผŒ0๏ผšๆ™ฎ้€š็”จๆˆท๏ผŒ1๏ผš็ฎก็†ๅ‘˜") private Integer type; @ApiModelProperty("ๅง“ๅ") @NotEmpty(message = "ๅง“ๅไธ่ƒฝไธบ็ฉบ") private String realName; @ApiModelProperty("ๆ˜ต็งฐ") @NotEmpty(message = "ๆ˜ต็งฐไธ่ƒฝไธบ็ฉบ") private String nickName; @ApiModelProperty("ๆ‰‹ๆœบๅท") @NotNull(message = "ๆ‰‹ๆœบๅทไธ่ƒฝไธบ็ฉบ") private String mobile; @ApiModelProperty("token") private String token; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } }
UTF-8
Java
1,979
java
UserDto.java
Java
[ { "context": "validation.constraints.NotNull;\n\n/**\n * Created by bzheng on 2019/1/27.\n */\npublic class UserDto extends Ba", "end": 186, "score": 0.9997453093528748, "start": 180, "tag": "USERNAME", "value": "bzheng" }, { "context": "\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String userna", "end": 891, "score": 0.7643942832946777, "start": 883, "tag": "USERNAME", "value": "username" }, { "context": "sername(String username) {\n this.username = username;\n }\n\n public String getPassword() {\n ", "end": 979, "score": 0.9154125452041626, "start": 971, "tag": "USERNAME", "value": "username" }, { "context": "assword(String password) {\n this.password = password;\n }\n\n public Integer getType() {\n re", "end": 1133, "score": 0.5275457501411438, "start": 1125, "tag": "PASSWORD", "value": "password" } ]
null
[]
package com.zb.dto; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; /** * Created by bzheng on 2019/1/27. */ public class UserDto extends BaseDto { @ApiModelProperty("็”จๆˆทๅ") @NotEmpty(message = "็”จๆˆทๅไธ่ƒฝไธบ็ฉบ") private String username; @ApiModelProperty("ๅฏ†็ ") @NotEmpty(message = "ๅฏ†็ ไธ่ƒฝไธบ็ฉบ") private String password; @ApiModelProperty("็”จๆˆท็ฑปๅž‹๏ผŒ0๏ผšๆ™ฎ้€š็”จๆˆท๏ผŒ1๏ผš็ฎก็†ๅ‘˜") private Integer type; @ApiModelProperty("ๅง“ๅ") @NotEmpty(message = "ๅง“ๅไธ่ƒฝไธบ็ฉบ") private String realName; @ApiModelProperty("ๆ˜ต็งฐ") @NotEmpty(message = "ๆ˜ต็งฐไธ่ƒฝไธบ็ฉบ") private String nickName; @ApiModelProperty("ๆ‰‹ๆœบๅท") @NotNull(message = "ๆ‰‹ๆœบๅทไธ่ƒฝไธบ็ฉบ") private String mobile; @ApiModelProperty("token") private String token; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = <PASSWORD>; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } }
1,981
0.629232
0.624395
94
18.797873
15.95311
47
false
false
0
0
0
0
0
0
0.265957
false
false
10
f124d67209f554829278774813fce5e7d8d6b551
31,190,052,551,206
32cb7a4b3707d847f0574aed0845b99833ac267d
/src/com/javarush/test/level19/lesson05/task05/Solution.java
842c219b6fe6aed254a124831cdc7cf9f00bd316
[]
no_license
Li0n13/JavaRushHomeWork
https://github.com/Li0n13/JavaRushHomeWork
703a8e314b6b7feb3dbba2214b0a84208d242db4
cdcc0b8d61a839ae62809c425a07ccb36bbe21a4
refs/heads/master
2019-07-31T17:09:24.001000
2016-12-03T20:51:34
2016-12-03T20:51:34
75,499,640
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.javarush.test.level19.lesson05.task05; /* ะŸัƒะฝะบั‚ัƒะฐั†ะธั ะกั‡ะธั‚ะฐั‚ัŒ ั ะบะพะฝัะพะปะธ 2 ะธะผะตะฝะธ ั„ะฐะนะปะฐ. ะŸะตั€ะฒั‹ะน ะคะฐะนะป ัะพะดะตั€ะถะธั‚ ั‚ะตะบัั‚. ะฃะดะฐะปะธั‚ัŒ ะฒัะต ะทะฝะฐะบะธ ะฟัƒะฝะบั‚ัƒะฐั†ะธะธ, ะฒะบะปัŽั‡ะฐั ัะธะผะฒะพะปั‹ ะฝะพะฒะพะน ัั‚ั€ะพะบะธ. ะ ะตะทัƒะปัŒั‚ะฐั‚ ะฒั‹ะฒะตัั‚ะธ ะฒะพ ะฒั‚ะพั€ะพะน ั„ะฐะนะป. http://ru.wikipedia.org/wiki/%D0%9F%D1%83%D0%BD%D0%BA%D1%82%D1%83%D0%B0%D1%86%D0%B8%D1%8F ะ—ะฐะบั€ั‹ั‚ัŒ ะฟะพั‚ะพะบะธ. ะะต ะธัะฟะพะปัŒะทะพะฒะฐั‚ัŒ try-with-resources */ import java.io.*; public class Solution { public static void main(String[] args) throws IOException { BufferedReader kbReader = new BufferedReader(new InputStreamReader(System.in)); BufferedReader fileInput = new BufferedReader(new FileReader(kbReader.readLine())); BufferedWriter fileOutput = new BufferedWriter(new FileWriter(kbReader.readLine())); kbReader.close(); String s; while ((s = fileInput.readLine()) != null) { s = s.replaceAll("\\p{Punct}|\n|\r\n", ""); fileOutput.write(s); } fileInput.close(); fileOutput.close(); } }
UTF-8
Java
1,171
java
Solution.java
Java
[]
null
[]
package com.javarush.test.level19.lesson05.task05; /* ะŸัƒะฝะบั‚ัƒะฐั†ะธั ะกั‡ะธั‚ะฐั‚ัŒ ั ะบะพะฝัะพะปะธ 2 ะธะผะตะฝะธ ั„ะฐะนะปะฐ. ะŸะตั€ะฒั‹ะน ะคะฐะนะป ัะพะดะตั€ะถะธั‚ ั‚ะตะบัั‚. ะฃะดะฐะปะธั‚ัŒ ะฒัะต ะทะฝะฐะบะธ ะฟัƒะฝะบั‚ัƒะฐั†ะธะธ, ะฒะบะปัŽั‡ะฐั ัะธะผะฒะพะปั‹ ะฝะพะฒะพะน ัั‚ั€ะพะบะธ. ะ ะตะทัƒะปัŒั‚ะฐั‚ ะฒั‹ะฒะตัั‚ะธ ะฒะพ ะฒั‚ะพั€ะพะน ั„ะฐะนะป. http://ru.wikipedia.org/wiki/%D0%9F%D1%83%D0%BD%D0%BA%D1%82%D1%83%D0%B0%D1%86%D0%B8%D1%8F ะ—ะฐะบั€ั‹ั‚ัŒ ะฟะพั‚ะพะบะธ. ะะต ะธัะฟะพะปัŒะทะพะฒะฐั‚ัŒ try-with-resources */ import java.io.*; public class Solution { public static void main(String[] args) throws IOException { BufferedReader kbReader = new BufferedReader(new InputStreamReader(System.in)); BufferedReader fileInput = new BufferedReader(new FileReader(kbReader.readLine())); BufferedWriter fileOutput = new BufferedWriter(new FileWriter(kbReader.readLine())); kbReader.close(); String s; while ((s = fileInput.readLine()) != null) { s = s.replaceAll("\\p{Punct}|\n|\r\n", ""); fileOutput.write(s); } fileInput.close(); fileOutput.close(); } }
1,171
0.676587
0.647817
29
33.758621
31.568924
93
false
false
0
0
0
0
0
0
0.517241
false
false
10
6af06fbdd87575d263cd6c6e15432403403e665d
32,306,744,045,084
4bde004f5ce6f915b48ba5ed995fc7b96db33b22
/sample-blog/src/test/java/com/qiumingkui/sample/imedia/blog/helper/BlogEntryCategoryTestHelper.java
52353186dc870725fa25b5b2862b8143c18c724a
[ "Apache-2.0" ]
permissive
qiumingkui/sample
https://github.com/qiumingkui/sample
c2cf390503326983ef8ccb7012d47e4365172edf
a04980a52b2419e2ae6d319ebb248ebcd745592e
refs/heads/master
2020-05-20T19:47:06.405000
2017-11-14T01:36:05
2017-11-14T01:36:05
84,514,192
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.qiumingkui.sample.imedia.blog.helper; import com.qiumingkui.sample.imedia.blog.domain.model.category.BlogEntryCategory; import com.qiumingkui.sample.imedia.blog.domain.model.category.BlogEntryCategoryFactory; public class BlogEntryCategoryTestHelper { public static BlogEntryCategory buildBlogEntryCategoryExample(){ BlogEntryCategory blogEntryCategory = BlogEntryCategoryFactory.create("blogEntryId:1", "categoryId:1"); return blogEntryCategory ; } }
UTF-8
Java
479
java
BlogEntryCategoryTestHelper.java
Java
[]
null
[]
package com.qiumingkui.sample.imedia.blog.helper; import com.qiumingkui.sample.imedia.blog.domain.model.category.BlogEntryCategory; import com.qiumingkui.sample.imedia.blog.domain.model.category.BlogEntryCategoryFactory; public class BlogEntryCategoryTestHelper { public static BlogEntryCategory buildBlogEntryCategoryExample(){ BlogEntryCategory blogEntryCategory = BlogEntryCategoryFactory.create("blogEntryId:1", "categoryId:1"); return blogEntryCategory ; } }
479
0.82881
0.824635
14
33.214287
36.9095
105
false
false
0
0
0
0
0
0
1.142857
false
false
10
1d2bf645d7ccdb099c79bdd971ae798f2a5a9ced
31,095,563,247,299
d1a49d0f411f694bc629ec4f26f9731a667f5676
/app/src/main/java/com/xbw/unmanned/Utils/TTSController.java
770cb8da0399108b338d6f68f9f193547879d9fc
[]
no_license
WuShaoling/Epay-Android
https://github.com/WuShaoling/Epay-Android
fc3ee70172041b21f522443a7aa9696acc6a0b00
f0ac53410fbf7baeddc96b9ac01ea905b31e0a52
refs/heads/master
2021-01-01T05:58:28.824000
2017-07-29T02:31:00
2017-07-29T02:31:00
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xbw.unmanned.Utils; import android.content.Context; import android.os.Bundle; import com.amap.api.navi.AMapNaviListener; import com.amap.api.navi.model.AMapLaneInfo; import com.amap.api.navi.model.AMapNaviCross; import com.amap.api.navi.model.AMapNaviInfo; import com.amap.api.navi.model.AMapNaviLocation; import com.amap.api.navi.model.AMapNaviTrafficFacilityInfo; import com.amap.api.navi.model.AimLessModeCongestionInfo; import com.amap.api.navi.model.AimLessModeStat; import com.amap.api.navi.model.NaviInfo; import com.autonavi.tbt.TrafficFacilityInfo; import com.iflytek.cloud.InitListener; import com.iflytek.cloud.SpeechConstant; import com.iflytek.cloud.SpeechError; import com.iflytek.cloud.SpeechSynthesizer; import com.iflytek.cloud.SynthesizerListener; import com.xbw.unmanned.R; /** * ่ฏญ้Ÿณๆ’ญๆŠฅ็ป„ไปถ */ public class TTSController implements SynthesizerListener, AMapNaviListener { public static TTSController ttsManager; boolean isfinish = true; private Context mContext; // ๅˆๆˆๅฏน่ฑก. private SpeechSynthesizer mSpeechSynthesizer; TTSController(Context context) { mContext = context; } public static TTSController getInstance(Context context) { if (ttsManager == null) { ttsManager = new TTSController(context); } return ttsManager; } private InitListener mTtsInitListener = new InitListener() { @Override public void onInit(int code) { } }; public void init() { // ๅˆๅง‹ๅŒ–ๅˆๆˆๅฏน่ฑก. mSpeechSynthesizer = SpeechSynthesizer.createSynthesizer(mContext,mTtsInitListener); initSpeechSynthesizer(); } public void playText(String playText) { if (!isfinish) { return; } if (null == mSpeechSynthesizer) { // ๅˆ›ๅปบๅˆๆˆๅฏน่ฑก. mSpeechSynthesizer = SpeechSynthesizer.createSynthesizer(mContext,mTtsInitListener); initSpeechSynthesizer(); } // ่ฟ›่กŒ่ฏญ้Ÿณๅˆๆˆ. mSpeechSynthesizer.startSpeaking(playText, this); } private void initSpeechSynthesizer() { // ่ฎพ็ฝฎๅ‘้Ÿณไบบ mSpeechSynthesizer.setParameter(SpeechConstant.VOICE_NAME, mContext.getString(R.string.preference_default_tts_role)); // ่ฎพ็ฝฎ่ฏญ้€Ÿ mSpeechSynthesizer.setParameter(SpeechConstant.SPEED, "" + mContext.getString(R.string.preference_key_tts_speed)); // ่ฎพ็ฝฎ้Ÿณ้‡ mSpeechSynthesizer.setParameter(SpeechConstant.VOLUME, "" + mContext.getString(R.string.preference_key_tts_volume)); // ่ฎพ็ฝฎ่ฏญ่ฐƒ mSpeechSynthesizer.setParameter(SpeechConstant.PITCH, "" + mContext.getString(R.string.preference_key_tts_pitch)); } public void destroy() { if (mSpeechSynthesizer != null) { mSpeechSynthesizer.stopSpeaking(); } } public void stopSpeaking() { if (mSpeechSynthesizer != null) mSpeechSynthesizer.stopSpeaking(); } public void startSpeaking() { isfinish = true; } @Override public void onInitNaviFailure() { } @Override public void onInitNaviSuccess() { } @Override public void onStartNavi(int i) { } @Override public void onTrafficStatusUpdate() { } @Override public void onLocationChange(AMapNaviLocation aMapNaviLocation) { } @Override public void onGetNavigationText(int i, String s) { } @Override public void onEndEmulatorNavi() { this.playText("ๅฏผ่ˆช็ป“ๆŸ"); } @Override public void onArriveDestination() { this.playText("ๅˆฐ่พพ็›ฎ็š„ๅœฐ"); } @Override public void onCalculateRouteSuccess() { this.playText("่ทฏๅพ„่ฎก็ฎ—ๅฐฑ็ปช"); } @Override public void onCalculateRouteFailure(int i) { this.playText("่ทฏๅพ„่ฎก็ฎ—ๅคฑ่ดฅ๏ผŒ่ฏทๆฃ€ๆŸฅ็ฝ‘็ปœๆˆ–่พ“ๅ…ฅๅ‚ๆ•ฐ"); } @Override public void onReCalculateRouteForYaw() { this.playText("ๆ‚จๅทฒๅ่ˆช"); } @Override public void onReCalculateRouteForTrafficJam() { this.playText("ๅ‰ๆ–น่ทฏ็บฟๆ‹ฅๅ ต๏ผŒ่ทฏ็บฟ้‡ๆ–ฐ่ง„ๅˆ’"); } @Override public void onArrivedWayPoint(int i) { } @Override public void onGpsOpenStatus(boolean b) { } @Override public void onNaviInfoUpdated(AMapNaviInfo aMapNaviInfo) { } @Override public void onNaviInfoUpdate(NaviInfo naviInfo) { } @Override public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo aMapNaviTrafficFacilityInfo) { } @Override public void OnUpdateTrafficFacility(TrafficFacilityInfo trafficFacilityInfo) { } @Override public void showCross(AMapNaviCross aMapNaviCross) { } @Override public void hideCross() { } @Override public void showLaneInfo(AMapLaneInfo[] aMapLaneInfos, byte[] bytes, byte[] bytes1) { } @Override public void hideLaneInfo() { } @Override public void onCalculateMultipleRoutesSuccess(int[] ints) { } @Override public void notifyParallelRoad(int i) { } @Override public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo[] aMapNaviTrafficFacilityInfos) { } @Override public void updateAimlessModeStatistics(AimLessModeStat aimLessModeStat) { } @Override public void updateAimlessModeCongestionInfo(AimLessModeCongestionInfo aimLessModeCongestionInfo) { } @Override public void onSpeakBegin() { } @Override public void onBufferProgress(int i, int i1, int i2, String s) { } @Override public void onSpeakPaused() { } @Override public void onSpeakResumed() { } @Override public void onSpeakProgress(int i, int i1, int i2) { } @Override public void onCompleted(SpeechError speechError) { } @Override public void onEvent(int i, int i1, int i2, Bundle bundle) { } }
UTF-8
Java
6,080
java
TTSController.java
Java
[]
null
[]
package com.xbw.unmanned.Utils; import android.content.Context; import android.os.Bundle; import com.amap.api.navi.AMapNaviListener; import com.amap.api.navi.model.AMapLaneInfo; import com.amap.api.navi.model.AMapNaviCross; import com.amap.api.navi.model.AMapNaviInfo; import com.amap.api.navi.model.AMapNaviLocation; import com.amap.api.navi.model.AMapNaviTrafficFacilityInfo; import com.amap.api.navi.model.AimLessModeCongestionInfo; import com.amap.api.navi.model.AimLessModeStat; import com.amap.api.navi.model.NaviInfo; import com.autonavi.tbt.TrafficFacilityInfo; import com.iflytek.cloud.InitListener; import com.iflytek.cloud.SpeechConstant; import com.iflytek.cloud.SpeechError; import com.iflytek.cloud.SpeechSynthesizer; import com.iflytek.cloud.SynthesizerListener; import com.xbw.unmanned.R; /** * ่ฏญ้Ÿณๆ’ญๆŠฅ็ป„ไปถ */ public class TTSController implements SynthesizerListener, AMapNaviListener { public static TTSController ttsManager; boolean isfinish = true; private Context mContext; // ๅˆๆˆๅฏน่ฑก. private SpeechSynthesizer mSpeechSynthesizer; TTSController(Context context) { mContext = context; } public static TTSController getInstance(Context context) { if (ttsManager == null) { ttsManager = new TTSController(context); } return ttsManager; } private InitListener mTtsInitListener = new InitListener() { @Override public void onInit(int code) { } }; public void init() { // ๅˆๅง‹ๅŒ–ๅˆๆˆๅฏน่ฑก. mSpeechSynthesizer = SpeechSynthesizer.createSynthesizer(mContext,mTtsInitListener); initSpeechSynthesizer(); } public void playText(String playText) { if (!isfinish) { return; } if (null == mSpeechSynthesizer) { // ๅˆ›ๅปบๅˆๆˆๅฏน่ฑก. mSpeechSynthesizer = SpeechSynthesizer.createSynthesizer(mContext,mTtsInitListener); initSpeechSynthesizer(); } // ่ฟ›่กŒ่ฏญ้Ÿณๅˆๆˆ. mSpeechSynthesizer.startSpeaking(playText, this); } private void initSpeechSynthesizer() { // ่ฎพ็ฝฎๅ‘้Ÿณไบบ mSpeechSynthesizer.setParameter(SpeechConstant.VOICE_NAME, mContext.getString(R.string.preference_default_tts_role)); // ่ฎพ็ฝฎ่ฏญ้€Ÿ mSpeechSynthesizer.setParameter(SpeechConstant.SPEED, "" + mContext.getString(R.string.preference_key_tts_speed)); // ่ฎพ็ฝฎ้Ÿณ้‡ mSpeechSynthesizer.setParameter(SpeechConstant.VOLUME, "" + mContext.getString(R.string.preference_key_tts_volume)); // ่ฎพ็ฝฎ่ฏญ่ฐƒ mSpeechSynthesizer.setParameter(SpeechConstant.PITCH, "" + mContext.getString(R.string.preference_key_tts_pitch)); } public void destroy() { if (mSpeechSynthesizer != null) { mSpeechSynthesizer.stopSpeaking(); } } public void stopSpeaking() { if (mSpeechSynthesizer != null) mSpeechSynthesizer.stopSpeaking(); } public void startSpeaking() { isfinish = true; } @Override public void onInitNaviFailure() { } @Override public void onInitNaviSuccess() { } @Override public void onStartNavi(int i) { } @Override public void onTrafficStatusUpdate() { } @Override public void onLocationChange(AMapNaviLocation aMapNaviLocation) { } @Override public void onGetNavigationText(int i, String s) { } @Override public void onEndEmulatorNavi() { this.playText("ๅฏผ่ˆช็ป“ๆŸ"); } @Override public void onArriveDestination() { this.playText("ๅˆฐ่พพ็›ฎ็š„ๅœฐ"); } @Override public void onCalculateRouteSuccess() { this.playText("่ทฏๅพ„่ฎก็ฎ—ๅฐฑ็ปช"); } @Override public void onCalculateRouteFailure(int i) { this.playText("่ทฏๅพ„่ฎก็ฎ—ๅคฑ่ดฅ๏ผŒ่ฏทๆฃ€ๆŸฅ็ฝ‘็ปœๆˆ–่พ“ๅ…ฅๅ‚ๆ•ฐ"); } @Override public void onReCalculateRouteForYaw() { this.playText("ๆ‚จๅทฒๅ่ˆช"); } @Override public void onReCalculateRouteForTrafficJam() { this.playText("ๅ‰ๆ–น่ทฏ็บฟๆ‹ฅๅ ต๏ผŒ่ทฏ็บฟ้‡ๆ–ฐ่ง„ๅˆ’"); } @Override public void onArrivedWayPoint(int i) { } @Override public void onGpsOpenStatus(boolean b) { } @Override public void onNaviInfoUpdated(AMapNaviInfo aMapNaviInfo) { } @Override public void onNaviInfoUpdate(NaviInfo naviInfo) { } @Override public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo aMapNaviTrafficFacilityInfo) { } @Override public void OnUpdateTrafficFacility(TrafficFacilityInfo trafficFacilityInfo) { } @Override public void showCross(AMapNaviCross aMapNaviCross) { } @Override public void hideCross() { } @Override public void showLaneInfo(AMapLaneInfo[] aMapLaneInfos, byte[] bytes, byte[] bytes1) { } @Override public void hideLaneInfo() { } @Override public void onCalculateMultipleRoutesSuccess(int[] ints) { } @Override public void notifyParallelRoad(int i) { } @Override public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo[] aMapNaviTrafficFacilityInfos) { } @Override public void updateAimlessModeStatistics(AimLessModeStat aimLessModeStat) { } @Override public void updateAimlessModeCongestionInfo(AimLessModeCongestionInfo aimLessModeCongestionInfo) { } @Override public void onSpeakBegin() { } @Override public void onBufferProgress(int i, int i1, int i2, String s) { } @Override public void onSpeakPaused() { } @Override public void onSpeakResumed() { } @Override public void onSpeakProgress(int i, int i1, int i2) { } @Override public void onCompleted(SpeechError speechError) { } @Override public void onEvent(int i, int i1, int i2, Bundle bundle) { } }
6,080
0.662818
0.66163
273
20.578754
24.003096
102
false
false
0
0
0
0
0
0
0.238095
false
false
10
2cc09757eb0ac0341bc874a9ce96eff2c307e396
31,945,966,776,673
71b14e7f6827c82818de87c6d0e2431e11aaa994
/Day23/src/com/itheima/_04methodref/demo05/Man.java
dc0c822fd8e3727503a06637a9a61766e7f7741f
[]
no_license
shaoyingying-git/JAVA_SE
https://github.com/shaoyingying-git/JAVA_SE
fd0c460fb998b946fbdb0d54c68306520d72f62b
8fd9cb184c91170c6428432990e1a40dcd76d3ab
refs/heads/master
2023-02-27T21:56:07.079000
2021-02-03T19:14:09
2021-02-03T19:14:09
334,726,683
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.itheima._04methodref.demo05; public class Man extends Human { @Override public void sayHello() { System.out.println("ๅคงๅฎถๅฅฝๆˆ‘ๆ˜ฏไป–ๅ„ฟๅญ!"); } public void fun(Greetable lambda) { lambda.greed(); } public void method() { // ่ฐƒ็”จ็ˆถ็ฑป็š„sayHello /*fun(new Greetable() { @Override public void greed() { // ่ฐƒ็”จMan็ฑป็š„็ˆถ็ฑปไธญ็š„ๆ–นๆณ• Man.super.sayHello(); } }); // ่ฐƒ็”จๆœฌ็ฑป็š„sayHello fun(new Greetable() { @Override public void greed() { Man.this.sayHello(); } });*/ fun(() -> super.sayHello()); fun(() -> this.sayHello()); // ๆ–นๆณ•ๅผ•็”จ // sayHelloๅŠŸ่ƒฝ, ๅทฒ็ปๅฎšไน‰ๅฅฝไบ† // A ไธญ็š„ BๅŠŸ่ƒฝ fun(super::sayHello); fun(this::sayHello); } }
UTF-8
Java
952
java
Man.java
Java
[]
null
[]
package com.itheima._04methodref.demo05; public class Man extends Human { @Override public void sayHello() { System.out.println("ๅคงๅฎถๅฅฝๆˆ‘ๆ˜ฏไป–ๅ„ฟๅญ!"); } public void fun(Greetable lambda) { lambda.greed(); } public void method() { // ่ฐƒ็”จ็ˆถ็ฑป็š„sayHello /*fun(new Greetable() { @Override public void greed() { // ่ฐƒ็”จMan็ฑป็š„็ˆถ็ฑปไธญ็š„ๆ–นๆณ• Man.super.sayHello(); } }); // ่ฐƒ็”จๆœฌ็ฑป็š„sayHello fun(new Greetable() { @Override public void greed() { Man.this.sayHello(); } });*/ fun(() -> super.sayHello()); fun(() -> this.sayHello()); // ๆ–นๆณ•ๅผ•็”จ // sayHelloๅŠŸ่ƒฝ, ๅทฒ็ปๅฎšไน‰ๅฅฝไบ† // A ไธญ็š„ BๅŠŸ่ƒฝ fun(super::sayHello); fun(this::sayHello); } }
952
0.461806
0.457176
44
18.636364
14.013128
40
false
false
0
0
0
0
0
0
0.272727
false
false
10
e2e8e533d598da28c59ceeb6c66d68626f88baba
3,281,355,072,861
6b60e60dce1602b9c1a6c6c147c0d183598508a7
/src/main/java/Resort/Domain/Buildings/GolfRepository.java
3d6be89b6f8e7849682a9714cf40210b8878d30b
[]
no_license
21600WJK9529/HospitalityResort
https://github.com/21600WJK9529/HospitalityResort
65e9746aa217721bb4fed83d8548468e659a7180
a0a0151fd421e48ac58aa18c99993098cd0be190
refs/heads/master
2022-04-27T07:24:06.298000
2019-10-02T09:15:15
2019-10-02T09:15:15
180,548,517
0
1
null
false
2022-03-31T18:55:15
2019-04-10T09:29:03
2019-10-02T09:24:36
2022-03-31T18:55:15
231
0
1
2
Java
false
false
package Resort.Domain.Buildings; import Resort.Database.Repository; import Resort.Domain.Facilities.Building.GolfFacility; import java.util.Set; public interface GolfRepository extends Repository<GolfFacility,String> { Set<GolfFacility> getAll(); }
UTF-8
Java
256
java
GolfRepository.java
Java
[]
null
[]
package Resort.Domain.Buildings; import Resort.Database.Repository; import Resort.Domain.Facilities.Building.GolfFacility; import java.util.Set; public interface GolfRepository extends Repository<GolfFacility,String> { Set<GolfFacility> getAll(); }
256
0.8125
0.8125
10
24.6
24.034142
73
false
false
0
0
0
0
0
0
0.6
false
false
10
3ed0e808950f9f465e846016aa4a5f1e28ade040
13,417,477,882,316
d46fa74714590417142a8f1fcfd630d1ba31cb28
/src/oc/playback/rsync/RsyncConstants.java
9e731144330b754dcfd1bf53fef35b235e5811bb
[]
no_license
oscarchan/oc.playback
https://github.com/oscarchan/oc.playback
f08eb862649cb36b8731839d9cecbef0f66a02d9
b76947941896f4eb7251545fd2552c0d89478f27
refs/heads/master
2020-04-20T13:20:34.647000
2012-10-17T04:41:52
2012-10-17T04:41:52
6,256,193
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package oc.playback.rsync; public interface RsyncConstants { public static final String BASE_DIR = "/mnt/sdcard/oc.player"; public static final String RSYNC_LOG_DIR = "/mnt/sdcard/oc.player/rsync_logs"; }
UTF-8
Java
211
java
RsyncConstants.java
Java
[]
null
[]
package oc.playback.rsync; public interface RsyncConstants { public static final String BASE_DIR = "/mnt/sdcard/oc.player"; public static final String RSYNC_LOG_DIR = "/mnt/sdcard/oc.player/rsync_logs"; }
211
0.748815
0.748815
7
29.142857
29.887545
80
false
false
0
0
0
0
0
0
0.714286
false
false
10
ee7c07ed3c9cb0457e290b04b477e54dec461942
39,238,821,228,633
ea8c649fffe4c04b21b01335b11881ba2b383145
/src/me/kymmel/jaagup/fow/fow/FogOfWarManager.java
cc5609a9f692e7fa34d2bc126b065aac97bb03fe
[ "MIT" ]
permissive
jaagupkymmel/FogOfWar
https://github.com/jaagupkymmel/FogOfWar
69e21b8ecf9af55dd2123381590a3341e425381f
6610adb69bc8241060ef11582ba9dad4828f7b07
refs/heads/master
2016-09-03T06:50:13.832000
2015-01-02T17:23:11
2015-01-02T17:23:11
28,609,728
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package me.kymmel.jaagup.fow.fow; import me.kymmel.jaagup.fow.dummy.Unit; import me.kymmel.jaagup.fow.listener.FogOfWarListener; import me.kymmel.jaagup.fow.listener.MovementListener; import me.kymmel.jaagup.fow.listener.UnitListener; import me.kymmel.jaagup.fow.util.Coordinates; import java.util.ArrayList; import java.util.List; /** * Builds and updates the fog of war. * <p> * This class is thread-safe. * <p> * Note that this should <em>always</em> be wired up as {@link me.kymmel.jaagup.fow.listener.MovementListener} and * {@link me.kymmel.jaagup.fow.listener.UnitListener}. * * @author Jaagup Kรผmmel {@literal <jaagup.kymmel@gmail.com>} * @see me.kymmel.jaagup.fow.fow.VisionMask * @since 1.0 */ public class FogOfWarManager implements MovementListener, UnitListener { private final int[][] visibleCountMatrix; private final boolean[][] visibleMatrix; private final VisionMaskCache visionMaskCache = VisionMaskCache.getInstance(); private final List<FogOfWarListener> fogOfWarListeners = new ArrayList<>(); private final int mapWidth; private final int mapHeight; /** * Constructs a new {@link me.kymmel.jaagup.fow.fow.FogOfWarManager}. * <p> * Since fog of war data is stored in a statically sized matrix, width and height of the map need to be specified. * * @param mapWidth the width of the map * @param mapHeight the height of the map * @since 1.0 */ public FogOfWarManager(int mapWidth, int mapHeight) { this.mapWidth = mapWidth; this.mapHeight = mapHeight; visibleCountMatrix = new int[mapHeight][mapWidth]; visibleMatrix = new boolean[mapHeight][mapWidth]; } /** * Registers a listener to fire when the fog of war on a tile changes. * * @param listener the listener to register */ public void registerFogOfWarListener(FogOfWarListener listener) { fogOfWarListeners.add(listener); } /** * Unregisters a listener from firing when the fog of war on a tile changes. * * @param listener the listener to unregister */ public void unregisterFogOfWarListener(FogOfWarListener listener) { fogOfWarListeners.remove(listener); } /** * Returns the visibility matrix. * <p> * Note that the matrix is an array of lines, rather than array of columns, so Y offset should be used as the first * index, rather than second. * <p> * Example: {@code visibilityMatrix[coords.getY()][coords.getX()]}. * * @return visibility matrix * @since 1.0 */ public boolean[][] getVisibleMatrix() { synchronized(visibleMatrix) { return visibleMatrix; } } /** * Returns {@code true} if point at {@code coords} is visible * * @param coords the target coordinates * @return {@code true} if point at {@code coords} is visible * @since 1.0 */ public boolean isVisible(Coordinates coords) { return isVisible(coords.getX(), coords.getY()); } /** * Returns {@code true} if point at {@code x}, {@code y} is visible * * @param x the X coordinate of target point * @param y the Y coordinate of target point * @return {@code true} if point at {@code x}, {@code y} is visible * @since 1.0 */ public boolean isVisible(int x, int y) { return isInBounds(x, y) && isVisibleUnsecure(x, y); } /** * Returns {@code true} if point at {@code coords} is visible * <p> * Note that this does not do bounds-checking and may cause {@link java.lang.NullPointerException} when target point * is out of bounds * * @param coords the target coordinates * @return {@code true} if point at {@code coords} is visible * @since 1.0 */ public boolean isVisibleUnsecure(Coordinates coords) { return isVisibleUnsecure(coords.getX(), coords.getY()); } /** * Returns {@code true} if point at {@code x}, {@code y} is visible * <p> * Note that this does not do bounds-checking and may cause {@link java.lang.NullPointerException} when target point * is out of bounds * * @param x the X coordinate of target point * @param y the Y coordinate of target point * @return {@code true} if point at {@code x}, {@code y} is visible * @since 1.0 */ public boolean isVisibleUnsecure(int x, int y) { synchronized(visibleMatrix) { return visibleMatrix[y][x]; } } /** * Checks if point at {@code x}, {@code y} is in bounds. * * @param x the X coordinate of target point * @param y the Y coordinate of target point * @return {@code true} if point at {@code x}, {@code y} is in bounds * @since 1.0 */ private boolean isInBounds(int x, int y) { return 0 <= x && x < mapWidth && 0 <= y && y < mapHeight; } @Override public void onMovement(Unit unit, Coordinates from, Coordinates to) { synchronized(visibleMatrix) { removeVision(from, unit.getVisionRange()); addVision(to, unit.getVisionRange()); } } @Override public void onAddUnit(Unit unit) { synchronized(visibleMatrix) { addVision(unit.getCoordinates(), unit.getVisionRange()); } } @Override public void onRemoveUnit(Unit unit) { synchronized(visibleMatrix) { removeVision(unit.getCoordinates(), unit.getVisionRange()); } } /** * Updates visibility matrix to include vision from entity with specified coordinates and vision range. * * @param coords coordinates of entity * @param visionRange vision range of entity * @since 1.0 */ private void addVision(Coordinates coords, VisionRange visionRange) { updateMatrix(coords, visionRange, 1); } /** * Updates visibility matrix to exclude vision from entity with specified coordinates and vision range. * <p> * Note that points that are visible to other entities will still remain visible even if they are visible to current * entity too. * * @param coords coordinates of entity * @param visionRange vision range of entity * @since 1.0 */ private void removeVision(Coordinates coords, VisionRange visionRange) { updateMatrix(coords, visionRange, -1); } /** * Updates the matrix by adding or removing {@code modifier} amount of "visible to" entities from points visible to * current entity * * @param middleCoords coordinates of entity * @param visionRange vision range of entity * @param modifier {@code 1} for addition, {@code -1} for removal * @since 1.0 */ private void updateMatrix(Coordinates middleCoords, VisionRange visionRange, int modifier) { VisionMask visionMask = visionMaskCache.getMask(visionRange); int range = visionRange.get(); for(int y = -range; y <= range; y++) { for(int x = -range; x <= range; x++) { Coordinates coords = middleCoords.relative(x, y); if(!visionMask.isVisible(x, y) || !isInBounds(coords.getX(), coords.getY())) continue; visibleCountMatrix[coords.getY()][coords.getX()] += modifier; updatePoint(coords, y, x); } } } private void updatePoint(Coordinates coords, int y, int x) { boolean wasVisible = visibleMatrix[coords.getY()][coords.getX()]; boolean isVisible = 0 < visibleCountMatrix[coords.getY()][coords.getX()]; visibleMatrix[coords.getY()][coords.getX()] = isVisible; if(isVisible == wasVisible) return; for(FogOfWarListener fogOfWarListener : fogOfWarListeners) fogOfWarListener.onChange(coords, isVisible); } }
UTF-8
Java
7,947
java
FogOfWarManager.java
Java
[ { "context": "l.jaagup.fow.listener.UnitListener}.\n *\n * @author Jaagup Kรผmmel {@literal <jaagup.kymmel@gmail.com>}\n * @see me.k", "end": 618, "score": 0.9998999834060669, "start": 605, "tag": "NAME", "value": "Jaagup Kรผmmel" }, { "context": "ener.UnitListener}.\n *\n * @author Jaagup Kรผmmel {@literal <jaagup.kymmel@gmail.com>}\n * @see me.kymmel.jaag", "end": 628, "score": 0.6047092080116272, "start": 621, "tag": "USERNAME", "value": "literal" }, { "context": "Listener}.\n *\n * @author Jaagup Kรผmmel {@literal <jaagup.kymmel@gmail.com>}\n * @see me.kymmel.jaagup.fow.fow.VisionMask\n * ", "end": 653, "score": 0.9999307990074158, "start": 630, "tag": "EMAIL", "value": "jaagup.kymmel@gmail.com" } ]
null
[]
package me.kymmel.jaagup.fow.fow; import me.kymmel.jaagup.fow.dummy.Unit; import me.kymmel.jaagup.fow.listener.FogOfWarListener; import me.kymmel.jaagup.fow.listener.MovementListener; import me.kymmel.jaagup.fow.listener.UnitListener; import me.kymmel.jaagup.fow.util.Coordinates; import java.util.ArrayList; import java.util.List; /** * Builds and updates the fog of war. * <p> * This class is thread-safe. * <p> * Note that this should <em>always</em> be wired up as {@link me.kymmel.jaagup.fow.listener.MovementListener} and * {@link me.kymmel.jaagup.fow.listener.UnitListener}. * * @author <NAME> {@literal <<EMAIL>>} * @see me.kymmel.jaagup.fow.fow.VisionMask * @since 1.0 */ public class FogOfWarManager implements MovementListener, UnitListener { private final int[][] visibleCountMatrix; private final boolean[][] visibleMatrix; private final VisionMaskCache visionMaskCache = VisionMaskCache.getInstance(); private final List<FogOfWarListener> fogOfWarListeners = new ArrayList<>(); private final int mapWidth; private final int mapHeight; /** * Constructs a new {@link me.kymmel.jaagup.fow.fow.FogOfWarManager}. * <p> * Since fog of war data is stored in a statically sized matrix, width and height of the map need to be specified. * * @param mapWidth the width of the map * @param mapHeight the height of the map * @since 1.0 */ public FogOfWarManager(int mapWidth, int mapHeight) { this.mapWidth = mapWidth; this.mapHeight = mapHeight; visibleCountMatrix = new int[mapHeight][mapWidth]; visibleMatrix = new boolean[mapHeight][mapWidth]; } /** * Registers a listener to fire when the fog of war on a tile changes. * * @param listener the listener to register */ public void registerFogOfWarListener(FogOfWarListener listener) { fogOfWarListeners.add(listener); } /** * Unregisters a listener from firing when the fog of war on a tile changes. * * @param listener the listener to unregister */ public void unregisterFogOfWarListener(FogOfWarListener listener) { fogOfWarListeners.remove(listener); } /** * Returns the visibility matrix. * <p> * Note that the matrix is an array of lines, rather than array of columns, so Y offset should be used as the first * index, rather than second. * <p> * Example: {@code visibilityMatrix[coords.getY()][coords.getX()]}. * * @return visibility matrix * @since 1.0 */ public boolean[][] getVisibleMatrix() { synchronized(visibleMatrix) { return visibleMatrix; } } /** * Returns {@code true} if point at {@code coords} is visible * * @param coords the target coordinates * @return {@code true} if point at {@code coords} is visible * @since 1.0 */ public boolean isVisible(Coordinates coords) { return isVisible(coords.getX(), coords.getY()); } /** * Returns {@code true} if point at {@code x}, {@code y} is visible * * @param x the X coordinate of target point * @param y the Y coordinate of target point * @return {@code true} if point at {@code x}, {@code y} is visible * @since 1.0 */ public boolean isVisible(int x, int y) { return isInBounds(x, y) && isVisibleUnsecure(x, y); } /** * Returns {@code true} if point at {@code coords} is visible * <p> * Note that this does not do bounds-checking and may cause {@link java.lang.NullPointerException} when target point * is out of bounds * * @param coords the target coordinates * @return {@code true} if point at {@code coords} is visible * @since 1.0 */ public boolean isVisibleUnsecure(Coordinates coords) { return isVisibleUnsecure(coords.getX(), coords.getY()); } /** * Returns {@code true} if point at {@code x}, {@code y} is visible * <p> * Note that this does not do bounds-checking and may cause {@link java.lang.NullPointerException} when target point * is out of bounds * * @param x the X coordinate of target point * @param y the Y coordinate of target point * @return {@code true} if point at {@code x}, {@code y} is visible * @since 1.0 */ public boolean isVisibleUnsecure(int x, int y) { synchronized(visibleMatrix) { return visibleMatrix[y][x]; } } /** * Checks if point at {@code x}, {@code y} is in bounds. * * @param x the X coordinate of target point * @param y the Y coordinate of target point * @return {@code true} if point at {@code x}, {@code y} is in bounds * @since 1.0 */ private boolean isInBounds(int x, int y) { return 0 <= x && x < mapWidth && 0 <= y && y < mapHeight; } @Override public void onMovement(Unit unit, Coordinates from, Coordinates to) { synchronized(visibleMatrix) { removeVision(from, unit.getVisionRange()); addVision(to, unit.getVisionRange()); } } @Override public void onAddUnit(Unit unit) { synchronized(visibleMatrix) { addVision(unit.getCoordinates(), unit.getVisionRange()); } } @Override public void onRemoveUnit(Unit unit) { synchronized(visibleMatrix) { removeVision(unit.getCoordinates(), unit.getVisionRange()); } } /** * Updates visibility matrix to include vision from entity with specified coordinates and vision range. * * @param coords coordinates of entity * @param visionRange vision range of entity * @since 1.0 */ private void addVision(Coordinates coords, VisionRange visionRange) { updateMatrix(coords, visionRange, 1); } /** * Updates visibility matrix to exclude vision from entity with specified coordinates and vision range. * <p> * Note that points that are visible to other entities will still remain visible even if they are visible to current * entity too. * * @param coords coordinates of entity * @param visionRange vision range of entity * @since 1.0 */ private void removeVision(Coordinates coords, VisionRange visionRange) { updateMatrix(coords, visionRange, -1); } /** * Updates the matrix by adding or removing {@code modifier} amount of "visible to" entities from points visible to * current entity * * @param middleCoords coordinates of entity * @param visionRange vision range of entity * @param modifier {@code 1} for addition, {@code -1} for removal * @since 1.0 */ private void updateMatrix(Coordinates middleCoords, VisionRange visionRange, int modifier) { VisionMask visionMask = visionMaskCache.getMask(visionRange); int range = visionRange.get(); for(int y = -range; y <= range; y++) { for(int x = -range; x <= range; x++) { Coordinates coords = middleCoords.relative(x, y); if(!visionMask.isVisible(x, y) || !isInBounds(coords.getX(), coords.getY())) continue; visibleCountMatrix[coords.getY()][coords.getX()] += modifier; updatePoint(coords, y, x); } } } private void updatePoint(Coordinates coords, int y, int x) { boolean wasVisible = visibleMatrix[coords.getY()][coords.getX()]; boolean isVisible = 0 < visibleCountMatrix[coords.getY()][coords.getX()]; visibleMatrix[coords.getY()][coords.getX()] = isVisible; if(isVisible == wasVisible) return; for(FogOfWarListener fogOfWarListener : fogOfWarListeners) fogOfWarListener.onChange(coords, isVisible); } }
7,923
0.633023
0.629373
232
33.25
30.03701
120
false
false
0
0
0
0
0
0
0.392241
false
false
10
3f3be84ad0d424ee0ce96bba88ef36d98e9c4282
18,167,711,727,244
5e6cf42924d980ef092524b84c0dfcf4b4e18946
/Outery/src/main/java/com/dev/Outery/enums/EntryType.java
7c9d8b3fae0da819451f19c63ec191b759a1db21
[ "Unlicense" ]
permissive
TomoyukiOnline/Outery
https://github.com/TomoyukiOnline/Outery
7334ec3b0718ba52031e415fb4715aacdc1cf794
70c6998bf0ee59e3c0b58d59d4d366fcac05d76a
refs/heads/main
2023-01-27T16:02:11.486000
2020-12-05T09:02:54
2020-12-05T09:02:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dev.Outery.enums; public enum EntryType { ENTRY, COMMENT, SHARED, }
UTF-8
Java
93
java
EntryType.java
Java
[]
null
[]
package com.dev.Outery.enums; public enum EntryType { ENTRY, COMMENT, SHARED, }
93
0.655914
0.655914
7
12.285714
9.851966
29
false
false
0
0
0
0
0
0
0.571429
false
false
10
c6be96dfad388bb505028091ab27d5a8e56457a9
37,769,942,431,315
5f597d37634ff27c20bf003600905e1f7f7ce935
/jzy3d-svm-mapper/src/svm3d/org/jzy3d/svm/editors/EditorToolkit.java
554a4e535cf781698b2e7eb52ce7aec369794729
[ "BSD-3-Clause" ]
permissive
zhivko/jzy3d-api
https://github.com/zhivko/jzy3d-api
555e137a4ecc1018cd3a26b1bc4391b655dfb776
5ce03f116c1cd98a0695f27484ad9df449773260
refs/heads/master
2021-04-03T01:56:54.090000
2017-05-28T10:49:22
2017-05-28T10:49:22
36,815,482
0
1
null
true
2020-02-16T19:38:12
2015-06-03T16:15:18
2016-05-02T07:38:10
2020-01-09T12:15:57
36,101
0
0
0
Java
false
false
package org.jzy3d.svm.editors; import java.awt.Component; import javax.swing.JSlider; import javax.swing.JTextField; public class EditorToolkit { public static JSlider createSlider(final String title, int min, int max){ final JSlider slider = new JSlider(); //slider.setBorder(BorderFactory.createTitledBorder(title)); Component[] c = slider.getComponents(); for(Component ci: c){ System.out.println(ci); } slider.setMinimum(min); slider.setMaximum(max); slider.setMajorTickSpacing(20); slider.setMinorTickSpacing(5); slider.setPaintTicks(true); slider.setPaintLabels(true); /*slider.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { System.out.println(title + ": " + slider.getValue()); } });*/ return slider; } public static JTextField createTextField(String content){ JTextField field = new JTextField(content); return field; } }
UTF-8
Java
970
java
EditorToolkit.java
Java
[]
null
[]
package org.jzy3d.svm.editors; import java.awt.Component; import javax.swing.JSlider; import javax.swing.JTextField; public class EditorToolkit { public static JSlider createSlider(final String title, int min, int max){ final JSlider slider = new JSlider(); //slider.setBorder(BorderFactory.createTitledBorder(title)); Component[] c = slider.getComponents(); for(Component ci: c){ System.out.println(ci); } slider.setMinimum(min); slider.setMaximum(max); slider.setMajorTickSpacing(20); slider.setMinorTickSpacing(5); slider.setPaintTicks(true); slider.setPaintLabels(true); /*slider.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { System.out.println(title + ": " + slider.getValue()); } });*/ return slider; } public static JTextField createTextField(String content){ JTextField field = new JTextField(content); return field; } }
970
0.704124
0.7
36
24.944445
19.933144
74
false
false
0
0
0
0
0
0
2.055556
false
false
10
955a17e64e10007311811099855d668b906fa1cb
36,275,293,826,836
36125dd4be133bd7f3c23b728c22d1c30e04038a
/src/tables/evals/PaylineEvaluator.java
6c16f4b7a147e82c03111f6bef5fc0c35fe48fc2
[]
no_license
samwbrett/casinomath
https://github.com/samwbrett/casinomath
73e1a7639d46ae13656842ac0983e8eee0c67e47
f26c9dec2b7cab9867c5484b0caec3319c6ba54d
refs/heads/master
2023-03-22T23:02:26.416000
2021-03-17T01:46:44
2021-03-17T01:46:44
273,986,975
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tables.evals; /** * Payline evaluator holds the hit logic, the payout, and the name of the payline. */ public class PaylineEvaluator { private final String name; private final HitEvaluator hitEvaluator; private final double forPay; public PaylineEvaluator(String name, double forPay, HitEvaluator hitEvaluator) { this.name = name; this.forPay = forPay; this.hitEvaluator = hitEvaluator; } public static PaylineEvaluator newLoseEvaluator() { return new PaylineEvaluator("Lose", 0, (hands) -> true); } public PaylineStatistics getNewPaylineStatistics() { return new PaylineStatistics(this); } public String getName() { return name; } public HitEvaluator getHitEvaluator() { return hitEvaluator; } public double getForPay() { return forPay; } }
UTF-8
Java
884
java
PaylineEvaluator.java
Java
[]
null
[]
package tables.evals; /** * Payline evaluator holds the hit logic, the payout, and the name of the payline. */ public class PaylineEvaluator { private final String name; private final HitEvaluator hitEvaluator; private final double forPay; public PaylineEvaluator(String name, double forPay, HitEvaluator hitEvaluator) { this.name = name; this.forPay = forPay; this.hitEvaluator = hitEvaluator; } public static PaylineEvaluator newLoseEvaluator() { return new PaylineEvaluator("Lose", 0, (hands) -> true); } public PaylineStatistics getNewPaylineStatistics() { return new PaylineStatistics(this); } public String getName() { return name; } public HitEvaluator getHitEvaluator() { return hitEvaluator; } public double getForPay() { return forPay; } }
884
0.662896
0.661765
37
22.891891
23.477169
84
false
false
0
0
0
0
0
0
0.486486
false
false
10
2a51c1189c653d68572fb37685cc585c2e8eebd0
37,769,942,433,212
a456b870118fe3034eb72f4f94bde593e5c016d0
/src/com/innowhere/jnieasy/core/impl/rt/typedec/natobj/method/TypeNativeStaticFieldCallbackDefaultRuntimeImpl.java
b4f9a54f7a7fb0bc9abd3c1f5b197ff5b9b76474
[ "Apache-2.0" ]
permissive
fengxiaochuang/jnieasy
https://github.com/fengxiaochuang/jnieasy
0b0fed598e1d0ea2f24ab9a9e9476b58ec2fd510
e295b23ee7418c8e412b025b957e64ceaba40fac
refs/heads/master
2022-01-21T04:21:58.382000
2016-08-21T17:17:34
2016-08-21T17:17:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * TypeNativeStaticFieldCallbackDefaultRuntimeImpl.java * * Created on 12 de enero de 2005, 19:11 */ package com.innowhere.jnieasy.core.impl.rt.typedec.natobj.method; import com.innowhere.jnieasy.core.impl.common.typedec.model.natobj.method.TypeNativeStaticFieldCallbackDefaultImpl; import com.innowhere.jnieasy.core.impl.rt.RuntimeManagerImpl; import com.innowhere.jnieasy.core.typedec.*; import com.innowhere.jnieasy.core.impl.rt.typedec.TypeNativeStaticFieldMethodRuntime; public class TypeNativeStaticFieldCallbackDefaultRuntimeImpl extends TypeNativeFieldCallbackDefaultRuntimeImpl implements TypeNativeStaticFieldMethodRuntime { /** * Creates a new instance of TypeNativeStaticFieldCallbackDefaultRuntimeImpl */ public TypeNativeStaticFieldCallbackDefaultRuntimeImpl(TypeNativeStaticFieldCallbackDefaultImpl typeDec,Class javaClass,RuntimeManagerImpl rtMgr) { super(typeDec,javaClass,rtMgr); } public NativeBehaviorSignature checkSignature(NativeBehaviorSignature signature) { return (NativeStaticFieldMethodSignature)signature; } public NativeStaticFieldMethodSignature getStaticFieldMethodSignature() { return (NativeStaticFieldMethodSignature)signature; } public void setStaticFieldMethodSignature(NativeStaticFieldMethodSignature signature) { setBehaviorSignature(signature); } }
UTF-8
Java
1,409
java
TypeNativeStaticFieldCallbackDefaultRuntimeImpl.java
Java
[]
null
[]
/* * TypeNativeStaticFieldCallbackDefaultRuntimeImpl.java * * Created on 12 de enero de 2005, 19:11 */ package com.innowhere.jnieasy.core.impl.rt.typedec.natobj.method; import com.innowhere.jnieasy.core.impl.common.typedec.model.natobj.method.TypeNativeStaticFieldCallbackDefaultImpl; import com.innowhere.jnieasy.core.impl.rt.RuntimeManagerImpl; import com.innowhere.jnieasy.core.typedec.*; import com.innowhere.jnieasy.core.impl.rt.typedec.TypeNativeStaticFieldMethodRuntime; public class TypeNativeStaticFieldCallbackDefaultRuntimeImpl extends TypeNativeFieldCallbackDefaultRuntimeImpl implements TypeNativeStaticFieldMethodRuntime { /** * Creates a new instance of TypeNativeStaticFieldCallbackDefaultRuntimeImpl */ public TypeNativeStaticFieldCallbackDefaultRuntimeImpl(TypeNativeStaticFieldCallbackDefaultImpl typeDec,Class javaClass,RuntimeManagerImpl rtMgr) { super(typeDec,javaClass,rtMgr); } public NativeBehaviorSignature checkSignature(NativeBehaviorSignature signature) { return (NativeStaticFieldMethodSignature)signature; } public NativeStaticFieldMethodSignature getStaticFieldMethodSignature() { return (NativeStaticFieldMethodSignature)signature; } public void setStaticFieldMethodSignature(NativeStaticFieldMethodSignature signature) { setBehaviorSignature(signature); } }
1,409
0.800568
0.793471
39
35.128204
42.612854
156
false
false
0
0
0
0
0
0
0.358974
false
false
10
6293edf628361b64f46cd0a809af282f1e7c2485
32,031,866,129,391
809e156d5a679e9463140b9cec393fd45ad46451
/app/src/main/java/com/selema/newproject/Messages/Messages.java
2810c0d7f7814784d4a06e1d4bb3f0adae658d1a
[]
no_license
aboshahba/Graduation_project
https://github.com/aboshahba/Graduation_project
c6150116ae9c78e40e1c161b77fc57d2b9d9b581
b83806be5cf08382afda5aab0ac9d42430214177
refs/heads/master
2020-03-23T02:01:21.600000
2018-07-14T14:18:21
2018-07-14T14:18:21
140,951,712
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.selema.newproject.Messages; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; /** * Created by selema on 4/28/18. */ public class Messages { @SerializedName("messageId") @Expose private Integer messageId; @SerializedName("senderID") @Expose private String senderID; @SerializedName("receiverID") @Expose private String receiverID; @SerializedName("message_content") @Expose private String messageContent; @SerializedName("message_time") @Expose private String messageTime; @SerializedName("requested_Money") @Expose private String requestedMoney; public Integer getMessageId() { return messageId; } public void setMessageId(Integer messageId) { this.messageId = messageId; } public String getSenderID() { return senderID; } public void setSenderID(String senderID) { this.senderID = senderID; } public String getReceiverID() { return receiverID; } public void setReceiverID(String receiverID) { this.receiverID = receiverID; } public String getMessageContent() { return messageContent; } public void setMessageContent(String messageContent) { this.messageContent = messageContent; } public String getMessageTime() { return messageTime; } public void setMessageTime(String messageTime) { this.messageTime = messageTime; } public String getRequestedMoney() { return requestedMoney; } public void setRequestedMoney(String requestedMoney) { this.requestedMoney = requestedMoney; } }
UTF-8
Java
1,716
java
Messages.java
Java
[ { "context": "son.annotations.SerializedName;\n\n/**\n * Created by selema on 4/28/18.\n */\npublic class Messages {\n\n @Ser", "end": 160, "score": 0.9997305870056152, "start": 154, "tag": "USERNAME", "value": "selema" } ]
null
[]
package com.selema.newproject.Messages; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; /** * Created by selema on 4/28/18. */ public class Messages { @SerializedName("messageId") @Expose private Integer messageId; @SerializedName("senderID") @Expose private String senderID; @SerializedName("receiverID") @Expose private String receiverID; @SerializedName("message_content") @Expose private String messageContent; @SerializedName("message_time") @Expose private String messageTime; @SerializedName("requested_Money") @Expose private String requestedMoney; public Integer getMessageId() { return messageId; } public void setMessageId(Integer messageId) { this.messageId = messageId; } public String getSenderID() { return senderID; } public void setSenderID(String senderID) { this.senderID = senderID; } public String getReceiverID() { return receiverID; } public void setReceiverID(String receiverID) { this.receiverID = receiverID; } public String getMessageContent() { return messageContent; } public void setMessageContent(String messageContent) { this.messageContent = messageContent; } public String getMessageTime() { return messageTime; } public void setMessageTime(String messageTime) { this.messageTime = messageTime; } public String getRequestedMoney() { return requestedMoney; } public void setRequestedMoney(String requestedMoney) { this.requestedMoney = requestedMoney; } }
1,716
0.668998
0.666084
78
21.012821
17.893198
58
false
false
0
0
0
0
0
0
0.269231
false
false
10
356dea142500bbab03def3a3eeedee564c6c9e61
28,776,280,904,116
58bfdac9ac7d397ca37907173e567861202d2f67
/trunk/src/base/scheduler/src/main/java/com/dt/scheduler/task/dao/impl/ScheduleJobDaoImpl.java
17751d6e936f17c1f5e3ea8d73bbfa42f99ea0e9
[]
no_license
datatiger/project
https://github.com/datatiger/project
690734aacca36221d56c94d8c56c446b58e02393
3faccbf8ddc3f076b8b41b586eb2c87cf8a6eec5
refs/heads/master
2020-03-30T18:15:26.286000
2019-01-01T21:55:24
2019-01-01T21:55:24
151,491,094
2
0
null
false
2019-11-13T08:13:05
2018-10-03T22:57:10
2019-03-07T12:02:32
2019-11-13T08:13:04
226,847
0
0
6
Java
false
false
package com.dt.scheduler.task.dao.impl; import org.springframework.stereotype.Repository; import com.dt.frame.DefaultDaoImpl; import com.dt.scheduler.task.dao.IScheduleJobDao; /** * <pre> * ๅฎšๆ—ถไปปๅŠกDao * @author dt@sina.com * @date 2016ๅนด5ๆœˆ18ๆ—ฅ ไธ‹ๅˆ10:06:03 * <pre> */ @Repository public class ScheduleJobDaoImpl extends DefaultDaoImpl implements IScheduleJobDao { // public int deleteById(String id) { // String statement = this.getStatement("deleteById"); // int cn = sqlSessionTemplate.delete(statement, id); // return cn; // } /*public int insert(ScheduleTaskVO vo) { String statement = this.getStatement("insert"); int cn = sqlSessionTemplate.insert(statement, vo); return cn; }*/ // public ScheduleTaskVO selectById(String id) { // String statement = this.getStatement("selectById"); // ScheduleTaskVO vo =sqlSessionTemplate.selectOne(statement, id); // return vo; // } /*public int update(ScheduleTaskVO vo) { String statement = this.getStatement("update"); int cn = sqlSessionTemplate.update(statement, vo); return cn; }*/ // public List<ScheduleTaskVO> findList(ScheduleTaskVO vo) { // String statement = this.getStatement("findList"); // List<ScheduleTaskVO> list = sqlSessionTemplate.selectList(statement, vo); // return list; // } /*public int findListCount(ScheduleTaskVO vo) { String statement = this.getStatement("findListCount"); int cn = (Integer)sqlSessionTemplate.selectOne(statement, vo); return cn; } public List<ScheduleTaskVO> getAll() { String statement = this.getStatement("getAll"); List<ScheduleTaskVO> list = sqlSessionTemplate.selectList(statement); return list; } */ }
UTF-8
Java
1,668
java
ScheduleJobDaoImpl.java
Java
[ { "context": "cheduleJobDao;\n\n/**\n * <pre>\n * ๅฎšๆ—ถไปปๅŠกDao\n * @author dt@sina.com\n * @date 2016ๅนด5ๆœˆ18ๆ—ฅ ไธ‹ๅˆ10:06:03\n * <pre>\n */\n@Repo", "end": 225, "score": 0.9999291896820068, "start": 214, "tag": "EMAIL", "value": "dt@sina.com" } ]
null
[]
package com.dt.scheduler.task.dao.impl; import org.springframework.stereotype.Repository; import com.dt.frame.DefaultDaoImpl; import com.dt.scheduler.task.dao.IScheduleJobDao; /** * <pre> * ๅฎšๆ—ถไปปๅŠกDao * @author <EMAIL> * @date 2016ๅนด5ๆœˆ18ๆ—ฅ ไธ‹ๅˆ10:06:03 * <pre> */ @Repository public class ScheduleJobDaoImpl extends DefaultDaoImpl implements IScheduleJobDao { // public int deleteById(String id) { // String statement = this.getStatement("deleteById"); // int cn = sqlSessionTemplate.delete(statement, id); // return cn; // } /*public int insert(ScheduleTaskVO vo) { String statement = this.getStatement("insert"); int cn = sqlSessionTemplate.insert(statement, vo); return cn; }*/ // public ScheduleTaskVO selectById(String id) { // String statement = this.getStatement("selectById"); // ScheduleTaskVO vo =sqlSessionTemplate.selectOne(statement, id); // return vo; // } /*public int update(ScheduleTaskVO vo) { String statement = this.getStatement("update"); int cn = sqlSessionTemplate.update(statement, vo); return cn; }*/ // public List<ScheduleTaskVO> findList(ScheduleTaskVO vo) { // String statement = this.getStatement("findList"); // List<ScheduleTaskVO> list = sqlSessionTemplate.selectList(statement, vo); // return list; // } /*public int findListCount(ScheduleTaskVO vo) { String statement = this.getStatement("findListCount"); int cn = (Integer)sqlSessionTemplate.selectOne(statement, vo); return cn; } public List<ScheduleTaskVO> getAll() { String statement = this.getStatement("getAll"); List<ScheduleTaskVO> list = sqlSessionTemplate.selectList(statement); return list; } */ }
1,664
0.730909
0.72303
61
26.049181
24.861206
83
false
false
0
0
0
0
0
0
1.442623
false
false
10
2b84292d0ea1819708efa1d1f2162ed49d07238f
31,542,239,868,820
0a0623b1cfb16f51dbc69c5a03225ac703c9a3c7
/src/test/java/com/microservice/regression/restassured/get/RestAssuredGetTests.java
2899497d65f1dd5f300fea81f24457f5bd698bc4
[ "MIT" ]
permissive
aryaghan-mutum/WebServicesAutomation
https://github.com/aryaghan-mutum/WebServicesAutomation
0852955676bb7817a2409e4a4d1bd369096e10c2
d94fa42984b660863173c7fb32a103d8dbb9c5b9
refs/heads/master
2021-06-25T20:11:45.731000
2021-01-18T04:04:51
2021-01-18T04:04:51
199,224,099
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.microservice.regression.restassured.get; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import static com.microservice.regression.restassured.resthelper.RestAssuredHttpRequests.getHttp; import static org.hamcrest.Matchers.*; /** * @author Anurag Muthyam * url: https://github.com/aryaghan-mutum */ public class RestAssuredGetTests { private static final String SERVICE_ENDPOINT = "https://reqres.in/api/users?page=2"; @Test @DisplayName("print response body") public void printResponseBody() { getHttp(SERVICE_ENDPOINT) .then() .log().all() .assertThat() .statusCode(200); } @Test @DisplayName("test first ID") public void testFirstID() { getHttp(SERVICE_ENDPOINT) .then() .assertThat() .statusLine("HTTP/1.1 200 OK") .statusCode(200) .body("data.id[0]", equalTo(7)); //note: can also be used is(7) } @Test @DisplayName("test first Email") public void testFirstEmail() { getHttp(SERVICE_ENDPOINT) .then() .assertThat() .statusLine("HTTP/1.1 200 OK") .statusCode(200) .body("data.email[0]", equalTo("michael.lawson@reqres.in")); } @Test @DisplayName("test all the values in the first object in an array") public void testAllValuesInFirstObject() { getHttp(SERVICE_ENDPOINT) .then() .assertThat() .statusLine("HTTP/1.1 200 OK") .statusCode(200) .body("data.id[0]", equalTo(7)) .body("data.email[0]", equalTo("michael.lawson@reqres.in")) .body("data.first_name[0]", equalTo("Michael")) .body("data.last_name[0]", equalTo("Lawson")); } @Test @DisplayName("test all the last names") public void testAllLastNames() { getHttp(SERVICE_ENDPOINT) .then() .assertThat() .statusLine("HTTP/1.1 200 OK") .statusCode(200) .body("data.last_name", hasItems("Lawson", "Ferguson", "Funke", "Fields", "Edwards", "Howell")); } @Test @DisplayName("test the total length9size of the objects") public void testTotalLengthOfObjects() { getHttp(SERVICE_ENDPOINT) .then() .assertThat() .statusLine("HTTP/1.1 200 OK") .statusCode(200) .body("size()", is(6)); } }
UTF-8
Java
2,652
java
RestAssuredGetTests.java
Java
[ { "context": "rt static org.hamcrest.Matchers.*;\n\n/**\n * @author Anurag Muthyam\n * url: https://github.com/aryaghan-mutum\n */\n\npu", "end": 299, "score": 0.9998903870582581, "start": 285, "tag": "NAME", "value": "Anurag Muthyam" }, { "context": "@author Anurag Muthyam\n * url: https://github.com/aryaghan-mutum\n */\n\npublic class RestAssuredGetTests {\n\n priv", "end": 341, "score": 0.9995548725128174, "start": 327, "tag": "USERNAME", "value": "aryaghan-mutum" }, { "context": ")\n .body(\"data.email[0]\", equalTo(\"michael.lawson@reqres.in\"));\n }\n\n @Test\n @DisplayName(\"test all t", "end": 1372, "score": 0.9999033212661743, "start": 1348, "tag": "EMAIL", "value": "michael.lawson@reqres.in" }, { "context": ")\n .body(\"data.email[0]\", equalTo(\"michael.lawson@reqres.in\"))\n .body(\"data.first_name[0]\", eq", "end": 1801, "score": 0.9999062418937683, "start": 1777, "tag": "EMAIL", "value": "michael.lawson@reqres.in" }, { "context": " .body(\"data.first_name[0]\", equalTo(\"Michael\"))\n .body(\"data.last_name[0]\", equ", "end": 1865, "score": 0.9998379945755005, "start": 1858, "tag": "NAME", "value": "Michael" }, { "context": " .body(\"data.last_name[0]\", equalTo(\"Lawson\"));\n }\n\n @Test\n @DisplayName(\"test all t", "end": 1927, "score": 0.9991185665130615, "start": 1921, "tag": "NAME", "value": "Lawson" }, { "context": " .body(\"data.last_name\", hasItems(\"Lawson\", \"Ferguson\", \"Funke\", \"Fields\", \"Edwards\", \"Howe", "end": 2254, "score": 0.999823808670044, "start": 2248, "tag": "NAME", "value": "Lawson" }, { "context": " .body(\"data.last_name\", hasItems(\"Lawson\", \"Ferguson\", \"Funke\", \"Fields\", \"Edwards\", \"Howell\"));\n }", "end": 2266, "score": 0.9995278120040894, "start": 2258, "tag": "NAME", "value": "Ferguson" }, { "context": "\"data.last_name\", hasItems(\"Lawson\", \"Ferguson\", \"Funke\", \"Fields\", \"Edwards\", \"Howell\"));\n }\n\n @Te", "end": 2275, "score": 0.9997644424438477, "start": 2270, "tag": "NAME", "value": "Funke" }, { "context": "t_name\", hasItems(\"Lawson\", \"Ferguson\", \"Funke\", \"Fields\", \"Edwards\", \"Howell\"));\n }\n\n @Test\n @Di", "end": 2285, "score": 0.9993640780448914, "start": 2279, "tag": "NAME", "value": "Fields" }, { "context": "asItems(\"Lawson\", \"Ferguson\", \"Funke\", \"Fields\", \"Edwards\", \"Howell\"));\n }\n\n @Test\n @DisplayName(\"", "end": 2296, "score": 0.9994577169418335, "start": 2289, "tag": "NAME", "value": "Edwards" }, { "context": "wson\", \"Ferguson\", \"Funke\", \"Fields\", \"Edwards\", \"Howell\"));\n }\n\n @Test\n @DisplayName(\"test the t", "end": 2306, "score": 0.9989529848098755, "start": 2300, "tag": "NAME", "value": "Howell" } ]
null
[]
package com.microservice.regression.restassured.get; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import static com.microservice.regression.restassured.resthelper.RestAssuredHttpRequests.getHttp; import static org.hamcrest.Matchers.*; /** * @author <NAME> * url: https://github.com/aryaghan-mutum */ public class RestAssuredGetTests { private static final String SERVICE_ENDPOINT = "https://reqres.in/api/users?page=2"; @Test @DisplayName("print response body") public void printResponseBody() { getHttp(SERVICE_ENDPOINT) .then() .log().all() .assertThat() .statusCode(200); } @Test @DisplayName("test first ID") public void testFirstID() { getHttp(SERVICE_ENDPOINT) .then() .assertThat() .statusLine("HTTP/1.1 200 OK") .statusCode(200) .body("data.id[0]", equalTo(7)); //note: can also be used is(7) } @Test @DisplayName("test first Email") public void testFirstEmail() { getHttp(SERVICE_ENDPOINT) .then() .assertThat() .statusLine("HTTP/1.1 200 OK") .statusCode(200) .body("data.email[0]", equalTo("<EMAIL>")); } @Test @DisplayName("test all the values in the first object in an array") public void testAllValuesInFirstObject() { getHttp(SERVICE_ENDPOINT) .then() .assertThat() .statusLine("HTTP/1.1 200 OK") .statusCode(200) .body("data.id[0]", equalTo(7)) .body("data.email[0]", equalTo("<EMAIL>")) .body("data.first_name[0]", equalTo("Michael")) .body("data.last_name[0]", equalTo("Lawson")); } @Test @DisplayName("test all the last names") public void testAllLastNames() { getHttp(SERVICE_ENDPOINT) .then() .assertThat() .statusLine("HTTP/1.1 200 OK") .statusCode(200) .body("data.last_name", hasItems("Lawson", "Ferguson", "Funke", "Fields", "Edwards", "Howell")); } @Test @DisplayName("test the total length9size of the objects") public void testTotalLengthOfObjects() { getHttp(SERVICE_ENDPOINT) .then() .assertThat() .statusLine("HTTP/1.1 200 OK") .statusCode(200) .body("size()", is(6)); } }
2,610
0.54638
0.525641
86
29.83721
23.894079
112
false
false
0
0
0
0
0
0
0.290698
false
false
10
a350ea870f389b397586dec54bd26609bf394f05
15,934,328,716,945
f7ed70f3c757d003c87c919162a59f93f4b4b2b8
/app/src/main/java/com/example/dollartopounds/MainActivity.java
ba8424ee5c2691a51d33e08565437383ba58a477
[]
no_license
mohammed1478/Dollar-to-Pounds-App
https://github.com/mohammed1478/Dollar-to-Pounds-App
8eb84b2b4dd067c5321acaecf6dd61b944db858b
7bc11052493103035e35335e5336bf70f040e8ca
refs/heads/master
2020-06-01T22:16:39.748000
2019-07-12T21:37:32
2019-07-12T21:37:32
190,947,532
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.dollartopounds; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends AppCompatActivity { public void DollarToPoundClick(View view){ EditText DollarInput = (EditText) findViewById(R.id.DollarInputET); //Takes user input of type EditText double NumberValue = Double.parseDouble(DollarInput.getText().toString()); //converts DollarInput from EditText to a double double InPounds = NumberValue * 0.79; String PoundInString = Double.toString(InPounds); Log.i("Status","The (Dollar to Pound) Button is Pressed"); Toast.makeText(this, "$" + DollarInput.getText().toString() + " is " + " ยฃ" + PoundInString , Toast.LENGTH_LONG ).show(); } public void PoundToDollarClick (View view){ EditText PoundInput = (EditText) findViewById(R.id.DollarInputET); //Takes user input of type EditText double NumberValue2 = Double.parseDouble(PoundInput.getText().toString());//converts PoundInput from EditText to a double double InDollars = NumberValue2 * 1.26; //Converts pound value to dollar value String DollarInString = Double.toString(InDollars); //Converts the dollar value to a string to be put inside to toast Log.i("Status","The (Dollar to Pound) Button is Pressed"); Toast.makeText(this, "ยฃ" + PoundInput.getText().toString() + " is " + "$" + DollarInString, Toast.LENGTH_LONG).show(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
UTF-8
Java
1,760
java
MainActivity.java
Java
[]
null
[]
package com.example.dollartopounds; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends AppCompatActivity { public void DollarToPoundClick(View view){ EditText DollarInput = (EditText) findViewById(R.id.DollarInputET); //Takes user input of type EditText double NumberValue = Double.parseDouble(DollarInput.getText().toString()); //converts DollarInput from EditText to a double double InPounds = NumberValue * 0.79; String PoundInString = Double.toString(InPounds); Log.i("Status","The (Dollar to Pound) Button is Pressed"); Toast.makeText(this, "$" + DollarInput.getText().toString() + " is " + " ยฃ" + PoundInString , Toast.LENGTH_LONG ).show(); } public void PoundToDollarClick (View view){ EditText PoundInput = (EditText) findViewById(R.id.DollarInputET); //Takes user input of type EditText double NumberValue2 = Double.parseDouble(PoundInput.getText().toString());//converts PoundInput from EditText to a double double InDollars = NumberValue2 * 1.26; //Converts pound value to dollar value String DollarInString = Double.toString(InDollars); //Converts the dollar value to a string to be put inside to toast Log.i("Status","The (Dollar to Pound) Button is Pressed"); Toast.makeText(this, "ยฃ" + PoundInput.getText().toString() + " is " + "$" + DollarInString, Toast.LENGTH_LONG).show(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
1,760
0.70876
0.703641
39
44.076923
43.533298
131
false
false
0
0
0
0
0
0
0.692308
false
false
10
e45c4a8eb72f491e8f92310fe66926ae75b322a9
15,934,328,718,161
4efc19260b177732b57a63be4d24af92bec812dc
/src/fragmentos/Despesas_Fragment.java
5d7e3f019d231ac4951b6533a4656e2a7c6251a7
[]
no_license
fullservicecar/project
https://github.com/fullservicecar/project
d5f0ab92ef5ee22f6486ac252b2154ecb0be8143
f7cd35fd16cec5cc85d1872f13da727085dce617
refs/heads/master
2021-05-21T22:35:01.973000
2014-11-24T00:51:29
2014-11-24T00:51:29
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package fragmentos; import java.util.ArrayList; import lista.Despesas_AdapterListView; import lista.Despesas_ItemListView; import android.app.Fragment; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import atividades.Despesas_View_Activity; import banco_de_dados.DAODespesas; import banco_de_dados.Despesas; import com.example.fullservicecar.R; import funcoes.FAbastecimento; public class Despesas_Fragment extends Fragment implements OnItemClickListener{ private ListView listView; private Despesas_AdapterListView adapterListView; private ArrayList<Despesas_ItemListView> itens; public static int idDespesa = 0; public Despesas_Fragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view; if(DAODespesas.getInstancia(getActivity()).getTamanho() == 0){ view = inflater.inflate(R.layout.despesas_fragment_tutorial, container, false); }else{ view = inflater.inflate(R.layout.despesas_fragment, container, false); listView = (ListView) view.findViewById(R.id.Despesas_ListView_ListaDeDespesasRegistrados); // Define o Listener quando alguem clicar no item. listView.setOnItemClickListener(this); createListView(); } return view; } private void createListView() { // Criamos nossa lista que preenchera o ListView itens = new ArrayList<Despesas_ItemListView>(); int id = 0; String tipoDeDespesa = "", data = "", localDaDespesa = ""; double odometro = 0, valorTotal = 0; Despesas_ItemListView item[] = new Despesas_ItemListView[DAODespesas.getInstancia(getActivity()).getTamanho()]; ArrayList<Despesas> lista = new ArrayList<Despesas>(DAODespesas.getInstancia(getActivity()).recuperarPorQuery("SELECT * FROM " + DAODespesas.NOME_TABELA + " ORDER BY " + DAODespesas.COLUNA_ODOMETRO + ", " + DAODespesas.COLUNA_MILLIS + ", " + DAODespesas.COLUNA_VALORTOTAL + " ASC")); for (int x = 0; x < DAODespesas.getInstancia(getActivity()).getTamanho(); x++) { id = lista.get(x).getId(); tipoDeDespesa = lista.get(x).getTipo(); localDaDespesa = lista.get(x).getLocal(); odometro = lista.get(x).getOdometro(); data = lista.get(x).getData(); valorTotal = lista.get(x).getValorTotal(); item[x] = new Despesas_ItemListView(id, tipoDeDespesa, data, localDaDespesa, FAbastecimento.conv(odometro), FAbastecimento.conv(valorTotal)); } for (int x = item.length - 1; x >= 0; x--) { itens.add(item[x]); } // Cria o adapter adapterListView = new Despesas_AdapterListView(getActivity(),itens); // Define o Adapter listView.setAdapter(adapterListView); // Cor quando a lista รฉ selecionada para ralagem. listView.setCacheColorHint(Color.TRANSPARENT); } public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // Pega o item que foi selecionado. Despesas_ItemListView item = adapterListView.getItem(arg2); idDespesa = item.getId(); startActivity(new Intent(getActivity(), Despesas_View_Activity.class)); } }
WINDOWS-1252
Java
3,436
java
Despesas_Fragment.java
Java
[]
null
[]
package fragmentos; import java.util.ArrayList; import lista.Despesas_AdapterListView; import lista.Despesas_ItemListView; import android.app.Fragment; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import atividades.Despesas_View_Activity; import banco_de_dados.DAODespesas; import banco_de_dados.Despesas; import com.example.fullservicecar.R; import funcoes.FAbastecimento; public class Despesas_Fragment extends Fragment implements OnItemClickListener{ private ListView listView; private Despesas_AdapterListView adapterListView; private ArrayList<Despesas_ItemListView> itens; public static int idDespesa = 0; public Despesas_Fragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view; if(DAODespesas.getInstancia(getActivity()).getTamanho() == 0){ view = inflater.inflate(R.layout.despesas_fragment_tutorial, container, false); }else{ view = inflater.inflate(R.layout.despesas_fragment, container, false); listView = (ListView) view.findViewById(R.id.Despesas_ListView_ListaDeDespesasRegistrados); // Define o Listener quando alguem clicar no item. listView.setOnItemClickListener(this); createListView(); } return view; } private void createListView() { // Criamos nossa lista que preenchera o ListView itens = new ArrayList<Despesas_ItemListView>(); int id = 0; String tipoDeDespesa = "", data = "", localDaDespesa = ""; double odometro = 0, valorTotal = 0; Despesas_ItemListView item[] = new Despesas_ItemListView[DAODespesas.getInstancia(getActivity()).getTamanho()]; ArrayList<Despesas> lista = new ArrayList<Despesas>(DAODespesas.getInstancia(getActivity()).recuperarPorQuery("SELECT * FROM " + DAODespesas.NOME_TABELA + " ORDER BY " + DAODespesas.COLUNA_ODOMETRO + ", " + DAODespesas.COLUNA_MILLIS + ", " + DAODespesas.COLUNA_VALORTOTAL + " ASC")); for (int x = 0; x < DAODespesas.getInstancia(getActivity()).getTamanho(); x++) { id = lista.get(x).getId(); tipoDeDespesa = lista.get(x).getTipo(); localDaDespesa = lista.get(x).getLocal(); odometro = lista.get(x).getOdometro(); data = lista.get(x).getData(); valorTotal = lista.get(x).getValorTotal(); item[x] = new Despesas_ItemListView(id, tipoDeDespesa, data, localDaDespesa, FAbastecimento.conv(odometro), FAbastecimento.conv(valorTotal)); } for (int x = item.length - 1; x >= 0; x--) { itens.add(item[x]); } // Cria o adapter adapterListView = new Despesas_AdapterListView(getActivity(),itens); // Define o Adapter listView.setAdapter(adapterListView); // Cor quando a lista รฉ selecionada para ralagem. listView.setCacheColorHint(Color.TRANSPARENT); } public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // Pega o item que foi selecionado. Despesas_ItemListView item = adapterListView.getItem(arg2); idDespesa = item.getId(); startActivity(new Intent(getActivity(), Despesas_View_Activity.class)); } }
3,436
0.711499
0.707715
109
29.513762
37.31065
285
false
false
0
0
0
0
0
0
2.055046
false
false
10
70b24417b00f5b1ff73f555dc8e4a1931704b820
25,709,674,278,248
c6ea03b1755c0edf0c39e660cd3601825be77b9c
/book/ch8/TimeServerThread.java
f694d11be2040f972cd283d1607619369a186ad4
[]
no_license
goalsgo1/github_HD
https://github.com/goalsgo1/github_HD
a74b1b2ccf344de7befe7badf6b9a261656074ef
412b0daf0226b2fd0c4447aea96212c6017d0055
refs/heads/master
2022-12-09T23:26:31.999000
2020-08-26T09:41:07
2020-08-26T09:41:07
287,242,268
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package book.ch8; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; public class TimeServerThread extends Thread { TimeServer2 ts = null; // null์„ ์“ฐ๋Š” ๊ฒƒ์ด ์ค‘์š”ํ•˜๋‹ค. ObjectOutputStream oos = null; ObjectInputStream ois = null; Socket client = null; String timeStr = null; public TimeServerThread(TimeServer2 ts) {// ์ด ์ฝ”๋“œ๋„ ์ค‘์š”. this.ts = ts; this.client = ts.socket;// ์—ฌ๊ธฐ๊นŒ์ง€ ๋„๋‹ฌํ•˜๋Š” ํ๋ฆ„์ด ๊ฐ€์žฅ ์ค‘์š”. timeStr = ts.pushTime(); try { oos = new ObjectOutputStream(client.getOutputStream()); ois = new ObjectInputStream(client.getInputStream()); for (TimeServerThread tst : ts.globalList) {// ๊ฐœ์„ ๋œ for๋ฌธ - ์ „์ฒด ์กฐํšŒํ•  ๋•Œ - ๊ฐ€์ง„๊ฑฐ ๋‹ค ๋‚˜์™€ oos.writeObject(timeStr); } // ํ˜„์žฌ ์„œ๋ฒ„์— ์ž…์žฅํ•œ ํด๋ผ์ด์–ธํŠธ ์Šค๋ ˆ๋“œ ์ถ”๊ฐ€ํ•˜๊ธฐ. ts.globalList.add(this);// ๋ถ„์„ํ•ด๋ณด๊ธฐ, ์ค‘์š”ํ•จ. this.broadCasting(timeStr);// ๋ถ„์„ํ•ด๋ณด๊ธฐ, ์ค‘์š”ํ•จ. } catch (Exception e) { System.out.println(e.toString()); } } // ํ˜„์žฌ ์ž…์žฅํ•ด ์žˆ๋Š” ๋ชจ๋“  ์นœ๊ตฌ๋“ค์—๊ฒŒ ๋ชจ๋‘ ๋ฉ”์„ธ์ง€๋ฅผ ์ „์†กํ•˜๊ณ  ์‹ถ์–ด์š” public void broadCasting(String msg) { for (TimeServerThread tst : ts.globalList) { try { oos.writeObject(msg); } catch (Exception e) { e.printStackTrace();// stack์˜์—ญ์— ์Œ“์—ฌ ์žˆ๋Š” ์—๋Ÿฌ ๋ฉ”์„ธ์ง€ ๋ชจ๋‘ ์ถœ๋ ฅํ•ด์ค€๋‹ค. } } } //run ๋ฉ”์†Œ๋“œ์—๋Š” ๋ญ˜ ์จ์•ผ ํ•˜์ง€? @Override public void run() { System.out.println("TimeServerThread run ํ˜ธ์ถœ ์„ฑ๊ณต"); } }
UTF-8
Java
1,597
java
TimeServerThread.java
Java
[]
null
[]
package book.ch8; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; public class TimeServerThread extends Thread { TimeServer2 ts = null; // null์„ ์“ฐ๋Š” ๊ฒƒ์ด ์ค‘์š”ํ•˜๋‹ค. ObjectOutputStream oos = null; ObjectInputStream ois = null; Socket client = null; String timeStr = null; public TimeServerThread(TimeServer2 ts) {// ์ด ์ฝ”๋“œ๋„ ์ค‘์š”. this.ts = ts; this.client = ts.socket;// ์—ฌ๊ธฐ๊นŒ์ง€ ๋„๋‹ฌํ•˜๋Š” ํ๋ฆ„์ด ๊ฐ€์žฅ ์ค‘์š”. timeStr = ts.pushTime(); try { oos = new ObjectOutputStream(client.getOutputStream()); ois = new ObjectInputStream(client.getInputStream()); for (TimeServerThread tst : ts.globalList) {// ๊ฐœ์„ ๋œ for๋ฌธ - ์ „์ฒด ์กฐํšŒํ•  ๋•Œ - ๊ฐ€์ง„๊ฑฐ ๋‹ค ๋‚˜์™€ oos.writeObject(timeStr); } // ํ˜„์žฌ ์„œ๋ฒ„์— ์ž…์žฅํ•œ ํด๋ผ์ด์–ธํŠธ ์Šค๋ ˆ๋“œ ์ถ”๊ฐ€ํ•˜๊ธฐ. ts.globalList.add(this);// ๋ถ„์„ํ•ด๋ณด๊ธฐ, ์ค‘์š”ํ•จ. this.broadCasting(timeStr);// ๋ถ„์„ํ•ด๋ณด๊ธฐ, ์ค‘์š”ํ•จ. } catch (Exception e) { System.out.println(e.toString()); } } // ํ˜„์žฌ ์ž…์žฅํ•ด ์žˆ๋Š” ๋ชจ๋“  ์นœ๊ตฌ๋“ค์—๊ฒŒ ๋ชจ๋‘ ๋ฉ”์„ธ์ง€๋ฅผ ์ „์†กํ•˜๊ณ  ์‹ถ์–ด์š” public void broadCasting(String msg) { for (TimeServerThread tst : ts.globalList) { try { oos.writeObject(msg); } catch (Exception e) { e.printStackTrace();// stack์˜์—ญ์— ์Œ“์—ฌ ์žˆ๋Š” ์—๋Ÿฌ ๋ฉ”์„ธ์ง€ ๋ชจ๋‘ ์ถœ๋ ฅํ•ด์ค€๋‹ค. } } } //run ๋ฉ”์†Œ๋“œ์—๋Š” ๋ญ˜ ์จ์•ผ ํ•˜์ง€? @Override public void run() { System.out.println("TimeServerThread run ํ˜ธ์ถœ ์„ฑ๊ณต"); } }
1,597
0.659558
0.657273
47
25.936171
19.804796
80
false
false
0
0
0
0
0
0
2.12766
false
false
10
939b240220439c6b0506a95145d053d589e7cdc6
33,208,687,158,789
49021839171b3b11a86851cdddb9fd97d470c15d
/MyApplication/app/src/main/java/com/example/administrator/myapplication/RegisterActivity.java
11b7398884c75ee98f3f3f11f6b2408e5f128e6a
[]
no_license
tonghua97/Food
https://github.com/tonghua97/Food
744d2bc9ba62aacaaf9fa0a4b5f1f3d5183a45c5
c05e61c89e008849968cc6a61b9c38cd222c534d
refs/heads/master
2020-07-02T22:23:03.327000
2016-12-26T08:29:41
2016-12-26T08:29:41
74,276,533
1
8
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.administrator.myapplication; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import com.example.administrator.ui.Urls; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; /** * ๆณจๅ†Œ้กต */ public class RegisterActivity extends Activity { private ImageView mTvBack; private Button mRegister; private EditText mUserAccount; private EditText mUserPassword; private EditText mUserCpassword; private EditText mUserName; private EditText mUserNum; private EditText mUserPost; private String str; private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == 1){ if (str.equals("0")){ mUserAccount.setError("่ฏฅ่ดฆๅทๅทฒๅญ˜ๅœจ"); }else{ mUserAccount.setError(null); } // Toast.makeText(getApplicationContext(),str,Toast.LENGTH_SHORT).show(); } if (msg.what == 2){ if (str.equals("0")){ Toast.makeText(getApplicationContext(),"่ดฆๅทๅทฒๅญ˜ๅœจ๏ผŒ่ฏท้‡ๆ–ฐ่พ“ๅ…ฅ",Toast.LENGTH_SHORT).show(); }else if (str.equals("1")){ Toast.makeText(getApplicationContext(),"ๆ‰‹ๆœบๅทๅทฒ็ปไฝฟ็”จ่ฟ‡๏ผŒ่ฏท่พ“ๅ…ฅๆ–ฐไธชๆ‰‹ๆœบๅท",Toast.LENGTH_SHORT).show(); }else if (str.equals("2")){ Toast.makeText(getApplicationContext(),"ๆณจๅ†ŒๆˆๅŠŸ",Toast.LENGTH_SHORT).show(); Intent intent = new Intent(RegisterActivity.this,LoginVerifyActivity.class); startActivity(intent); finish(); }else if (str.equals("3")){ Toast.makeText(getApplicationContext(),"ๆณจๅ†Œๅคฑ่ดฅ",Toast.LENGTH_SHORT).show(); } } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); //่Žทๅ–ๆŽงไปถ getViews(); //่ฎพ็ฝฎ็›‘ๅฌ setListener(); } private void setListener() { mTvBack.setOnClickListener(myListener); mRegister.setOnClickListener(myListener); mUserAccount.setOnFocusChangeListener(mFocusListener); mUserCpassword.setOnFocusChangeListener(mFocusListener); } public void getViews() { //่ฟ”ๅ›ž mTvBack = (ImageView)findViewById(R.id.register_Tv_back); //ๆณจๅ†Œ mRegister = (Button)findViewById(R.id.register_Btn_register); //็”จๆˆท่ดฆๅท mUserAccount = (EditText)findViewById(R.id.register_userAccount); //็”จๆˆทๅฏ†็  mUserPassword = (EditText)findViewById(R.id.register_userPassword); //็กฎ่ฎคๅฏ†็  mUserCpassword = (EditText)findViewById(R.id.register_userCpassword); //ๆ˜ต็งฐ mUserName = (EditText)findViewById(R.id.register_userName); //ๆ‰‹ๆœบๅท mUserNum = (EditText)findViewById(R.id.register_userNum); } View.OnClickListener myListener = new View.OnClickListener() { @Override public void onClick(View view) { switch (view.getId()){ case R.id.register_Tv_back: finish(); break; case R.id.register_Btn_register: Thread t = new Thread(){ @Override public void run() { super.run(); getHttpRegister(); Message m = new Message(); handler.sendEmptyMessage(2); } }; t.start(); break; } } }; View.OnFocusChangeListener mFocusListener = new View.OnFocusChangeListener() { @Override public void onFocusChange(View view, boolean b) { switch (view.getId()){ case R.id.register_userAccount: if (b){ }else{ Thread thread = new Thread(){ @Override public void run() { super.run(); getHttpUserAccount(); Message m = new Message(); handler.sendEmptyMessage(1); } }; thread.start(); } break; case R.id.register_userCpassword: if (b){ }else{ if (mUserPassword.getText().toString() .equals(mUserCpassword.getText().toString())){ mUserCpassword.setError(null); }else{ mUserCpassword.setError("็กฎ่ฎคๅฏ†็ ไธŽๅฏ†็ ไธไธ€่‡ด"); } } break; } } }; public void getHttpUserAccount() { try { str = ""; URI u = new URI(Urls.urlIsUserAccount); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(u); NameValuePair pair = new BasicNameValuePair("userAccount",mUserAccount.getText().toString()); List<NameValuePair> pairs = new ArrayList<>(); pairs.add(pair); HttpEntity entity = new UrlEncodedFormEntity(pairs, "utf-8"); httppost.setEntity(entity); HttpResponse response = httpclient.execute(httppost); HttpEntity httpentity = response.getEntity(); if (httpentity != null) { BufferedReader buffer = new BufferedReader(new InputStreamReader(httpentity.getContent())); String string = null; while ((string = buffer.readLine()) != null) { str += string; } } } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } } public void getHttpRegister() { try { str = ""; URI u = new URI(Urls.urlRegister); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(u); NameValuePair pair1 = new BasicNameValuePair("userAccount",mUserAccount.getText().toString()); NameValuePair pair2 = new BasicNameValuePair("userPassword",mUserPassword.getText().toString()); NameValuePair pair3 = new BasicNameValuePair("userName",mUserName.getText().toString()); NameValuePair pair4 = new BasicNameValuePair("userNum",mUserNum.getText().toString()); List<NameValuePair> pairs = new ArrayList<>(); pairs.add(pair1); pairs.add(pair2); pairs.add(pair3); pairs.add(pair4); HttpEntity entity = new UrlEncodedFormEntity(pairs, "utf-8"); httppost.setEntity(entity); HttpResponse response = httpclient.execute(httppost); HttpEntity httpentity = response.getEntity(); if (httpentity != null) { BufferedReader buffer = new BufferedReader(new InputStreamReader(httpentity.getContent())); String string = null; while ((string = buffer.readLine()) != null) { str += string; } } } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } } }
UTF-8
Java
8,681
java
RegisterActivity.java
Java
[]
null
[]
package com.example.administrator.myapplication; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import com.example.administrator.ui.Urls; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; /** * ๆณจๅ†Œ้กต */ public class RegisterActivity extends Activity { private ImageView mTvBack; private Button mRegister; private EditText mUserAccount; private EditText mUserPassword; private EditText mUserCpassword; private EditText mUserName; private EditText mUserNum; private EditText mUserPost; private String str; private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == 1){ if (str.equals("0")){ mUserAccount.setError("่ฏฅ่ดฆๅทๅทฒๅญ˜ๅœจ"); }else{ mUserAccount.setError(null); } // Toast.makeText(getApplicationContext(),str,Toast.LENGTH_SHORT).show(); } if (msg.what == 2){ if (str.equals("0")){ Toast.makeText(getApplicationContext(),"่ดฆๅทๅทฒๅญ˜ๅœจ๏ผŒ่ฏท้‡ๆ–ฐ่พ“ๅ…ฅ",Toast.LENGTH_SHORT).show(); }else if (str.equals("1")){ Toast.makeText(getApplicationContext(),"ๆ‰‹ๆœบๅทๅทฒ็ปไฝฟ็”จ่ฟ‡๏ผŒ่ฏท่พ“ๅ…ฅๆ–ฐไธชๆ‰‹ๆœบๅท",Toast.LENGTH_SHORT).show(); }else if (str.equals("2")){ Toast.makeText(getApplicationContext(),"ๆณจๅ†ŒๆˆๅŠŸ",Toast.LENGTH_SHORT).show(); Intent intent = new Intent(RegisterActivity.this,LoginVerifyActivity.class); startActivity(intent); finish(); }else if (str.equals("3")){ Toast.makeText(getApplicationContext(),"ๆณจๅ†Œๅคฑ่ดฅ",Toast.LENGTH_SHORT).show(); } } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); //่Žทๅ–ๆŽงไปถ getViews(); //่ฎพ็ฝฎ็›‘ๅฌ setListener(); } private void setListener() { mTvBack.setOnClickListener(myListener); mRegister.setOnClickListener(myListener); mUserAccount.setOnFocusChangeListener(mFocusListener); mUserCpassword.setOnFocusChangeListener(mFocusListener); } public void getViews() { //่ฟ”ๅ›ž mTvBack = (ImageView)findViewById(R.id.register_Tv_back); //ๆณจๅ†Œ mRegister = (Button)findViewById(R.id.register_Btn_register); //็”จๆˆท่ดฆๅท mUserAccount = (EditText)findViewById(R.id.register_userAccount); //็”จๆˆทๅฏ†็  mUserPassword = (EditText)findViewById(R.id.register_userPassword); //็กฎ่ฎคๅฏ†็  mUserCpassword = (EditText)findViewById(R.id.register_userCpassword); //ๆ˜ต็งฐ mUserName = (EditText)findViewById(R.id.register_userName); //ๆ‰‹ๆœบๅท mUserNum = (EditText)findViewById(R.id.register_userNum); } View.OnClickListener myListener = new View.OnClickListener() { @Override public void onClick(View view) { switch (view.getId()){ case R.id.register_Tv_back: finish(); break; case R.id.register_Btn_register: Thread t = new Thread(){ @Override public void run() { super.run(); getHttpRegister(); Message m = new Message(); handler.sendEmptyMessage(2); } }; t.start(); break; } } }; View.OnFocusChangeListener mFocusListener = new View.OnFocusChangeListener() { @Override public void onFocusChange(View view, boolean b) { switch (view.getId()){ case R.id.register_userAccount: if (b){ }else{ Thread thread = new Thread(){ @Override public void run() { super.run(); getHttpUserAccount(); Message m = new Message(); handler.sendEmptyMessage(1); } }; thread.start(); } break; case R.id.register_userCpassword: if (b){ }else{ if (mUserPassword.getText().toString() .equals(mUserCpassword.getText().toString())){ mUserCpassword.setError(null); }else{ mUserCpassword.setError("็กฎ่ฎคๅฏ†็ ไธŽๅฏ†็ ไธไธ€่‡ด"); } } break; } } }; public void getHttpUserAccount() { try { str = ""; URI u = new URI(Urls.urlIsUserAccount); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(u); NameValuePair pair = new BasicNameValuePair("userAccount",mUserAccount.getText().toString()); List<NameValuePair> pairs = new ArrayList<>(); pairs.add(pair); HttpEntity entity = new UrlEncodedFormEntity(pairs, "utf-8"); httppost.setEntity(entity); HttpResponse response = httpclient.execute(httppost); HttpEntity httpentity = response.getEntity(); if (httpentity != null) { BufferedReader buffer = new BufferedReader(new InputStreamReader(httpentity.getContent())); String string = null; while ((string = buffer.readLine()) != null) { str += string; } } } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } } public void getHttpRegister() { try { str = ""; URI u = new URI(Urls.urlRegister); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(u); NameValuePair pair1 = new BasicNameValuePair("userAccount",mUserAccount.getText().toString()); NameValuePair pair2 = new BasicNameValuePair("userPassword",mUserPassword.getText().toString()); NameValuePair pair3 = new BasicNameValuePair("userName",mUserName.getText().toString()); NameValuePair pair4 = new BasicNameValuePair("userNum",mUserNum.getText().toString()); List<NameValuePair> pairs = new ArrayList<>(); pairs.add(pair1); pairs.add(pair2); pairs.add(pair3); pairs.add(pair4); HttpEntity entity = new UrlEncodedFormEntity(pairs, "utf-8"); httppost.setEntity(entity); HttpResponse response = httpclient.execute(httppost); HttpEntity httpentity = response.getEntity(); if (httpentity != null) { BufferedReader buffer = new BufferedReader(new InputStreamReader(httpentity.getContent())); String string = null; while ((string = buffer.readLine()) != null) { str += string; } } } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } } }
8,681
0.547281
0.545049
244
33.889343
25.562204
108
false
false
0
0
0
0
0
0
0.577869
false
false
10
32409ceab7ce92286fd938ff0cbd0a5524bd8e42
16,243,566,352,870
52b3d7da648acb309ff0c742bb05ec57b5c7091a
/src/com/company/Main.java
fab2f020cab2abaa64c83fd529812406c88a486d
[]
no_license
DacePet/Array-Assignments
https://github.com/DacePet/Array-Assignments
cc4ba8a35f1f2ae5df2a13d07c235847192528dc
c08769c8dabaf0f2b40826971f0ca25a5c1966f5
refs/heads/master
2023-08-31T06:12:30.294000
2021-10-24T18:54:53
2021-10-24T18:54:53
413,564,000
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.company; import java.util.Arrays; public class Main { public static void main(String[] args) { { int[] arrOne = {1, 9, 5, 7, 6}; System.out.println(Arrays.toString(arrOne)); arrOne[1] = 0; for (int i = 0; i < arrOne.length; i++) { System.out.println(arrOne[i]); } } } }
UTF-8
Java
410
java
Main.java
Java
[]
null
[]
package com.company; import java.util.Arrays; public class Main { public static void main(String[] args) { { int[] arrOne = {1, 9, 5, 7, 6}; System.out.println(Arrays.toString(arrOne)); arrOne[1] = 0; for (int i = 0; i < arrOne.length; i++) { System.out.println(arrOne[i]); } } } }
410
0.451219
0.431707
16
24.6875
19.4188
68
false
false
0
0
0
0
0
0
0.75
false
false
10
bb63dbc23d17a5105cf39cd7c7b6fd753e841284
30,425,548,376,224
9cdf4a803b5851915b53edaeead2546f788bddc6
/machinelearning/5.0/drools-examples/drools-examples-drl/src/main/java/org/drools/examples/sudoku/rules/DroolsSudokuGridModel.java
08c59abc81f16b7ed10d0ae07f869623894a733f
[ "Apache-2.0" ]
permissive
kiegroup/droolsjbpm-contributed-experiments
https://github.com/kiegroup/droolsjbpm-contributed-experiments
8051a70cfa39f18bc3baa12ca819a44cc7146700
6f032d28323beedae711a91f70960bf06ee351e5
refs/heads/master
2023-06-01T06:11:42.641000
2020-07-15T15:09:02
2020-07-15T15:09:02
1,184,582
1
13
null
false
2021-06-24T08:45:52
2010-12-20T15:42:26
2020-09-08T11:21:22
2020-07-15T16:13:45
157,850
15
30
21
Java
false
false
/* * JBoss, the OpenSource J2EE webOS * * Distributable under LGPL license. * See terms of license at gnu.org. */ package org.drools.examples.sudoku.rules; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.drools.RuleBase; import org.drools.StatefulSession; import org.drools.event.ObjectInsertedEvent; import org.drools.event.ObjectRetractedEvent; import org.drools.event.ObjectUpdatedEvent; import org.drools.event.WorkingMemoryEventListener; import org.drools.examples.sudoku.swing.AbstractSudokuGridModel; import org.drools.examples.sudoku.swing.SudokuGridEvent; import org.drools.examples.sudoku.swing.SudokuGridModel; /** * An implementation of the SudokuGridModel interface which is backed by the Drools engine. * <p> * Two rule bases are used in this implementation. The first, defined at SUDOKU_SOLVER_DRL * provides a set of rules that attempt to solve a partially completed Sudoku grid. The * second, defined at SUDOKU_VALIDATOR_DRL provides a set of rules which can validate * whether the current state of the model represents a valid solution. * <p> * * @author <a href="pbennett@redhat.com">Pete Bennett</a> * @version $Revision: 1.1 $ */ @SuppressWarnings("unchecked") public class DroolsSudokuGridModel extends AbstractSudokuGridModel implements SudokuGridModel { /** * The location of the DRL file which defines the rule base for solving a Sudoku grid */ public final static String SUDOKU_SOLVER_DRL = "../sudokuSolver.drl"; /** * The location of the DRL file which defines the rule base for validating the content of a Sudoku grid */ public final static String SUDOKU_VALIDATOR_DRL = "../sudokuValidator.drl"; /** A set of AbtractCellValues capturing the current state of the grid */ private Set<AbstractCellValue> allCellValues = new HashSet<AbstractCellValue>(); /** A index into the AbstractCellValues based on row and column */ private Set<Integer>[][] cellValuesByRowAndCol = new HashSet[SudokuGridModel.NUM_ROWS][SudokuGridModel.NUM_COLS]; /** The solver rule base */ private RuleBase solverRuleBase; /** The stateful session working memory for the solver rule base */ private StatefulSession solverStatefulSession; /** An inner class implementation listening to working memory events */ private SudokuWorkingMemoryListener workingMemoryListener = new SudokuWorkingMemoryListener(); /** * Create a new DroolsSudokuGridModel with an empty grid. */ public DroolsSudokuGridModel() { } /** * Create a new DroolsSudokuGridModel with the specified values. * * @param cellValues a two dimensional grid of Integer values for cells, a null means the value is not yet resolved */ public DroolsSudokuGridModel(Integer[][] cellValues) { this(); setCellValues(cellValues); } /** * Set the state of the Grid based on a two dimensional array of Integers. * * @param cellValues a two dimensional grid of Integer values for cells, a null means the value is not yet resolved */ public void setCellValues(Integer[][] cellValues) { long startTime = System.currentTimeMillis(); if (solverRuleBase == null) { try { solverRuleBase = DroolsUtil.getInstance().readRuleBase(SUDOKU_SOLVER_DRL); } catch(Exception ex) { ex.printStackTrace(); throw new RuntimeException("Error Reading RuleBase for Solver"); } } if (solverStatefulSession != null) { solverStatefulSession.removeEventListener(workingMemoryListener); } solverStatefulSession = solverRuleBase.newStatefulSession(); solverStatefulSession.addEventListener(workingMemoryListener); for(int row=0; row<cellValues.length; row++) { for (int col=0; col<cellValues[row].length; col++) { cellValuesByRowAndCol[row][col] = new HashSet<Integer>(); if(cellValues[row][col] == null) { for(int value=1; value<10; value++) { PossibleCellValue cellValue = new PossibleCellValue(value, row, col); addCellValue(cellValue); allCellValues.add(cellValue); } } else { ResolvedCellValue cellValue = new ResolvedCellValue(cellValues[row][col], row, col); addCellValue(cellValue); } } } insertAllCellValues(solverStatefulSession); System.out.println("Setting up working memory and inserting all cell value POJOs took "+(System.currentTimeMillis()-startTime)+"ms."); } /** * Determines whether a given cell is editable from another class. * * @param row the row in the grid for the cell * @param col the column in the grid for the cell * @return is the specified cell editable */ public boolean isCellEditable(int row, int col) { return false; } /** * Determines whether a given cell has been solved. * * @param row the row in the grid for the cell * @param col the column in the grid for the cell * @return is the specified cell solved */ public boolean isCellResolved(int row, int col) { return getPossibleCellValues(row, col).size() == 1; } /** * Evaluates the current state of the Grid against the * validation rules determined in the SUDOKU_VALIDATOR_DRL * and indicates if the grid is currently solved or not. * * @return true if the current state represents a completely filled out * and valid Sudoku solution, false otherwise */ public boolean isGridSolved() { boolean solved = true; // TODO: move this logic into SUDOKU_VALIDATOR_DRL and out of Java code for(int row=0; row<NUM_ROWS; row++) { for (int col=0; col<NUM_COLS; col++) { if(!isCellResolved(row, col)) { System.out.print("("+row+","+col+") has not been resolved but has been narrowed down to "); for (Integer possibleInt : getPossibleCellValues(row, col)) { System.out.print(possibleInt+" "); } System.out.println(); solved=false; } } } if (solved) { try { RuleBase validatorRuleBase = DroolsUtil.getInstance().readRuleBase(SUDOKU_VALIDATOR_DRL); StatefulSession validatorStatefulSession = validatorRuleBase.newStatefulSession(); List issues = new ArrayList(); validatorStatefulSession.setGlobal("issues", issues); insertAllCellValues(validatorStatefulSession); validatorStatefulSession.fireAllRules(); if (issues.isEmpty()) { System.out.println("Sucessfully Validated Solution"); } else { solved = false; for (Object issue : issues) { System.out.println(issue); } } } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException(); } } return solved; } /** * Returns the possible values of the cell at a specific * row and column in the Grid. * * @param row the row in the Grid * @param col the column in the Grid * @return the Set of possible Integer values this cell can have, if * the Set is of size one then this is the value this cell * must have, otherwise it is a list of the possibilities */ public Set<Integer> getPossibleCellValues(int row, int col) { return cellValuesByRowAndCol[row][col]; } /** * Attempt to solve the Sudoku puzzle from its current state by * firing all of the rules in SUDOKU_SOLVER_DRL against the * current state of the Grid then validate if we have solved the * Grid after this. * * @return true if the state after firing all rules * represents a completely filled out * and valid Sudoku solution, false otherwise */ public boolean solve() { solverStatefulSession.fireAllRules(); return isGridSolved(); } /** * Fire the next rule on the agenda and return * * @return true if the state after firing the single rule * represents a completely filled out * and valid Sudoku solution, false otherwise */ public boolean step() { // TODO: I am not sure where the fireAllRules(int) method has gone // should be solverStatefulSession.fireAllRules(1) solverStatefulSession.fireAllRules(); return isGridSolved(); } /** * Inserts all of the current state of the Grid as represented * by the set of AbstractCellValues this class is maintaining * into the specified StatefulSession working memory. * * @param statefulSession the target StatefulSession */ private void insertAllCellValues(StatefulSession statefulSession) { for (AbstractCellValue cellValue : allCellValues) { statefulSession.insert(cellValue); } } /** * Adds the specified AbstractCellValue into the set of * AbstractCellValues that this class is maintaining. * * @param cellValue the AbstractCellValue to add */ private void addCellValue(AbstractCellValue cellValue) { allCellValues.add(cellValue); cellValuesByRowAndCol[cellValue.getRow()][cellValue.getCol()].add(cellValue.getValue()); } /** * Removes the specified AbstractCellValue from the set of * AbstractCellValues that this class is maintaining. * * @param cellValue the AbstractCellValue to remove */ private void removeCellValue(AbstractCellValue cellValue) { allCellValues.remove(cellValue); cellValuesByRowAndCol[cellValue.getRow()][cellValue.getCol()].remove(cellValue.getValue()); } class SudokuWorkingMemoryListener implements WorkingMemoryEventListener { public void objectInserted(ObjectInsertedEvent ev) { if (ev.getObject() instanceof AbstractCellValue) { addCellValue(((AbstractCellValue) ev.getObject())); } if (ev.getObject() instanceof ResolvedCellValue) { ResolvedCellValue cellValue = (ResolvedCellValue) ev.getObject(); fireCellResolvedEvent(new SudokuGridEvent(this, cellValue.getRow(), cellValue.getCol(), cellValue.getValue())); } if (ev.getObject() instanceof String) { System.out.println(ev.getObject()); } } public void objectRetracted(ObjectRetractedEvent ev) { if (ev.getOldObject() instanceof AbstractCellValue) { AbstractCellValue cellValue = (AbstractCellValue) ev.getOldObject(); removeCellValue(cellValue); fireCellUpdatedEvent(new SudokuGridEvent(this, cellValue.getRow(), cellValue.getCol(), cellValue.getValue())); } } public void objectUpdated(ObjectUpdatedEvent ev) { if (ev.getObject() instanceof ResolvedCellValue) { ResolvedCellValue cellValue = (ResolvedCellValue) ev.getObject(); fireCellUpdatedEvent(new SudokuGridEvent(this, cellValue.getRow(), cellValue.getCol(), cellValue.getValue())); } } } }
UTF-8
Java
11,903
java
DroolsSudokuGridModel.java
Java
[ { "context": " a valid solution.\n * <p>\n * \n * @author <a href=\"pbennett@redhat.com\">Pete Bennett</a>\n * @version $Revision: 1.1 $\n *", "end": 1183, "score": 0.9999325275421143, "start": 1164, "tag": "EMAIL", "value": "pbennett@redhat.com" }, { "context": " <p>\n * \n * @author <a href=\"pbennett@redhat.com\">Pete Bennett</a>\n * @version $Revision: 1.1 $\n */\n@SuppressWar", "end": 1197, "score": 0.9998671412467957, "start": 1185, "tag": "NAME", "value": "Pete Bennett" } ]
null
[]
/* * JBoss, the OpenSource J2EE webOS * * Distributable under LGPL license. * See terms of license at gnu.org. */ package org.drools.examples.sudoku.rules; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.drools.RuleBase; import org.drools.StatefulSession; import org.drools.event.ObjectInsertedEvent; import org.drools.event.ObjectRetractedEvent; import org.drools.event.ObjectUpdatedEvent; import org.drools.event.WorkingMemoryEventListener; import org.drools.examples.sudoku.swing.AbstractSudokuGridModel; import org.drools.examples.sudoku.swing.SudokuGridEvent; import org.drools.examples.sudoku.swing.SudokuGridModel; /** * An implementation of the SudokuGridModel interface which is backed by the Drools engine. * <p> * Two rule bases are used in this implementation. The first, defined at SUDOKU_SOLVER_DRL * provides a set of rules that attempt to solve a partially completed Sudoku grid. The * second, defined at SUDOKU_VALIDATOR_DRL provides a set of rules which can validate * whether the current state of the model represents a valid solution. * <p> * * @author <a href="<EMAIL>"><NAME></a> * @version $Revision: 1.1 $ */ @SuppressWarnings("unchecked") public class DroolsSudokuGridModel extends AbstractSudokuGridModel implements SudokuGridModel { /** * The location of the DRL file which defines the rule base for solving a Sudoku grid */ public final static String SUDOKU_SOLVER_DRL = "../sudokuSolver.drl"; /** * The location of the DRL file which defines the rule base for validating the content of a Sudoku grid */ public final static String SUDOKU_VALIDATOR_DRL = "../sudokuValidator.drl"; /** A set of AbtractCellValues capturing the current state of the grid */ private Set<AbstractCellValue> allCellValues = new HashSet<AbstractCellValue>(); /** A index into the AbstractCellValues based on row and column */ private Set<Integer>[][] cellValuesByRowAndCol = new HashSet[SudokuGridModel.NUM_ROWS][SudokuGridModel.NUM_COLS]; /** The solver rule base */ private RuleBase solverRuleBase; /** The stateful session working memory for the solver rule base */ private StatefulSession solverStatefulSession; /** An inner class implementation listening to working memory events */ private SudokuWorkingMemoryListener workingMemoryListener = new SudokuWorkingMemoryListener(); /** * Create a new DroolsSudokuGridModel with an empty grid. */ public DroolsSudokuGridModel() { } /** * Create a new DroolsSudokuGridModel with the specified values. * * @param cellValues a two dimensional grid of Integer values for cells, a null means the value is not yet resolved */ public DroolsSudokuGridModel(Integer[][] cellValues) { this(); setCellValues(cellValues); } /** * Set the state of the Grid based on a two dimensional array of Integers. * * @param cellValues a two dimensional grid of Integer values for cells, a null means the value is not yet resolved */ public void setCellValues(Integer[][] cellValues) { long startTime = System.currentTimeMillis(); if (solverRuleBase == null) { try { solverRuleBase = DroolsUtil.getInstance().readRuleBase(SUDOKU_SOLVER_DRL); } catch(Exception ex) { ex.printStackTrace(); throw new RuntimeException("Error Reading RuleBase for Solver"); } } if (solverStatefulSession != null) { solverStatefulSession.removeEventListener(workingMemoryListener); } solverStatefulSession = solverRuleBase.newStatefulSession(); solverStatefulSession.addEventListener(workingMemoryListener); for(int row=0; row<cellValues.length; row++) { for (int col=0; col<cellValues[row].length; col++) { cellValuesByRowAndCol[row][col] = new HashSet<Integer>(); if(cellValues[row][col] == null) { for(int value=1; value<10; value++) { PossibleCellValue cellValue = new PossibleCellValue(value, row, col); addCellValue(cellValue); allCellValues.add(cellValue); } } else { ResolvedCellValue cellValue = new ResolvedCellValue(cellValues[row][col], row, col); addCellValue(cellValue); } } } insertAllCellValues(solverStatefulSession); System.out.println("Setting up working memory and inserting all cell value POJOs took "+(System.currentTimeMillis()-startTime)+"ms."); } /** * Determines whether a given cell is editable from another class. * * @param row the row in the grid for the cell * @param col the column in the grid for the cell * @return is the specified cell editable */ public boolean isCellEditable(int row, int col) { return false; } /** * Determines whether a given cell has been solved. * * @param row the row in the grid for the cell * @param col the column in the grid for the cell * @return is the specified cell solved */ public boolean isCellResolved(int row, int col) { return getPossibleCellValues(row, col).size() == 1; } /** * Evaluates the current state of the Grid against the * validation rules determined in the SUDOKU_VALIDATOR_DRL * and indicates if the grid is currently solved or not. * * @return true if the current state represents a completely filled out * and valid Sudoku solution, false otherwise */ public boolean isGridSolved() { boolean solved = true; // TODO: move this logic into SUDOKU_VALIDATOR_DRL and out of Java code for(int row=0; row<NUM_ROWS; row++) { for (int col=0; col<NUM_COLS; col++) { if(!isCellResolved(row, col)) { System.out.print("("+row+","+col+") has not been resolved but has been narrowed down to "); for (Integer possibleInt : getPossibleCellValues(row, col)) { System.out.print(possibleInt+" "); } System.out.println(); solved=false; } } } if (solved) { try { RuleBase validatorRuleBase = DroolsUtil.getInstance().readRuleBase(SUDOKU_VALIDATOR_DRL); StatefulSession validatorStatefulSession = validatorRuleBase.newStatefulSession(); List issues = new ArrayList(); validatorStatefulSession.setGlobal("issues", issues); insertAllCellValues(validatorStatefulSession); validatorStatefulSession.fireAllRules(); if (issues.isEmpty()) { System.out.println("Sucessfully Validated Solution"); } else { solved = false; for (Object issue : issues) { System.out.println(issue); } } } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException(); } } return solved; } /** * Returns the possible values of the cell at a specific * row and column in the Grid. * * @param row the row in the Grid * @param col the column in the Grid * @return the Set of possible Integer values this cell can have, if * the Set is of size one then this is the value this cell * must have, otherwise it is a list of the possibilities */ public Set<Integer> getPossibleCellValues(int row, int col) { return cellValuesByRowAndCol[row][col]; } /** * Attempt to solve the Sudoku puzzle from its current state by * firing all of the rules in SUDOKU_SOLVER_DRL against the * current state of the Grid then validate if we have solved the * Grid after this. * * @return true if the state after firing all rules * represents a completely filled out * and valid Sudoku solution, false otherwise */ public boolean solve() { solverStatefulSession.fireAllRules(); return isGridSolved(); } /** * Fire the next rule on the agenda and return * * @return true if the state after firing the single rule * represents a completely filled out * and valid Sudoku solution, false otherwise */ public boolean step() { // TODO: I am not sure where the fireAllRules(int) method has gone // should be solverStatefulSession.fireAllRules(1) solverStatefulSession.fireAllRules(); return isGridSolved(); } /** * Inserts all of the current state of the Grid as represented * by the set of AbstractCellValues this class is maintaining * into the specified StatefulSession working memory. * * @param statefulSession the target StatefulSession */ private void insertAllCellValues(StatefulSession statefulSession) { for (AbstractCellValue cellValue : allCellValues) { statefulSession.insert(cellValue); } } /** * Adds the specified AbstractCellValue into the set of * AbstractCellValues that this class is maintaining. * * @param cellValue the AbstractCellValue to add */ private void addCellValue(AbstractCellValue cellValue) { allCellValues.add(cellValue); cellValuesByRowAndCol[cellValue.getRow()][cellValue.getCol()].add(cellValue.getValue()); } /** * Removes the specified AbstractCellValue from the set of * AbstractCellValues that this class is maintaining. * * @param cellValue the AbstractCellValue to remove */ private void removeCellValue(AbstractCellValue cellValue) { allCellValues.remove(cellValue); cellValuesByRowAndCol[cellValue.getRow()][cellValue.getCol()].remove(cellValue.getValue()); } class SudokuWorkingMemoryListener implements WorkingMemoryEventListener { public void objectInserted(ObjectInsertedEvent ev) { if (ev.getObject() instanceof AbstractCellValue) { addCellValue(((AbstractCellValue) ev.getObject())); } if (ev.getObject() instanceof ResolvedCellValue) { ResolvedCellValue cellValue = (ResolvedCellValue) ev.getObject(); fireCellResolvedEvent(new SudokuGridEvent(this, cellValue.getRow(), cellValue.getCol(), cellValue.getValue())); } if (ev.getObject() instanceof String) { System.out.println(ev.getObject()); } } public void objectRetracted(ObjectRetractedEvent ev) { if (ev.getOldObject() instanceof AbstractCellValue) { AbstractCellValue cellValue = (AbstractCellValue) ev.getOldObject(); removeCellValue(cellValue); fireCellUpdatedEvent(new SudokuGridEvent(this, cellValue.getRow(), cellValue.getCol(), cellValue.getValue())); } } public void objectUpdated(ObjectUpdatedEvent ev) { if (ev.getObject() instanceof ResolvedCellValue) { ResolvedCellValue cellValue = (ResolvedCellValue) ev.getObject(); fireCellUpdatedEvent(new SudokuGridEvent(this, cellValue.getRow(), cellValue.getCol(), cellValue.getValue())); } } } }
11,885
0.630093
0.629085
361
31.9723
29.537418
140
false
false
0
0
0
0
0
0
0.3241
false
false
10
112a2694402487bf9883978eef97666eb47a8276
3,100,966,430,441
95774b0e78efd98f4d883680bbcfbc96a198702e
/src/main/java/app/MainServer.java
59514af0aa4f064ba8519aacac5269b69114a9fb
[]
no_license
AAMergulhao/eg-gradle
https://github.com/AAMergulhao/eg-gradle
b61a2a4d77072195b16c4c202d4d9265a583a642
465f31bc24abea9c62075e8446e3a0685f89e49f
refs/heads/master
2020-08-07T18:39:22.924000
2019-12-01T23:16:19
2019-12-01T23:16:19
213,554,011
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package app; import static spark.Spark.port; import static spark.Spark.staticFileLocation; import model.Formula; import model.Model; public class MainServer{ final static Model model = new Model(); public static void main(String[] args) { // Get port config of heroku on environment variable ProcessBuilder process = new ProcessBuilder(); Integer port; if (process.environment().get("PORT") != null) { port = Integer.parseInt(process.environment().get("PORT")); } else { port = 8080; } port(port); //Servir conteudo html, css e javascript staticFileLocation("/static"); initForms(); Controller controller = new Controller(model); controller.srcFormula(); } public static void initForms(){ model.addFormula(new Formula(1, "{\"Formula\": \"Velocidade Media\", \"DeltaS\": \" intervalo de deslocamento (espaco) - posicao final - a posicao inicial\",\"DeltaT\": \" intervalo de tempo - tempo final - o tempo inicial\"}")); model.addFormula(new Formula(2, "{\"Formula\": \"Aceleracao Media\", \"DeltaV\": \" Variacao da velocidade (ฮ”V = V - V0)\",\"DeltaT\": \"Variacao do tempo (ฮ”t = T - T0)\"}")); model.addFormula(new Formula(3, "{\"Formula\": \"Equacao de Torricelli\", \"V\": \" Velocidade final (m/s)\",\"V0\": \"Velocidade inicial (m/s)\", \"A\": \"Aceleracao (m/s)ao quardrado\", \"DeltaS\": \"Espaco percorrido pelo corpo (m)\"}")); model.addFormula(new Formula(4, "{\"Formula\": \"Movimento Uniforme\", \"S\": \" Posicao\",\"S0\": \"Posicao inicial\", \"V\": \"Velocidade\", \"DeltaT\": \"Variacao do tempo (ฮ”t = T - T0)\"}")); } }
UTF-8
Java
1,711
java
MainServer.java
Java
[]
null
[]
package app; import static spark.Spark.port; import static spark.Spark.staticFileLocation; import model.Formula; import model.Model; public class MainServer{ final static Model model = new Model(); public static void main(String[] args) { // Get port config of heroku on environment variable ProcessBuilder process = new ProcessBuilder(); Integer port; if (process.environment().get("PORT") != null) { port = Integer.parseInt(process.environment().get("PORT")); } else { port = 8080; } port(port); //Servir conteudo html, css e javascript staticFileLocation("/static"); initForms(); Controller controller = new Controller(model); controller.srcFormula(); } public static void initForms(){ model.addFormula(new Formula(1, "{\"Formula\": \"Velocidade Media\", \"DeltaS\": \" intervalo de deslocamento (espaco) - posicao final - a posicao inicial\",\"DeltaT\": \" intervalo de tempo - tempo final - o tempo inicial\"}")); model.addFormula(new Formula(2, "{\"Formula\": \"Aceleracao Media\", \"DeltaV\": \" Variacao da velocidade (ฮ”V = V - V0)\",\"DeltaT\": \"Variacao do tempo (ฮ”t = T - T0)\"}")); model.addFormula(new Formula(3, "{\"Formula\": \"Equacao de Torricelli\", \"V\": \" Velocidade final (m/s)\",\"V0\": \"Velocidade inicial (m/s)\", \"A\": \"Aceleracao (m/s)ao quardrado\", \"DeltaS\": \"Espaco percorrido pelo corpo (m)\"}")); model.addFormula(new Formula(4, "{\"Formula\": \"Movimento Uniforme\", \"S\": \" Posicao\",\"S0\": \"Posicao inicial\", \"V\": \"Velocidade\", \"DeltaT\": \"Variacao do tempo (ฮ”t = T - T0)\"}")); } }
1,711
0.61007
0.602459
42
39.666668
61.429272
249
false
false
0
0
0
0
0
0
1.214286
false
false
10
26ed39215fb8df939a1203fa33fe816f92951dd2
11,330,123,784,600
46a940dbd6e630bd6018d471275af3630063dbf9
/src/chico3434/billjobs/windows/CreateCompany.java
0910120097beedae768f9bb058fc77d82fe175d7
[ "Apache-2.0" ]
permissive
chico3434/bill-jobs
https://github.com/chico3434/bill-jobs
268730db35b14066c58af468551c1fc74b423116
37f70f7d45cdb4579de4b476f1f43c615ee6d7a9
refs/heads/master
2020-04-08T21:36:22.363000
2019-03-14T01:59:26
2019-03-14T01:59:26
159,750,974
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package chico3434.billjobs.windows; import chico3434.billjobs.exceptions.MissingMoney; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.Slider; import javafx.scene.control.TextField; import chico3434.billjobs.utils.Game; import java.text.NumberFormat; public class CreateCompany { @FXML private TextField companyName; @FXML private Slider transferredFunds; @FXML private TextField tfFunds; public void initialize(){ transferredFunds.setMin(0); transferredFunds.setMax(Game.getBusinessman().getMoney()); transferredFunds.setValue(Game.getBusinessman().getMoney()/2); tfFunds.setDisable(true); tfFunds.textProperty().bindBidirectional(transferredFunds.valueProperty(), NumberFormat.getNumberInstance()); } public void createCompany(){ try { Game.createCompany(companyName.getText(), transferredFunds.getValue()); Main.createCompany.close(); } catch (MissingMoney e){ Alert a = new Alert(Alert.AlertType.WARNING, "Dinheiro Insuficiente"); a.show(); } } }
UTF-8
Java
1,153
java
CreateCompany.java
Java
[]
null
[]
package chico3434.billjobs.windows; import chico3434.billjobs.exceptions.MissingMoney; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.Slider; import javafx.scene.control.TextField; import chico3434.billjobs.utils.Game; import java.text.NumberFormat; public class CreateCompany { @FXML private TextField companyName; @FXML private Slider transferredFunds; @FXML private TextField tfFunds; public void initialize(){ transferredFunds.setMin(0); transferredFunds.setMax(Game.getBusinessman().getMoney()); transferredFunds.setValue(Game.getBusinessman().getMoney()/2); tfFunds.setDisable(true); tfFunds.textProperty().bindBidirectional(transferredFunds.valueProperty(), NumberFormat.getNumberInstance()); } public void createCompany(){ try { Game.createCompany(companyName.getText(), transferredFunds.getValue()); Main.createCompany.close(); } catch (MissingMoney e){ Alert a = new Alert(Alert.AlertType.WARNING, "Dinheiro Insuficiente"); a.show(); } } }
1,153
0.696444
0.684302
42
26.452381
26.490971
117
false
false
0
0
0
0
0
0
0.547619
false
false
10
862a687945b39a94cf97d0da1466c449a1d73050
8,624,294,375,476
adf53d15a5c6dcd6ca13e04d6861098dcfb3a28c
/src/main/java/com/lhf/mall/management/domain/enums/OrderProcessType.java
370270d6f49af633b14ebf488d1fed3e845e1693
[]
no_license
18309225600/mall-management
https://github.com/18309225600/mall-management
8e92f7efdf08a4c1b043c371059f34a4adb285b7
3a8717418107f106ec59d82fc224f3a7138961aa
refs/heads/master
2022-06-27T04:29:56.919000
2020-04-20T16:11:58
2020-04-20T16:11:58
254,655,609
0
0
null
false
2022-06-17T03:03:29
2020-04-10T14:31:43
2020-04-20T16:12:28
2022-06-17T03:03:26
2,465
0
0
1
Java
false
false
package com.lhf.mall.management.domain.enums; /** * @author ๅˆ˜ๅฎ้ฃž * @version v1.0 * @date 2020/4/18 **/ public enum OrderProcessType { ADD_REMARK(0,"ๆทปๅŠ ๅค‡ๆณจ"), UPDATE_STATUS(1,"ๆ›ดๆ–ฐ่ฎขๅ•็Šถๆ€"), WRITE_DELIVERY_INFO(2,"ๅกซๅ†™็‰ฉๆตไฟกๆฏ") ; private int code; private String description; OrderProcessType(int code, String description) { this.code = code; this.description = description; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
UTF-8
Java
793
java
OrderProcessType.java
Java
[ { "context": ".mall.management.domain.enums;\r\n\r\n/**\r\n * @author ๅˆ˜ๅฎ้ฃž\r\n * @version v1.0\r\n * @date 2020/4/18\r\n **/\r\npubl", "end": 68, "score": 0.9997221231460571, "start": 65, "tag": "NAME", "value": "ๅˆ˜ๅฎ้ฃž" } ]
null
[]
package com.lhf.mall.management.domain.enums; /** * @author ๅˆ˜ๅฎ้ฃž * @version v1.0 * @date 2020/4/18 **/ public enum OrderProcessType { ADD_REMARK(0,"ๆทปๅŠ ๅค‡ๆณจ"), UPDATE_STATUS(1,"ๆ›ดๆ–ฐ่ฎขๅ•็Šถๆ€"), WRITE_DELIVERY_INFO(2,"ๅกซๅ†™็‰ฉๆตไฟกๆฏ") ; private int code; private String description; OrderProcessType(int code, String description) { this.code = code; this.description = description; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
793
0.581457
0.565563
38
17.868422
16.159031
52
false
false
0
0
0
0
0
0
0.421053
false
false
10
baf7551127bd8ee0a6a7e07493161fb948b0d3d3
30,331,059,105,985
f778aaba950e6269baaaa2196a6e93396ec32c8f
/Java/helloworld.java
471d6fbf8db354709c93b07c222a8e0ca4ef6399
[]
no_license
ramanverma-dev/Baka_Codes
https://github.com/ramanverma-dev/Baka_Codes
ce8654c3227b216eb2a4455b8519983355945b09
0e0a95d0f81913b1f413240c71b8948012d30891
refs/heads/master
2020-12-01T14:08:02.247000
2020-11-26T07:01:33
2020-11-26T07:01:33
230,655,431
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** This is to ensure that the Java extension pack of VSCode is working properly with IntelliSense */ public class helloworld { public static void main(String[] args) { System.out.println("Hello World."); } }
UTF-8
Java
231
java
helloworld.java
Java
[]
null
[]
/** This is to ensure that the Java extension pack of VSCode is working properly with IntelliSense */ public class helloworld { public static void main(String[] args) { System.out.println("Hello World."); } }
231
0.675325
0.675325
9
24.777779
29.757456
95
false
false
0
0
0
0
0
0
0.111111
false
false
10
66b73c017c9c2660b5c3655ec67304abf03f7dc1
9,302,899,218,093
7cfc966b6c6aa7b32fb9046fb3e35901066618b4
/esportingplus-resource-service/src/main/java/com/kaihei/esportingplus/resource/controller/PVPBaojiPricingConfigController.java
37c9de4ca024b0f917b486a811bfa5d39dc4c43c
[]
no_license
cckmit/esportlus-zhouyu
https://github.com/cckmit/esportlus-zhouyu
88a9f92ab685b2a0d3490434b56cc353944ccf0f
8df44c2d513783ffac232268fb5617e8df6e0cb0
refs/heads/master
2022-05-08T14:34:03.598000
2018-12-05T09:33:07
2018-12-05T09:33:07
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kaihei.esportingplus.resource.controller; import com.kaihei.esportingplus.api.enums.DictionaryCategoryCodeEnum; import com.kaihei.esportingplus.api.feign.PVPBaojiPricingConfigServiceClient; import com.kaihei.esportingplus.api.params.BaojiPricingConfigParams; import com.kaihei.esportingplus.api.vo.DictBaseVO; import com.kaihei.esportingplus.api.vo.GameDictVO; import com.kaihei.esportingplus.api.vo.PVPBaojiGameDanIncomeVO; import com.kaihei.esportingplus.api.vo.PVPBaojiPricingConfigVO; import com.kaihei.esportingplus.api.vo.freeteam.DanDictVo; import com.kaihei.esportingplus.common.BeanMapper; import com.kaihei.esportingplus.common.ResponsePacket; import com.kaihei.esportingplus.common.ValidateAssert; import com.kaihei.esportingplus.common.enums.BizExceptionEnum; import com.kaihei.esportingplus.resource.data.manager.impl.DictionaryDictManager; import com.kaihei.esportingplus.resource.data.repository.PVPBaojiPricingConfigRepository; import com.kaihei.esportingplus.resource.domain.entity.Dictionary; import com.kaihei.esportingplus.resource.domain.entity.PVPBaojiPricingConfig; import com.kaihei.esportingplus.resource.domain.service.PVPBaojiPricingConfigService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * ๆšด้ธก่ฎกไปท้…็ฝฎ * @author liangyi */ @RestController @RequestMapping("/baoji/pricing/config") @Api(tags = {"ๆšด้ธก่ฎกไปท้…็ฝฎ"}) public class PVPBaojiPricingConfigController implements PVPBaojiPricingConfigServiceClient { @Autowired DictionaryDictManager dictionaryDictManager; @Autowired PVPBaojiPricingConfigRepository pvpBaojiPricingConfigRepository; @Autowired PVPBaojiPricingConfigService pvpBaojiPricingConfigService; @ApiOperation(value = "ๆŸฅ่ฏขๅ•ไธช่ฏฆ็ป†็š„ๆšด้ธก่ฎกไปท้…็ฝฎ") @Override public ResponsePacket<PVPBaojiPricingConfigVO> getBaojiPricingConfigDetail( @ApiParam(value = "ๆŸฅ่ฏขๅ‚ๆ•ฐ", required = true) @RequestBody BaojiPricingConfigParams baojiPricingConfigParams) { ValidateAssert.allNotNull(BizExceptionEnum.PARAM_VALID_FAIL, baojiPricingConfigParams); PVPBaojiPricingConfig pricingConfig = BeanMapper .map(baojiPricingConfigParams, PVPBaojiPricingConfig.class); // ๆ นๆฎๆšด้ธก็ญ‰็บง code ๆŸฅ่ฏขๅ‡บๆšด้ธก็ญ‰็บง id Dictionary baojiLevelDict = dictionaryDictManager.findByCodeAndCategoryCode( String.valueOf(baojiPricingConfigParams.getBaojiLevelCodeList().get(0)), DictionaryCategoryCodeEnum.BAOJI_LEVEL.getCode()); DictBaseVO baojiLevel = BeanMapper.map(baojiLevelDict, DictBaseVO.class); pricingConfig.setBaojiLevelId(baojiLevel.getDictId()); pricingConfig.setBossGameDanId(baojiPricingConfigParams.getBossGameDanIdList().get(0)); // ๅชๆŸฅ่ฏขๅฏ็”จ็š„ pricingConfig.setStatus((byte)1); PVPBaojiPricingConfig pvpBaojiPricingConfig = pvpBaojiPricingConfigRepository .selectOne(pricingConfig); PVPBaojiPricingConfigVO pvpBaojiPricingConfigVO = bulidPVPBaojiPricingConfigVO( pvpBaojiPricingConfig); pvpBaojiPricingConfigVO.setBaojiLevel(baojiLevel); return ResponsePacket.onSuccess(pvpBaojiPricingConfigVO); } @ApiOperation(value = "ๆŸฅ่ฏขๆšด้ธกๆฎตไฝ็š„่ฎกไปท้…็ฝฎ") @Override public ResponsePacket<List<PVPBaojiGameDanIncomeVO>> getBaojiGameDanIncome( @ApiParam(value = "ๆŸฅ่ฏขๅ‚ๆ•ฐ", required = true) @RequestBody BaojiPricingConfigParams baojiPricingConfigParams) { ValidateAssert.allNotNull(BizExceptionEnum.PARAM_VALID_FAIL, baojiPricingConfigParams); List<PVPBaojiGameDanIncomeVO> baojiGameDanIncomeList = pvpBaojiPricingConfigService .getBaojiGameDanIncome(baojiPricingConfigParams); return ResponsePacket.onSuccess(baojiGameDanIncomeList); } private PVPBaojiPricingConfigVO bulidPVPBaojiPricingConfigVO( PVPBaojiPricingConfig pvpBaojiPricingConfig) { PVPBaojiPricingConfigVO pricingConfigVO = BeanMapper .map(pvpBaojiPricingConfig, PVPBaojiPricingConfigVO.class); pricingConfigVO.setBaojiPricingConfigId(pvpBaojiPricingConfig.getId()); // ๆธธๆˆ if (pvpBaojiPricingConfig.getGameId() != 0) { DictBaseVO<GameDictVO> gameDict = dictionaryDictManager .buildDictBase(pvpBaojiPricingConfig.getGameId(), GameDictVO.class); pricingConfigVO.setGame(gameDict.getValue()); } // ๆฎตไฝ if (pvpBaojiPricingConfig.getBossGameDanId() != 0) { DictBaseVO<DanDictVo> danDict = dictionaryDictManager .buildDictBase(pvpBaojiPricingConfig.getBossGameDanId(), DanDictVo.class); pricingConfigVO.setGameDan(danDict.getValue()); } return pricingConfigVO; } }
UTF-8
Java
5,213
java
PVPBaojiPricingConfigController.java
Java
[ { "context": "notation.RestController;\n\n/**\n * ๆšด้ธก่ฎกไปท้…็ฝฎ\n * @author liangyi\n */\n@RestController\n@RequestMapping(\"/baoji/prici", "end": 1612, "score": 0.9844545722007751, "start": 1605, "tag": "USERNAME", "value": "liangyi" } ]
null
[]
package com.kaihei.esportingplus.resource.controller; import com.kaihei.esportingplus.api.enums.DictionaryCategoryCodeEnum; import com.kaihei.esportingplus.api.feign.PVPBaojiPricingConfigServiceClient; import com.kaihei.esportingplus.api.params.BaojiPricingConfigParams; import com.kaihei.esportingplus.api.vo.DictBaseVO; import com.kaihei.esportingplus.api.vo.GameDictVO; import com.kaihei.esportingplus.api.vo.PVPBaojiGameDanIncomeVO; import com.kaihei.esportingplus.api.vo.PVPBaojiPricingConfigVO; import com.kaihei.esportingplus.api.vo.freeteam.DanDictVo; import com.kaihei.esportingplus.common.BeanMapper; import com.kaihei.esportingplus.common.ResponsePacket; import com.kaihei.esportingplus.common.ValidateAssert; import com.kaihei.esportingplus.common.enums.BizExceptionEnum; import com.kaihei.esportingplus.resource.data.manager.impl.DictionaryDictManager; import com.kaihei.esportingplus.resource.data.repository.PVPBaojiPricingConfigRepository; import com.kaihei.esportingplus.resource.domain.entity.Dictionary; import com.kaihei.esportingplus.resource.domain.entity.PVPBaojiPricingConfig; import com.kaihei.esportingplus.resource.domain.service.PVPBaojiPricingConfigService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * ๆšด้ธก่ฎกไปท้…็ฝฎ * @author liangyi */ @RestController @RequestMapping("/baoji/pricing/config") @Api(tags = {"ๆšด้ธก่ฎกไปท้…็ฝฎ"}) public class PVPBaojiPricingConfigController implements PVPBaojiPricingConfigServiceClient { @Autowired DictionaryDictManager dictionaryDictManager; @Autowired PVPBaojiPricingConfigRepository pvpBaojiPricingConfigRepository; @Autowired PVPBaojiPricingConfigService pvpBaojiPricingConfigService; @ApiOperation(value = "ๆŸฅ่ฏขๅ•ไธช่ฏฆ็ป†็š„ๆšด้ธก่ฎกไปท้…็ฝฎ") @Override public ResponsePacket<PVPBaojiPricingConfigVO> getBaojiPricingConfigDetail( @ApiParam(value = "ๆŸฅ่ฏขๅ‚ๆ•ฐ", required = true) @RequestBody BaojiPricingConfigParams baojiPricingConfigParams) { ValidateAssert.allNotNull(BizExceptionEnum.PARAM_VALID_FAIL, baojiPricingConfigParams); PVPBaojiPricingConfig pricingConfig = BeanMapper .map(baojiPricingConfigParams, PVPBaojiPricingConfig.class); // ๆ นๆฎๆšด้ธก็ญ‰็บง code ๆŸฅ่ฏขๅ‡บๆšด้ธก็ญ‰็บง id Dictionary baojiLevelDict = dictionaryDictManager.findByCodeAndCategoryCode( String.valueOf(baojiPricingConfigParams.getBaojiLevelCodeList().get(0)), DictionaryCategoryCodeEnum.BAOJI_LEVEL.getCode()); DictBaseVO baojiLevel = BeanMapper.map(baojiLevelDict, DictBaseVO.class); pricingConfig.setBaojiLevelId(baojiLevel.getDictId()); pricingConfig.setBossGameDanId(baojiPricingConfigParams.getBossGameDanIdList().get(0)); // ๅชๆŸฅ่ฏขๅฏ็”จ็š„ pricingConfig.setStatus((byte)1); PVPBaojiPricingConfig pvpBaojiPricingConfig = pvpBaojiPricingConfigRepository .selectOne(pricingConfig); PVPBaojiPricingConfigVO pvpBaojiPricingConfigVO = bulidPVPBaojiPricingConfigVO( pvpBaojiPricingConfig); pvpBaojiPricingConfigVO.setBaojiLevel(baojiLevel); return ResponsePacket.onSuccess(pvpBaojiPricingConfigVO); } @ApiOperation(value = "ๆŸฅ่ฏขๆšด้ธกๆฎตไฝ็š„่ฎกไปท้…็ฝฎ") @Override public ResponsePacket<List<PVPBaojiGameDanIncomeVO>> getBaojiGameDanIncome( @ApiParam(value = "ๆŸฅ่ฏขๅ‚ๆ•ฐ", required = true) @RequestBody BaojiPricingConfigParams baojiPricingConfigParams) { ValidateAssert.allNotNull(BizExceptionEnum.PARAM_VALID_FAIL, baojiPricingConfigParams); List<PVPBaojiGameDanIncomeVO> baojiGameDanIncomeList = pvpBaojiPricingConfigService .getBaojiGameDanIncome(baojiPricingConfigParams); return ResponsePacket.onSuccess(baojiGameDanIncomeList); } private PVPBaojiPricingConfigVO bulidPVPBaojiPricingConfigVO( PVPBaojiPricingConfig pvpBaojiPricingConfig) { PVPBaojiPricingConfigVO pricingConfigVO = BeanMapper .map(pvpBaojiPricingConfig, PVPBaojiPricingConfigVO.class); pricingConfigVO.setBaojiPricingConfigId(pvpBaojiPricingConfig.getId()); // ๆธธๆˆ if (pvpBaojiPricingConfig.getGameId() != 0) { DictBaseVO<GameDictVO> gameDict = dictionaryDictManager .buildDictBase(pvpBaojiPricingConfig.getGameId(), GameDictVO.class); pricingConfigVO.setGame(gameDict.getValue()); } // ๆฎตไฝ if (pvpBaojiPricingConfig.getBossGameDanId() != 0) { DictBaseVO<DanDictVo> danDict = dictionaryDictManager .buildDictBase(pvpBaojiPricingConfig.getBossGameDanId(), DanDictVo.class); pricingConfigVO.setGameDan(danDict.getValue()); } return pricingConfigVO; } }
5,213
0.767868
0.766883
112
44.348213
31.310003
95
false
false
0
0
0
0
0
0
0.535714
false
false
10
f48360afbb264cb80114d52264f2eaf279456267
9,302,899,220,713
b414b2891703f7ee85fc72ec54ff9ef2b74c73cd
/tools-dao/src/main/java/com/gialen/tools/dao/repository/gialenMain/RomaStoreMapper.java
46d1f2d4b9b10d118de8f07d940f77e4e649b01f
[]
no_license
jack0liang/gialen-tools
https://github.com/jack0liang/gialen-tools
42781afe1ae94e8bed5eae6a25f00bb34be148dc
65df080c1e28730139e58cfbd4e146ad981f8b8a
refs/heads/master
2023-02-08T01:56:41.990000
2020-11-12T03:40:48
2020-11-12T03:40:48
325,214,152
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gialen.tools.dao.repository.gialenMain; import com.gialen.tools.dao.entity.gialen.RomaStore; import com.gialen.tools.dao.entity.gialen.RomaStoreExample; import org.apache.ibatis.annotations.Param; import java.util.List; @org.springframework.stereotype.Repository("mainRomaStoreMapper") public interface RomaStoreMapper { int batchUpdateStore(List<RomaStore> storeList); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table roma_store * * @mbg.generated */ long countByExample(RomaStoreExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table roma_store * * @mbg.generated */ int deleteByExample(RomaStoreExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table roma_store * * @mbg.generated */ int deleteByPrimaryKey(Integer storeId); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table roma_store * * @mbg.generated */ int insert(RomaStore record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table roma_store * * @mbg.generated */ int insertSelective(RomaStore record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table roma_store * * @mbg.generated */ List<RomaStore> selectByExample(RomaStoreExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table roma_store * * @mbg.generated */ RomaStore selectByPrimaryKey(Integer storeId); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table roma_store * * @mbg.generated */ int updateByExampleSelective(@Param("record") RomaStore record, @Param("example") RomaStoreExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table roma_store * * @mbg.generated */ int updateByExample(@Param("record") RomaStore record, @Param("example") RomaStoreExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table roma_store * * @mbg.generated */ int updateByPrimaryKeySelective(RomaStore record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table roma_store * * @mbg.generated */ int updateByPrimaryKey(RomaStore record); }
UTF-8
Java
2,862
java
RomaStoreMapper.java
Java
[]
null
[]
package com.gialen.tools.dao.repository.gialenMain; import com.gialen.tools.dao.entity.gialen.RomaStore; import com.gialen.tools.dao.entity.gialen.RomaStoreExample; import org.apache.ibatis.annotations.Param; import java.util.List; @org.springframework.stereotype.Repository("mainRomaStoreMapper") public interface RomaStoreMapper { int batchUpdateStore(List<RomaStore> storeList); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table roma_store * * @mbg.generated */ long countByExample(RomaStoreExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table roma_store * * @mbg.generated */ int deleteByExample(RomaStoreExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table roma_store * * @mbg.generated */ int deleteByPrimaryKey(Integer storeId); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table roma_store * * @mbg.generated */ int insert(RomaStore record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table roma_store * * @mbg.generated */ int insertSelective(RomaStore record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table roma_store * * @mbg.generated */ List<RomaStore> selectByExample(RomaStoreExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table roma_store * * @mbg.generated */ RomaStore selectByPrimaryKey(Integer storeId); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table roma_store * * @mbg.generated */ int updateByExampleSelective(@Param("record") RomaStore record, @Param("example") RomaStoreExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table roma_store * * @mbg.generated */ int updateByExample(@Param("record") RomaStore record, @Param("example") RomaStoreExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table roma_store * * @mbg.generated */ int updateByPrimaryKeySelective(RomaStore record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table roma_store * * @mbg.generated */ int updateByPrimaryKey(RomaStore record); }
2,862
0.67645
0.67645
101
27.346535
26.318851
112
false
false
0
0
0
0
0
0
0.188119
false
false
10
637395db61a73086177bb5aafe38d8d2cde3a945
18,365,280,192,970
b929e551143a3cda07ce27ab2bb12f4a37513d9c
/servers/BuildTools/work/decompile-ad891a5c/net/minecraft/server/BehaviorNop.java
635c931a7cc0fd139613e7a179c636e0b36967d3
[]
no_license
viniciusaportela/minecraft-kotlin-plugin
https://github.com/viniciusaportela/minecraft-kotlin-plugin
452b3aa81d57cab1ac33936ce6a1271bc515f0f0
d45bcd38e2759a62eb33575c27763783fec62ced
refs/heads/master
2022-03-25T21:35:16.322000
2019-11-27T13:03:18
2019-11-27T13:03:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.minecraft.server; import com.google.common.collect.ImmutableSet; import com.mojang.datafixers.util.Pair; import java.util.Set; public class BehaviorNop extends Behavior<EntityLiving> { public BehaviorNop(int i, int j) { super(i, j); } @Override protected boolean g(WorldServer worldserver, EntityLiving entityliving, long i) { return true; } @Override protected Set<Pair<MemoryModuleType<?>, MemoryStatus>> a() { return ImmutableSet.of(); } }
UTF-8
Java
516
java
BehaviorNop.java
Java
[]
null
[]
package net.minecraft.server; import com.google.common.collect.ImmutableSet; import com.mojang.datafixers.util.Pair; import java.util.Set; public class BehaviorNop extends Behavior<EntityLiving> { public BehaviorNop(int i, int j) { super(i, j); } @Override protected boolean g(WorldServer worldserver, EntityLiving entityliving, long i) { return true; } @Override protected Set<Pair<MemoryModuleType<?>, MemoryStatus>> a() { return ImmutableSet.of(); } }
516
0.687984
0.687984
22
22.454546
23.494152
85
false
false
0
0
0
0
0
0
0.545455
false
false
10
4ed682e112e19699428831e6c3ab67f5dfd7ffd9
19,774,029,443,218
9379cf746f5aac4317665c86881116efd1ab21ae
/winter I.Y java/src/day_33_CollectionsMaps/collections01.java
8fdbd44263bfa3c53b1d1e1973f4b6713789e1db
[]
no_license
islmy/mygitpro
https://github.com/islmy/mygitpro
e5a18623484282a6066c4fa47af215d54b6e0317
4b8d02ab0fa7790bd1177886490400d6e874ed95
refs/heads/master
2023-07-13T09:08:13.370000
2021-08-30T13:31:53
2021-08-30T13:31:53
401,026,583
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package day_33_CollectionsMaps; public class collections01 { }
UTF-8
Java
65
java
collections01.java
Java
[]
null
[]
package day_33_CollectionsMaps; public class collections01 { }
65
0.784615
0.723077
5
12
14.324803
31
false
false
0
0
0
0
0
0
0.2
false
false
10
64f3d9fd88521cc020b4e3f31b0ec6b60d94111a
20,375,324,864,558
f1725b7592f404fcafa6760fcf574fb1f5d668dc
/src/model/dao/UserBeanHibernateDAO.java
0de47c1f12660899eb9507a0762962b8700d34d0
[]
no_license
JackyLin0/meetingnote
https://github.com/JackyLin0/meetingnote
99a9fb5de079255b5e2669823b8f32518af67a9a
e99c78c480226a73dd15dba4fe8122f272c2eef3
refs/heads/master
2021-09-02T14:24:35.685000
2018-01-03T06:29:41
2018-01-03T06:29:41
96,760,052
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package model.dao; import java.util.LinkedList; import java.util.List; import org.hibernate.Hibernate; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.sql.ordering.antlr.Factory; import model.UserBean; import model.Interface.IDAO; import model.misc.HibernateUtil; public class UserBeanHibernateDAO implements IDAO<UserBean> { public static Session session; public static SessionFactory factory; public static Transaction trx; public static void main(String[] args) { test(); System.out.println("test"); } private static void test() { factory = HibernateUtil.getSessionFactory(); session = factory.getCurrentSession(); UserBeanHibernateDAO dao = new UserBeanHibernateDAO(factory); // insert try { trx = dao.getSession().beginTransaction(); UserBean bean = new UserBean(); bean.setId(0); bean.setUser("Jacky"); bean.setPasswd("123456"); bean.setChineseName("ๆž—ๅฝฅไบจ"); bean.setEmail("Goerge@gmail.com"); UserBean insert = dao.insert(bean); System.out.println("insert" + insert); trx.commit(); } catch (Exception e) { for (StackTraceElement s : e.getStackTrace()) System.out.println(s.toString()); System.out.println(e.getMessage()); } /* update */ try { session = factory.getCurrentSession(); trx = dao.getSession().beginTransaction(); UserBean bean = new UserBean(); bean.setId(3); bean.setUser("Jacky"); bean.setPasswd("654321"); bean.setEmail("lhm0531@gmail.com"); UserBean update = dao.update(bean); System.out.println("update" + update); trx.commit(); } catch (Exception e) { } // Select try { session = factory.getCurrentSession(); trx = session.beginTransaction(); List<UserBean> select = dao.select(); System.out.println("select" + select); trx.commit(); } catch (Exception e) { } /* * delete try { session = factory.getCurrentSession(); trx = * dao.getSession().beginTransaction(); Boolean delete = dao.delete(5); * System.out.println("delete" + delete); trx.commit(); } catch (Exception e) { * } */ } public UserBeanHibernateDAO(SessionFactory factory) { this.factory = factory; } @Override public UserBean select(UserBean bean) { if (bean != null) { bean = this.getSession().get(UserBean.class, bean.getId()); } return bean; } @Override public UserBean select(int id) { return this.getSession().get(UserBean.class, id); } @Override public List<UserBean> select() { return this.getSession().createQuery("from UserBean", UserBean.class).getResultList(); } @Override public UserBean insert(UserBean bean) { UserBean tmp = select(bean); if (tmp == null) { this.getSession().save(bean); System.out.println("tmp bean" + tmp); } return bean; } @Override public Boolean delete(UserBean bean) { UserBean tmp = select(bean.getId()); if (tmp != null) { return delete(bean.getId()); } else { return false; } } @Override public Boolean delete(int id) { UserBean temp = select(id); if (temp != null) { this.getSession().delete(temp); return true; } else { return false; } } @Override public UserBean update(UserBean bean) { UserBean tmp = select(bean.getId()); if (tmp != null) { tmp.setId(bean.getId()); tmp.setUser(bean.getUser()); tmp.setPasswd(bean.getPasswd()); tmp.setEmail(bean.getEmail()); } return tmp; } @Override public Session getSession() { return factory.getCurrentSession(); } }
UTF-8
Java
3,549
java
UserBeanHibernateDAO.java
Java
[ { "context": "ew UserBean();\n\t\t\tbean.setId(0);\n\t\t\tbean.setUser(\"Jacky\");\n\t\t\tbean.setPasswd(\"123456\");\n\t\t\tbean.setChines", "end": 917, "score": 0.7595272064208984, "start": 912, "tag": "NAME", "value": "Jacky" }, { "context": "(0);\n\t\t\tbean.setUser(\"Jacky\");\n\t\t\tbean.setPasswd(\"123456\");\n\t\t\tbean.setChineseName(\"ๆž—ๅฝฅไบจ\");\n\t\t\tbean.setEmai", "end": 946, "score": 0.9993612766265869, "start": 940, "tag": "PASSWORD", "value": "123456" }, { "context": "bean.setPasswd(\"123456\");\n\t\t\tbean.setChineseName(\"ๆž—ๅฝฅไบจ\");\n\t\t\tbean.setEmail(\"Goerge@gmail.com\");\n\t\t\tUserB", "end": 977, "score": 0.9998350143432617, "start": 974, "tag": "NAME", "value": "ๆž—ๅฝฅไบจ" }, { "context": "\n\t\t\tbean.setChineseName(\"ๆž—ๅฝฅไบจ\");\n\t\t\tbean.setEmail(\"Goerge@gmail.com\");\n\t\t\tUserBean insert = dao.insert(bean);\n\t\t\tSyst", "end": 1015, "score": 0.9999200701713562, "start": 999, "tag": "EMAIL", "value": "Goerge@gmail.com" }, { "context": "ew UserBean();\n\t\t\tbean.setId(3);\n\t\t\tbean.setUser(\"Jacky\");\n\t\t\tbean.setPasswd(\"654321\");\n\t\t\t\n\t\t\tbean.setE", "end": 1459, "score": 0.9524996876716614, "start": 1455, "tag": "USERNAME", "value": "Jack" }, { "context": "serBean();\n\t\t\tbean.setId(3);\n\t\t\tbean.setUser(\"Jacky\");\n\t\t\tbean.setPasswd(\"654321\");\n\t\t\t\n\t\t\tbean.setEm", "end": 1460, "score": 0.966230571269989, "start": 1459, "tag": "NAME", "value": "y" }, { "context": "(3);\n\t\t\tbean.setUser(\"Jacky\");\n\t\t\tbean.setPasswd(\"654321\");\n\t\t\t\n\t\t\tbean.setEmail(\"lhm0531@gmail.com\");\n\t\t\t", "end": 1489, "score": 0.9993874430656433, "start": 1483, "tag": "PASSWORD", "value": "654321" }, { "context": "\t\tbean.setPasswd(\"654321\");\n\t\t\t\n\t\t\tbean.setEmail(\"lhm0531@gmail.com\");\n\t\t\tUserBean update = dao.update(bean);\n\t\t\tSyst", "end": 1532, "score": 0.9999233484268188, "start": 1515, "tag": "EMAIL", "value": "lhm0531@gmail.com" }, { "context": "\n\t\t\ttmp.setUser(bean.getUser());\n\t\t\ttmp.setPasswd(bean.getPasswd());\n\t\t\ttmp.setEmail(bean.getEmail());\n\t\t}\n\t\tretur", "end": 3396, "score": 0.9904931783676147, "start": 3382, "tag": "PASSWORD", "value": "bean.getPasswd" } ]
null
[]
package model.dao; import java.util.LinkedList; import java.util.List; import org.hibernate.Hibernate; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.sql.ordering.antlr.Factory; import model.UserBean; import model.Interface.IDAO; import model.misc.HibernateUtil; public class UserBeanHibernateDAO implements IDAO<UserBean> { public static Session session; public static SessionFactory factory; public static Transaction trx; public static void main(String[] args) { test(); System.out.println("test"); } private static void test() { factory = HibernateUtil.getSessionFactory(); session = factory.getCurrentSession(); UserBeanHibernateDAO dao = new UserBeanHibernateDAO(factory); // insert try { trx = dao.getSession().beginTransaction(); UserBean bean = new UserBean(); bean.setId(0); bean.setUser("Jacky"); bean.setPasswd("<PASSWORD>"); bean.setChineseName("ๆž—ๅฝฅไบจ"); bean.setEmail("<EMAIL>"); UserBean insert = dao.insert(bean); System.out.println("insert" + insert); trx.commit(); } catch (Exception e) { for (StackTraceElement s : e.getStackTrace()) System.out.println(s.toString()); System.out.println(e.getMessage()); } /* update */ try { session = factory.getCurrentSession(); trx = dao.getSession().beginTransaction(); UserBean bean = new UserBean(); bean.setId(3); bean.setUser("Jacky"); bean.setPasswd("<PASSWORD>"); bean.setEmail("<EMAIL>"); UserBean update = dao.update(bean); System.out.println("update" + update); trx.commit(); } catch (Exception e) { } // Select try { session = factory.getCurrentSession(); trx = session.beginTransaction(); List<UserBean> select = dao.select(); System.out.println("select" + select); trx.commit(); } catch (Exception e) { } /* * delete try { session = factory.getCurrentSession(); trx = * dao.getSession().beginTransaction(); Boolean delete = dao.delete(5); * System.out.println("delete" + delete); trx.commit(); } catch (Exception e) { * } */ } public UserBeanHibernateDAO(SessionFactory factory) { this.factory = factory; } @Override public UserBean select(UserBean bean) { if (bean != null) { bean = this.getSession().get(UserBean.class, bean.getId()); } return bean; } @Override public UserBean select(int id) { return this.getSession().get(UserBean.class, id); } @Override public List<UserBean> select() { return this.getSession().createQuery("from UserBean", UserBean.class).getResultList(); } @Override public UserBean insert(UserBean bean) { UserBean tmp = select(bean); if (tmp == null) { this.getSession().save(bean); System.out.println("tmp bean" + tmp); } return bean; } @Override public Boolean delete(UserBean bean) { UserBean tmp = select(bean.getId()); if (tmp != null) { return delete(bean.getId()); } else { return false; } } @Override public Boolean delete(int id) { UserBean temp = select(id); if (temp != null) { this.getSession().delete(temp); return true; } else { return false; } } @Override public UserBean update(UserBean bean) { UserBean tmp = select(bean.getId()); if (tmp != null) { tmp.setId(bean.getId()); tmp.setUser(bean.getUser()); tmp.setPasswd(<PASSWORD>()); tmp.setEmail(bean.getEmail()); } return tmp; } @Override public Session getSession() { return factory.getCurrentSession(); } }
3,534
0.676263
0.6709
159
21.283018
18.732857
88
false
false
0
0
0
0
0
0
2.069182
false
false
10
38fe568719a2792ce1a75168fd8a96df800a3ca8
2,070,174,300,471
af8669e2096aadcfb21827fd5273a5bec2025136
/taotao-manger/taotao-manger-web/src/test/java/com/taotao/controller/testPagecontroller.java
4a01c6e2d2fc47a496d6c2dfe1a5bff772b3b529
[]
no_license
storm520/workspace
https://github.com/storm520/workspace
9ab786a076a27a15fc1ec59bf7af3b7abc92dd79
0faddfa76819ee67efc86bca2804d6fc48813e7c
refs/heads/master
2021-01-23T00:33:58.624000
2017-05-30T09:29:27
2017-05-30T09:29:27
92,816,637
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.taotao.controller; import java.util.List; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.taotao.mapper.TbItemMapper; import com.taotao.pojo.TbItem; import com.taotao.pojo.TbItemExample; public class testPagecontroller { @Test public void testPageHelper(){ //ๅˆ›ๅปบไธ€ไธชspringๅฎนๅ™จ ApplicationContext applicationContext =new ClassPathXmlApplicationContext("classpath:spring/applicationContext-*.xml"); //ไปŽspringๅฎนๅ™จไธญ่Žทๅพ—mapperไปฃ็†ๅฏน่ฑก TbItemMapper mapper = applicationContext.getBean(TbItemMapper.class); //ๆ‰ง่กŒๆŸฅ่ฏข๏ผŒๅนถๅˆ†้กต TbItemExample example =new TbItemExample(); //ๅˆ†้กตๅค„็† PageHelper.startPage(1, 10); List<TbItem> list = mapper.selectByExample(example); //ๅ–ๅ‡บๅ•†ๅ“ๅˆ—่กจ for (TbItem tbItem : list) { System.out.println(tbItem.getTitle()); } //ๅ–ๅ‡บๅˆ†้กตๆ€ปๆ•ฐ PageInfo<TbItem> pageinfo =new PageInfo<>(list); long total = pageinfo.getTotal(); System.out.println("ไฟกๆฏๆ€ปๅ…ฑๆœ‰:"+total); } }
UTF-8
Java
1,172
java
testPagecontroller.java
Java
[]
null
[]
package com.taotao.controller; import java.util.List; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.taotao.mapper.TbItemMapper; import com.taotao.pojo.TbItem; import com.taotao.pojo.TbItemExample; public class testPagecontroller { @Test public void testPageHelper(){ //ๅˆ›ๅปบไธ€ไธชspringๅฎนๅ™จ ApplicationContext applicationContext =new ClassPathXmlApplicationContext("classpath:spring/applicationContext-*.xml"); //ไปŽspringๅฎนๅ™จไธญ่Žทๅพ—mapperไปฃ็†ๅฏน่ฑก TbItemMapper mapper = applicationContext.getBean(TbItemMapper.class); //ๆ‰ง่กŒๆŸฅ่ฏข๏ผŒๅนถๅˆ†้กต TbItemExample example =new TbItemExample(); //ๅˆ†้กตๅค„็† PageHelper.startPage(1, 10); List<TbItem> list = mapper.selectByExample(example); //ๅ–ๅ‡บๅ•†ๅ“ๅˆ—่กจ for (TbItem tbItem : list) { System.out.println(tbItem.getTitle()); } //ๅ–ๅ‡บๅˆ†้กตๆ€ปๆ•ฐ PageInfo<TbItem> pageinfo =new PageInfo<>(list); long total = pageinfo.getTotal(); System.out.println("ไฟกๆฏๆ€ปๅ…ฑๆœ‰:"+total); } }
1,172
0.788355
0.785582
40
26.049999
21.780668
79
false
false
0
0
0
0
0
0
1.1
false
false
10
5f369bf925199fb49160cfa52206c0e2eee1b77f
27,032,524,190,752
71f6aa44bb47478172cde61f42c1ba00d69adf66
/ChatClient/src/main/java/edu/ucsd/cse110/client/Gui/GuiApplication.java
44fd23244f3d48136a84db6ec8c80dda341ceada
[]
no_license
UCSD-CSE110-TEAM3/Chat-App
https://github.com/UCSD-CSE110-TEAM3/Chat-App
5c826711d409c61e1fcfb5ae4507713a70186f5e
0222ce45ba49f215c560b2b35612181a8eda6409
refs/heads/master
2016-09-06T14:23:24.186000
2013-12-06T19:14:33
2013-12-06T19:14:33
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.ucsd.cse110.client.Gui; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import edu.ucsd.cse110.client.Gui.MainWindow.*; import javax.swing.JFrame; import Commands.*; public class GuiApplication implements CommandHandler{ private LoginWindow loginWindow; // Login Window for User private MainWindow mainWindow; // Main Window for loggedOnUser public static GuiApplication instance = new GuiApplication(); private Controller controller = Controller.getInstance(); // We will import a list of Windows here for chatrooms private GuiApplication() { } public static GuiApplication getInstance() { if (instance == null) { instance = new GuiApplication(); } return instance; } /* * Only method accessible by an executable file * * Run declares a new loginWindow. For the user to make */ public void run() { loginWindow = new LoginWindow(); loginWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); loginWindow.setSize(300, 600); loginWindow.setVisible(true); } public void attemptLogin() { if (mainWindow == null) loadMainWindow(); } private void loadMainWindow() { loginWindow.dispose(); loginWindow = null; mainWindow = new MainWindow(); mainWindow.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e ){ controller.sendCommand(new LogoutCommand()); } }); mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainWindow.setSize(600, 600); mainWindow.setVisible(true); } public void logOut() { mainWindow.dispose(); mainWindow = null; loginWindow = new LoginWindow(); loginWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); loginWindow.setSize(300, 600); loginWindow.setVisible(true); } public void receiveLogon(LoginCommand command){ if(command.getStatus()){ if(loginWindow != null && mainWindow == null) attemptLogin(); else { mainWindow.addUser(command.getUsername()); mainWindow.displayBroadcast( command.getUsername() + " has logged on." ); } }else{ if(loginWindow != null) loginWindow.notifyFailLogin(command.getLogMessage()); } } public void receiveWhisper(WhisperCommand command) { if(mainWindow != null){ mainWindow.redirectWhisper(command.getReceiver(), command.getMessage()); } return; } public void receiveBroadcast(BroadcastCommand command) { if(mainWindow != null){ mainWindow.displayBroadcast(command.getMessage()); } } public void recieveRegisterResponse(RegisterCommand command) { if(command.getStatus() == false){ loginWindow.notifyFailLogin(command.getLog()); }else{ loginWindow.notifyFailLogin("Your account is now registered"); } } public void receiveUsers(CheckUsersCommand command) { if(mainWindow != null) { mainWindow.addUser(command.getUsers()); } } public void sendCommand(Commands command) { // TODO Auto-generated method stub } public void recieveCommand(Commands command) { if (command == null) { return; } switch (command.getType()) { case Commands.LOGIN: receiveLogon((LoginCommand)command); break; case Commands.LOGOUT: this.receiveLogout((LogoutCommand)command); break; case Commands.WHISPER: this.receiveWhisper((WhisperCommand)command); break; case Commands.BROADCAST: this.receiveBroadcast((BroadcastCommand)command); break; case Commands.REGISTER: this.recieveRegisterResponse((RegisterCommand)command);; break; case Commands.CHECKUSERS: this.receiveUsers((CheckUsersCommand)command); break; } } private void receiveLogout(LogoutCommand command) { if(command.getStatus()){ this.logOut(); }else{ if(mainWindow != null) mainWindow.removeUser(command.getUser()); mainWindow.displayBroadcast( command.getUser() + " has logged out." ); } } }
UTF-8
Java
4,017
java
GuiApplication.java
Java
[]
null
[]
package edu.ucsd.cse110.client.Gui; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import edu.ucsd.cse110.client.Gui.MainWindow.*; import javax.swing.JFrame; import Commands.*; public class GuiApplication implements CommandHandler{ private LoginWindow loginWindow; // Login Window for User private MainWindow mainWindow; // Main Window for loggedOnUser public static GuiApplication instance = new GuiApplication(); private Controller controller = Controller.getInstance(); // We will import a list of Windows here for chatrooms private GuiApplication() { } public static GuiApplication getInstance() { if (instance == null) { instance = new GuiApplication(); } return instance; } /* * Only method accessible by an executable file * * Run declares a new loginWindow. For the user to make */ public void run() { loginWindow = new LoginWindow(); loginWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); loginWindow.setSize(300, 600); loginWindow.setVisible(true); } public void attemptLogin() { if (mainWindow == null) loadMainWindow(); } private void loadMainWindow() { loginWindow.dispose(); loginWindow = null; mainWindow = new MainWindow(); mainWindow.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e ){ controller.sendCommand(new LogoutCommand()); } }); mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainWindow.setSize(600, 600); mainWindow.setVisible(true); } public void logOut() { mainWindow.dispose(); mainWindow = null; loginWindow = new LoginWindow(); loginWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); loginWindow.setSize(300, 600); loginWindow.setVisible(true); } public void receiveLogon(LoginCommand command){ if(command.getStatus()){ if(loginWindow != null && mainWindow == null) attemptLogin(); else { mainWindow.addUser(command.getUsername()); mainWindow.displayBroadcast( command.getUsername() + " has logged on." ); } }else{ if(loginWindow != null) loginWindow.notifyFailLogin(command.getLogMessage()); } } public void receiveWhisper(WhisperCommand command) { if(mainWindow != null){ mainWindow.redirectWhisper(command.getReceiver(), command.getMessage()); } return; } public void receiveBroadcast(BroadcastCommand command) { if(mainWindow != null){ mainWindow.displayBroadcast(command.getMessage()); } } public void recieveRegisterResponse(RegisterCommand command) { if(command.getStatus() == false){ loginWindow.notifyFailLogin(command.getLog()); }else{ loginWindow.notifyFailLogin("Your account is now registered"); } } public void receiveUsers(CheckUsersCommand command) { if(mainWindow != null) { mainWindow.addUser(command.getUsers()); } } public void sendCommand(Commands command) { // TODO Auto-generated method stub } public void recieveCommand(Commands command) { if (command == null) { return; } switch (command.getType()) { case Commands.LOGIN: receiveLogon((LoginCommand)command); break; case Commands.LOGOUT: this.receiveLogout((LogoutCommand)command); break; case Commands.WHISPER: this.receiveWhisper((WhisperCommand)command); break; case Commands.BROADCAST: this.receiveBroadcast((BroadcastCommand)command); break; case Commands.REGISTER: this.recieveRegisterResponse((RegisterCommand)command);; break; case Commands.CHECKUSERS: this.receiveUsers((CheckUsersCommand)command); break; } } private void receiveLogout(LogoutCommand command) { if(command.getStatus()){ this.logOut(); }else{ if(mainWindow != null) mainWindow.removeUser(command.getUser()); mainWindow.displayBroadcast( command.getUser() + " has logged out." ); } } }
4,017
0.689818
0.683844
159
23.264151
21.735243
78
false
false
0
0
0
0
0
0
1.937107
false
false
10
01aa7c77c5706ee349a03b015771ed2d9ff0fb54
10,917,806,900,580
16290e76de6270f0d6ec6070a63c80b401c64ea5
/core/src/test/java/com/github/dockerjava/core/util/FiltersEncoderTest.java
353133ae1485687750c14f8af027aa157c8fd21f
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
HaMatthias/testcontainers-java
https://github.com/HaMatthias/testcontainers-java
d2a4d2b1ac884e753fdc7f66358d207e07bb218b
9fd8398220fcfba36f5099be3cef340cb59c0fb9
refs/heads/master
2020-05-30T06:03:21.452000
2019-06-25T07:48:54
2019-06-25T07:48:54
189,571,323
1
0
MIT
true
2019-06-25T07:48:56
2019-05-31T09:55:32
2019-06-24T11:47:30
2019-06-25T07:48:54
3,151
1
0
0
Java
false
false
package com.github.dockerjava.core.util; import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.model.Image; import org.junit.Test; import org.rnorth.visibleassertions.VisibleAssertions; import org.testcontainers.DockerClientFactory; import java.util.List; import java.util.UUID; /** * This test checks that our custom monkey-patched version works * and does not throw {@link ClassNotFoundException}. */ public class FiltersEncoderTest { @Test public void filtersShouldWork() throws Exception { DockerClient client = DockerClientFactory.instance().client(); List<Image> images = client.listImagesCmd() .withLabelFilter("com.example=" + UUID.randomUUID().toString()) .exec(); VisibleAssertions.assertTrue("List is empty", images.isEmpty()); } }
UTF-8
Java
838
java
FiltersEncoderTest.java
Java
[]
null
[]
package com.github.dockerjava.core.util; import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.model.Image; import org.junit.Test; import org.rnorth.visibleassertions.VisibleAssertions; import org.testcontainers.DockerClientFactory; import java.util.List; import java.util.UUID; /** * This test checks that our custom monkey-patched version works * and does not throw {@link ClassNotFoundException}. */ public class FiltersEncoderTest { @Test public void filtersShouldWork() throws Exception { DockerClient client = DockerClientFactory.instance().client(); List<Image> images = client.listImagesCmd() .withLabelFilter("com.example=" + UUID.randomUUID().toString()) .exec(); VisibleAssertions.assertTrue("List is empty", images.isEmpty()); } }
838
0.73031
0.73031
28
28.928572
25.73065
75
false
false
0
0
0
0
0
0
0.428571
false
false
10
8329683f5d96ec9bd01ffe33c1302dff4df10577
24,532,853,230,809
035c71daac5252031a0935e22cfe0f63324d1b9f
/src/test/java/cucumberOptions/TestRunner.java
eb9af36057b583b2aa92c319768ce59956380f34
[]
no_license
madhus10/BRMAutomation
https://github.com/madhus10/BRMAutomation
c6f60e99a834883613093ac486ff217034943a0b
f5c1233d3808d17f34afe8ca29ca52243b53dcf4
refs/heads/master
2020-12-19T21:59:32.120000
2020-01-23T21:11:26
2020-01-23T21:11:26
235,864,990
0
0
null
false
2020-10-13T19:02:27
2020-01-23T19:00:30
2020-01-23T21:11:46
2020-10-13T19:02:26
64
0
0
1
JavaScript
false
false
package cucumberOptions; import org.junit.runner.RunWith; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; @RunWith(Cucumber.class) @CucumberOptions(features = "src/test/java/features", glue = "stepDefinations", tags = "@SeleniumTest",monochrome=true,strict=true, plugin = { "pretty", "html: target/cucumber", "json:target/cucumber.json", "junit:target/cukes.xml" }) public class TestRunner { }
UTF-8
Java
425
java
TestRunner.java
Java
[]
null
[]
package cucumberOptions; import org.junit.runner.RunWith; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; @RunWith(Cucumber.class) @CucumberOptions(features = "src/test/java/features", glue = "stepDefinations", tags = "@SeleniumTest",monochrome=true,strict=true, plugin = { "pretty", "html: target/cucumber", "json:target/cucumber.json", "junit:target/cukes.xml" }) public class TestRunner { }
425
0.762353
0.762353
13
31.692308
40.267155
142
false
false
0
0
0
0
0
0
1.076923
false
false
10
907e1c00dfc4485bd22a2f36dc88609250dcf598
24,532,853,231,054
df7966fdc0684a8d675efb555afeb055afa7a259
/concurrent/parseq/src/main/java/com/manfred/parseq/study/RetryExampleV2.java
b9a65718dafe384b2383a329f9e3f3d788d10c33
[ "Apache-2.0" ]
permissive
manfredma/exercises
https://github.com/manfredma/exercises
90760db34c33d6d38d92edf1377e54e8029bef72
f487ece7b0cd761e8afb14ae8be0b1b668f97d8c
refs/heads/master
2023-09-06T04:15:15.960000
2023-08-25T06:15:46
2023-08-25T06:15:46
176,470,365
3
0
null
false
2021-04-08T07:11:50
2019-03-19T09:07:26
2021-03-26T03:41:21
2021-04-08T07:11:49
3,033
0
0
0
Java
false
false
package com.manfred.parseq.study; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.linkedin.parseq.Engine; import com.linkedin.parseq.EngineBuilder; import com.linkedin.parseq.ParTask; import com.linkedin.parseq.Task; import com.linkedin.parseq.promise.Promises; import com.linkedin.parseq.promise.SettablePromise; import com.linkedin.parseq.retry.ErrorClassification; import com.linkedin.parseq.retry.RetryPolicy; import com.linkedin.parseq.retry.RetryPolicyBuilder; import com.linkedin.parseq.retry.termination.TerminationPolicy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.*; import java.util.function.Function; public class RetryExampleV2 { private static final List<Task> taskList = new ArrayList<>(); private static ExecutorService outPool = new ThreadPoolExecutor(20, 50, 0L, TimeUnit.MILLISECONDS, new SynchronousQueue<>(), new ThreadFactoryBuilder().setDaemon(false) .setNameFormat("out-%d") .build(), new AsyncCallerRunsPolicy()); private static final Logger LOGGER = LoggerFactory.getLogger(RetryExampleV2.class); private static int x = 1; public static void main(String[] args) throws IOException, InterruptedException { ExecutorService enginePool = new ThreadPoolExecutor(20, 50, 0L, TimeUnit.MILLISECONDS, new SynchronousQueue<>(), new ThreadFactoryBuilder().setDaemon(false) .setNameFormat("parseq-%d") .build(), new AsyncCallerRunsPolicy()); Engine engine = new EngineBuilder().setTaskExecutor(enginePool) .setTimerScheduler(Executors.newScheduledThreadPool(2)) .build(); Task task = createRetryTask(); engine.run(task, "xxx"); task.await(); engine.shutdown(); System.exit(0); } private static Task<Object> createAsyncTask(String desc, boolean isException) { Task<Object> task = Task.async("Task " + desc, () -> { SettablePromise<Object> promise = Promises.settable(); outPool.execute(() -> { LOGGER.info("id = {} ๅผ€ๅง‹ๅœจๅค–้ƒจ็บฟ็จ‹ๆฑ ๆ‰ง่กŒ", desc); if (isException) { promise.fail(new RuntimeException(desc)); } else { promise.done("Task " + desc + " result!!!"); } LOGGER.info("id = {} ๆ‰ง่กŒๅฎŒๆˆ", desc); }); return promise; }); taskList.add(task); return task; } private static Task createRetryTask() { Function<Throwable, ErrorClassification> errorClassifier = error -> error instanceof Exception ? ErrorClassification.RECOVERABLE : ErrorClassification.UNRECOVERABLE; RetryPolicy retryPolicy = new RetryPolicyBuilder() .setTerminationPolicy(TerminationPolicy.limitAttempts(20)) .setErrorClassifier(errorClassifier) .build(); Task<Object> re = Task.withRetryPolicy(retryPolicy, () -> { Task<Object> result = createAsyncTask("retry-" + x++ + "", true); return result; }).map("map-print-1", (x) -> { LOGGER.info("่พ“ๅ‡บไธ€ไธ‹็ป“ๆžœ, {}", x); return x; }); Task<Object> x2 = createAsyncTask("0", false).map("map-print-2", (x) -> { LOGGER.info("่พ“ๅ‡บไธ€ไธ‹็ป“ๆžœ, {}", x); return x; }); ParTask<Object> task = Task.par(Arrays.asList(re, x2)); taskList.add(task); return task; } public static class AsyncCallerRunsPolicy implements RejectedExecutionHandler { private static final Logger LOGGER = LoggerFactory.getLogger(AsyncCallerRunsPolicy.class); private static int i = 0; @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { LOGGER.error("ๅผ‚ๆญฅๆ‰ง่กŒ็บฟ็จ‹ๆฑ ไปปๅŠกๆ‰ง่กŒๅทฒ็ป่ขซๆ‰“ๆปก๏ผŒ่ฏทๆฃ€ๆŸฅๅฝ“ๅ‰้˜Ÿๅˆ—ไปปๅŠกๆ•ฐๆฎ็บฟ็จ‹ๆ•ฐๆฎๆƒ…ๅ†ตr={}, executor={}", r.toString(), executor.toString()); throw new RuntimeException("่ฎฟ้—ฎ้กต้ขๅคฑ่ดฅ๏ผŒ่ฏท้‡่ฏ• " + i++); } } }
UTF-8
Java
4,469
java
RetryExampleV2.java
Java
[]
null
[]
package com.manfred.parseq.study; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.linkedin.parseq.Engine; import com.linkedin.parseq.EngineBuilder; import com.linkedin.parseq.ParTask; import com.linkedin.parseq.Task; import com.linkedin.parseq.promise.Promises; import com.linkedin.parseq.promise.SettablePromise; import com.linkedin.parseq.retry.ErrorClassification; import com.linkedin.parseq.retry.RetryPolicy; import com.linkedin.parseq.retry.RetryPolicyBuilder; import com.linkedin.parseq.retry.termination.TerminationPolicy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.*; import java.util.function.Function; public class RetryExampleV2 { private static final List<Task> taskList = new ArrayList<>(); private static ExecutorService outPool = new ThreadPoolExecutor(20, 50, 0L, TimeUnit.MILLISECONDS, new SynchronousQueue<>(), new ThreadFactoryBuilder().setDaemon(false) .setNameFormat("out-%d") .build(), new AsyncCallerRunsPolicy()); private static final Logger LOGGER = LoggerFactory.getLogger(RetryExampleV2.class); private static int x = 1; public static void main(String[] args) throws IOException, InterruptedException { ExecutorService enginePool = new ThreadPoolExecutor(20, 50, 0L, TimeUnit.MILLISECONDS, new SynchronousQueue<>(), new ThreadFactoryBuilder().setDaemon(false) .setNameFormat("parseq-%d") .build(), new AsyncCallerRunsPolicy()); Engine engine = new EngineBuilder().setTaskExecutor(enginePool) .setTimerScheduler(Executors.newScheduledThreadPool(2)) .build(); Task task = createRetryTask(); engine.run(task, "xxx"); task.await(); engine.shutdown(); System.exit(0); } private static Task<Object> createAsyncTask(String desc, boolean isException) { Task<Object> task = Task.async("Task " + desc, () -> { SettablePromise<Object> promise = Promises.settable(); outPool.execute(() -> { LOGGER.info("id = {} ๅผ€ๅง‹ๅœจๅค–้ƒจ็บฟ็จ‹ๆฑ ๆ‰ง่กŒ", desc); if (isException) { promise.fail(new RuntimeException(desc)); } else { promise.done("Task " + desc + " result!!!"); } LOGGER.info("id = {} ๆ‰ง่กŒๅฎŒๆˆ", desc); }); return promise; }); taskList.add(task); return task; } private static Task createRetryTask() { Function<Throwable, ErrorClassification> errorClassifier = error -> error instanceof Exception ? ErrorClassification.RECOVERABLE : ErrorClassification.UNRECOVERABLE; RetryPolicy retryPolicy = new RetryPolicyBuilder() .setTerminationPolicy(TerminationPolicy.limitAttempts(20)) .setErrorClassifier(errorClassifier) .build(); Task<Object> re = Task.withRetryPolicy(retryPolicy, () -> { Task<Object> result = createAsyncTask("retry-" + x++ + "", true); return result; }).map("map-print-1", (x) -> { LOGGER.info("่พ“ๅ‡บไธ€ไธ‹็ป“ๆžœ, {}", x); return x; }); Task<Object> x2 = createAsyncTask("0", false).map("map-print-2", (x) -> { LOGGER.info("่พ“ๅ‡บไธ€ไธ‹็ป“ๆžœ, {}", x); return x; }); ParTask<Object> task = Task.par(Arrays.asList(re, x2)); taskList.add(task); return task; } public static class AsyncCallerRunsPolicy implements RejectedExecutionHandler { private static final Logger LOGGER = LoggerFactory.getLogger(AsyncCallerRunsPolicy.class); private static int i = 0; @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { LOGGER.error("ๅผ‚ๆญฅๆ‰ง่กŒ็บฟ็จ‹ๆฑ ไปปๅŠกๆ‰ง่กŒๅทฒ็ป่ขซๆ‰“ๆปก๏ผŒ่ฏทๆฃ€ๆŸฅๅฝ“ๅ‰้˜Ÿๅˆ—ไปปๅŠกๆ•ฐๆฎ็บฟ็จ‹ๆ•ฐๆฎๆƒ…ๅ†ตr={}, executor={}", r.toString(), executor.toString()); throw new RuntimeException("่ฎฟ้—ฎ้กต้ขๅคฑ่ดฅ๏ผŒ่ฏท้‡่ฏ• " + i++); } } }
4,469
0.616309
0.610534
114
36.973682
27.848103
99
false
false
0
0
0
0
0
0
0.798246
false
false
10
278071e34cf15f507a1dde799163bf29ba1d6495
14,328,010,913,576
354dd01622bf7a928fb007d38992e8f457192898
/Assignment6/src/HuffmanTree.java
4b5e8548562960180dda1922b95fce0e749025a2
[]
no_license
chenyf0328/SJU_AlgorithmCourseProject
https://github.com/chenyf0328/SJU_AlgorithmCourseProject
c3fdeecebc6c18f1daea2e9ba842c38d46263c2e
d37340727eb49f30526263bf00da460d8c85e8c0
refs/heads/master
2020-03-23T15:55:12.252000
2018-07-21T05:02:02
2018-07-21T05:02:02
141,782,689
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.ArrayList; import java.util.List; import java.util.PriorityQueue; public class HuffmanTree<E> { private Node<E> root; private double totalWeight; private ArrayList<Node<E>> records = new ArrayList<>(); private ArrayList<Node<E>> weplRecords = new ArrayList<>(); public Node<E> getRoot() { return root; } public ArrayList<Node<E>> getWeplRecords() { return weplRecords; } public ArrayList<Node<E>> getRecords() { return records; } public HuffmanTree(int n, E[] ch, int[] f){ root = huff(n, ch, f); // calculate total weight for (int iter: f){ totalWeight += iter; } code(root); wepl(root, 0); } public Node<E> huff(int n, E[] ch, int[] f){ PriorityQueue<Node<E>> pq = new PriorityQueue<>(); for (Node<E> iter: generateList(ch, f)) pq.add(iter); while (pq.size()>1) { Node<E> left = pq.poll(); Node<E> right = pq.poll(); Node<E> parent = new Node<E>(ch[ch.length-1], left.getWeight() + right.getWeight()); parent.setLeft(left); parent.setRight(right); left.setCode("0"); right.setCode("1"); pq.add(parent); } return pq.peek(); } private List<Node<E>> generateList(E[] ch, int[] f){ List<Node<E>> nodeList = new ArrayList<>(); for (int i=0;i<ch.length-1;i++) nodeList.add(new Node(ch[i],f[i])); return nodeList; } public void printTree(){ BTreePrinter bTreePrinter=new BTreePrinter(); bTreePrinter.printNode(root); System.out.print(bTreePrinter.getString()); } public void code(Node<E> root){ if (root.getLeft()==null && root.getRight()==null){ // // Test // System.out.println(root.getData()+": "+root.getHcode()); records.add(root); return; } root.getLeft().setHcode(root.getHcode()+root.getLeft().getCode()); code(root.getLeft()); root.getRight().setHcode(root.getHcode()+root.getRight().getCode()); code(root.getRight()); } public void wepl(Node<E> root, int pathLength){ if (root.getLeft()==null && root.getRight()==null){ root.setPathLength(pathLength); root.setWeightedAvg(root.getWeight()/totalWeight); root.setSavingAvg(root.getHcode().length()/16.0); // assume the fixed length of binary code is 16 weplRecords.add(root); return; } pathLength++; wepl(root.getLeft(), pathLength); wepl(root.getRight(), pathLength); } }
UTF-8
Java
2,752
java
HuffmanTree.java
Java
[]
null
[]
import java.util.ArrayList; import java.util.List; import java.util.PriorityQueue; public class HuffmanTree<E> { private Node<E> root; private double totalWeight; private ArrayList<Node<E>> records = new ArrayList<>(); private ArrayList<Node<E>> weplRecords = new ArrayList<>(); public Node<E> getRoot() { return root; } public ArrayList<Node<E>> getWeplRecords() { return weplRecords; } public ArrayList<Node<E>> getRecords() { return records; } public HuffmanTree(int n, E[] ch, int[] f){ root = huff(n, ch, f); // calculate total weight for (int iter: f){ totalWeight += iter; } code(root); wepl(root, 0); } public Node<E> huff(int n, E[] ch, int[] f){ PriorityQueue<Node<E>> pq = new PriorityQueue<>(); for (Node<E> iter: generateList(ch, f)) pq.add(iter); while (pq.size()>1) { Node<E> left = pq.poll(); Node<E> right = pq.poll(); Node<E> parent = new Node<E>(ch[ch.length-1], left.getWeight() + right.getWeight()); parent.setLeft(left); parent.setRight(right); left.setCode("0"); right.setCode("1"); pq.add(parent); } return pq.peek(); } private List<Node<E>> generateList(E[] ch, int[] f){ List<Node<E>> nodeList = new ArrayList<>(); for (int i=0;i<ch.length-1;i++) nodeList.add(new Node(ch[i],f[i])); return nodeList; } public void printTree(){ BTreePrinter bTreePrinter=new BTreePrinter(); bTreePrinter.printNode(root); System.out.print(bTreePrinter.getString()); } public void code(Node<E> root){ if (root.getLeft()==null && root.getRight()==null){ // // Test // System.out.println(root.getData()+": "+root.getHcode()); records.add(root); return; } root.getLeft().setHcode(root.getHcode()+root.getLeft().getCode()); code(root.getLeft()); root.getRight().setHcode(root.getHcode()+root.getRight().getCode()); code(root.getRight()); } public void wepl(Node<E> root, int pathLength){ if (root.getLeft()==null && root.getRight()==null){ root.setPathLength(pathLength); root.setWeightedAvg(root.getWeight()/totalWeight); root.setSavingAvg(root.getHcode().length()/16.0); // assume the fixed length of binary code is 16 weplRecords.add(root); return; } pathLength++; wepl(root.getLeft(), pathLength); wepl(root.getRight(), pathLength); } }
2,752
0.547238
0.542878
101
26.247524
23.987375
125
false
false
0
0
0
0
0
0
0.613861
false
false
10
154a270437cad8fe5b60988de566abbda17638b6
31,147,102,844,829
1f16fb39cb014b573aabb5d52fa42ecee2cce1fb
/src/jp/co/minori/eclipse/bytecodeviewer/views/ByteCodeView.java
32fef0b7cefaf693b902b7d55ba50aa36670e646
[ "Apache-2.0" ]
permissive
crow-misia/ByteCodeViewer
https://github.com/crow-misia/ByteCodeViewer
6d1ce20c27b59d037a5a83b1c80d41a175fcbaa0
6e95de1feab2f62f3c2a0c34b92bea67741c8b0a
refs/heads/master
2020-05-17T03:35:45.916000
2013-02-07T03:22:35
2013-02-07T03:22:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ package jp.co.minori.eclipse.bytecodeviewer.views; import org.eclipse.core.resources.IFile; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.ToolFactory; import org.eclipse.jdt.core.util.ClassFileBytesDisassembler; import org.eclipse.jdt.core.util.ClassFormatException; import org.eclipse.jdt.internal.ui.javaeditor.ClassFileEditor; import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.part.ViewPart; /** * This sample class demonstrates how to plug-in a new * workbench view. The view shows data obtained from the * model. The sample creates a dummy model on the fly, * but a real implementation would connect to the model * available either in this or another plug-in (e.g. the workspace). * The view is connected to the model using a content provider. * <p> * The view uses a label provider to define how model * objects should be presented in the view. Each * view can present the same model objects using * different labels and icons, if needed. Alternatively, * a single label provider can be shared between views * in order to ensure that objects of the same type are * presented in the same way everywhere. * <p> */ @SuppressWarnings("restriction") public class ByteCodeView extends ViewPart implements ILinkedWithEditorView { /** * The ID of the view as specified by the extension. */ public static final String ID = "jp.co.minori.eclipse.bytecodeviewer.views.ByteCodeView"; private LinkWithEditorPartListener linkWithEditorPartListener = new LinkWithEditorPartListener(this); private Text text; /** * The constructor. */ public ByteCodeView() { } /** * This is a callback that will allow us * to create the viewer and initialize it. */ public void createPartControl(final Composite parent) { text = new Text(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL); text.setEditable(false); getSite().getPage().addPartListener(linkWithEditorPartListener); } public void editorActivated(final IEditorPart activeEditor) { change(activeEditor); } private void change(final IEditorPart activeEditor) { // Javaใ‚จใƒ‡ใ‚ฃใ‚ฟ ไปฅๅค–ใฏ็„ก่ฆ– if (!(activeEditor instanceof CompilationUnitEditor)) { return; } final IFileEditorInput editorInput = ((IFileEditorInput)activeEditor.getEditorInput()); final IFile resource = editorInput.getFile(); final IClassFile classfile = JdtUtils.getByteCodePath(resource); try { final byte[] bytes = classfile.getBytes(); final ClassFileBytesDisassembler disassembler = ToolFactory.createDefaultClassFileBytesDisassembler(); text.setText(disassembler.disassemble(bytes, "\n", ClassFileBytesDisassembler.DETAILED)); } catch (final ClassFormatException e) { text.setText(e.getMessage()); } catch (final JavaModelException e) { text.setText(e.getMessage()); } } /** * Passing the focus request to the viewer's control. */ public void setFocus() { text.setFocus(); } }
UTF-8
Java
4,131
java
ByteCodeView.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 jp.co.minori.eclipse.bytecodeviewer.views; import org.eclipse.core.resources.IFile; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.ToolFactory; import org.eclipse.jdt.core.util.ClassFileBytesDisassembler; import org.eclipse.jdt.core.util.ClassFormatException; import org.eclipse.jdt.internal.ui.javaeditor.ClassFileEditor; import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.part.ViewPart; /** * This sample class demonstrates how to plug-in a new * workbench view. The view shows data obtained from the * model. The sample creates a dummy model on the fly, * but a real implementation would connect to the model * available either in this or another plug-in (e.g. the workspace). * The view is connected to the model using a content provider. * <p> * The view uses a label provider to define how model * objects should be presented in the view. Each * view can present the same model objects using * different labels and icons, if needed. Alternatively, * a single label provider can be shared between views * in order to ensure that objects of the same type are * presented in the same way everywhere. * <p> */ @SuppressWarnings("restriction") public class ByteCodeView extends ViewPart implements ILinkedWithEditorView { /** * The ID of the view as specified by the extension. */ public static final String ID = "jp.co.minori.eclipse.bytecodeviewer.views.ByteCodeView"; private LinkWithEditorPartListener linkWithEditorPartListener = new LinkWithEditorPartListener(this); private Text text; /** * The constructor. */ public ByteCodeView() { } /** * This is a callback that will allow us * to create the viewer and initialize it. */ public void createPartControl(final Composite parent) { text = new Text(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL); text.setEditable(false); getSite().getPage().addPartListener(linkWithEditorPartListener); } public void editorActivated(final IEditorPart activeEditor) { change(activeEditor); } private void change(final IEditorPart activeEditor) { // Javaใ‚จใƒ‡ใ‚ฃใ‚ฟ ไปฅๅค–ใฏ็„ก่ฆ– if (!(activeEditor instanceof CompilationUnitEditor)) { return; } final IFileEditorInput editorInput = ((IFileEditorInput)activeEditor.getEditorInput()); final IFile resource = editorInput.getFile(); final IClassFile classfile = JdtUtils.getByteCodePath(resource); try { final byte[] bytes = classfile.getBytes(); final ClassFileBytesDisassembler disassembler = ToolFactory.createDefaultClassFileBytesDisassembler(); text.setText(disassembler.disassemble(bytes, "\n", ClassFileBytesDisassembler.DETAILED)); } catch (final ClassFormatException e) { text.setText(e.getMessage()); } catch (final JavaModelException e) { text.setText(e.getMessage()); } } /** * Passing the focus request to the viewer's control. */ public void setFocus() { text.setFocus(); } }
4,131
0.736689
0.735716
114
35.087719
28.854919
105
false
false
0
0
0
0
69
0.033552
1.061404
false
false
10
ee8e0c94d8754c58eca02c6505e2c7b2fdb6f61a
7,017,976,625,470
186365bca9d385728122e5b8abda6df31a120e86
/ProjectX/src/com/bj4/yhh/projectx/lot/blot/BLotAddOrMinusFragment.java
803792d4f0e857b3f44b364701daab4d102678da
[]
no_license
s011208/ProjectX
https://github.com/s011208/ProjectX
80b43fb0b04bf5c630fc2cce50c9aedc974a2482
5b5fffe2b4e73d9bc1b07d445382cde7e413694b
refs/heads/master
2020-04-06T03:53:31.360000
2014-12-18T05:05:57
2014-12-18T05:05:57
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bj4.yhh.projectx.lot.blot; import com.bj4.yhh.projectx.lot.AddOrMinusFragment; import com.bj4.yhh.projectx.lot.LotteryData; public class BLotAddOrMinusFragment extends AddOrMinusFragment { public static BLotAddOrMinusFragment getNewInstance() { BLotAddOrMinusFragment fragment = new BLotAddOrMinusFragment(); return fragment; } @Override public int getGameType() { return LotteryData.TYPE_BLOT; } }
UTF-8
Java
459
java
BLotAddOrMinusFragment.java
Java
[]
null
[]
package com.bj4.yhh.projectx.lot.blot; import com.bj4.yhh.projectx.lot.AddOrMinusFragment; import com.bj4.yhh.projectx.lot.LotteryData; public class BLotAddOrMinusFragment extends AddOrMinusFragment { public static BLotAddOrMinusFragment getNewInstance() { BLotAddOrMinusFragment fragment = new BLotAddOrMinusFragment(); return fragment; } @Override public int getGameType() { return LotteryData.TYPE_BLOT; } }
459
0.740741
0.734205
18
24.555555
24.506739
71
false
false
0
0
0
0
0
0
0.333333
false
false
10
bbc26fd6dccd7b78253045a6de6e9d5d87863e19
21,122,649,175,575
15640aa6cc7bc5c1ca835d22f0d3ae5fa4fdf8d6
/Extenso.java
5e34ca8a57e6f50125d33961d1e9b0a134c2bb15
[]
no_license
RicardoBarradas/java-code
https://github.com/RicardoBarradas/java-code
4b9974a7b869aa12d514fc768e27c25d5ba1dc46
dc1f87d0033c31873c1b8e5d5ab689ac93eecb47
refs/heads/master
2020-04-26T10:59:21.697000
2019-03-27T17:04:44
2019-03-27T17:04:44
173,501,700
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Extenso.java - Classe para "traduzir" inteiros cardinais para a sua notaรงรฃo por extenso. * -------------------------------------------------------------------------------------------- * Ex: para o input String "1212", o output String deverรก ser "mil duzentos e doze". * * Versรฃo 6 - 02/03/2019 - neste momento recebe inteiros compostos por atรฉ 66 algarismos. * Versรฃo 7 - 19/03/2019 - Acrescentado constructor overloaded para receber "varargs"; * - recebe um objecto tipo String[] e devolve um objecto do mesmo tipo * - melhorias no cรณdigo * - comentรกrios ao longo da classe * */ import java.math.BigInteger; /* Apenas para efeitos de teste - comment out no ficheiro principal. class teste{ public static void main(String[] arg) { System.out.println(Extenso.extenso("323")); System.out.println(); String[] teste = new String[3]; String[] teste2 = new String[3]; String[] teste3 = new String[7]; teste[0] = "333"; teste[1] = "444"; teste[2] = "555"; teste2 = Extenso.extenso(teste); System.out.println(teste2[0]); System.out.println(teste2[1]); System.out.println(teste2[2]); System.out.println(); teste3 = Extenso.extenso("125", "32", "-45", "0", "", "fdf", "343"); for(int i =0; i < 7; i++ ) System.out.println(teste3[i]); } } */ public class Extenso { /* Mรฉtodo "de entrada": * Por aqui passam todos os inputs, quer directos, quer vindos de outros mรฉtodos "overloaded". * Este mรฉtodo verifica a informaรงรฃo recebida e encaminha os pedidos para o mรฉtodo "triagemInicial". * (ou entรฃo rejeita o pedido, devolvendo uma mensagem de alerta...) */ public static String extenso(String inputVal) { if(inputVal.isEmpty()) return "Foi passada uma express\u00E3o vazia."; boolean isNeg = false; if (inputVal.startsWith("-")) { isNeg = true; inputVal = inputVal.substring(1); } // Caรงar caracteres nรฃo permitidos: char[] diagS = inputVal.toCharArray(); for (char algarismo : diagS) { if (!Character.isDigit(algarismo)) { return "A express\u00E3o cont\u00E9m caracteres n\u00E3o num\u00E9ricos."; } } // Chamada ao mรฉtodo central de triagem da grandeza e seguimento do fluxo: return (isNeg ? "menos " : "") + triagemInicial(inputVal); } /* Mรฉtodo "Overloaded" - permite a passagem de vรกrios argumentos sequenciais, * em alternativa a apenas um argumento. Ex: extenso("3232", "433", "", "-232". "0") * Tambรฉm permite receber directamente um Array do tipo String. * Devolve um Array do tipo String com o extenso de cada valor passado como argumento. */ public static String[] extenso(String... inputVal) { String[] retVal2 = new String[inputVal.length]; for(int i = 0; i < inputVal.length; i++ ){ retVal2[i] = extenso(inputVal[i]); } return retVal2; } private static String triagemInicial(String i) { String valorFinal; BigInteger inputVal = new BigInteger(i); // Determinar se รฉ maior ou menor que 1 milhรฃo if (inputVal.compareTo(BigInteger.valueOf(1_000_000)) < 0) { int inputValNum = Integer.parseInt(i); if (inputValNum < 20) { valorFinal = deZeroaDezanove(inputValNum); } else if (inputValNum <= 100) { valorFinal = menorQueCem(inputValNum); } else if (inputValNum <= 1000) { valorFinal = menorQueMil(inputValNum); } else { // <1_000_000 valorFinal = menorQueUmMilhao(inputValNum); } } else { // >= 1_000_000 BigInteger milhaoComparador = new BigInteger("1" + "000000"); BigInteger iterador = inputVal; int tamanhoGrandeza = 0; String extensoGrandeza = "1"; while (iterador.compareTo(milhaoComparador) >= 0) { tamanhoGrandeza += 1; extensoGrandeza += "000000"; iterador = iterador.divide(milhaoComparador); } String preExt; switch (tamanhoGrandeza) { case 1: // < 1_000_000_000_000, menor do que 1 Biliรฃo preExt = "milh"; break; case 2: // < 1_000_000_000_000_000_000, menor do que 1 Triliรฃo preExt = "bili"; break; case 3: // < 1_000_000_000_000_000_000, menor do que 1 Quatriliรฃo preExt = "trili"; break; case 4: // < 1 Quintiliรฃo .... preExt = "quatrili"; break; case 5: // < 1 Sextiliรฃo preExt = "quintili"; break; case 6: // < 1 Setptiliรฃo preExt = "sextili"; break; case 7: // < 1 Octiliรฃo preExt = "septili"; break; case 8: // < 1 Noniliรฃo preExt = "octili"; break; case 9: // < 1 Deciliรฃo preExt = "nonili"; break; case 10: // < 1 Undeciliรฃo preExt = "decili"; break; // Acrescentar aqui novas grandezas... default: preExt = "nulo"; } valorFinal = (preExt != "nulo" ? metodoMilionario(inputVal.toString(), preExt, extensoGrandeza) : "Inteiro demasiado grande - ainda n\u00E3o suportado."); } return valorFinal; } private static String deZeroaDezanove(int i) { String valorFinal; switch (i) { case 0: valorFinal = "zero"; break; case 1: valorFinal = "um"; break; case 2: valorFinal = "dois"; break; case 3: valorFinal = "tr\u00EAs"; break; case 4: valorFinal = "quatro"; break; case 5: valorFinal = "cinco"; break; case 6: valorFinal = "seis"; break; case 7: valorFinal = "sete"; break; case 8: valorFinal = "oito"; break; case 9: valorFinal = "nove"; break; case 10: valorFinal = "dez"; break; case 11: valorFinal = "onze"; break; case 12: valorFinal = "doze"; break; case 13: valorFinal = "treze"; break; case 14: valorFinal = "catorze"; break; case 15: valorFinal = "quinze"; break; case 16: valorFinal = "dezasseis"; break; case 17: valorFinal = "dezassete"; break; case 18: valorFinal = "dezoito"; break; case 19: valorFinal = "dezanove"; break; default: valorFinal = "BUG eating method deZeroaVinte"; } return valorFinal; } private static String menorQueCem(int i) { String valorFinal; if (i % 10 == 0) { valorFinal = deVinteaNoventaeNove(i); } else { valorFinal = deVinteaNoventaeNove(i - (i % 10)) + " e " + deZeroaDezanove(i % 10); } return valorFinal; } private static String deVinteaNoventaeNove(int i) { String valorFinal; switch (i) { case 20: valorFinal = "vinte"; break; case 30: valorFinal = "trinta"; break; case 40: valorFinal = "quarenta"; break; case 50: valorFinal = "cinquenta"; break; case 60: valorFinal = "sessenta"; break; case 70: valorFinal = "setenta"; break; case 80: valorFinal = "oitenta"; break; case 90: valorFinal = "noventa"; break; case 100: valorFinal = "cem"; break; default: valorFinal = "A BUG is chewing method deVinteaNoventaeNove"; } return valorFinal; } private static String menorQueMil(int i) { String valorFinal; if (i % 100 == 0) valorFinal = deCemaNoveNoveNove(i); else if (i < 200) valorFinal = "cento e " + triagemInicial(String.valueOf(i % 100)); else valorFinal = deCemaNoveNoveNove(i - i % 100) + " e " + triagemInicial(String.valueOf(i % 100)); return valorFinal; } private static String deCemaNoveNoveNove(int i) { String valorFinal; switch (i) { case 200: valorFinal = "duzentos"; break; case 300: valorFinal = "trezentos"; break; case 400: valorFinal = "quatrocentos"; break; case 500: valorFinal = "quinhentos"; break; case 600: valorFinal = "seiscentos"; break; case 700: valorFinal = "setecentos"; break; case 800: valorFinal = "oitocentos"; break; case 900: valorFinal = "novecentos"; break; case 1000: valorFinal = "mil"; break; default: valorFinal = "A BUG is chewing method deCemaNoveNoveNove"; } return valorFinal; } private static String menorQueUmMilhao(int i) { String valorFinal; if (i % 1000 == 0) { valorFinal = triagemInicial(String.valueOf(i / 1000)) + " mil"; } else if (i % 1000 <= 100 || ((i % 1000) % 100) == 0) { if (i / 1000 == 1) { valorFinal = "mil e " + triagemInicial(String.valueOf(i % 1000)); } else { valorFinal = triagemInicial(String.valueOf(i / 1000)) + " mil e " + triagemInicial(String.valueOf(i % 1000)); } } else { if (i / 1000 == 1) { valorFinal = "mil " + triagemInicial(String.valueOf(i % 1000)); } else { valorFinal = triagemInicial(String.valueOf(i / 1000)) + " mil " + triagemInicial(String.valueOf(i % 1000)); } } return valorFinal; } private static String metodoMilionario(String i, String preExt, String grand) { BigInteger grandeza = new BigInteger(grand); String singular = preExt + "\u00E3o", plural = preExt + "\u00F5es"; String valorFinal; BigInteger inputVal = new BigInteger(i); BigInteger i2 = inputVal.divide(grandeza); BigInteger i3 = inputVal.mod(grandeza); if (i3.compareTo(BigInteger.valueOf(0)) == 0) { if (inputVal.compareTo(grandeza) == 0) { valorFinal = "um " + singular; } else { inputVal = inputVal.divide(grandeza); valorFinal = triagemInicial(inputVal.toString()) + " " + plural; } } else if (levaE(i)) { if (i2.compareTo(BigInteger.valueOf(1)) == 0) { valorFinal = "um " + singular + " e " + triagemInicial(i3.toString()); } else { valorFinal = triagemInicial(i2.toString()) + " " + plural + " e " + triagemInicial(i3.toString()); } } else { if (i2.compareTo(BigInteger.valueOf(1)) == 0) { valorFinal = "um " + singular + ", " + triagemInicial(i3.toString()); } else { valorFinal = triagemInicial(i2.toString()) + " " + plural + ", " + triagemInicial(i3.toString()); } } return valorFinal; } private static boolean levaE(String grandeza) { /* Mรฉtodo para verificar a necessidade de * utilizaรงรฃo de um "e" logo apรณs a grandeza maior do inteiro. * Este mรฉtodo รฉ chamado unicamente a partir do mรฉtodo "metodoMilionario". * Exs: * 1.000.001 = "um milhรฃo e um" (verifica as condiรงรตes) - devolve TRUE * 1.000.200 = "um milhรฃo e duzentos" (verifica as condiรงรตes) - devolve TRUE * 1.200.000 = "um milhรฃo e duzentos mil" (verifica as condiรงรตes) - devolve TRUE * 1.000.101 = "um milhรฃo, cento e um" (NรƒO verifica as condiรงรตes - logo a seguir a milhรฃo, leva uma vรญrgula) - devolve FALSE */ boolean comE; BigInteger grandezaA = new BigInteger(grandeza); BigInteger grandezaB = new BigInteger(grandeza); int powerVal = 0; while (grandezaB.compareTo(BigInteger.valueOf(1_000_000)) >= 0) { grandezaB = grandezaB.divide(BigInteger.valueOf(1_000_000)); powerVal++; } BigInteger resto; BigInteger comparador = new BigInteger("1000000"); // Um milhรฃo comparador = comparador.pow(powerVal); resto = grandezaA.mod(comparador); // Teste Condiรงรฃo 1: Resto da grandeza a dividir pelo comparador รฉ menor ou igual a 100 (ex input: 1.0000.100) if (resto.compareTo(BigInteger.valueOf(100)) <= 0) { comE = true; return comE; } else { comE = false; } // Condiรงรฃo 2 BigInteger resto2; BigInteger comparador2; comparador2 = comparador.divide(BigInteger.valueOf(10)); for (BigInteger z = new BigInteger("100000"), x = new BigInteger("1000"); z.compareTo(comparador2) <= 0; z = z.multiply(BigInteger.valueOf(1_000)), x = x.multiply(BigInteger.valueOf(10))) { resto2 = resto.mod(x); if (resto.compareTo(z) <= 0 && resto2.compareTo(BigInteger.valueOf(0)) == 0) { comE = true; return comE; } else { comE = false; } } // Condiรงรฃo 3 BigInteger resto3; for (BigInteger w = new BigInteger("1000"), y = new BigInteger("100"); w.compareTo(comparador) <= 0; w = w.multiply(BigInteger.valueOf(1_000)), y = y.multiply(BigInteger.valueOf(1000))) { resto3 = resto.mod(y); if (resto.compareTo(w) <= 0 && resto3.compareTo(BigInteger.valueOf(0)) == 0) { comE = true; return comE; } else { comE = false; } } return comE; } }
UTF-8
Java
15,990
java
Extenso.java
Java
[ { "context": " case 16:\r\n valorFinal = \"dezasseis\";\r\n break;\r\n case 17:\r\n", "end": 7531, "score": 0.8250803351402283, "start": 7522, "tag": "NAME", "value": "dezasseis" } ]
null
[]
/* * Extenso.java - Classe para "traduzir" inteiros cardinais para a sua notaรงรฃo por extenso. * -------------------------------------------------------------------------------------------- * Ex: para o input String "1212", o output String deverรก ser "mil duzentos e doze". * * Versรฃo 6 - 02/03/2019 - neste momento recebe inteiros compostos por atรฉ 66 algarismos. * Versรฃo 7 - 19/03/2019 - Acrescentado constructor overloaded para receber "varargs"; * - recebe um objecto tipo String[] e devolve um objecto do mesmo tipo * - melhorias no cรณdigo * - comentรกrios ao longo da classe * */ import java.math.BigInteger; /* Apenas para efeitos de teste - comment out no ficheiro principal. class teste{ public static void main(String[] arg) { System.out.println(Extenso.extenso("323")); System.out.println(); String[] teste = new String[3]; String[] teste2 = new String[3]; String[] teste3 = new String[7]; teste[0] = "333"; teste[1] = "444"; teste[2] = "555"; teste2 = Extenso.extenso(teste); System.out.println(teste2[0]); System.out.println(teste2[1]); System.out.println(teste2[2]); System.out.println(); teste3 = Extenso.extenso("125", "32", "-45", "0", "", "fdf", "343"); for(int i =0; i < 7; i++ ) System.out.println(teste3[i]); } } */ public class Extenso { /* Mรฉtodo "de entrada": * Por aqui passam todos os inputs, quer directos, quer vindos de outros mรฉtodos "overloaded". * Este mรฉtodo verifica a informaรงรฃo recebida e encaminha os pedidos para o mรฉtodo "triagemInicial". * (ou entรฃo rejeita o pedido, devolvendo uma mensagem de alerta...) */ public static String extenso(String inputVal) { if(inputVal.isEmpty()) return "Foi passada uma express\u00E3o vazia."; boolean isNeg = false; if (inputVal.startsWith("-")) { isNeg = true; inputVal = inputVal.substring(1); } // Caรงar caracteres nรฃo permitidos: char[] diagS = inputVal.toCharArray(); for (char algarismo : diagS) { if (!Character.isDigit(algarismo)) { return "A express\u00E3o cont\u00E9m caracteres n\u00E3o num\u00E9ricos."; } } // Chamada ao mรฉtodo central de triagem da grandeza e seguimento do fluxo: return (isNeg ? "menos " : "") + triagemInicial(inputVal); } /* Mรฉtodo "Overloaded" - permite a passagem de vรกrios argumentos sequenciais, * em alternativa a apenas um argumento. Ex: extenso("3232", "433", "", "-232". "0") * Tambรฉm permite receber directamente um Array do tipo String. * Devolve um Array do tipo String com o extenso de cada valor passado como argumento. */ public static String[] extenso(String... inputVal) { String[] retVal2 = new String[inputVal.length]; for(int i = 0; i < inputVal.length; i++ ){ retVal2[i] = extenso(inputVal[i]); } return retVal2; } private static String triagemInicial(String i) { String valorFinal; BigInteger inputVal = new BigInteger(i); // Determinar se รฉ maior ou menor que 1 milhรฃo if (inputVal.compareTo(BigInteger.valueOf(1_000_000)) < 0) { int inputValNum = Integer.parseInt(i); if (inputValNum < 20) { valorFinal = deZeroaDezanove(inputValNum); } else if (inputValNum <= 100) { valorFinal = menorQueCem(inputValNum); } else if (inputValNum <= 1000) { valorFinal = menorQueMil(inputValNum); } else { // <1_000_000 valorFinal = menorQueUmMilhao(inputValNum); } } else { // >= 1_000_000 BigInteger milhaoComparador = new BigInteger("1" + "000000"); BigInteger iterador = inputVal; int tamanhoGrandeza = 0; String extensoGrandeza = "1"; while (iterador.compareTo(milhaoComparador) >= 0) { tamanhoGrandeza += 1; extensoGrandeza += "000000"; iterador = iterador.divide(milhaoComparador); } String preExt; switch (tamanhoGrandeza) { case 1: // < 1_000_000_000_000, menor do que 1 Biliรฃo preExt = "milh"; break; case 2: // < 1_000_000_000_000_000_000, menor do que 1 Triliรฃo preExt = "bili"; break; case 3: // < 1_000_000_000_000_000_000, menor do que 1 Quatriliรฃo preExt = "trili"; break; case 4: // < 1 Quintiliรฃo .... preExt = "quatrili"; break; case 5: // < 1 Sextiliรฃo preExt = "quintili"; break; case 6: // < 1 Setptiliรฃo preExt = "sextili"; break; case 7: // < 1 Octiliรฃo preExt = "septili"; break; case 8: // < 1 Noniliรฃo preExt = "octili"; break; case 9: // < 1 Deciliรฃo preExt = "nonili"; break; case 10: // < 1 Undeciliรฃo preExt = "decili"; break; // Acrescentar aqui novas grandezas... default: preExt = "nulo"; } valorFinal = (preExt != "nulo" ? metodoMilionario(inputVal.toString(), preExt, extensoGrandeza) : "Inteiro demasiado grande - ainda n\u00E3o suportado."); } return valorFinal; } private static String deZeroaDezanove(int i) { String valorFinal; switch (i) { case 0: valorFinal = "zero"; break; case 1: valorFinal = "um"; break; case 2: valorFinal = "dois"; break; case 3: valorFinal = "tr\u00EAs"; break; case 4: valorFinal = "quatro"; break; case 5: valorFinal = "cinco"; break; case 6: valorFinal = "seis"; break; case 7: valorFinal = "sete"; break; case 8: valorFinal = "oito"; break; case 9: valorFinal = "nove"; break; case 10: valorFinal = "dez"; break; case 11: valorFinal = "onze"; break; case 12: valorFinal = "doze"; break; case 13: valorFinal = "treze"; break; case 14: valorFinal = "catorze"; break; case 15: valorFinal = "quinze"; break; case 16: valorFinal = "dezasseis"; break; case 17: valorFinal = "dezassete"; break; case 18: valorFinal = "dezoito"; break; case 19: valorFinal = "dezanove"; break; default: valorFinal = "BUG eating method deZeroaVinte"; } return valorFinal; } private static String menorQueCem(int i) { String valorFinal; if (i % 10 == 0) { valorFinal = deVinteaNoventaeNove(i); } else { valorFinal = deVinteaNoventaeNove(i - (i % 10)) + " e " + deZeroaDezanove(i % 10); } return valorFinal; } private static String deVinteaNoventaeNove(int i) { String valorFinal; switch (i) { case 20: valorFinal = "vinte"; break; case 30: valorFinal = "trinta"; break; case 40: valorFinal = "quarenta"; break; case 50: valorFinal = "cinquenta"; break; case 60: valorFinal = "sessenta"; break; case 70: valorFinal = "setenta"; break; case 80: valorFinal = "oitenta"; break; case 90: valorFinal = "noventa"; break; case 100: valorFinal = "cem"; break; default: valorFinal = "A BUG is chewing method deVinteaNoventaeNove"; } return valorFinal; } private static String menorQueMil(int i) { String valorFinal; if (i % 100 == 0) valorFinal = deCemaNoveNoveNove(i); else if (i < 200) valorFinal = "cento e " + triagemInicial(String.valueOf(i % 100)); else valorFinal = deCemaNoveNoveNove(i - i % 100) + " e " + triagemInicial(String.valueOf(i % 100)); return valorFinal; } private static String deCemaNoveNoveNove(int i) { String valorFinal; switch (i) { case 200: valorFinal = "duzentos"; break; case 300: valorFinal = "trezentos"; break; case 400: valorFinal = "quatrocentos"; break; case 500: valorFinal = "quinhentos"; break; case 600: valorFinal = "seiscentos"; break; case 700: valorFinal = "setecentos"; break; case 800: valorFinal = "oitocentos"; break; case 900: valorFinal = "novecentos"; break; case 1000: valorFinal = "mil"; break; default: valorFinal = "A BUG is chewing method deCemaNoveNoveNove"; } return valorFinal; } private static String menorQueUmMilhao(int i) { String valorFinal; if (i % 1000 == 0) { valorFinal = triagemInicial(String.valueOf(i / 1000)) + " mil"; } else if (i % 1000 <= 100 || ((i % 1000) % 100) == 0) { if (i / 1000 == 1) { valorFinal = "mil e " + triagemInicial(String.valueOf(i % 1000)); } else { valorFinal = triagemInicial(String.valueOf(i / 1000)) + " mil e " + triagemInicial(String.valueOf(i % 1000)); } } else { if (i / 1000 == 1) { valorFinal = "mil " + triagemInicial(String.valueOf(i % 1000)); } else { valorFinal = triagemInicial(String.valueOf(i / 1000)) + " mil " + triagemInicial(String.valueOf(i % 1000)); } } return valorFinal; } private static String metodoMilionario(String i, String preExt, String grand) { BigInteger grandeza = new BigInteger(grand); String singular = preExt + "\u00E3o", plural = preExt + "\u00F5es"; String valorFinal; BigInteger inputVal = new BigInteger(i); BigInteger i2 = inputVal.divide(grandeza); BigInteger i3 = inputVal.mod(grandeza); if (i3.compareTo(BigInteger.valueOf(0)) == 0) { if (inputVal.compareTo(grandeza) == 0) { valorFinal = "um " + singular; } else { inputVal = inputVal.divide(grandeza); valorFinal = triagemInicial(inputVal.toString()) + " " + plural; } } else if (levaE(i)) { if (i2.compareTo(BigInteger.valueOf(1)) == 0) { valorFinal = "um " + singular + " e " + triagemInicial(i3.toString()); } else { valorFinal = triagemInicial(i2.toString()) + " " + plural + " e " + triagemInicial(i3.toString()); } } else { if (i2.compareTo(BigInteger.valueOf(1)) == 0) { valorFinal = "um " + singular + ", " + triagemInicial(i3.toString()); } else { valorFinal = triagemInicial(i2.toString()) + " " + plural + ", " + triagemInicial(i3.toString()); } } return valorFinal; } private static boolean levaE(String grandeza) { /* Mรฉtodo para verificar a necessidade de * utilizaรงรฃo de um "e" logo apรณs a grandeza maior do inteiro. * Este mรฉtodo รฉ chamado unicamente a partir do mรฉtodo "metodoMilionario". * Exs: * 1.000.001 = "um milhรฃo e um" (verifica as condiรงรตes) - devolve TRUE * 1.000.200 = "um milhรฃo e duzentos" (verifica as condiรงรตes) - devolve TRUE * 1.200.000 = "um milhรฃo e duzentos mil" (verifica as condiรงรตes) - devolve TRUE * 1.000.101 = "um milhรฃo, cento e um" (NรƒO verifica as condiรงรตes - logo a seguir a milhรฃo, leva uma vรญrgula) - devolve FALSE */ boolean comE; BigInteger grandezaA = new BigInteger(grandeza); BigInteger grandezaB = new BigInteger(grandeza); int powerVal = 0; while (grandezaB.compareTo(BigInteger.valueOf(1_000_000)) >= 0) { grandezaB = grandezaB.divide(BigInteger.valueOf(1_000_000)); powerVal++; } BigInteger resto; BigInteger comparador = new BigInteger("1000000"); // Um milhรฃo comparador = comparador.pow(powerVal); resto = grandezaA.mod(comparador); // Teste Condiรงรฃo 1: Resto da grandeza a dividir pelo comparador รฉ menor ou igual a 100 (ex input: 1.0000.100) if (resto.compareTo(BigInteger.valueOf(100)) <= 0) { comE = true; return comE; } else { comE = false; } // Condiรงรฃo 2 BigInteger resto2; BigInteger comparador2; comparador2 = comparador.divide(BigInteger.valueOf(10)); for (BigInteger z = new BigInteger("100000"), x = new BigInteger("1000"); z.compareTo(comparador2) <= 0; z = z.multiply(BigInteger.valueOf(1_000)), x = x.multiply(BigInteger.valueOf(10))) { resto2 = resto.mod(x); if (resto.compareTo(z) <= 0 && resto2.compareTo(BigInteger.valueOf(0)) == 0) { comE = true; return comE; } else { comE = false; } } // Condiรงรฃo 3 BigInteger resto3; for (BigInteger w = new BigInteger("1000"), y = new BigInteger("100"); w.compareTo(comparador) <= 0; w = w.multiply(BigInteger.valueOf(1_000)), y = y.multiply(BigInteger.valueOf(1000))) { resto3 = resto.mod(y); if (resto.compareTo(w) <= 0 && resto3.compareTo(BigInteger.valueOf(0)) == 0) { comE = true; return comE; } else { comE = false; } } return comE; } }
15,990
0.474666
0.441766
472
31.747881
26.695831
134
false
false
0
0
0
0
0
0
0.521186
false
false
10
549835481368fe33742fe01a643fe7a6c66b6d91
23,459,111,414,668
edfc534172ef479be8844eaf30aa499cf31b3b8d
/ged-crypto/src/main/java/fr/nimrod/info/crypto/certificats/CertificatProvider.java
8343b7f395378f2e03d60a48c9228b55b4cb676f
[]
no_license
primael/ged
https://github.com/primael/ged
5ef99b8c143866ba267a59b2ae1f08e16ae48b9e
a4c576828232b55bdedc956fd448f2dec70d78d8
refs/heads/master
2021-01-18T21:29:01.252000
2014-11-02T00:34:37
2014-11-02T00:34:37
23,472,697
0
0
null
false
2014-08-29T21:21:15
2014-08-29T17:54:06
2014-08-29T18:10:59
2014-08-29T21:19:49
0
0
0
0
Java
null
null
package fr.nimrod.info.crypto.certificats; import java.math.BigInteger; import java.security.KeyPair; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Date; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cert.X509v1CertificateBuilder; import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; import org.bouncycastle.cert.jcajce.JcaX509v1CertificateBuilder; import org.bouncycastle.operator.ContentSigner; import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; public enum CertificatProvider { INSTANCE; public Certificate createMasterCert(KeyPair keyPair) throws OperatorCreationException, CertificateException{ X509v1CertificateBuilder certificateBuilder = new JcaX509v1CertificateBuilder( // new X500Name("CN=Storage Certificate"), // BigInteger.valueOf(System.currentTimeMillis()), // Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()), // Date.from(LocalDateTime.parse("01/01/2100", DateTimeFormatter.ofPattern("dd/mm/YYYY")).atZone(ZoneId.systemDefault()).toInstant()), // new X500Name("CN=Storage Certificate"), // keyPair.getPublic()); JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder("SHA256withRSA"); ContentSigner contentSigner = contentSignerBuilder.build(keyPair.getPrivate()); X509CertificateHolder certificateHolder = certificateBuilder.build(contentSigner); JcaX509CertificateConverter certificateConverter = new JcaX509CertificateConverter(); return certificateConverter.getCertificate(certificateHolder); } }
UTF-8
Java
1,993
java
CertificatProvider.java
Java
[]
null
[]
package fr.nimrod.info.crypto.certificats; import java.math.BigInteger; import java.security.KeyPair; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Date; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cert.X509v1CertificateBuilder; import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; import org.bouncycastle.cert.jcajce.JcaX509v1CertificateBuilder; import org.bouncycastle.operator.ContentSigner; import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; public enum CertificatProvider { INSTANCE; public Certificate createMasterCert(KeyPair keyPair) throws OperatorCreationException, CertificateException{ X509v1CertificateBuilder certificateBuilder = new JcaX509v1CertificateBuilder( // new X500Name("CN=Storage Certificate"), // BigInteger.valueOf(System.currentTimeMillis()), // Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()), // Date.from(LocalDateTime.parse("01/01/2100", DateTimeFormatter.ofPattern("dd/mm/YYYY")).atZone(ZoneId.systemDefault()).toInstant()), // new X500Name("CN=Storage Certificate"), // keyPair.getPublic()); JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder("SHA256withRSA"); ContentSigner contentSigner = contentSignerBuilder.build(keyPair.getPrivate()); X509CertificateHolder certificateHolder = certificateBuilder.build(contentSigner); JcaX509CertificateConverter certificateConverter = new JcaX509CertificateConverter(); return certificateConverter.getCertificate(certificateHolder); } }
1,993
0.755645
0.728048
46
42.326088
35.673065
150
false
false
0
0
0
0
0
0
0.673913
false
false
10
2ed29170d51db6fcc3eae1e7968afa034834bc9b
20,590,073,225,979
b1c6b6fda9a40b9ae1d1811db13d90d6bb38bb1a
/.svn/pristine/45/45f0c4581c2246f832be55a725124b345b89678f.svn-base
0e1ec4f302e775ec82ec299815c26b36c01739e3
[]
no_license
feiniaoying/Inet
https://github.com/feiniaoying/Inet
e7ef42ca9578f463d11e0faca2308afa0804019e
5cb1918f7ba03024dc3b20aa32254abb2f3ec2fd
refs/heads/master
2016-06-06T20:48:56.142000
2016-03-05T14:50:58
2016-03-05T14:50:58
53,204,179
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.asiainfo.cs.qm.qualquery.bo; import java.sql.*; import com.ai.appframe2.bo.DataContainer; import com.ai.appframe2.common.DataContainerInterface; import com.ai.appframe2.common.AIException; import com.ai.appframe2.common.ServiceManager; import com.ai.appframe2.common.ObjectType; import com.ai.appframe2.common.DataType; import com.asiainfo.cs.qm.qualquery.ivalues.*; public class BOEdExamProcedureBean extends DataContainer implements DataContainerInterface,IBOEdExamProcedureValue{ private static String m_boName = "com.asiainfo.cs.qm.qualquery.bo.BOEdExamProcedure"; public final static String S_ExePoint = "EXE_POINT"; public final static String S_ExeFunction = "EXE_FUNCTION"; public final static String S_ProceduresName = "PROCEDURES_NAME"; public final static String S_FailPoint = "FAIL_POINT"; public final static String S_ProceduresInfo = "PROCEDURES_INFO"; public final static String S_BreakFunction = "BREAK_FUNCTION"; public final static String S_ProceduresExt = "PROCEDURES_EXT"; public final static String S_Reserve1 = "RESERVE1"; public final static String S_BreakPoint = "BREAK_POINT"; public final static String S_Reserve3 = "RESERVE3"; public final static String S_Reserve2 = "RESERVE2"; public final static String S_FailFunction = "FAIL_FUNCTION"; public final static String S_ProceduresId = "PROCEDURES_ID"; public static ObjectType S_TYPE = null; static{ try { S_TYPE = ServiceManager.getObjectTypeFactory().getInstance(m_boName); }catch(Exception e){ throw new RuntimeException(e); } } public BOEdExamProcedureBean() throws AIException{ super(S_TYPE); } public static ObjectType getObjectTypeStatic() throws AIException{ return S_TYPE; } public void setObjectType(ObjectType value) throws AIException{ //ๆญค็งๆ•ฐๆฎๅฎนๅ™จไธ่ƒฝ้‡็ฝฎไธšๅŠกๅฏน่ฑก็ฑปๅž‹ throw new AIException("Cannot reset ObjectType"); } public void initExePoint(String value){ this.initProperty(S_ExePoint,value); } public void setExePoint(String value){ this.set(S_ExePoint,value); } public void setExePointNull(){ this.set(S_ExePoint,null); } public String getExePoint(){ return DataType.getAsString(this.get(S_ExePoint)); } public String getExePointInitialValue(){ return DataType.getAsString(this.getOldObj(S_ExePoint)); } public void initExeFunction(String value){ this.initProperty(S_ExeFunction,value); } public void setExeFunction(String value){ this.set(S_ExeFunction,value); } public void setExeFunctionNull(){ this.set(S_ExeFunction,null); } public String getExeFunction(){ return DataType.getAsString(this.get(S_ExeFunction)); } public String getExeFunctionInitialValue(){ return DataType.getAsString(this.getOldObj(S_ExeFunction)); } public void initProceduresName(String value){ this.initProperty(S_ProceduresName,value); } public void setProceduresName(String value){ this.set(S_ProceduresName,value); } public void setProceduresNameNull(){ this.set(S_ProceduresName,null); } public String getProceduresName(){ return DataType.getAsString(this.get(S_ProceduresName)); } public String getProceduresNameInitialValue(){ return DataType.getAsString(this.getOldObj(S_ProceduresName)); } public void initFailPoint(String value){ this.initProperty(S_FailPoint,value); } public void setFailPoint(String value){ this.set(S_FailPoint,value); } public void setFailPointNull(){ this.set(S_FailPoint,null); } public String getFailPoint(){ return DataType.getAsString(this.get(S_FailPoint)); } public String getFailPointInitialValue(){ return DataType.getAsString(this.getOldObj(S_FailPoint)); } public void initProceduresInfo(String value){ this.initProperty(S_ProceduresInfo,value); } public void setProceduresInfo(String value){ this.set(S_ProceduresInfo,value); } public void setProceduresInfoNull(){ this.set(S_ProceduresInfo,null); } public String getProceduresInfo(){ return DataType.getAsString(this.get(S_ProceduresInfo)); } public String getProceduresInfoInitialValue(){ return DataType.getAsString(this.getOldObj(S_ProceduresInfo)); } public void initBreakFunction(String value){ this.initProperty(S_BreakFunction,value); } public void setBreakFunction(String value){ this.set(S_BreakFunction,value); } public void setBreakFunctionNull(){ this.set(S_BreakFunction,null); } public String getBreakFunction(){ return DataType.getAsString(this.get(S_BreakFunction)); } public String getBreakFunctionInitialValue(){ return DataType.getAsString(this.getOldObj(S_BreakFunction)); } public void initProceduresExt(String value){ this.initProperty(S_ProceduresExt,value); } public void setProceduresExt(String value){ this.set(S_ProceduresExt,value); } public void setProceduresExtNull(){ this.set(S_ProceduresExt,null); } public String getProceduresExt(){ return DataType.getAsString(this.get(S_ProceduresExt)); } public String getProceduresExtInitialValue(){ return DataType.getAsString(this.getOldObj(S_ProceduresExt)); } public void initReserve1(String value){ this.initProperty(S_Reserve1,value); } public void setReserve1(String value){ this.set(S_Reserve1,value); } public void setReserve1Null(){ this.set(S_Reserve1,null); } public String getReserve1(){ return DataType.getAsString(this.get(S_Reserve1)); } public String getReserve1InitialValue(){ return DataType.getAsString(this.getOldObj(S_Reserve1)); } public void initBreakPoint(String value){ this.initProperty(S_BreakPoint,value); } public void setBreakPoint(String value){ this.set(S_BreakPoint,value); } public void setBreakPointNull(){ this.set(S_BreakPoint,null); } public String getBreakPoint(){ return DataType.getAsString(this.get(S_BreakPoint)); } public String getBreakPointInitialValue(){ return DataType.getAsString(this.getOldObj(S_BreakPoint)); } public void initReserve3(String value){ this.initProperty(S_Reserve3,value); } public void setReserve3(String value){ this.set(S_Reserve3,value); } public void setReserve3Null(){ this.set(S_Reserve3,null); } public String getReserve3(){ return DataType.getAsString(this.get(S_Reserve3)); } public String getReserve3InitialValue(){ return DataType.getAsString(this.getOldObj(S_Reserve3)); } public void initReserve2(String value){ this.initProperty(S_Reserve2,value); } public void setReserve2(String value){ this.set(S_Reserve2,value); } public void setReserve2Null(){ this.set(S_Reserve2,null); } public String getReserve2(){ return DataType.getAsString(this.get(S_Reserve2)); } public String getReserve2InitialValue(){ return DataType.getAsString(this.getOldObj(S_Reserve2)); } public void initFailFunction(String value){ this.initProperty(S_FailFunction,value); } public void setFailFunction(String value){ this.set(S_FailFunction,value); } public void setFailFunctionNull(){ this.set(S_FailFunction,null); } public String getFailFunction(){ return DataType.getAsString(this.get(S_FailFunction)); } public String getFailFunctionInitialValue(){ return DataType.getAsString(this.getOldObj(S_FailFunction)); } public void initProceduresId(long value){ this.initProperty(S_ProceduresId,new Long(value)); } public void setProceduresId(long value){ this.set(S_ProceduresId,new Long(value)); } public void setProceduresIdNull(){ this.set(S_ProceduresId,null); } public long getProceduresId(){ return DataType.getAsLong(this.get(S_ProceduresId)); } public long getProceduresIdInitialValue(){ return DataType.getAsLong(this.getOldObj(S_ProceduresId)); } }
GB18030
Java
8,185
45f0c4581c2246f832be55a725124b345b89678f.svn-base
Java
[]
null
[]
package com.asiainfo.cs.qm.qualquery.bo; import java.sql.*; import com.ai.appframe2.bo.DataContainer; import com.ai.appframe2.common.DataContainerInterface; import com.ai.appframe2.common.AIException; import com.ai.appframe2.common.ServiceManager; import com.ai.appframe2.common.ObjectType; import com.ai.appframe2.common.DataType; import com.asiainfo.cs.qm.qualquery.ivalues.*; public class BOEdExamProcedureBean extends DataContainer implements DataContainerInterface,IBOEdExamProcedureValue{ private static String m_boName = "com.asiainfo.cs.qm.qualquery.bo.BOEdExamProcedure"; public final static String S_ExePoint = "EXE_POINT"; public final static String S_ExeFunction = "EXE_FUNCTION"; public final static String S_ProceduresName = "PROCEDURES_NAME"; public final static String S_FailPoint = "FAIL_POINT"; public final static String S_ProceduresInfo = "PROCEDURES_INFO"; public final static String S_BreakFunction = "BREAK_FUNCTION"; public final static String S_ProceduresExt = "PROCEDURES_EXT"; public final static String S_Reserve1 = "RESERVE1"; public final static String S_BreakPoint = "BREAK_POINT"; public final static String S_Reserve3 = "RESERVE3"; public final static String S_Reserve2 = "RESERVE2"; public final static String S_FailFunction = "FAIL_FUNCTION"; public final static String S_ProceduresId = "PROCEDURES_ID"; public static ObjectType S_TYPE = null; static{ try { S_TYPE = ServiceManager.getObjectTypeFactory().getInstance(m_boName); }catch(Exception e){ throw new RuntimeException(e); } } public BOEdExamProcedureBean() throws AIException{ super(S_TYPE); } public static ObjectType getObjectTypeStatic() throws AIException{ return S_TYPE; } public void setObjectType(ObjectType value) throws AIException{ //ๆญค็งๆ•ฐๆฎๅฎนๅ™จไธ่ƒฝ้‡็ฝฎไธšๅŠกๅฏน่ฑก็ฑปๅž‹ throw new AIException("Cannot reset ObjectType"); } public void initExePoint(String value){ this.initProperty(S_ExePoint,value); } public void setExePoint(String value){ this.set(S_ExePoint,value); } public void setExePointNull(){ this.set(S_ExePoint,null); } public String getExePoint(){ return DataType.getAsString(this.get(S_ExePoint)); } public String getExePointInitialValue(){ return DataType.getAsString(this.getOldObj(S_ExePoint)); } public void initExeFunction(String value){ this.initProperty(S_ExeFunction,value); } public void setExeFunction(String value){ this.set(S_ExeFunction,value); } public void setExeFunctionNull(){ this.set(S_ExeFunction,null); } public String getExeFunction(){ return DataType.getAsString(this.get(S_ExeFunction)); } public String getExeFunctionInitialValue(){ return DataType.getAsString(this.getOldObj(S_ExeFunction)); } public void initProceduresName(String value){ this.initProperty(S_ProceduresName,value); } public void setProceduresName(String value){ this.set(S_ProceduresName,value); } public void setProceduresNameNull(){ this.set(S_ProceduresName,null); } public String getProceduresName(){ return DataType.getAsString(this.get(S_ProceduresName)); } public String getProceduresNameInitialValue(){ return DataType.getAsString(this.getOldObj(S_ProceduresName)); } public void initFailPoint(String value){ this.initProperty(S_FailPoint,value); } public void setFailPoint(String value){ this.set(S_FailPoint,value); } public void setFailPointNull(){ this.set(S_FailPoint,null); } public String getFailPoint(){ return DataType.getAsString(this.get(S_FailPoint)); } public String getFailPointInitialValue(){ return DataType.getAsString(this.getOldObj(S_FailPoint)); } public void initProceduresInfo(String value){ this.initProperty(S_ProceduresInfo,value); } public void setProceduresInfo(String value){ this.set(S_ProceduresInfo,value); } public void setProceduresInfoNull(){ this.set(S_ProceduresInfo,null); } public String getProceduresInfo(){ return DataType.getAsString(this.get(S_ProceduresInfo)); } public String getProceduresInfoInitialValue(){ return DataType.getAsString(this.getOldObj(S_ProceduresInfo)); } public void initBreakFunction(String value){ this.initProperty(S_BreakFunction,value); } public void setBreakFunction(String value){ this.set(S_BreakFunction,value); } public void setBreakFunctionNull(){ this.set(S_BreakFunction,null); } public String getBreakFunction(){ return DataType.getAsString(this.get(S_BreakFunction)); } public String getBreakFunctionInitialValue(){ return DataType.getAsString(this.getOldObj(S_BreakFunction)); } public void initProceduresExt(String value){ this.initProperty(S_ProceduresExt,value); } public void setProceduresExt(String value){ this.set(S_ProceduresExt,value); } public void setProceduresExtNull(){ this.set(S_ProceduresExt,null); } public String getProceduresExt(){ return DataType.getAsString(this.get(S_ProceduresExt)); } public String getProceduresExtInitialValue(){ return DataType.getAsString(this.getOldObj(S_ProceduresExt)); } public void initReserve1(String value){ this.initProperty(S_Reserve1,value); } public void setReserve1(String value){ this.set(S_Reserve1,value); } public void setReserve1Null(){ this.set(S_Reserve1,null); } public String getReserve1(){ return DataType.getAsString(this.get(S_Reserve1)); } public String getReserve1InitialValue(){ return DataType.getAsString(this.getOldObj(S_Reserve1)); } public void initBreakPoint(String value){ this.initProperty(S_BreakPoint,value); } public void setBreakPoint(String value){ this.set(S_BreakPoint,value); } public void setBreakPointNull(){ this.set(S_BreakPoint,null); } public String getBreakPoint(){ return DataType.getAsString(this.get(S_BreakPoint)); } public String getBreakPointInitialValue(){ return DataType.getAsString(this.getOldObj(S_BreakPoint)); } public void initReserve3(String value){ this.initProperty(S_Reserve3,value); } public void setReserve3(String value){ this.set(S_Reserve3,value); } public void setReserve3Null(){ this.set(S_Reserve3,null); } public String getReserve3(){ return DataType.getAsString(this.get(S_Reserve3)); } public String getReserve3InitialValue(){ return DataType.getAsString(this.getOldObj(S_Reserve3)); } public void initReserve2(String value){ this.initProperty(S_Reserve2,value); } public void setReserve2(String value){ this.set(S_Reserve2,value); } public void setReserve2Null(){ this.set(S_Reserve2,null); } public String getReserve2(){ return DataType.getAsString(this.get(S_Reserve2)); } public String getReserve2InitialValue(){ return DataType.getAsString(this.getOldObj(S_Reserve2)); } public void initFailFunction(String value){ this.initProperty(S_FailFunction,value); } public void setFailFunction(String value){ this.set(S_FailFunction,value); } public void setFailFunctionNull(){ this.set(S_FailFunction,null); } public String getFailFunction(){ return DataType.getAsString(this.get(S_FailFunction)); } public String getFailFunctionInitialValue(){ return DataType.getAsString(this.getOldObj(S_FailFunction)); } public void initProceduresId(long value){ this.initProperty(S_ProceduresId,new Long(value)); } public void setProceduresId(long value){ this.set(S_ProceduresId,new Long(value)); } public void setProceduresIdNull(){ this.set(S_ProceduresId,null); } public long getProceduresId(){ return DataType.getAsLong(this.get(S_ProceduresId)); } public long getProceduresIdInitialValue(){ return DataType.getAsLong(this.getOldObj(S_ProceduresId)); } }
8,185
0.712008
0.706856
291
27.013746
23.864159
115
false
false
0
0
0
0
0
0
0.460481
false
false
10
a39ab269ae73009420317efe8fb047bece4e8b2f
7,902,739,841,138
4b9eb9634b957486a8a4f34c1f8ea05ad27b1805
/Projeto/Java/src/control/AtualizaTabela.java
2f775472da181fff16c8ad412cfd7809a424f33f
[]
no_license
nisep/EngenhariaApple
https://github.com/nisep/EngenhariaApple
c54894fd1e305a9494fd6347932cdbd586ea7789
24a04edaebb334050bf2555a545b4285536fa8dd
refs/heads/master
2021-08-14T14:01:43.029000
2017-11-15T23:26:20
2017-11-15T23:26:20
105,332,054
0
0
null
true
2017-09-30T01:50:22
2017-09-30T01:50:22
2017-09-26T20:20:10
2017-09-29T01:44:57
23,808
0
0
0
null
null
null
package control; import javax.swing.table.DefaultTableModel; import model.FuncionarioDAO; import view.FuncionarioView; public class AtualizaTabela implements Runnable{ FuncionarioView funcionarioView; FuncionarioDAO funcDAO = new FuncionarioDAO(); public AtualizaTabela(FuncionarioView funcionarioView) { this.funcionarioView = funcionarioView; } @Override public void run() { try { for(;;) { Thread.sleep(3000); atualizarTabela(); } } catch (InterruptedException e) { // TODO Auto-generatee.printStackTrace(); } } private void atualizarTabela() { String[][] funcs = funcDAO.listaFuncionarioArray(""); String[] colunas = {"id","Nome", "CPF", "Endereลกo", "Telefone","Nascimento"}; DefaultTableModel model = new DefaultTableModel(funcs,colunas) { /** * */ private static final long serialVersionUID = -7680235106608274804L; boolean[] canEdit = new boolean []{ false, false, false, false,false,false }; @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }; funcionarioView.getTableFuncionario().setModel(model); funcionarioView.repaint(); funcionarioView.revalidate(); } }
IBM852
Java
1,294
java
AtualizaTabela.java
Java
[]
null
[]
package control; import javax.swing.table.DefaultTableModel; import model.FuncionarioDAO; import view.FuncionarioView; public class AtualizaTabela implements Runnable{ FuncionarioView funcionarioView; FuncionarioDAO funcDAO = new FuncionarioDAO(); public AtualizaTabela(FuncionarioView funcionarioView) { this.funcionarioView = funcionarioView; } @Override public void run() { try { for(;;) { Thread.sleep(3000); atualizarTabela(); } } catch (InterruptedException e) { // TODO Auto-generatee.printStackTrace(); } } private void atualizarTabela() { String[][] funcs = funcDAO.listaFuncionarioArray(""); String[] colunas = {"id","Nome", "CPF", "Endereลกo", "Telefone","Nascimento"}; DefaultTableModel model = new DefaultTableModel(funcs,colunas) { /** * */ private static final long serialVersionUID = -7680235106608274804L; boolean[] canEdit = new boolean []{ false, false, false, false,false,false }; @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }; funcionarioView.getTableFuncionario().setModel(model); funcionarioView.repaint(); funcionarioView.revalidate(); } }
1,294
0.67208
0.654292
52
23.865385
22.873421
79
false
false
0
0
0
0
0
0
2.346154
false
false
10
e933553b0f55bd9e55b101bf26f5b1f110b3aac5
23,725,399,411,182
a540e470713a39e1e1b19e6987355da6b7b12703
/src/main/java/com/vynaloze/pgmeter/model/translate/Param.java
ba684a2877658e8afd99ddaef92aa7de557e5af2
[]
no_license
vynaloze/pgmeter
https://github.com/vynaloze/pgmeter
87cd39e832c785304104e401d955f990f510aeaf
2b8cf984aa526db90c7d69f8c680b9edc9bf84bb
refs/heads/master
2020-06-01T20:00:42.620000
2019-10-12T17:06:32
2019-10-12T17:06:32
190,908,974
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.vynaloze.pgmeter.model.translate; import javax.validation.constraints.NotNull; public class Param { @NotNull private final String name; @NotNull private final Type type; public Param(final @NotNull String name, final @NotNull Type type) { this.name = name; this.type = type; } @NotNull public String getName() { return name; } @NotNull public Type getType() { return type; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof Param)) { return false; } final Param param = (Param) o; if (!name.equals(param.name)) { return false; } return type == param.type; } @Override public int hashCode() { int result = name.hashCode(); result = 31 * result + type.hashCode(); return result; } }
UTF-8
Java
981
java
Param.java
Java
[]
null
[]
package com.vynaloze.pgmeter.model.translate; import javax.validation.constraints.NotNull; public class Param { @NotNull private final String name; @NotNull private final Type type; public Param(final @NotNull String name, final @NotNull Type type) { this.name = name; this.type = type; } @NotNull public String getName() { return name; } @NotNull public Type getType() { return type; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof Param)) { return false; } final Param param = (Param) o; if (!name.equals(param.name)) { return false; } return type == param.type; } @Override public int hashCode() { int result = name.hashCode(); result = 31 * result + type.hashCode(); return result; } }
981
0.54842
0.546381
49
19.040817
16.178797
72
false
false
0
0
0
0
0
0
0.346939
false
false
10
90d18ad9de108d8c7145ef8cec520aeb300f55cc
31,920,196,980,987
c9a9e6a2b385691128da88f78b3d61e080ef701f
/V1_Total/V1_Total/TpHibernateSujet4_YongdaLIN_CatarinaRB/Code/src/fr/polytech/tours/hibernate/application/controleur/IndexControleur.java
96ea1418b880ed838b34cde574cd45700f87129c
[]
no_license
axelrandolph/tpshibernate
https://github.com/axelrandolph/tpshibernate
6570fd9f2aad8e700a8229783ab5140cb34634bd
4a434f5fb8f65f5f0767b0ffab2a974303874e3d
refs/heads/master
2020-11-23T20:58:06.238000
2020-01-14T21:11:41
2020-01-14T21:11:41
227,817,889
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package fr.polytech.tours.hibernate.application.controleur; import java.net.URL; import java.util.ResourceBundle; import fr.polytech.tours.hibernate.application.controleur.dao.MessageDAO; import fr.polytech.tours.hibernate.application.modele.Message; import javafx.collections.FXCollections; import javafx.collections.ObservableList; //import fr.polytech.tours.hibernate.application.controleur.invite.ResultatCherNonConn; //import javafx.collections.FXCollections; //import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; public class IndexControleur { private BlogControleur blogControleur; private MessageDAO messDAO; @FXML // ResourceBundle that was given to the FXMLLoader private ResourceBundle resources; @FXML // URL location of the FXML file that was given to the FXMLLoader private URL location; @FXML // fx:id="date" private TableColumn<Message, String> date; // Value injected by FXMLLoader @FXML // fx:id="affiche" private TableView<Message> affiche; // Value injected by FXMLLoader @FXML // fx:id="seConn" private Button seConn; // Value injected by FXMLLoader @FXML // fx:id="util" private TableColumn<Message, String> util; // Value injected by FXMLLoader @FXML // fx:id="titr" private TableColumn<Message, String> titr; // Value injected by FXMLLoader @FXML // fx:id="textItem" private TextField textItem; // Value injected by FXMLLoader @FXML // fx:id="index" private Button index; // Value injected by FXMLLoader @FXML // fx:id="motCles" private TableColumn<Message, String> motCles; // Value injected by FXMLLoader @FXML // fx:id="text" private TableColumn<Message, String> text; // Value injected by FXMLLoader @FXML // fx:id="chercher" private Button chercher; // Value injected by FXMLLoader @FXML // fx:id="sInsc" private Button sInsc; // Value injected by FXMLLoader public IndexControleur(BlogControleur blogControleur) { super(); this.setBlogControleur(blogControleur); messDAO = new MessageDAO(blogControleur.getEm()); } public BlogControleur getBlogControleur() { return blogControleur; } public void setBlogControleur(BlogControleur blogControleur) { this.blogControleur = blogControleur; } public TableView<Message> getAffiche() { return affiche; } public void setAffiche(TableView<Message> affiche) { this.affiche = affiche; } @FXML void allerIndex(ActionEvent event) { blogControleur.preparerIndexNonConn(); System.out.println("allerIndex"); blogControleur.activer("index"); } @FXML void allerConn(ActionEvent event) { System.out.println("allerConn"); blogControleur.activer("connexion"); } @FXML void allerInsc(ActionEvent event) { System.out.println("allerInsc"); blogControleur.activer("inscription"); } @FXML void allerResu(ActionEvent event) { blogControleur.preparerResNonConn(textItem.getText()); System.out.println("allerResu"); blogControleur.activer("resultatCherNonConn"); } @FXML // This method is called by the FXMLLoader when initialization is complete void initialize() { assert date != null : "fx:id=\"date\" was not injected: check your FXML file 'Index.fxml'."; assert affiche != null : "fx:id=\"affiche\" was not injected: check your FXML file 'Index.fxml'."; assert seConn != null : "fx:id=\"seConn\" was not injected: check your FXML file 'Index.fxml'."; assert util != null : "fx:id=\"util\" was not injected: check your FXML file 'Index.fxml'."; assert titr != null : "fx:id=\"titr\" was not injected: check your FXML file 'Index.fxml'."; assert textItem != null : "fx:id=\"textItem\" was not injected: check your FXML file 'Index.fxml'."; assert index != null : "fx:id=\"index\" was not injected: check your FXML file 'Index.fxml'."; assert motCles != null : "fx:id=\"motCles\" was not injected: check your FXML file 'Index.fxml'."; assert text != null : "fx:id=\"text\" was not injected: check your FXML file 'Index.fxml'."; assert chercher != null : "fx:id=\"chercher\" was not injected: check your FXML file 'Index.fxml'."; assert sInsc != null : "fx:id=\"sInsc\" was not injected: check your FXML file 'Index.fxml'."; ObservableList<Message> items = FXCollections.observableArrayList(messDAO.chercherTous()); affiche.setItems(items); titr.setCellValueFactory(new PropertyValueFactory<Message, String>("Titre")); text.setCellValueFactory(new PropertyValueFactory<Message, String>("Texte")); util.setCellValueFactory(new PropertyValueFactory<Message, String>("Utilisateur")); motCles.setCellValueFactory(new PropertyValueFactory<Message, String>("ListeMotCle")); date.setCellValueFactory(new PropertyValueFactory<Message, String>("Date")); } }
UTF-8
Java
4,911
java
IndexControleur.java
Java
[]
null
[]
package fr.polytech.tours.hibernate.application.controleur; import java.net.URL; import java.util.ResourceBundle; import fr.polytech.tours.hibernate.application.controleur.dao.MessageDAO; import fr.polytech.tours.hibernate.application.modele.Message; import javafx.collections.FXCollections; import javafx.collections.ObservableList; //import fr.polytech.tours.hibernate.application.controleur.invite.ResultatCherNonConn; //import javafx.collections.FXCollections; //import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; public class IndexControleur { private BlogControleur blogControleur; private MessageDAO messDAO; @FXML // ResourceBundle that was given to the FXMLLoader private ResourceBundle resources; @FXML // URL location of the FXML file that was given to the FXMLLoader private URL location; @FXML // fx:id="date" private TableColumn<Message, String> date; // Value injected by FXMLLoader @FXML // fx:id="affiche" private TableView<Message> affiche; // Value injected by FXMLLoader @FXML // fx:id="seConn" private Button seConn; // Value injected by FXMLLoader @FXML // fx:id="util" private TableColumn<Message, String> util; // Value injected by FXMLLoader @FXML // fx:id="titr" private TableColumn<Message, String> titr; // Value injected by FXMLLoader @FXML // fx:id="textItem" private TextField textItem; // Value injected by FXMLLoader @FXML // fx:id="index" private Button index; // Value injected by FXMLLoader @FXML // fx:id="motCles" private TableColumn<Message, String> motCles; // Value injected by FXMLLoader @FXML // fx:id="text" private TableColumn<Message, String> text; // Value injected by FXMLLoader @FXML // fx:id="chercher" private Button chercher; // Value injected by FXMLLoader @FXML // fx:id="sInsc" private Button sInsc; // Value injected by FXMLLoader public IndexControleur(BlogControleur blogControleur) { super(); this.setBlogControleur(blogControleur); messDAO = new MessageDAO(blogControleur.getEm()); } public BlogControleur getBlogControleur() { return blogControleur; } public void setBlogControleur(BlogControleur blogControleur) { this.blogControleur = blogControleur; } public TableView<Message> getAffiche() { return affiche; } public void setAffiche(TableView<Message> affiche) { this.affiche = affiche; } @FXML void allerIndex(ActionEvent event) { blogControleur.preparerIndexNonConn(); System.out.println("allerIndex"); blogControleur.activer("index"); } @FXML void allerConn(ActionEvent event) { System.out.println("allerConn"); blogControleur.activer("connexion"); } @FXML void allerInsc(ActionEvent event) { System.out.println("allerInsc"); blogControleur.activer("inscription"); } @FXML void allerResu(ActionEvent event) { blogControleur.preparerResNonConn(textItem.getText()); System.out.println("allerResu"); blogControleur.activer("resultatCherNonConn"); } @FXML // This method is called by the FXMLLoader when initialization is complete void initialize() { assert date != null : "fx:id=\"date\" was not injected: check your FXML file 'Index.fxml'."; assert affiche != null : "fx:id=\"affiche\" was not injected: check your FXML file 'Index.fxml'."; assert seConn != null : "fx:id=\"seConn\" was not injected: check your FXML file 'Index.fxml'."; assert util != null : "fx:id=\"util\" was not injected: check your FXML file 'Index.fxml'."; assert titr != null : "fx:id=\"titr\" was not injected: check your FXML file 'Index.fxml'."; assert textItem != null : "fx:id=\"textItem\" was not injected: check your FXML file 'Index.fxml'."; assert index != null : "fx:id=\"index\" was not injected: check your FXML file 'Index.fxml'."; assert motCles != null : "fx:id=\"motCles\" was not injected: check your FXML file 'Index.fxml'."; assert text != null : "fx:id=\"text\" was not injected: check your FXML file 'Index.fxml'."; assert chercher != null : "fx:id=\"chercher\" was not injected: check your FXML file 'Index.fxml'."; assert sInsc != null : "fx:id=\"sInsc\" was not injected: check your FXML file 'Index.fxml'."; ObservableList<Message> items = FXCollections.observableArrayList(messDAO.chercherTous()); affiche.setItems(items); titr.setCellValueFactory(new PropertyValueFactory<Message, String>("Titre")); text.setCellValueFactory(new PropertyValueFactory<Message, String>("Texte")); util.setCellValueFactory(new PropertyValueFactory<Message, String>("Utilisateur")); motCles.setCellValueFactory(new PropertyValueFactory<Message, String>("ListeMotCle")); date.setCellValueFactory(new PropertyValueFactory<Message, String>("Date")); } }
4,911
0.748931
0.748931
138
34.586956
31.642645
102
false
false
0
0
0
0
0
0
1.449275
false
false
10
33d66c88f5dd77475394dd7f65b9dd7fcb91c38d
6,949,257,118,364
3a29faf0305cdfab654a500cd14b88377a2c5d1d
/uni/src/main/java/com/markjmind/uni/thread/ThreadProcessObservable.java
da4847ed309abf1a26990989d7b9d1f35d89f203
[]
no_license
JaeWoongOh/markj
https://github.com/JaeWoongOh/markj
6dc0e8a0171196a2793b33f5b5699fb1ef0d9e88
e566141f4fba0a862288bdeee37fbbf35bd726cc
refs/heads/master
2020-05-21T19:47:43.950000
2020-05-19T09:42:21
2020-05-19T09:42:21
15,650,595
4
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (c) 2016. Lorem ipsum dolor sit amet, consectetur adipiscing elit. * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. * Vestibulum commodo. Ut rhoncus gravida arcu. */ package com.markjmind.uni.thread; import java.util.ArrayList; /** * <br>ๆฒๅœŸ้‡ไพ†<br> * @author ์˜ค์žฌ์›…(JaeWoong-Oh) * @email markjmind@gmail.com * @since 2016-02-17 */ public class ThreadProcessObservable extends ThreadProcessObserver { private ArrayList<ThreadProcessObserver> observers = new ArrayList<>(); @Override public void onPreExecute(CancelAdapter cancelAdapter) { for(ThreadProcessObserver observer : observers){ observer.onPreExecute(cancelAdapter); } } @Override public void doInBackground(LoadEvent event, CancelAdapter cancelAdapter) throws Exception{ for(ThreadProcessObserver observer : observers){ observer.doInBackground(event, cancelAdapter); } } @Override public void onProgressUpdate(Object value, CancelAdapter cancelAdapter) { for(ThreadProcessObserver observer : observers){ observer.onProgressUpdate(value, cancelAdapter); } } @Override public void onPostExecute() { for(ThreadProcessObserver observer : observers){ observer.onPostExecute(); } } @Override public void onFailedExecute(String message, Object arg) { for(ThreadProcessObserver observer : observers){ observer.onFailedExecute(message, arg); } } @Override public void onExceptionExecute(Exception e) { for(ThreadProcessObserver observer : observers){ observer.onExceptionExecute(e); } } @Override public void onCancelled(boolean attached) { for(ThreadProcessObserver observer : observers){ observer.onCancelled(attached); } } public void add(ThreadProcessObserver threadProcessObserver){ observers.add(threadProcessObserver); } }
UTF-8
Java
2,240
java
ThreadProcessObservable.java
Java
[ { "context": "va.util.ArrayList;\n\n/**\n * <br>ๆฒๅœŸ้‡ไพ†<br>\n * @author ์˜ค์žฌ์›…(JaeWoong-Oh)\n * @email markjmind@gmail.com\n * @si", "end": 495, "score": 0.9998475313186646, "start": 492, "tag": "NAME", "value": "์˜ค์žฌ์›…" }, { "context": "il.ArrayList;\n\n/**\n * <br>ๆฒๅœŸ้‡ไพ†<br>\n * @author ์˜ค์žฌ์›…(JaeWoong-Oh)\n * @email markjmind@gmail.com\n * @since 2016-02-", "end": 507, "score": 0.9997830390930176, "start": 496, "tag": "NAME", "value": "JaeWoong-Oh" }, { "context": "<br>ๆฒๅœŸ้‡ไพ†<br>\n * @author ์˜ค์žฌ์›…(JaeWoong-Oh)\n * @email markjmind@gmail.com\n * @since 2016-02-17\n */\npublic class ThreadProce", "end": 538, "score": 0.9999314546585083, "start": 519, "tag": "EMAIL", "value": "markjmind@gmail.com" } ]
null
[]
/* * Copyright (c) 2016. Lorem ipsum dolor sit amet, consectetur adipiscing elit. * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. * Vestibulum commodo. Ut rhoncus gravida arcu. */ package com.markjmind.uni.thread; import java.util.ArrayList; /** * <br>ๆฒๅœŸ้‡ไพ†<br> * @author ์˜ค์žฌ์›…(JaeWoong-Oh) * @email <EMAIL> * @since 2016-02-17 */ public class ThreadProcessObservable extends ThreadProcessObserver { private ArrayList<ThreadProcessObserver> observers = new ArrayList<>(); @Override public void onPreExecute(CancelAdapter cancelAdapter) { for(ThreadProcessObserver observer : observers){ observer.onPreExecute(cancelAdapter); } } @Override public void doInBackground(LoadEvent event, CancelAdapter cancelAdapter) throws Exception{ for(ThreadProcessObserver observer : observers){ observer.doInBackground(event, cancelAdapter); } } @Override public void onProgressUpdate(Object value, CancelAdapter cancelAdapter) { for(ThreadProcessObserver observer : observers){ observer.onProgressUpdate(value, cancelAdapter); } } @Override public void onPostExecute() { for(ThreadProcessObserver observer : observers){ observer.onPostExecute(); } } @Override public void onFailedExecute(String message, Object arg) { for(ThreadProcessObserver observer : observers){ observer.onFailedExecute(message, arg); } } @Override public void onExceptionExecute(Exception e) { for(ThreadProcessObserver observer : observers){ observer.onExceptionExecute(e); } } @Override public void onCancelled(boolean attached) { for(ThreadProcessObserver observer : observers){ observer.onCancelled(attached); } } public void add(ThreadProcessObserver threadProcessObserver){ observers.add(threadProcessObserver); } }
2,228
0.686433
0.681042
75
28.68
28.04718
97
false
false
0
0
0
0
0
0
0.24
false
false
10