blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 5
132
| path
stringlengths 2
382
| src_encoding
stringclasses 34
values | length_bytes
int64 9
3.8M
| score
float64 1.5
4.94
| int_score
int64 2
5
| detected_licenses
listlengths 0
142
| license_type
stringclasses 2
values | text
stringlengths 9
3.8M
| download_success
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|
eca448338c1f12d3401d897faa588b5f9b6bc996
|
Java
|
CUjamin/DemoOfSpring
|
/Spring-AOP/src/main/java/cuj.spring.aop/demo/controller/UserController.java
|
UTF-8
| 1,298 | 2.140625 | 2 |
[] |
no_license
|
package cuj.spring.aop.demo.controller;
import cuj.spring.aop.demo.service.UserService;
import io.swagger.annotations.ApiParam;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @Auther: cujamin
* @Date: 2019/2/18 17:16
* @Description:
*/
@RestController
@RequestMapping(value = "/v1")
@Log4j
public class UserController {
@Autowired
UserService userService;
@RequestMapping(method = RequestMethod.GET,value = "/user")
public Response getUser(
@ApiParam(value = "" , required = true)@RequestParam String id,
@ApiParam(value = "" , required = true)@RequestParam String username,
@ApiParam(value = "" ,required = true)@RequestParam String notename){
Response response = new Response();
UserVo userVo = new UserVo();
userVo.setId(id);
userVo.setName(username);
userVo.setNote(notename);
userService.printUser(userVo);
log.info("getUser:"+response);
return response;
}
}
| true |
1bf98265cde79e29aab0aa8a661f9874d1e49097
|
Java
|
aditi9413/Core-Java-Programs
|
/src/Tree/heightofbinarytree.java
|
UTF-8
| 723 | 3.609375 | 4 |
[] |
no_license
|
package Tree;
public class heightofbinarytree {
static Node root;
heightofbinarytree()
{
root = null;
}
public static int height(Node root){
if(root==null){
return 0;
}
int lheight=height(root.left);
int rheight=height(root.right);
return 1 + Math.max(lheight, rheight);
}
public static void main(String[] args) {
heightofbinarytree tree = new heightofbinarytree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
System.out.println("Height of binary tree is " +tree.height(root));
}
}
| true |
eb8f5b3776ace33d4c67d22b050b20fea3ceb2ad
|
Java
|
ijolidino/leetCodeTest
|
/leetcodeTest/Easy/findMaxConsecutiveOnes.java
|
UTF-8
| 1,295 | 3.625 | 4 |
[] |
no_license
|
package leetcodeTest.Easy;
/**
* Create by Fuwen on 2021/2/2
* 最大连续1的个数
* 给定一个二进制数组, 计算其中最大连续1的个数。
*
* 示例 1:
*
* 输入: [1,1,0,1,1,1]
* 输出: 3
* 解释: 开头的两位和最后的三位都是连续1,所以最大连续1的个数是 3.
* 注意:
*
* 输入的数组只包含 0 和1。
* 输入数组的长度是正整数,且不超过 10,000。
*
* 作者:力扣 (LeetCode)
* 链接:https://leetcode-cn.com/leetbook/read/array-and-string/cd71t/
* 来源:力扣(LeetCode)
* 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
*/
public class findMaxConsecutiveOnes {
public int findMaxConsecutiveOnes(int[] nums) {
int count = 0, tmp = 0;
for (int num : nums) {
if (num == 1) {
tmp++;
} else if (tmp > count) {
count = tmp;
tmp = 0;
} else {
tmp = 0;
}
}
if (tmp > count) {
count = tmp;
}
return count;
}
public static void main(String[] args) {
System.out.println(new findMaxConsecutiveOnes().findMaxConsecutiveOnes(new int[]{1,1,0,1,1,1}));
}
}
| true |
ba6b81e5e67ec7cbb548dae69d3c5ed55bd3b875
|
Java
|
jk1z/Monash-Weather-Monitor-Application
|
/GUI/MainFrame.java
|
UTF-8
| 5,323 | 2.546875 | 3 |
[] |
no_license
|
import java.awt.*;
import javax.swing.*;
import javax.swing.GroupLayout;
import javax.swing.LayoutStyle;
/*
* Created by JFormDesigner on Thu May 18 13:24:10 EST 2017
*/
/**
* @author CodeCracker
*/
public class MainFrame extends JFrame {
private void initComponents() {
// JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
scrollPane = new JScrollPane();
locationList = new JList();
loadLocationsButton = new JButton();
tempCheck = new JCheckBox();
rainCheck = new JCheckBox();
displayLiveButton = new JButton();
displayChangeButton = new JButton();
sourceLabel = new JLabel();
weather2Radio = new JRadioButton();
weatherTimeLapseRadio = new JRadioButton();
displayLabel = new JLabel();
//======== this ========
setTitle("Melbourne Weather Application");
setMinimumSize(new Dimension(450, 310));
Container contentPane = getContentPane();
//======== scrollPane ========
{
//---- locationList ----
locationList.setFont(new Font("Arial", Font.PLAIN, 12));
scrollPane.setViewportView(locationList);
}
//---- loadLocationsButton ----
loadLocationsButton.setText("Load Locations");
loadLocationsButton.setFont(new Font("Arial", Font.PLAIN, 12));
//---- tempCheck ----
tempCheck.setText("Temperature");
tempCheck.setFont(new Font("Arial", Font.PLAIN, 12));
//---- rainCheck ----
rainCheck.setText("Rainfall");
rainCheck.setFont(new Font("Arial", Font.PLAIN, 12));
//---- displayLiveButton ----
displayLiveButton.setText("Display Live Information");
displayLiveButton.setFont(new Font("Arial", Font.PLAIN, 12));
//---- displayChangeButton ----
displayChangeButton.setText("Display Change Over Time");
displayChangeButton.setFont(new Font("Arial", Font.PLAIN, 12));
//---- sourceLabel ----
sourceLabel.setText("Source:");
sourceLabel.setFont(new Font("Arial", Font.PLAIN, 12));
//---- weather2Radio ----
weather2Radio.setText("MelbourneWeather2");
weather2Radio.setSelected(true);
weather2Radio.setFont(new Font("Arial", Font.PLAIN, 12));
//---- weatherTimeLapseRadio ----
weatherTimeLapseRadio.setText("MelbourneWeatherTimeLapse");
weatherTimeLapseRadio.setFont(new Font("Arial", Font.PLAIN, 12));
//---- displayLabel ----
displayLabel.setText("Display:");
displayLabel.setFont(new Font("Arial", Font.PLAIN, 12));
GroupLayout contentPaneLayout = new GroupLayout(contentPane);
contentPane.setLayout(contentPaneLayout);
contentPaneLayout.setHorizontalGroup(
contentPaneLayout.createParallelGroup()
.addGroup(GroupLayout.Alignment.TRAILING, contentPaneLayout.createSequentialGroup()
.addContainerGap()
.addGroup(contentPaneLayout.createParallelGroup()
.addComponent(sourceLabel)
.addComponent(displayLabel)
.addGroup(contentPaneLayout.createSequentialGroup()
.addGap(10, 10, 10)
.addGroup(contentPaneLayout.createParallelGroup()
.addComponent(weatherTimeLapseRadio)
.addComponent(weather2Radio)
.addComponent(tempCheck)
.addComponent(rainCheck)
.addGroup(contentPaneLayout.createSequentialGroup()
.addGap(21, 21, 21)
.addComponent(loadLocationsButton))))
.addGroup(GroupLayout.Alignment.TRAILING, contentPaneLayout.createParallelGroup()
.addComponent(displayLiveButton)
.addComponent(displayChangeButton)))
.addGap(18, 18, 18)
.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 186, Short.MAX_VALUE))
);
contentPaneLayout.setVerticalGroup(
contentPaneLayout.createParallelGroup()
.addGroup(GroupLayout.Alignment.TRAILING, contentPaneLayout.createSequentialGroup()
.addContainerGap()
.addComponent(sourceLabel)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(weather2Radio)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(weatherTimeLapseRadio)
.addGap(14, 14, 14)
.addComponent(loadLocationsButton)
.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(displayLabel)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tempCheck)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(rainCheck)
.addGap(18, 18, Short.MAX_VALUE)
.addComponent(displayLiveButton)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(displayChangeButton)
.addGap(16, 16, 16))
.addComponent(scrollPane)
);
pack();
setLocationRelativeTo(getOwner());
//---- buttonGroup1 ----
ButtonGroup buttonGroup1 = new ButtonGroup();
buttonGroup1.add(weather2Radio);
buttonGroup1.add(weatherTimeLapseRadio);
// JFormDesigner - End of component initialization //GEN-END:initComponents
}
// JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables
private JScrollPane scrollPane;
private JList locationList;
private JButton loadLocationsButton;
private JCheckBox tempCheck;
private JCheckBox rainCheck;
private JButton displayLiveButton;
private JButton displayChangeButton;
private JLabel sourceLabel;
private JRadioButton weather2Radio;
private JRadioButton weatherTimeLapseRadio;
private JLabel displayLabel;
// JFormDesigner - End of variables declaration //GEN-END:variables
}
| true |
4498244d1478de516032de981e97e413841796fe
|
Java
|
rupertlssmith/lojix
|
/lojix/state/src/main/com/thesett/aima/state/Type.java
|
UTF-8
| 7,084 | 2.65625 | 3 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright The Sett Ltd, 2005 to 2014.
*
* 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.thesett.aima.state;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import com.thesett.aima.state.restriction.TypeRestriction;
/**
* A Type is a defined set from which attribute values are drawn. The type encapsulates information that applies accross
* the whole set of attributes that make up the type, such as, the cardinality of the set, the name of the set and so
* on. The type also supplies methods to enumerate or iterate over all the possible attributes that make up the set,
* where this is possible.
*
* <p/>A type is a set of possible values that a data item can take. For example the Java int type, { Integer.MIN_VALUE,
* ..., 0, 1, ..., Integer.MAX_VALUE }, defines the possible values that an int can take.
*
* <p/>It is only possible to enumerate or iterate over the attributes in a type where the number of attributes is
* finite or there exists some ordering over the attributes that maps them onto the natural numbers. In the second case
* there may be infinitely many but the iterator can lazily generate them as requested. Some algorithms can work with
* attributes that take on an infinite number of different values; real numbers, big decimals, all possible strings etc.
* In practice real numbers will be represented as floats or doubles which can only express a bounded number of the
* possible reals but for practical purposes this can be considered an infinity. Usually, algorithms that can only work
* with a fixed number of attributes can only do so where this is a small number, ideally two or three; in the tens can
* be too many in some cases. {@link InfiniteValuesException} will be thrown whenever a type cannot be enumerated
* because it is infinite or not able to be generated lazily as a sequence.
*
* <p/>Note that it is not the class that implements this interface that represents the attribute type but individual
* instances of it that represent different types. For example, there may be two string enumeration types, one that
* represents { Dog, Cat, Cow } and one that represents { Car, Van, Bus }, both will be represented by instances of the
* same class for string enumeration types but with different names. Such types are considered to be dynamic or runtime
* classes.
*
* <pre><p/><table id="crc"><caption>CRC Card</caption>
* <tr><th> Responsibilities <th> Collaborations
* <tr><td> Supply the name of the type.
* <tr><td> Supply the Java class for the type.
* <tr><td> Report how many different values instances of the type can take on.
* <tr><td> Supply all the different values that instances of the type can take on, where there are a finite number.
* </table></pre>
*
* @author Rupert Smith
*/
public interface Type<T>
{
/**
* Gets a new default instance of the type. The types value will be set to its default uninitialized value.
*
* @return A new default instance of the type.
*/
T getDefaultInstance();
/**
* Gets a random instance of the type. This is intended to be usefull for generating test data, as any type in a
* data model will be able to generate random data fitting the model. Some times may be impractical or impossible to
* generate random data for. For example, string patterns fitting a general regular expression cannot in general
* always be randomly generated. For this reason the method signature allows a checked exception to be raised when
* this method is not supported.
*
* @return A new random instance of the type.
*
* @throws RandomInstanceNotSupportedException If the implementation does not support random instance creation.
*/
T getRandomInstance() throws RandomInstanceNotSupportedException;
/**
* Should return a name that uniquely identifies the type.
*
* @return The name of the attribute type.
*/
String getName();
/**
* Returns the underlying Java class that this is the type for, if there is one.
*
* @return The underlying Java class that this is the type for, if there is one.
*/
Class<T> getBaseClass();
/**
* Provides the fully qualified name of the underlying Java class that this is the type for, if there is one.
*
* @return The fully qualified name of underlying Java class that this is the type for, if there is one.
*/
String getBaseClassName();
/**
* Provides a list of restrictions that reduce the possible values that instances of this type can take.
*
* @return A list of resctrictions, empty or <tt>null</tt> indicates that the type has no extra restrictions.
*/
List<TypeRestriction> getRestrictions();
/**
* Should determine how many different values an instance of the implementations type can take on.
*
* @return The number of possible values that an instance of this attribute can take on. If the value is -1 then
* this is to be interpreted as infinity.
*/
int getNumPossibleValues();
/**
* Should return all the different values that an instance of this type can take on.
*
* @return A set of values defining the possible value set for this attribute if this is finite.
*
* @throws InfiniteValuesException If the set of values cannot be listed because it is infinite.
*/
Set<T> getAllPossibleValuesSet() throws InfiniteValuesException;
/**
* Should return all the different values that an instance of this type can take on as an iterator over these
* values. The set of values may be infinte if the iterator can lazily generate them as needed. If the number is
* expected to be large it may be better to use this method to list the values than the
* {@link #getAllPossibleValuesSet} if a lazy iterator is used because this will avoid generating a large collection
* to hold all the possible values.
*
* @return An iterator over the set of attributes defining the possible value set for this attribute if this is
* finite or can be generated as required.
*
* @throws InfiniteValuesException If the set of values cannot be listed because it is infinite.
*/
Iterator<T> getAllPossibleValuesIterator() throws InfiniteValuesException;
/**
* Accepts a visitor, using a visitor pattern, to extend type behaviour with visitors.
*
* @param visitor The visitor to accept.
*/
void acceptVisitor(TypeVisitor visitor);
}
| true |
a9cb855183278ce2892d0970ac923e0a14d360f6
|
Java
|
s-mueller/hikr.org-Parser
|
/src/main/java/li/sebastianmueller/hikr/extractors/GPSExtractor.java
|
UTF-8
| 1,169 | 2.296875 | 2 |
[] |
no_license
|
package li.sebastianmueller.hikr.extractors;
import java.io.File;
import java.net.URL;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import li.sebastianmueller.hikr.util.Util;
public class GPSExtractor {
private static final String GPS_FOLDER = "gps/";
private static final String GEO_TAG = "geo_table";
private static final String HREF = "href";
private static final String HTTP = "https:";
private static final String LINK_TAG = "a";
public static void extract(Document doc, String path) {
try {
Elements ls = doc.getElementById(GEO_TAG).getElementsByTag(LINK_TAG);
for (Element link : ls) {
String linkHref = link.attr(HREF);
if (linkHref.startsWith(HTTP)) {
File localFile = new File(path + GPS_FOLDER + FilenameUtils.getBaseName(linkHref) + "." + FilenameUtils.getExtension(linkHref));
if (!localFile.exists()) {
FileUtils.copyURLToFile(new URL(linkHref), localFile);
ExtractHTML.addPayload(Util.getFileSizeInKB(localFile));
}
}
}
} catch (Exception e) {}
}
}
| true |
29f050c7a4c2abffdc52510ccb3e2527a806f4b9
|
Java
|
thesandx/Scientific-Calculator-with-DevOps
|
/src/test/java/Project/MainTest.java
|
UTF-8
| 899 | 2.53125 | 3 |
[] |
no_license
|
package Project;
import org.junit.Test;
import java.util.regex.Matcher;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.*;
public class MainTest {
Calculator c = new Calculator();
@Test
public void demoTest(){
assertThat("demotest","myvalue", containsString("myvalue"));
}
@Test
public void rootTest(){
assertThat("RootTest",c.calculateRoot(25.0), containsString(String.valueOf(5.0)));
}
@Test
public void factorialTest(){
assertThat("FactorialTest",c.calculateFactorial(5), containsString(String.valueOf(120)));
}
@Test
public void logTest(){
assertThat("LogTest",c.calculateLog(1.0), containsString(String.valueOf(0.0)));
}
@Test
public void powerTest(){
assertThat("PowerTest",c.calculatePower(5.0,2.0), containsString(String.valueOf(25.0)));
}
}
| true |
eb7640ea92c473a4450035d2edbfcce360b3109c
|
Java
|
EruDev/geektime-design-patterns
|
/src/main/java/com/erudev/design/creational/factory/di/BeanDefinition.java
|
UTF-8
| 3,324 | 2.96875 | 3 |
[] |
no_license
|
package com.erudev.design.creational.factory.di;
import java.util.ArrayList;
import java.util.List;
/**
* @author pengfei.zhao
* @date 2020/10/1 20:09
*/
public class BeanDefinition {
private String id;
private String className;
private List<ConstructorArg> constructorArgs = new ArrayList<>();
private boolean lazyInit;
private Scope scope = Scope.PROTOTYPE;
public BeanDefinition(String id, String className) {
this.id = id;
this.className = className;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public List<ConstructorArg> getConstructorArgs() {
return constructorArgs;
}
public void setConstructorArgs(List<ConstructorArg> constructorArgs) {
this.constructorArgs = constructorArgs;
}
public boolean isLazyInit() {
return lazyInit;
}
public void setLazyInit(boolean lazyInit) {
this.lazyInit = lazyInit;
}
public Scope getScope() {
return scope;
}
public void setScope(Scope scope) {
this.scope = scope;
}
public boolean isSingleton() {
return Scope.SINGLETON.equals(scope);
}
public void addConstructorArg(ConstructorArg arg) {
constructorArgs.add(arg);
}
public enum Scope {
SINGLETON,
PROTOTYPE;
}
public static class ConstructorArg {
private boolean isRef;
private Class type;
private Object arg;
public ConstructorArg(Builder builder) {
this.isRef = builder.isRef;
this.type = builder.type;
this.arg = builder.arg;
}
public boolean isRef() {
return isRef;
}
public Class getType() {
return type;
}
public Object getArg() {
return arg;
}
static class Builder {
private boolean isRef;
private Class type;
private Object arg;
public Builder setRef(boolean ref) {
this.isRef = ref;
return this;
}
public Builder setType(Class type) {
this.type = type;
return this;
}
public Builder setArg(Object arg) {
this.arg = arg;
return this;
}
public ConstructorArg build() {
if (this.isRef) {
if (this.type != null) {
throw new IllegalArgumentException("当参数为引用类型时, 无需设置 type 参数.");
}
if (!(arg instanceof String)) {
throw new IllegalArgumentException("请设置引用 ID");
}
} else {
if (this.type == null || this.arg == null) {
throw new IllegalArgumentException("当参数为非引用类型时,type 和 arg 参数必填");
}
}
return new ConstructorArg(this);
}
}
}
}
| true |
af134da7e166745ce6e015db80adbdacb5d32422
|
Java
|
fly327323571/ProjectManagement
|
/src/cn/xidian/parknshop/service/ShareService.java
|
UTF-8
| 286 | 1.65625 | 2 |
[] |
no_license
|
package cn.xidian.parknshop.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.xidian.parknshop.beans.Share;
@Service
@Transactional
public interface ShareService {
void add(Share share);
}
| true |
21d3a3272c6d7c3999b9f564762fac3906ef758d
|
Java
|
buriosca/cz.burios.uniql-jpa
|
/src/cz/burios/uniql/persistence/internal/sessions/DeferrableChangeRecord.java
|
UTF-8
| 6,822 | 2.03125 | 2 |
[] |
no_license
|
/*******************************************************************************
* Copyright (c) 1998, 2013 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package cz.burios.uniql.persistence.internal.sessions;
import cz.burios.uniql.persistence.indirection.IndirectCollection;
import cz.burios.uniql.persistence.internal.queries.ContainerPolicy;
/**
* Abstract change record for collection type records that allow deferrable change detection.
* Used for change tracking when user sets entire collection.
*/
public abstract class DeferrableChangeRecord extends ChangeRecord {
/**
* Used for change tracking when user sets entire collection.
*/
protected transient Object originalCollection;
/**
* Used for change tracking when user sets entire collection.
*/
protected transient Object latestCollection;
/**
* Defines if this change should be calculated at commit time using the two collections.
* This is used to handle collection replacement.
*/
protected boolean isDeferred = false;
public DeferrableChangeRecord() {
super();
}
public DeferrableChangeRecord(ObjectChangeSet owner) {
this.owner = owner;
}
/**
* Returns if this change should be calculated at commit time using the two collections.
* This is used to handle collection replacement.
*/
public boolean isDeferred() {
return isDeferred;
}
/**
* Sets if this change should be calculated at commit time using the two collections.
* This is used to handle collection replacement.
*/
public void setIsDeferred(boolean isDeferred) {
this.isDeferred = isDeferred;
}
/**
* Used for change tracking when user sets entire collection.
* This is the last collection that was set on the object.
*/
public Object getLatestCollection() {
return latestCollection;
}
/**
* Used for change tracking when user sets entire collection.
* This is the original collection that was set on the object when it was cloned.
*/
public Object getOriginalCollection() {
return originalCollection;
}
/**
* Used for change tracking when user sets entire collection.
* This is the last collection that was set on the object.
*/
public void setLatestCollection(Object latestCollection) {
this.latestCollection = latestCollection;
}
/**
* Used for change tracking when user sets entire collection.
* This is the original collection that was set on the object when it was cloned.
*/
public void setOriginalCollection(Object originalCollection) {
this.originalCollection = originalCollection;
}
/**
* Recreates the original state of currentCollection.
*/
abstract public void internalRecreateOriginalCollection(Object currentCollection, AbstractSession session);
/**
* Clears info about added / removed objects set by change tracker.
* Called after the change info has been already used for creation of originalCollection.
* Also called to make sure there is no change info before comparison for change is performed
* (change info is still in the record after comparison for change is performed
* and may cause wrong results when the second comparison for change performed on the same change record).
*/
abstract public void clearChanges();
/**
* Recreates the original state of the collection.
*/
public void recreateOriginalCollection(Object currentCollection, AbstractSession session) {
if(currentCollection == null) {
this.setOriginalCollection(null);
return;
}
if(currentCollection instanceof IndirectCollection) {
// to avoid raising event when we add/remove elements from this collection later in this method.
setOriginalCollection(((IndirectCollection)currentCollection).getDelegateObject());
} else {
setOriginalCollection(currentCollection);
}
internalRecreateOriginalCollection(this.originalCollection, session);
clearChanges();
}
/**
* ADVANCED:
* If the owning UnitOfWork has shouldChangeRecordKeepOldValue set to true,
* then return the old value of the attribute represented by this ChangeRecord.
*/
public Object getOldValue() {
if(this.originalCollection != null) {
return this.originalCollection;
} else {
if(getOwner() != null) {
Object obj = ((cz.burios.uniql.persistence.internal.sessions.ObjectChangeSet)getOwner()).getUnitOfWorkClone();
AbstractSession session = ((cz.burios.uniql.persistence.internal.sessions.UnitOfWorkChangeSet)getOwner().getUOWChangeSet()).getSession();
if(obj != null && session != null) {
Object currentCollection = this.mapping.getAttributeValueFromObject(obj);
ContainerPolicy cp = this.mapping.getContainerPolicy();
Object cloneCurrentCollection = cp.containerInstance(cp.sizeFor(currentCollection));
for (Object valuesIterator = cp.iteratorFor(currentCollection); cp.hasNext(valuesIterator);) {
Object member = cp.next(valuesIterator, session);
cp.addInto(cp.keyFromIterator(valuesIterator), member, cloneCurrentCollection , session);
}
return getOldValue(cloneCurrentCollection, session);
}
}
return null;
}
}
public Object getOldValue(Object currentCollection, AbstractSession session) {
if(currentCollection != null) {
if(currentCollection instanceof IndirectCollection) {
currentCollection = ((IndirectCollection)currentCollection).getDelegateObject();
}
internalRecreateOriginalCollection(currentCollection, session);
}
return currentCollection;
}
}
| true |
7dcc5223f9da4247d1030b4d5c91a8a23c71338d
|
Java
|
vitormoreiradematos/testeJava
|
/src/main/java/com/testejava/eventos/repositories/NotificacaoRepository.java
|
UTF-8
| 245 | 1.5 | 2 |
[] |
no_license
|
package com.testejava.eventos.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import com.testejava.eventos.entities.Notificacao;
public interface NotificacaoRepository extends JpaRepository<Notificacao, Long>
{
}
| true |
2de8e4cc2d4c5942867d69b862c55a08d9f22c90
|
Java
|
ebi-gene-expression-group/atlas
|
/base/src/main/java/uk/ac/ebi/atlas/search/baseline/LinkToBaselineProfile.java
|
UTF-8
| 1,258 | 1.953125 | 2 |
[
"Apache-2.0"
] |
permissive
|
package uk.ac.ebi.atlas.search.baseline;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang3.tuple.Pair;
import uk.ac.ebi.atlas.experimentpage.baseline.LinkToExperimentPage;
import uk.ac.ebi.atlas.model.experiment.baseline.FactorGroup;
import uk.ac.ebi.atlas.model.experiment.baseline.RichFactorGroup;
import uk.ac.ebi.atlas.search.SemanticQuery;
import java.util.Map;
public class LinkToBaselineProfile extends LinkToExperimentPage<BaselineExperimentProfile> {
public LinkToBaselineProfile(SemanticQuery geneQuery) {
super(geneQuery);
}
@Override
public Map<String, String> perInputQueryParameters(BaselineExperimentProfile baselineExperimentProfile) {
Pair<String, FactorGroup> accessionAndFilterFactors = baselineExperimentProfile.getExperimentSlice();
return accessionAndFilterFactors.getRight().isEmpty() ?
ImmutableMap.of() :
ImmutableMap.of(
"filterFactors", new RichFactorGroup(accessionAndFilterFactors.getRight()).asUrlEncodedJson());
}
@Override
public String accession(BaselineExperimentProfile baselineExperimentProfile) {
return baselineExperimentProfile.getExperimentSlice().getLeft();
}
}
| true |
883f8829a0152244ea6fa8a6e56dddd39b8203cb
|
Java
|
pedrotorchio/middleware-final
|
/src/middleAir/common/marshaller/Marshaller.java
|
UTF-8
| 1,759 | 2.6875 | 3 |
[] |
no_license
|
package middleAir.common.marshaller;
import middleAir.common.requesthandler.Request;
import java.io.*;
public class Marshaller {
public byte[] marshall(Request req) throws IOException {
// serializar request
byte[] head = req.getHeader().toString().replaceAll("(\\{|\\})", "").trim().getBytes();
byte[] body = req.getBody().getBytes();
ByteArrayOutputStream ba = new ByteArrayOutputStream();
DataOutputStream ds = new DataOutputStream(ba);
writeChunk(ds, head);
writeChunk(ds, body);
ds.flush();
ds.close();
return ba.toByteArray();
}
public Request unmarshall(InputStream stream) throws IOException {
DataInputStream oi = new DataInputStream(stream);
byte[] head = readChunk(oi);
byte[] body = readChunk(oi);
String sBody = new String(body);
String sHead = new String(head);
Request req = new Request();
for (String single : sHead.split(",")) {
String[] kv = single.split("=", 2);
if (kv.length == 2) {
String key = kv[0], value = kv[1];
req.addHeader(key.trim(), value.trim());
}
}
req.setBody(sBody);
return req;
}
protected void writeChunk(DataOutputStream stream, byte[] bytes) {
try {
stream.writeInt(bytes.length);
stream.write(bytes, 0, bytes.length);
} catch (IOException e) {
e.printStackTrace();
}
}
protected byte[] readChunk(DataInputStream stream) throws IOException {
byte[] chunk = new byte[stream.readInt()];
stream.read(chunk, 0, chunk.length);
return chunk;
}
}
| true |
3f352892f096b0384b129c1d293fed2c33fb74f6
|
Java
|
adriano-candido/BirdPointProf
|
/Bird Point/Source/BirdPoint/src/birdpoint/empresa/EmpresaTableModel.java
|
UTF-8
| 2,037 | 2.78125 | 3 |
[] |
no_license
|
/*
* 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 birdpoint.empresa;
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.AbstractTableModel;
/**
*
* @author Karlos
*/
public class EmpresaTableModel extends AbstractTableModel {
private List<Empresa> empresas = new ArrayList<>();
private String[] colunas = {"Código", "Nome", "Nome Fantasia", "CNPJ", "Cidade", "Telefone", "Email"};
public EmpresaTableModel(List<Empresa> empresa) {
this.empresas = empresa;
}
@Override
public int getRowCount() {
return empresas.size();
}
@Override
public int getColumnCount() {
return colunas.length;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Empresa empresa = empresas.get(rowIndex);
switch (columnIndex) {
case 0:
return empresa.getIdEmpresa();
case 1:
return empresa.getNomeEmpresa();
case 2:
return empresa.getNomeFantasiaEmpresa();
case 3:
return empresa.getCnpjEmpresa();
case 4:
return empresa.getCidadeEnderecoEmpresa();
case 5:
return empresa.getTelefoneEmpresa();
case 6:
return empresa.getEmailEmpresa();
}
return null;
}
@Override
public String getColumnName(int index) {
switch (index) {
case 0:
return colunas[0];
case 1:
return colunas[1];
case 2:
return colunas[2];
case 3:
return colunas[3];
case 4:
return colunas[4];
case 5:
return colunas[5];
case 6:
return colunas[5];
}
return null;
}
}
| true |
ba8c13013c7e0ce6b60f8e25389f35a57f900295
|
Java
|
wang3526/JavaSE
|
/src/day10/poly/TVs.java
|
GB18030
| 336 | 3.1875 | 3 |
[] |
no_license
|
package day10.poly;
/**
*
* */
public class TVs extends Goods{
//췽
public TVs(){
}
public TVs(String name,int price){
this.setName(name);
this.setPrice(price);
}
//дӡ
@Override
public void print() {
System.out.println(this.getName()+"ļ۸ǣ"+this.getPrice());
}
}
| true |
2b54851e81d9a00f6904c067e5804df73183e527
|
Java
|
leooliveiraz/euAtendo
|
/src/main/java/rocha/euAtendo/repository/PlanoConvenioRepository.java
|
UTF-8
| 375 | 1.671875 | 2 |
[] |
no_license
|
package rocha.euAtendo.repository;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import rocha.euAtendo.model.PlanoConvenio;
@Repository
public interface PlanoConvenioRepository extends CrudRepository<PlanoConvenio, Long> {
List<PlanoConvenio> findByNome(String nome);
}
| true |
fb83080ace0b74a45c9332399d5818b18852f223
|
Java
|
Ankit-adi/Practice
|
/src/HappyNumber.java
|
UTF-8
| 703 | 3.5 | 4 |
[] |
no_license
|
import java.util.*;
class HappyNumber {
public static int add(int k){
int rem;
int sum=0;
while(k!=0){
rem=k%10;
sum+=rem*rem;
k=k/10;
}
return sum;
}
public static boolean isHappy(int n){
int res=add(n);
int s=res;
int t=10;
while(s!=1 && t!=0) {
s = add(s);
t--;
}
if(s==1)
return true;
else
return false;
}
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
boolean result=isHappy(n);
System.out.println(result);
}
}
| true |
5e912db885e9672e4778dc2255589ca662d2e6cc
|
Java
|
bluelzx/xianjindai
|
/app/src/main/java/com/brioal/bottomtablayout/MainActivity.java
|
UTF-8
| 3,886 | 2.171875 | 2 |
[] |
no_license
|
package com.brioal.bottomtablayout;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import com.brioal.bottomtablayout.fragment.AboutFragment;
import com.brioal.bottomtablayout.fragment.FirstFragment;
import com.brioal.bottomtablayout.fragment.TodayFragment;
import com.umeng.analytics.MobclickAgent;
import me.majiajie.pagerbottomtabstrip.Controller;
import me.majiajie.pagerbottomtabstrip.PagerBottomTabLayout;
import me.majiajie.pagerbottomtabstrip.listener.OnTabItemSelectListener;
public class MainActivity extends AppCompatActivity {
private PagerBottomTabLayout bottomTabLayout;
private FragmentManager mFragmentManger;
private Fragment mCurrentFragment;
private Controller mController;
int[] testColors = {0xFF00796B,0xFF5B4947,0xFF607D8B,0xFFF57C00,0xFFF57C00};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initBottonLayout();
}
private void initBottonLayout() {
bottomTabLayout = (PagerBottomTabLayout) findViewById(R.id.tab);
bottomTabLayout.builder().build().setBackgroundColor(getResources().getColor(R.color.windows_color));
mCurrentFragment=new TodayFragment();
mFragmentManger=getSupportFragmentManager();
mFragmentManger.beginTransaction().add(R.id.app_item, mCurrentFragment).commit();
mController=bottomTabLayout.builder()
.addTabItem(R.mipmap.home, "首页")
.addTabItem(R.drawable.bug,"主页",testColors[0])
.addTabItem(android.R.drawable.btn_star, "帮助",testColors[3])
.build();
mController.addTabItemClickListener(listener);
}
OnTabItemSelectListener listener=new OnTabItemSelectListener() {
@Override
public void onSelected(int index, Object tag) {
switchMenu(getFragmentName(index+1));
}
@Override
public void onRepeatClick(int index, Object tag) {
}
};
private String getFragmentName(int menuId) {
switch (menuId) {
case 1:
return TodayFragment.class.getName();
case 2:
return FirstFragment.class.getName();
case 3:
return AboutFragment.class.getName();
default:
return null;
}
}
/**
* 底部菜单栏
*
* @param fragmentName
*/
private void switchMenu(String fragmentName) {
Fragment fragment = mFragmentManger.findFragmentByTag(fragmentName);
if (fragment != null) {
if (fragment == mCurrentFragment) return;
mFragmentManger.beginTransaction().show(fragment).commit();
} else {
fragment = Fragment.instantiate(this, fragmentName);
mFragmentManger.beginTransaction().add(R.id.app_item, fragment, fragmentName).commit();
}
if (mCurrentFragment != null) {
mFragmentManger.beginTransaction().hide(mCurrentFragment).commit();
}
mCurrentFragment = fragment;
}
private long mLastBackTime = 0;
@Override
public void onBackPressed() {
// finish while click back key 2 times during 1s.
if ((System.currentTimeMillis() - mLastBackTime) < 1000) {
finish();
} else {
mLastBackTime = System.currentTimeMillis();
Toast.makeText(this, R.string.exit_click_back_again, Toast.LENGTH_SHORT).show();
}
}
public void onResume() {
super.onResume();
MobclickAgent.onResume(this);
}
public void onPause() {
super.onPause();
MobclickAgent.onPause(this);
}
}
| true |
ce6c1de842243472bedb44d7f21fe73759e7cc68
|
Java
|
pradeepnemmani/school
|
/MarshUnmarshSchool.java
|
UTF-8
| 6,548 | 2.453125 | 2 |
[] |
no_license
|
package school;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import java.io.File;
import java.util.List;
/**
* Created by jan on 19/4/14.
*/
public class MarshUnmarshSchool {
public static final String schoolSchema = "/home/jan/IdeaProjects/xml/src/school.xsd";
private static Schema schema = null;
public static School createData(ObjectFactory of) {
School s = of.createSchool();
s.setSchoolName("Hydrogen");
BoardMember bm = MarshUnmarshSchool.createBoardMember(of, "amar", 10, createCalender(2121, 02, 02));
BoardMember bm1 = MarshUnmarshSchool.createBoardMember(of, "Jan", 22, createCalender(125, 02, 12));
BoardMembers bms = new BoardMembers();
bms.getBoardMember().add(bm);
bms.getBoardMember().add(bm1);
s.setBoardMembers(bms);
Student stu = MarshUnmarshSchool.createStudent(of, "amaarnath", 12, 5);
Student stu1 = MarshUnmarshSchool.createStudent(of, "abc", 125, 45);
Members mems = new Members();
mems.getMember().add(stu);
mems.getMember().add(stu1);
s.setMembers(mems);
Address add = new Address();
add.setLandmark("madhapur");
add.setArea("mdpur");
add.setStreet("ayyapa Society");
add.setCity("hyderabad");
add.setState("Andhra Pradesh");
add.setCountry("India");
add.setZipcode("50132");
s.setAddress(add);
return s;
}
public static BoardMember createBoardMember(ObjectFactory of, String bName, int bId, XMLGregorianCalendar bDate) {
BoardMember bm = of.createBoardMember();
bm.setName(bName);
bm.setId(bId);
bm.setFrom(bDate);
return bm;
}
public static Student createStudent(ObjectFactory of, String sName, int sId, int sClass) {
Student stu = of.createStudent();
stu.setName(sName);
stu.setId(sId);
stu.setClazz(sClass);
return stu;
}
public static XMLGregorianCalendar createCalender(int year, int month, int day) {
XMLGregorianCalendar xgc = null;
try {
DatatypeFactory df = DatatypeFactory.newInstance();
xgc = df.newXMLGregorianCalendarDate(year, month, day, 0);
} catch (DatatypeConfigurationException e) {
e.printStackTrace();
}
return xgc;
}
public static Schema createSchema(String fileName) throws Exception {
if (schema != null) {
SchemaFactory sf = SchemaFactory.newInstance(MarshUnmarshSchool.schoolSchema);
schema = sf.newSchema(new File(fileName));
}
return schema;
}
public static void serilaizable(JAXBContext ctxt, Object obj, String output) throws Exception {
if (ctxt != null) {
Marshaller m = ctxt.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
Schema schema = MarshUnmarshSchool.createSchema(MarshUnmarshSchool.schoolSchema);
m.setSchema(schema);
m.marshal(obj, new File(output));
}
}
public static School deserialize(JAXBContext ctxt, String xmlFile) throws Exception {
if (ctxt != null) {
try {
Unmarshaller um = ctxt.createUnmarshaller();
Schema schema = MarshUnmarshSchool.createSchema(MarshUnmarshSchool.schoolSchema);
um.setSchema(schema);
Object unobj = um.unmarshal(new File(xmlFile));
if (unobj instanceof School) {
return (School) unobj;
}
} catch (JAXBException e) {
e.printStackTrace();
}
}
return null;
}
public static void printUnmarshallData(School s) {
System.out.println("printing unmarshalling data");
System.out.println("School Name is : " + s.getSchoolName());
BoardMembers bms = s.getBoardMembers();
Members members = s.getMembers();
Address add = s.getAddress();
if (bms != null && members != null) {
List<BoardMember> boardMemberList = bms.getBoardMember();
List<Student> studentList = members.getMember();
if (boardMemberList != null && studentList != null && !studentList.isEmpty() && !boardMemberList.isEmpty()) {
for (BoardMember bm : boardMemberList) {
System.out.println("-------------------------");
System.out.println("Member Name :" + bm.getName());
System.out.println("Member Id :" + bm.getId());
System.out.println("Member From :" + bm.getFrom());
}
for (Member member : studentList) {
System.out.println("----------Student Details---------------");
System.out.println("Student Name :" + member.getName());
System.out.println("Student Id :" + member.getId());
System.out.println("Student Class :" + member.getClass());
}
System.out.println("-------------Address-----------");
System.out.println("Area :" + add.getArea());
System.out.println("Street :" + add.getStreet());
System.out.println("Landmark :" + add.getLandmark());
System.out.println("City :" + add.getCity());
System.out.println("State :" + add.getState());
System.out.println("Country :" + add.getCountry());
System.out.println("zip code :" + add.getZipcode());
}
}
}
public static void main(String[] args) {
try {
ObjectFactory of = new ObjectFactory();
School s = MarshUnmarshSchool.createData(of);
JAXBContext ctxt = JAXBContext.newInstance("school");
MarshUnmarshSchool.serilaizable(ctxt, s, "/tmp/out.xml");
System.out.println("Unmarshalling");
School ss = MarshUnmarshSchool.deserialize(ctxt, "/tmp/out.xml");
MarshUnmarshSchool.printUnmarshallData(ss);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true |
1a94410382f0e0085fb2091455001ac71d697947
|
Java
|
AIT-Rescue/CommunicationLibrary
|
/Comlib-ADK/src/main/java/comlib/adk/team/tactics/basic/event/BasicPoliceEvent.java
|
UTF-8
| 1,594 | 2.5625 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
package comlib.adk.team.tactics.basic.event;
import comlib.adk.team.tactics.basic.BasicAmbulance;
import comlib.event.information.PoliceForceMessageEvent;
import comlib.message.information.PoliceForceMessage;
import rescuecore2.standard.entities.PoliceForce;
import rescuecore2.standard.entities.StandardWorldModel;
public class BasicPoliceEvent implements PoliceForceMessageEvent{
private BasicAmbulance tactics;
public BasicPoliceEvent(BasicAmbulance basicAmbulance) {
this.tactics = basicAmbulance;
}
@Override
public void receivedRadio(PoliceForceMessage msg) {
PoliceForce policeForce = this.reflectedMessage(this.tactics.model, msg);
this.tactics.victimSelector.add(policeForce);
}
@Override
public void receivedVoice(PoliceForceMessage msg) {
this.receivedRadio(msg);
}
public PoliceForce reflectedMessage(StandardWorldModel swm, PoliceForceMessage msg) {
PoliceForce policeforce = (PoliceForce) swm.getEntity(msg.getHumanID());
if (policeforce == null) {
swm.addEntity(new PoliceForce(msg.getHumanID()));
policeforce = (PoliceForce) swm.getEntity(msg.getHumanID());
}
policeforce.isHPDefined();
policeforce.isBuriednessDefined();
policeforce.isDamageDefined();
policeforce.isPositionDefined();
policeforce.setHP(msg.getHP());
policeforce.setBuriedness(msg.getBuriedness());
policeforce.setDamage(msg.getDamage());
policeforce.setPosition(msg.getPosition());
return policeforce;
}
}
| true |
d593417386415144ab5b60f0d413e465f3b5678b
|
Java
|
empyrosx/sonar-branch-plugin
|
/branch-scanner/src/main/java/com/github/empyrosx/sonarqube/scanner/ScannerSettings.java
|
UTF-8
| 502 | 1.648438 | 2 |
[] |
no_license
|
package com.github.empyrosx.sonarqube.scanner;
public class ScannerSettings {
// branch analyze
public static final String SONAR_BRANCH_NAME = "sonar.branch.name";
public static final String SONAR_BRANCH_TARGET = "sonar.branch.target";
// pull request analyze
public static final String SONAR_PR_KEY = "sonar.pullrequest.key";
public static final String SONAR_PR_BRANCH = "sonar.pullrequest.branch";
public static final String SONAR_PR_BASE = "sonar.pullrequest.base";
}
| true |
4f6525d843ff2bdf8f54ee6c951110fb3ca35d4f
|
Java
|
lijinzhou2017/blog-dubbo
|
/blog-utils/src/main/java/com/blog/web/WebUtils.java
|
UTF-8
| 2,608 | 2.671875 | 3 |
[] |
no_license
|
package com.blog.web;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
/**
* @author lijinzhou
* @since 2017/12/20 19:19
*/
public class WebUtils {
/**
* 获取ip地址
* 在一般情况下使用Request.getRemoteAddr()即可,但是经过nginx等反向代理软件后,这个方法会失效。
* 本方法先从Header中获取X-Real-IP,如果不存在再从X-Forwarded-For获得第一个IP(用,分割),
* 如果还不存在则调用Request .getRemoteAddr()。
*
* @author lijinzhou
* @since 2017/12/20 19:19
*/
public static String getIpAddress(HttpServletRequest request) {
String ip = request.getHeader("X-Real-IP");
if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
return ip;
}
ip = request.getHeader("X-Forwarded-For");
if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
// 多次反向代理后会有多个IP值,第一个为真实IP。
int index = ip.indexOf(',');
return index != -1 ? ip.substring(0, index) : ip;
} else {
return request.getRemoteAddr();
}
}
/**
* 获取ip地址
* 在一般情况下使用Request.getRemoteAddr()即可,但是经过nginx等反向代理软件后,这个方法会失效。
* 本方法先从Header中获取X-Real-IP,如果不存在再从X-Forwarded-For获得第一个IP(用,分割),
* 如果还不存在则调用Request .getRemoteAddr()。
*
* @author lijinzhou
* @since 2017/12/20 19:19
*/
public static String getIpAddress(SerializableHttpServletRequest request) {
String ip = request.getHeaderMap().get("X-Real-IP");
if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
return ip;
}
ip = request.getHeaderMap().get("X-Forwarded-For");
if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
// 多次反向代理后会有多个IP值,第一个为真实IP。
int index = ip.indexOf(',');
return index != -1 ? ip.substring(0, index) : ip;
} else {
return request.getRemoteAddr();
}
}
/**
* 判断是否是ajax请求
*
* @author lijinzhou
* @since 2017/12/20 19:19
*/
public static boolean isAjax(HttpServletRequest request) {
return (request.getHeader("X-Requested-With") != null && "XMLHttpRequest".equals(request.getHeader("X-Requested-With").toString()));
}
}
| true |
af10af65c939587d64be717b7de485d812557200
|
Java
|
SubashS96/sample
|
/src/test/java/com/pages/SelectHotelPage.java
|
UTF-8
| 662 | 2.09375 | 2 |
[] |
no_license
|
package com.pages;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.base.LibGlobal;
public class SelectHotelPage extends LibGlobal {
public SelectHotelPage() {
PageFactory.initElements(driver, this);
}
@FindBy (id = "radiobutton_0")
private WebElement btnRadioButton;
@FindBy (id = "continue")
private WebElement btnContinue;
public WebElement getBtnRadioButton() {
return btnRadioButton;
}
public WebElement getBtnContinue() {
return btnContinue;
}
public void selectHotel() {
click(getBtnRadioButton());
click(getBtnContinue());
}
}
| true |
c25808233753c1966b411988f78e89c76493314d
|
Java
|
josiahelmer/Inheritance
|
/src/inheritance/controller/InheritanceController.java
|
UTF-8
| 667 | 3.359375 | 3 |
[] |
no_license
|
package inheritance.controller;
import inheritance.model.*;
import java.util.ArrayList;
public class InheritanceController
{
private ArrayList<SillyThings> sillyThingsList;
public InheritanceController()
{
sillyThingsList = new ArrayList<SillyThing>();
setupSillyList();
}
private void setupSillyList()
{
}
public String showInterfaceStuff()
{
String interfaceInfo = "";
for(SillyThing currentSilly : sillyThingsList)
{
interfaceInfo.concat("The current silly thing is a " + currentSilly.toString());
interfaceInfo.concat("\n" + "ad it has a silly level of" + currentSilly.sillinessLevel());
}
return interfaceInfo;
}
}
| true |
6a290962510cf446d461e2b42e7e19fc0ddc8172
|
Java
|
jerrysalonen/Prototype
|
/src/prototype/HourHand.java
|
UTF-8
| 280 | 2.75 | 3 |
[] |
no_license
|
package prototype;
/**
* @author Jerry Salonen
*/
public class HourHand {
int time;
public HourHand(int init) {
this.time = init;
}
public void setTime(int time) {
this.time = time;
}
public int getTime() {
return this.time;
}
}
| true |
bc7e920f9a4f83960f6a1d29f8a0ac937e885f0a
|
Java
|
kayceesrk/Sting
|
/trunk/compiler/src/sessionj/ast/typenodes/SJGProtocolRefNode_c.java
|
UTF-8
| 461 | 1.78125 | 2 |
[] |
no_license
|
//<By MQ> Added
package sessionj.ast.typenodes;
import polyglot.ast.*;
import polyglot.util.Position;
import static sessionj.SJConstants.*;
public class SJGProtocolRefNode_c extends SJGProtocolNode_c implements SJGProtocolRefNode
{
public SJGProtocolRefNode_c(Position pos, Receiver target)
{
super(pos, target);
}
public String nodeToString()
{
return SJ_STRING_GPROTOCOL_REF_PREFIX + "(" + target() + ")"; // Factor out constants.
}
}
//</By MQ>
| true |
cc289233b9dfe5e2543265c7675dc4657fe7d8c2
|
Java
|
zk798/jar
|
/src/main/java/com/example/demo/print.java
|
UTF-8
| 287 | 2.5 | 2 |
[] |
no_license
|
package com.example.demo;
public class print {
public void get(B a){
System.out.println("b");
}
public void get(A a){
System.out.println("a");
}
public static void main(String[] args) {
B a = new B();
new print().get(a);
}
}
| true |
ef182443f462a3b0ff7931caa24901060108f78b
|
Java
|
15875206987/Campus_Tours_JavaWeb
|
/src/com/dao/CategoryDao.java
|
UTF-8
| 1,677 | 2.34375 | 2 |
[] |
no_license
|
package com.dao;
import com.bean.Category;
import com.google.gson.Gson;
import java.sql.SQLException;
import java.util.List;
public class CategoryDao extends BasicDao<Category> {
public String getLivingCategory() throws SQLException {
String sql = "select * from categories where category_parent = 1";
List<Category> categoryList = queryMulti(sql,Category.class);
Gson gson = new Gson();
return gson.toJson(categoryList);
}
public String getStudyCategory() throws SQLException {
String sql = "select * from categories where category_parent = 2";
List<Category> categoryList = queryMulti(sql,Category.class);
Gson gson = new Gson();
return gson.toJson(categoryList);
}
public String getCategory() throws SQLException {
String sql = "select * from categories";
List<Category> categoryList = queryMulti(sql,Category.class);
Gson gson = new Gson();
return gson.toJson(categoryList);
}
public int deleteCategory(int id) throws Exception{
String sql = "delete from categories where category_id = ?";
return update(sql,id);
}
public int updateCategory(int c_id,String c_name,int c_parent) throws SQLException {
String sql = "update categories set category_name = ?,category_parent = ? where category_id = ?";
return update(sql, c_name,c_parent,c_id);
}
public int addCategory(String c_name,int c_parent) throws SQLException {
String sql = "insert into categories(category_name,category_parent) values(?,?)";
return update(sql, c_name,c_parent);
}
}
| true |
58380b20091790f1c9e071540fcc2507048d1a45
|
Java
|
research-iobserve/mobile
|
/thesis.iobserve/iobserve-analysis/analysis/src/main/java/org/iobserve/analysis/model/SystemModelProvider.java
|
UTF-8
| 1,785 | 1.671875 | 2 |
[
"Apache-2.0"
] |
permissive
|
/***************************************************************************
* Copyright (C) 2015 iObserve Project (https://www.iobserve-devops.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
***************************************************************************/
package org.iobserve.analysis.model;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EPackage;
import org.palladiosimulator.pcm.system.System;
import org.palladiosimulator.pcm.system.SystemPackage;
/**
* Model provider to provide {@link System} model.
*
* @author Robert Heinrich
* @author Alessandro Giusa
*
*/
public final class SystemModelProvider extends AbstractModelProvider<System> {
/**
* Create model provider to provide {@link System} model.
*
* @param uriModelInstance
* uri to model
*/
public SystemModelProvider(final URI uriModelInstance) {
super(uriModelInstance);
}
@Override
public void resetModel() {
final org.palladiosimulator.pcm.system.System model = this.getModel();
model.getAssemblyContexts__ComposedStructure().clear();
}
@Override
protected EPackage getPackage() {
return SystemPackage.eINSTANCE;
}
}
| true |
5fb62d821f30ea3a795753101245c1240a1da1f8
|
Java
|
byblinkdagger/JustColor
|
/app/src/main/java/com/blink/dagger/justcolor/ui/activity/WelcomeActivity.java
|
UTF-8
| 1,578 | 2.359375 | 2 |
[] |
no_license
|
package com.blink.dagger.justcolor.ui.activity;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.blink.dagger.justcolor.R;
import com.blink.dagger.justcolor.util.ColorDbUtil;
import com.blink.dagger.justcolor.util.PreferencesUtils;
public class WelcomeActivity extends AppCompatActivity {
//是否是第一次启动
boolean isFirst;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
isFirst = PreferencesUtils.getValueOfSharedPreferences(this, "isFirst", true);
initDB();
Handler handler = new Handler();
if (isFirst){
handler.postDelayed(new Runnable() {
@Override
public void run() {
gotoMain();
}
},1200);
}else {
gotoMain();
}
}
private void gotoMain() {
Intent intent = new Intent(this,MainActivity.class);
startActivity(intent);
finish();
}
/**
* 第一次进入app时初始化颜色库数据
*/
private void initDB() {
if (isFirst){
new Thread(new Runnable() {
@Override
public void run() {
ColorDbUtil.initColor();
}
}).start();
PreferencesUtils.addToSharedPreferences(WelcomeActivity.this,"isFirst",false);
}
}
}
| true |
d6d464d2a31efed76ab4c7ae208f35159af7a76f
|
Java
|
elteKrisztianKereszti/we_2019_02_04
|
/src/main/java/hu/elte/IssueTracker/controllers/rest/IssueRestController.java
|
UTF-8
| 3,060 | 2.140625 | 2 |
[] |
no_license
|
/*
* 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 hu.elte.IssueTracker.controllers.rest;
/**
*
* @author KeresztiKrisztián
*/
import hu.elte.IssueTracker.entities.Issue;
import hu.elte.IssueTracker.repositories.IssueRepository;
import hu.elte.IssueTracker.repositories.LabelRepository;
import hu.elte.IssueTracker.repositories.MessageRepository;
import hu.elte.IssueTracker.security.AuthenticatedUser;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/issues")
@CrossOrigin
public class IssueRestController {
@Autowired
private IssueRepository issueRepository;
@Autowired
private MessageRepository messageRepository;
@Autowired
private LabelRepository labelRepository;
@Autowired
private AuthenticatedUser authenticatedUser;
@GetMapping("")
public ResponseEntity<Iterable<Issue>> getAll() {
return ResponseEntity.ok(issueRepository.findAll());
}
@GetMapping("/{id}")
public ResponseEntity<Issue> get(@PathVariable Integer id) {
Optional<Issue> issue = issueRepository.findById(id);
if (issue.isPresent()) {
return ResponseEntity.ok(issue.get());
} else {
return ResponseEntity.notFound().build();
}
}
@PostMapping("")
public ResponseEntity<Issue> post(@RequestBody Issue issue) {
Issue savedIssue = issueRepository.save(issue);
return ResponseEntity.ok(savedIssue);
}
@PutMapping("/{id}")
public ResponseEntity<Issue> update
(@PathVariable Integer id,
@RequestBody Issue issue) {
Optional<Issue> oIssue = issueRepository.findById(id);
if (oIssue.isPresent()) {
issue.setId(id);
return ResponseEntity.ok(issueRepository.save(issue));
} else {
return ResponseEntity.notFound().build();
}
}
@DeleteMapping("/{id}")
public ResponseEntity<Issue> delete
(@PathVariable Integer id) {
Optional<Issue> oIssue = issueRepository.findById(id);
if (oIssue.isPresent()) {
issueRepository.deleteById(id);
return ResponseEntity.ok().build();
} else {
return ResponseEntity.notFound().build();
}
}
}
| true |
3381c60492c4156c1f2fa3c08803169e1adff641
|
Java
|
christ1750/NowCoder
|
/src/JZoffer/reverseLink.java
|
GB18030
| 580 | 2.90625 | 3 |
[] |
no_license
|
package JZoffer;
/**
* author: christ
* data201638 8:14:22
* ˵
*/
//תҪָͬʱϻ
public class reverseLink {
public ListNode ReverseLink(ListNode head){
if(head == null){
return null;
}
ListNode newHead = null;
ListNode pNode = head;
ListNode pPrev = null;
while(pNode != null){
ListNode pNext = pNode.next;
if(pNext == null){
newHead = pNode;
}
pNode.next = pPrev;
pPrev = pNode;
pNode = pNext;
}
return newHead;
}
}
| true |
c7b7ddd001ea225a5fa04803804dd1ed33b83e5d
|
Java
|
oneboat/highdsa
|
/highdsa-service-mybatis/src/main/java/pers/husen/highdsa/service/mybatis/impl/CustUserManagerImpl.java
|
UTF-8
| 8,336 | 2.140625 | 2 |
[] |
no_license
|
package pers.husen.highdsa.service.mybatis.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pers.husen.highdsa.common.encrypt.Md5Encrypt;
import pers.husen.highdsa.common.entity.enums.CustUserState;
import pers.husen.highdsa.common.entity.po.customer.CustNavigation;
import pers.husen.highdsa.common.entity.po.customer.CustRole;
import pers.husen.highdsa.common.entity.po.customer.CustUser;
import pers.husen.highdsa.common.entity.po.customer.CustUserInfo;
import pers.husen.highdsa.common.entity.po.customer.CustUserRole;
import pers.husen.highdsa.common.exception.db.NullPointerException;
import pers.husen.highdsa.common.sequence.SequenceManager;
import pers.husen.highdsa.common.utility.DateFormat;
import pers.husen.highdsa.service.mybatis.CustUserManager;
import pers.husen.highdsa.service.mybatis.dao.customer.CustPermissionMapper;
import pers.husen.highdsa.service.mybatis.dao.customer.CustRoleMapper;
import pers.husen.highdsa.service.mybatis.dao.customer.CustUserInfoMapper;
import pers.husen.highdsa.service.mybatis.dao.customer.CustUserMapper;
import pers.husen.highdsa.service.mybatis.dao.customer.CustUserRoleMapper;
/**
* @Desc 客户管理实现, dubbo api函数名称和 mybatis数据查询的对应关系为: create -> insert, find ->
* select, modify -> update, delete -> delete
*
* @Author 何明胜
*
* @Created at 2018年4月24日 上午10:26:55
*
* @Version 1.0.6
*/
@Service("custUserManager")
public class CustUserManagerImpl implements CustUserManager {
private static final Logger logger = LogManager.getLogger(CustUserManagerImpl.class.getName());
@Autowired
private CustUserMapper custUserMapper;
@Autowired
private CustUserInfoMapper custUserInfoMapper;
@Autowired
private CustUserRoleMapper custUserRoleMapper;
@Autowired
private CustRoleMapper custRoleMapper;
@Autowired
private CustPermissionMapper custPermissionMapper;
@Override
public String createUser(CustUser custUser) {
// 注册用户设置默认用户名
custUser.setUserName("用户" + custUser.getUserPhone() + DateFormat.formatDateYMD("ss"));
// 密码加密
encryptPassword(custUser);
// 设置分布式用户id
Long userId = SequenceManager.getNextId();
if (userId != null) {
custUser.setUserId(userId);
} else {
throw new NullPointerException("获取的userId为空");
}
// 设置正常状态
custUser.setUserState(CustUserState.VALID);
// 创建用户
custUserMapper.insert(custUser);
// 创建用户用户信息
CustUserInfo custUserInfo = new CustUserInfo();
custUserInfo.setUserId(userId);
custUserInfo.setUserRegisterTime(new Date());
custUserInfo.setUserLastLoginTime(new Date());
custUserInfoMapper.insert(custUserInfo);
return custUser.getUserName();
}
@Override
public CustUser addUser(CustUser custUser, Long... roleIds) {
// 密码加密
encryptPassword(custUser);
// 设置分布式用户id
Long userId = SequenceManager.getNextId();
if (userId != null) {
custUser.setUserId(userId);
} else {
throw new NullPointerException("获取的userId为空");
}
// 设置正常状态
custUser.setUserState(CustUserState.VALID);
custUserMapper.insert(custUser);
if (roleIds != null && roleIds.length > 0) {
for (Long roleId : roleIds) {
custUserRoleMapper.insert(new CustUserRole(custUser.getUserId(), roleId));
}
}
return custUser;
}
@Override
public CustUser findUserByUserId(Long userId) {
CustUser custUser = custUserMapper.selectUserByUserId(userId);
return custUser;
}
@Override
public CustUser findUserByUserName(String userName) {
return custUserMapper.selectUserByUserName(userName);
}
@Override
public CustUser findUserByUserPhone(String userPhone) {
return custUserMapper.selectUserByUserPhone(userPhone);
}
@Override
public CustUser findUserByUserEmail(String userEmail) {
return custUserMapper.selectUserByUserEmail(userEmail);
}
@Override
public CustUser findRolesByUserName(String userName) {
return custUserMapper.selectRolesByUserName(userName);
}
@Override
public CustUser findRolesByUserPhone(String userPhone) {
return custUserMapper.selectRolesByUserPhone(userPhone);
}
@Override
public CustUser findRolesByUserEmail(String userEmail) {
return custUserMapper.selectRolesByUserEmail(userEmail);
}
@Override
public CustUser findPermissionsByUserName(String userName) {
return custUserMapper.selectPermissionsByUserName(userName);
}
@Override
public CustUser findPermissionsByUserPhone(String userPhone) {
return custUserMapper.selectPermissionsByUserPhone(userPhone);
}
@Override
public CustUser findPermissionsByUserEmail(String userEmail) {
return custUserMapper.selectPermissionsByUserEmail(userEmail);
}
@Override
public List<CustUser> findAllUsers() {
return custUserMapper.selectAll();
}
@Override
public List<CustNavigation> findNavigationBar(String userName) {
List<CustNavigation> navigationBar = new ArrayList<CustNavigation>();
CustNavigation navigation;
List<CustRole> roles = custRoleMapper.selectRolesByUserName(userName);
for (CustRole role : roles) {
navigation = new CustNavigation();
navigation.setNavigationName(role.getRoleDesc());
navigation.setChildNavigations(custPermissionMapper.findNavisByRoleId(role.getRoleId()));
navigationBar.add(navigation);
}
return navigationBar;
}
/**
* 根据userId更新
*
* @param userId
*/
@Override
public void modifyUserByUserId(CustUser custUser) {
custUserMapper.updateByUserId(custUser);
}
@Override
public void modifyUserRoles(Long userId, Long... roleIds) {
custUserRoleMapper.deleteByUserId(userId);
if (roleIds != null && roleIds.length > 0) {
for (Long roleId : roleIds) {
custUserRoleMapper.insert(new CustUserRole(userId, roleId));
}
}
}
@Override
public void modifyPassword(Long userId, String newPassword) {
CustUser user = custUserMapper.selectUserByUserId(userId);
user.setUserPassword(newPassword);
encryptPassword(user);
custUserMapper.updateByUserId(user);
}
@Override
public void modifyPasswordByUserPhone(String userPhone, String newPassword) {
CustUser user = custUserMapper.selectUserByUserPhone(userPhone);
user.setUserPassword(newPassword);
encryptPassword(user);
logger.debug("新密码:{}", user.getUserPassword());
custUserMapper.updateByUserId(user);
}
@Override
public void deleteUser(Long userId) {
custUserRoleMapper.deleteByUserId(userId);
custUserMapper.deleteByPrimaryKey(userId);
}
@Override
public void deleteMoreUsers(Long... userIds) {
if (userIds != null && userIds.length > 0) {
for (Long userId : userIds) {
deleteUser(userId);
}
}
}
@Override
public void correlationRoles(Long userId, Long... roleIds) {
for (Long roleId : roleIds) {
custUserRoleMapper.insert(new CustUserRole(userId, roleId));
}
}
@Override
public void uncorrelationRoles(Long userId, Long... roleIds) {
for (Long roleId : roleIds) {
custUserRoleMapper.deleteByPrimaryKey(userId, roleId);
}
}
/**
* 密码加密
*
* @param user
*/
public void encryptPassword(CustUser custUser) {
RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
// String algorithmName = "md5";
final int hashIterations = 2;
custUser.setUserPwdSalt(randomNumberGenerator.nextBytes().toHex());
// String encryptedPwd1 = new SimpleHash(algorithmName, user.getUserPassword(),
// ByteSource.Util.bytes(user.getUserName() + user.getUserPwdSalt()),
// hashIterations).toHex();
String encryptedPwd = Md5Encrypt.getMD5Code(custUser.getUserPassword(), custUser.getUserName() + custUser.getUserPwdSalt(), hashIterations);
custUser.setUserPassword(encryptedPwd);
}
}
| true |
367530461030a7632b8781362b33ca06f644448c
|
Java
|
sf1213/Stock-Portfolio-Application
|
/src/portfolio/model/Portfolio.java
|
UTF-8
| 7,514 | 3 | 3 |
[] |
no_license
|
package portfolio.model;
import java.sql.Date;
import java.util.List;
import java.util.Map;
/**
* This interface represents a modelstock.portfolio of a customer stock, which might contain from 0
* to X stock share kinds of a customer.
* Extension update log 2018-11-26:
* 1, adding high level functions as required
* 2, adding one more input as commission fee in buyStockByShare(), buyStockByAmount(), and
* buyStockByIndex() methods.
* Extension update log 2018-12-05:
* 1, adding method to return a list of Portfolio values.
* 2, adding method to add a stock to a portfolio.
*/
public interface Portfolio {
/**
* Added extension function 2018-12-05: adding method to return a list of Portfolio values.
*
* @param startDate the Date as the start date
* @param endDate the Date as the end date
* @throws IllegalArgumentException when given endDate is later then today
*/
List<Double> getValueList(Date startDate, Date endDate) throws IllegalArgumentException;
/**
* Added extension function 2018-11-26.
* The methods buys a certain portfolio with certain ratio of percentage.
*
* @param ratioMap the ratioMap of the ratio percentage of String
* @param startDate the Date as the buy date
* @param interval the interval of day-number for each transaction
* @param amount the value of money to buy stocks each term
* @param comm the commission cost
* @throws IllegalArgumentException when given String of portfolioName is incorrect
* @throws IllegalArgumentException when given startDate is in future
* @throws IllegalArgumentException when given amount is not larger than 0
* @throws IllegalArgumentException when give sum of give ratio sum is not 100%
* @throws IllegalArgumentException when interval day number is not larger than 0
*/
void highLevelFixedValueTrade(Map<String, Double> ratioMap, Date startDate,
int interval, double amount, double comm)
throws IllegalArgumentException;
/**
* Added extension function 2018-11-26.
* The methods buys a certain portfolio with certain ratio of percentage.
*
* @param ratioMap the ratioMap of the ratio percentage of String
* @param startDate the Date as the buy date
* @param endDate the Date as the end date of the strategy
* @param interval the interval of day-number for each transaction
* @param amount the value of money to buy stocks each term
* @param comm the commission cost
* @throws IllegalArgumentException when given String of portfolioName is incorrect
* @throws IllegalArgumentException when given startDate is in future
* @throws IllegalArgumentException when given amount is not larger than 0
* @throws IllegalArgumentException when give sum of give ratio sum is not 100%
* @throws IllegalArgumentException when interval day number is not larger than 0
*/
void highLevelFixedValueTrade(Map<String, Double> ratioMap, Date startDate,
Date endDate, int interval, double amount, double comm)
throws IllegalArgumentException;
/**
* The methods buys a certain stock with certain amount of money.
* Update log 2018-11-26: add an int input as commission fee.
*
* @param sym the String as the ticker symbol the the stock
* @param targetDate the Date as the buy date
* @param amount the double value as the total amount of money
* @param comm the commission cost
* @throws IllegalArgumentException when given ticker symbol is incorrect
* @throws IllegalArgumentException when given date is in future
* @throws IllegalArgumentException when given date is not an open market date
* @throws IllegalArgumentException when given amount is not larger than 0
* @throws IllegalArgumentException when give sym name is not contained in target Portfolio
*/
void buyStockByAmount(String sym, Date targetDate, double amount, double comm)
throws IllegalArgumentException;
/**
* The methods buys a certain stock with certain amount of share.
* Update log 2018-11-26: add an int input as commission fee.
*
* @param sym the String as the ticker symbol the the stock
* @param targetDate the Date as the buy date
* @param share the double value as the share value of the stock
* @param comm the commission cost
* @throws IllegalArgumentException when given ticker symbol is incorrect
* @throws IllegalArgumentException when given date is in future
* @throws IllegalArgumentException when given date is not an open market date
* @throws IllegalArgumentException when given share value is not larger than 0
* @throws IllegalArgumentException when given share value is not larger than 0
* @throws IllegalArgumentException when give sym name is not contained in target Portfolio
*/
void buyStockByShare(String sym, Date targetDate, double share, double comm)
throws IllegalArgumentException;
/**
* The methods buys more of a certain stock in current portfolio with certain amount of share.
* Update log 2018-11-26: add an int input as commission fee.
*
* @param idx the index of the stock share in the portfolio
* @param share the double value as the share value of the stock
* @param comm the commission cost
* @throws IllegalArgumentException when given idx does not exist in the portfolio
* @throws IllegalArgumentException when given share value is not larger than 0
*/
void buyStockByIdx(int idx, double share, double comm) throws IllegalArgumentException;
/**
* The methods adds a stock to this portfolio.
* Update log 2018-12-05: add a stock to this portfolio.
*
* @param stockSym the String as the stock symbol to be added
*/
void addStock(String stockSym);
/**
* The methods returns a double value as the total cost of a modelstock.portfolio.
*
* @return a double value as the total cost of a modelstock.portfolio
*/
double getTotalCostBasic();
/**
* The methods returns a double value as the total cost of a modelstock.portfolio at a certain
* date, while trades before the given date not counted.
*
* @return a double value as the total cost of a modelstock.portfolio before the given date
*/
double getTotalCostBasic(Date targetDate);
/**
* The methods returns a double value as the total market value of a modelstock.portfolio until
* the latest status.
*
* @return a double value as the total market value of a modelstock.portfolio
*/
double getTotalVal();
/**
* The methods returns a double value as the total market value of a modelstock.portfolio until
* the given status.
*
* @return a double value as the total market value of a modelstock.portfolio before a given date
*/
double getTotalVal(Date targetDate);
/**
* The methods returns a String that represents all the shares of stocks owned in this
* modelstock.portfolio. If no stock share exists in the modelstock.portfolio, return an empty
* String.
*
* @return a String as all the stock share within a given modelstock.portfolio
*/
String examinePortfolio();
/**
* The methods return all the Stock Symbol in this Portfolio.
*
* @return all the Stock Symbol in this Portfolio.
*/
String getStockNames();
}
| true |
f06f106895ab8f3798fc068c841db6d93e41ed63
|
Java
|
htchepannou/tch-rails3
|
/tch-rails-maven/tch-rails-maven-web/src/main/resources/archetype-resources/src/main/java/action/HomeActionController.java
|
UTF-8
| 520 | 1.992188 | 2 |
[] |
no_license
|
package ${package}.action;
import com.tchepannou.rails.core.annotation.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Home page
*
*/
@Template (name="default")
public class HomeActionController
extends BaseActionController
{
//-- Static Methods
private static final Logger LOG = LoggerFactory.getLogger(HomeActionController.class);
//-- Public
public void index()
{
if (LOG.isTraceEnabled ())
{
LOG.trace("index()");
}
}
}
| true |
3e33968b6fe0692ccf2313d30e3cea2d341270ce
|
Java
|
womendeaitaiwunai/SixCode
|
/app/src/main/java/com/loong/sixcode/base/BaseFragment.java
|
UTF-8
| 5,706 | 2.109375 | 2 |
[] |
no_license
|
package com.loong.sixcode.base;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.AnimRes;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.loong.sixcode.R;
/**
* Created by lxl on 2017/7/7.
*/
public class BaseFragment extends Fragment {
private AlertDialog noCancelDialog;
private ProgressDialog progressDialog;
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
loadLayout= (LinearLayout) view.findViewById(R.id.load_layout);
}
/**
* 吐司的方法
* @param toastMsg StringId
*/
public void showToast(@StringRes int toastMsg){
showToast(getString(toastMsg));
}
/**
* 吐司的方法
* @param toastMsg ""
*/
public void showToast(String toastMsg){
Toast.makeText(getActivity(), toastMsg, Toast.LENGTH_SHORT).show();
}
/**
* 根据取控件
* @param viewId 控件ID
* @param <view> 获取的View
* @return
*/
public <view extends View> view getViewById(View parentView,@IdRes int viewId){
return (view)parentView.findViewById(viewId);
}
/**
* 显示加载的View
*/
LinearLayout loadLayout;
public void showLoadLayout(){
if (loadLayout==null){
Toast.makeText(getActivity(), "The Fragment not have LoadLayout", Toast.LENGTH_SHORT).show();
} else {
loadLayout.setVisibility(View.VISIBLE);
}
}
/**
* 关闭加载VIew
*/
public void hiddingLoadLayout(){
if (loadLayout==null){
Toast.makeText(getActivity(), "The Fragment not have LoadLayout", Toast.LENGTH_SHORT).show();
} else {
loadLayout.setVisibility(View.GONE);
}
}
/**
* 跳转页面
* @param context 要跳转的页面的上下文
* @param cls 跳转的结果页面
* @param isFinish 是否结束跳转页面
*/
public void startActivityByIntent(Context context, Class<?> cls, boolean isFinish){
startActivityByIntent(context,cls,isFinish,android.R.anim.slide_in_left, android.R.anim.slide_out_right);
}
/**
* 跳转页面
* @param context 要跳转的页面的上下文
* @param cls 跳转的结果页面
* @param isFinish 是否结束跳转页面
* @param startAnim 开始动画
* @param stopAnim 结束动画
*/
public void startActivityByIntent(Context context, Class<?> cls, boolean isFinish, @AnimRes int startAnim, @AnimRes int stopAnim){
startActivity(new Intent(context, cls));
if (isFinish) {
getActivity().finish();
}
getActivity().overridePendingTransition(startAnim, stopAnim);
}
/**
* 跳转页面
* @param intent 要跳转的意图 便于携带参数
* @param isFinish 是否结束跳转页面
*/
public void startActivityByIntent(Intent intent,boolean isFinish){
startActivity(intent);
if (isFinish) {
getActivity().finish();
}
getActivity().overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
}
public AlertDialog showNocancelDialog(String message){
if (noCancelDialog==null){
AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
noCancelDialog=builder.show();
}
noCancelDialog.setMessage(message);
noCancelDialog.setCanceledOnTouchOutside(false);
noCancelDialog.setCancelable(false);
noCancelDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return noCancelDialog;
}
public void showProgressDialog(String message){
showProgressDialog("",message);
}
public void showProgressDialog(String title,String message){
showProgressDialog(title,message,true);
}
public void showProgressDialog(String title,String message,boolean isFinish){
if (progressDialog==null){
progressDialog=new ProgressDialog(getActivity());
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setMessage(message);
progressDialog.setTitle(title);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setCancelable(isFinish);
progressDialog.show();
}else if (!progressDialog.isShowing()){
progressDialog.setMessage(message);
progressDialog.show();
}else {
progressDialog.setMessage(message);
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
if (progressDialog!=null&&progressDialog.isShowing())
progressDialog.dismiss();
}
public void hideNoCancelDialog(){
if (noCancelDialog!=null&&noCancelDialog.isShowing())
noCancelDialog.dismiss();
}
public void hideProgressDialog(){
if (progressDialog!=null&&progressDialog.isShowing())
progressDialog.dismiss();
}
}
| true |
0c8b804c4efa93047e6545b9085e5f9f9ff15510
|
Java
|
PraditiRede/DiffieHellman
|
/Client.java
|
UTF-8
| 1,346 | 3.203125 | 3 |
[] |
no_license
|
import java.net.*;
import java.io.*;
public class Client
{
private Socket socket = null;
private DataOutputStream out = null;
private DataInputStream in = null;
public int p = 23;
public int g = 5;
private int b = 3;
private int B = (int)Math.pow(g, b)%p;
public int A;
private int key2;
public Client(String address, int port)
{
try
{
socket = new Socket(address, port);
System.out.println("Connected");
System.out.println("");
out = new DataOutputStream(socket.getOutputStream());
in = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));
A = Integer.parseInt(in.readUTF());
String Binstring = String.valueOf(B);
out.writeUTF(Binstring);
System.out.println("Public key of client (B) = "+B);
System.out.println("Public key received by client = "+A);
key2 = (int)Math.pow(A, b)%p;
System.out.println("Key = "+key2);
System.out.println("");
System.out.println("Closing connection");
out.close();
socket.close();
in.close();
}
catch(UnknownHostException u)
{
System.out.println(u);
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String args[])
{
Client client = new Client("127.0.0.1", 6000);
}
}
| true |
deb6ee91030df8ecb49528a26b5135d43806d814
|
Java
|
GinoB96/Arkanoid-Game
|
/ArkanoidGame_7_3/src/Arkanoid.java
|
UTF-8
| 30,334 | 2.34375 | 2 |
[] |
no_license
|
import JGame.*;
import RankingDB.RankingDB;
import java.awt.*;
import java.awt.event.*; //eventos
import java.awt.image.*; //imagenes
import javax.imageio.*; //imagenes
import java.awt.Graphics2D;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.LinkedList;
import java.util.*;
import java.text.*;
import javax.swing.ImageIcon;
public class Arkanoid extends JGame {
//extras
Date dInit = new Date();
Date dAhora;
SimpleDateFormat ft = new SimpleDateFormat ("mm:ss");
//elementos del Update
final double NAVE_DESPLAZAMIENTO=200.0;
double BOLA_DESPLAZAMIENTO=100.0;
boolean chocoTop=false;
boolean chocoBottom=false;
boolean chocoL=false;
boolean chocoR=false;
boolean chocoNave=true;
boolean pausarBola=true;
boolean catchBonu=false;
boolean enlargeBonu=false;
boolean duplicate=false;
boolean bypass=false;
boolean pausaNivel=false;
boolean menu=true;
boolean gano=false;
boolean gameOver = false;
boolean ranking=false;
boolean pararJuego=false;//gino
Vector <String> lista = new Vector();
int fondoAncho=185;
int fondoAlto=176;
int tamanioNave=50;
int posY=30;
int posYGano=60;//gino
double orientacion=0;
TipoBonus tipoBonus=new TipoBonus();
Vector <Bonus> vectorBonus;
long dateDiff;
long diffSeconds;
long diffMinutes;
long tiempoActual=0;
double aceleracion=-50;
double velocidad=0.0;
//elementos graficos
BufferedImage img_fondo = null;
BufferedImage fondoMenu = null;
BufferedImage naveN;
BufferedImage naveG;
BufferedImage naveLaser;
BufferedImage salida;
BufferedImage titulo;
BufferedImage startGame;
BufferedImage play;
BufferedImage exit;
Image bucleSalida;
Image habreSalida;
Image gifMenu;
URL url;
Nave nave;
private int naveIzq;
private int naveDer;
Vector <Bola> vectorBola;
//arkanoid
Nivel nivel;
Jugador jugador;
RankingDB rdb;
//AjustesDeJuego aj;//maty
public static void main(String[] args) {
Arkanoid game = new Arkanoid();
game.run(1.0 / 60.0);
System.exit(0);
}
public Arkanoid() {
super("DemoJuego02",800,600);//, 176*2+300, 215*2+25);
System.out.println(appProperties.stringPropertyNames());
this.pausar();
}
@Override
public void gameStartup() { //Inicializa todos los elementos graficos que se utilizaran en el juego
try{
menu=true; //gino
nivel=new Nivel();
jugador=new Jugador();
rdb=new RankingDB();
//aj=new AjustesDeJuego();//maty
this.appProperties = new Properties();//maty
FileInputStream in = new FileInputStream("jgame.properties");
appProperties.load(in);
naveIzq=(char)(appProperties.getProperty("teclaIzquierda").charAt(0))-32;
naveDer=(char)(appProperties.getProperty("teclaDerecha").charAt(0)-32);
System.out.println("naveIzq "+naveIzq+" "+KeyEvent.VK_Q);
System.out.println("naveDer "+naveDer+" "+KeyEvent.VK_E);
if(naveIzq==28){
naveIzq=KeyEvent.VK_LEFT;
}
if(naveDer==30){
naveDer=KeyEvent.VK_RIGHT;
}//maty
nave=new Nave((fondoAncho / 2)-17,fondoAlto+13);
this.vectorBonus = new Vector();
this.vectorBola = new Vector();
fondoMenu=ImageIO.read(new File("imagenes/Arkanoid/fondoMenu.png"));
naveG=ImageIO.read(new File("imagenes/Arkanoid/"+(appProperties.getProperty("nave"))+"Grande.png"));
naveN=ImageIO.read(new File("imagenes/Arkanoid/"+(appProperties.getProperty("nave"))+".png"));
naveLaser=ImageIO.read(new File("imagenes/Arkanoid/naveLaser.png"));//gino
startGame=ImageIO.read(new File("imagenes/Arkanoid/vida.png"));//gino
salida=ImageIO.read(new File("imagenes/Arkanoid/salida1.png"));
titulo=ImageIO.read(new File("imagenes/Arkanoid/tituloArkanoid.png"));
play=ImageIO.read(new File("imagenes/Arkanoid/play.png"));//gino
exit=ImageIO.read(new File("imagenes/Arkanoid/exit.png"));//gino
System.out.println(getClass());
url = new URL(getClass().getResource("img/salidaBucle.gif").toString());
bucleSalida = new ImageIcon(url).getImage();
url = new URL(getClass().getResource("img/salidaConRayo.gif").toString());
habreSalida=new ImageIcon(url).getImage();
url = new URL(getClass().getResource("img/fondo_estrellas1.gif").toString());//gino
gifMenu=new ImageIcon(url).getImage();//gino
}
catch(Exception e){
//System.out.println("gameStartup: "+e);
e.printStackTrace();
}
}
public void reset(){
vectorBonus.clear();
vectorBola.clear();
vectorBola.add(new Bola((fondoAncho / 2)-2,fondoAlto+9));
nave.setPosicion((fondoAncho / 2)-17, fondoAlto+13);
SistemaDeSonidos.playSonido("inicioMusica");
aceleracion=0.0;
catchBonu=false;
enlargeBonu=false;
bypass=false;
duplicate=false;
nave.setImagen(naveN);
tamanioNave=50;
nave.espacioR.setSize(16,7);
nave.espacioL.setSize(16,7);
nave.espacio.setSize(32,7);
this.pausar();
pausaNivel=true;
}
public void nextLevel(){
try {
nivel.aumentarNivel();
switch(nivel.getNivelActualArkanoid()){
case 1:
img_fondo=ImageIO.read(new File("imagenes/Arkanoid/Arkanoid Nivel1 (con salida) - Fields.png"));
this.reset();
break;
case 2: img_fondo=ImageIO.read(new File("imagenes/Arkanoid/Arkanoid Nivel2 (con salida) - Fields.png"));
this.reset();
break;
case 3: img_fondo=ImageIO.read(new File("imagenes/Arkanoid/Arkanoid Nivel3 (con salida) - Fields.png"));
this.reset();
break;
case 4:
gano=true;
ranking=true;
break;
}
nivel.loadNivel();
} catch (IOException e) {
System.out.println("Error nextLevel: "+e);
}
}
public void colisionNave(int i){
try{
if (nave.espacioR.intersects(vectorBola.get(i).espacio)){
SistemaDeSonidos.playSonido("bolaNave");
if (catchBonu){
pausarBola=true;
this.pausar();
}
vectorBola.get(i).chocoBottom=true;
vectorBola.get(i).chocoTop=false;
vectorBola.get(i).chocoL=true;
vectorBola.get(i).chocoR=false;
}
if (nave.espacioL.intersects(vectorBola.get(i).espacio)){
SistemaDeSonidos.playSonido("bolaNave");
if (catchBonu){
pausarBola=true;
this.pausar();
}
vectorBola.get(i).chocoBottom=true;
vectorBola.get(i).chocoTop=false;
vectorBola.get(i).chocoL=false;
vectorBola.get(i).chocoR=true;
}
}
catch(Exception e){
System.out.println("Problema en ColisionNave "+e);
}
}
public void generarBonus(int e,int i){
(nivel.getObj(e)).restarDureza();
aceleracion+=0.5;
if ((nivel.getObj(e)).getDureza()==0){
if (vectorBola.size()==1&&vectorBonus.isEmpty()){
int calcular=95;//(nivel.getObj(e)).calcularBonus();
//System.out.println(calcular);
if (calcular>=50){
Bonus bonus=new Bonus();
bonus.setImagen(tipoBonus.loadBonus(bonus.getBonus(calcular)));
bonus.setPosicion((nivel.getObj(e)).getX()+3,(nivel.getObj(e)).getY()+5);
vectorBonus.add(bonus);
}
}
jugador.aumentarPuntajeJugador((nivel.getObj(e)).getPuntajeXBloque());
nivel.borrarBloque(e);
}
SistemaDeSonidos.playSonido("bolaBloque");
}
public void colisionBloques(int i){
try{
for(int e=0;e<nivel.getCantBloques();e++){
// CAMBIOOOOOOOOOOO
if ((nivel.getObj(e)).espacio.intersects(vectorBola.get(i).espacio)){//C
this.generarBonus(e,i);
if (vectorBola.get(i).chocoBottom){
vectorBola.get(i).chocoTop=true;
vectorBola.get(i).chocoBottom=false;
//System.out.println("abajo");
}else{
vectorBola.get(i).chocoTop=false;
vectorBola.get(i).chocoBottom=true;
//System.out.println("arriba");
}
}
else{
if ((nivel.getObj(e)).espacioR.intersects(vectorBola.get(i).espacio)){
this.generarBonus(e,i);
if (vectorBola.get(i).chocoL){
if (vectorBola.get(i).chocoTop){
vectorBola.get(i).chocoTop=false;
vectorBola.get(i).chocoBottom=true;
}
else{
vectorBola.get(i).chocoTop=true;
vectorBola.get(i).chocoBottom=false;
}
}else{
vectorBola.get(i).chocoR=false;
vectorBola.get(i).chocoL=true;
}
//System.out.println("derecha");
}
else{
if ((nivel.getObj(e)).espacioL.intersects(vectorBola.get(i).espacio)){
this.generarBonus(e,i);
if (vectorBola.get(i).chocoR){
if (vectorBola.get(i).chocoTop){
vectorBola.get(i).chocoTop=false;
vectorBola.get(i).chocoBottom=true;
}
else{
vectorBola.get(i).chocoTop=true;
vectorBola.get(i).chocoBottom=false;
}
}else{
vectorBola.get(i).chocoR=true;
vectorBola.get(i).chocoL=false;
}
//System.out.println("izquierda");
}
}
}
}
if(nivel.getCantidadBloquesVivos()==0){
System.out.println(nivel.getNivelActualArkanoid());
this.nextLevel();
}
}
catch(Exception e){
System.out.println("Problema en ColisionBloques "+e);
}
}
public void colisionBonus(){
try{
for (int i=0;i<vectorBonus.size();i++){
//if(vectorBonus.get(i).getY()+5==nave.getY()&&vectorBonus.get(i).getX()>nave.getX()-20&&vectorBonus.get(i).getX()<nave.getX()+tamanioNave-20){
if (vectorBonus.get(i).espacio.intersects(nave.espacio)){
switch(vectorBonus.get(i).tipo()){
case 1:
enlargeBonu=true;
tamanioNave=70;
nave.espacioR.setSize(24,2);
nave.espacioL.setSize(24,2);
nave.espacio.setSize(50,7);
nave.setImagen(naveG);
catchBonu=false;
pausarBola=false;
break;
case 2:
if (vectorBola.size()==1){
vectorBola.add(new Bola((int)vectorBola.get(0).getX(),(int)vectorBola.get(0).getY()));
vectorBola.get(1).chocoBottom=vectorBola.get(0).chocoBottom;
vectorBola.get(1).chocoL=(!vectorBola.get(0).chocoL);
vectorBola.get(1).chocoR=(!vectorBola.get(0).chocoR);
vectorBola.get(1).chocoTop=vectorBola.get(0).chocoTop;
vectorBola.add(new Bola((int)vectorBola.get(0).getX(),(int)vectorBola.get(0).getY()));
vectorBola.get(2).chocoBottom=vectorBola.get(0).chocoBottom;
vectorBola.get(2).chocoL=false;
vectorBola.get(2).chocoR=false;
vectorBola.get(2).chocoTop=vectorBola.get(0).chocoTop;
duplicate=true;
catchBonu=false;
//pausarBola=false;
}
break;
case 3:
catchBonu=true;
enlargeBonu=false;
nave.espacioR.setSize(16,7);
nave.espacioL.setSize(16,7);
nave.espacio.setSize(32,7);
nave.setImagen(naveN);
tamanioNave=50;
this.pausar(); // cambio
break;
case 4:
aceleracion=-50;
break;
case 5:
jugador.sumarVida();
SistemaDeSonidos.playSonido("extraLife");
break;
case 6:
this.pausar();
bypass=true;
break;
}
vectorBonus.remove(i);
}
else{
if (vectorBonus.get(i).getY()==fondoAlto+50){
vectorBonus.remove(i);
}
}
}
}
catch(Exception e){
System.out.println("Problema en colisionBonus "+e);
}
}
public void bolaAfuera(int i){
if(vectorBola.size()>1){
vectorBola.remove(i);
}else{
jugador.restarVida();
if (jugador.getVidas()==0){
SistemaDeSonidos.playSonido("gameOver");
this.pausar();
gameOver=true;
}else{
/*vectorBola.remove(i);
vectorBonus.clear();
aceleracion=0.0;
catchBonu=false;
enlargeBonu=false;
bypass=false;
duplicate=false;
nave.setImagen(naveN);
tamanioNave=50;
nave.espacioR.setSize(16,7);
nave.espacioL.setSize(16,7);
nave.espacio.setSize(32,7);
vectorBola.add(new Bola((fondoAncho / 2)-2,fondoAlto+9));
nave.setPosicion((fondoAncho / 2)-17, fondoAlto+13);
this.pausar();
pausaNivel=true;
SistemaDeSonidos.playSonido("inicioMusica");*/
this.reset();
}
}
}
@Override
public void gameUpdate(double delta) { //UPDATE actualiza frame a frame las acciones de los elementos graficos
Keyboard keyboard = this.getKeyboard();
// Esc fin del juego
LinkedList < KeyEvent > keyEvents = keyboard.getEvents();
for (KeyEvent event: keyEvents) {
if ((event.getID() == KeyEvent.KEY_PRESSED) &&
(event.getKeyCode() == KeyEvent.VK_ESCAPE)) {
stop();
}
}
// Seguimiento automatico de la bola
/*
if (nave.getX()>9&&nave.getX()<fondoAncho-50||bola.getX()>19&&bola.getX()<fondoAncho-30){
nave.setX( bola.getX()-15);
}
*/
// Seguimiento manual de la bola
SistemaDeSonidos.pararSonidos();
if (vectorBola.isEmpty())return;
if (!pararJuego){//gino
if (!pausaNivel){
if (pausarBola){
if (keyboard.isKeyPressed(naveIzq)){//maty if (keyboard.isKeyPressed(aj.getTeclaNaveIzq())){
if (nave.getX()>9){
nave.setX(nave.getX() - NAVE_DESPLAZAMIENTO * delta);
vectorBola.get(0).setX((vectorBola.get(0)).getX() - NAVE_DESPLAZAMIENTO * delta);
}
}
if (keyboard.isKeyPressed(naveDer)){//maty if (keyboard.isKeyPressed(aj.getTeclaNaveDer())){
if (nave.getX()<fondoAncho-tamanioNave){
nave.setX( nave.getX() + NAVE_DESPLAZAMIENTO * delta);
vectorBola.get(0).setX((vectorBola.get(0)).getX() + NAVE_DESPLAZAMIENTO * delta);
}
}
if(keyboard.isKeyPressed(KeyEvent.VK_X)){
pausarBola=false;
}
if (diffSeconds>tiempoActual+2){
pausarBola=false;
}
}
else{
if (keyboard.isKeyPressed(naveIzq)){
if (nave.getX()>9){
nave.setX( nave.getX() - NAVE_DESPLAZAMIENTO * delta);
}
}
if (keyboard.isKeyPressed(naveDer)){
if (!bypass){
if (nave.getX()<fondoAncho-tamanioNave){
nave.setX( nave.getX() + NAVE_DESPLAZAMIENTO * delta);
}
}else{
if (nave.getX()<fondoAncho-tamanioNave){
nave.setX( nave.getX() + NAVE_DESPLAZAMIENTO * delta);
}else{
this.nextLevel();
}
}
}
}
nave.espacioL.setLocation((int)nave.getX(), (int)nave.getY());//cambio
if (enlargeBonu){//cambio
nave.espacioR.setLocation((int)nave.getX()+24, (int)nave.getY());
}else{
nave.espacioR.setLocation((int)nave.getX()+16, (int)nave.getY());
}
nave.espacio.setLocation((int)nave.getX(), (int)nave.getY());
if (!vectorBonus.isEmpty()){//cambio
for (int e=0;e<vectorBonus.size();e++){
vectorBonus.get(e).setPosicion(vectorBonus.get(e).getX(),vectorBonus.get(e).getY()+0.5);
vectorBonus.get(e).espacio.setLocation((int)vectorBonus.get(e).getX(),(int)vectorBonus.get(e).getY());
}
}
this.colisionBonus();
if (pausarBola){
return;
}
if (velocidad<4.0){
velocidad=(BOLA_DESPLAZAMIENTO+aceleracion)*delta;
}else{
velocidad=4.0;
}
for (int i=0;i<vectorBola.size();i++){
if (vectorBola.get(i).getX()<10){//15
vectorBola.get(i).chocoL=true;
vectorBola.get(i).chocoR=false;
aceleracion+=0.5; // cambio
}
if (vectorBola.get(i).getX()>fondoAncho-25)//380
{
vectorBola.get(i).chocoR=true;
vectorBola.get(i).chocoL=false;
aceleracion+=0.5; // cambio
}
if (vectorBola.get(i).getY()<20){//35
vectorBola.get(i).chocoTop=true;
vectorBola.get(i).chocoBottom=false;
aceleracion+=0.5; // cambio
}
if (vectorBola.get(i).getY()>fondoAlto+50){//447
this.bolaAfuera(i);
/*vectorBola.get(i).chocoBottom=true;
vectorBola.get(i).chocoTop=false;
aceleracion+=0.5;*/
}else{
if (vectorBola.get(i).chocoL){
vectorBola.get(i).setX( vectorBola.get(i).getX() + velocidad);
}
if (vectorBola.get(i).chocoR){
vectorBola.get(i).setX( vectorBola.get(i).getX() - velocidad);
}
if (vectorBola.get(i).chocoTop){
vectorBola.get(i).setY( vectorBola.get(i).getY() + velocidad);
}
if(vectorBola.get(i).chocoBottom){
vectorBola.get(i).setY( vectorBola.get(i).getY() - velocidad);
}
vectorBola.get(i).espacio.setLocation((int) Math.round(vectorBola.get(i).getX())+2,(int) Math.round(vectorBola.get(i).getY()));
/*vectorBola.get(i).top.setLocation((int) Math.round(vectorBola.get(i).getX())+2,(int) Math.round(vectorBola.get(i).getY()));
vectorBola.get(i).espacioL.setLocation((int) Math.round(vectorBola.get(i).getX()),(int) Math.round(vectorBola.get(i).getY())+2);
vectorBola.get(i).down.setLocation((int) Math.round(vectorBola.get(i).getX())+2,(int) Math.round(vectorBola.get(i).getY())+4);
vectorBola.get(i).espacioR.setLocation((int) Math.round(vectorBola.get(i).getX())+4,(int) Math.round(vectorBola.get(i).getY())+2);*/
this.colisionBloques(i);
this.colisionNave(i);
}
}
}
}
jugador.sumarVidaPuntaje();
}
public void pausar(){
tiempoActual=diffSeconds;
}
@Override
public void gameDraw(Graphics2D g){ //DRAW dibuja los elementos graficos Frame a Frame
dAhora= new Date();
dateDiff = dAhora.getTime() - dInit.getTime();
diffSeconds = dateDiff / 1000 % 60;
//System.out.println(diffSeconds);
diffMinutes = dateDiff / (60 * 1000) % 60;
Keyboard keyboard = this.getKeyboard();
//Permite escalar el fondo
g.scale(2.8,2.8);//gino
g.setColor(Color.white);//gino
if (menu){
g.drawImage(gifMenu,0,0,null);
g.drawImage(titulo,32,10,null);
g.setColor(Color.white);
g.drawImage(play,fondoAncho/2+35,fondoAlto/2+20,null);
g.drawImage(exit,fondoAncho/2+35,fondoAlto/2+60,null);
g.drawImage(startGame,fondoAncho/2+10,fondoAlto/2+posY,null);
if (keyboard.isKeyPressed(KeyEvent.VK_UP)){
posY=30;
}
if (keyboard.isKeyPressed(KeyEvent.VK_DOWN)){
posY=70;
}
if (keyboard.isKeyPressed(KeyEvent.VK_ENTER)){
if (posY==30){
pararJuego=false;//gino
gano=false;
menu=false;
jugador.reiniciarJugador();
nivel.reiniciarNiveles();
this.nextLevel();
}
else{
stop();
}
}
}else{
if (ranking){//gino
if (!pararJuego){//gino
System.out.println("juego parado");
rdb.insertarJugadorAlRanking(jugador.getNombre(),jugador.getPuntajeJugador(),nivel.getNivelActualArkanoid());//gino
lista=rdb.mostrarRanking();//gino
System.out.println("lista.size: "+lista.size());
pararJuego=true;//gino
}
//Scanner entradaEscaner = new Scanner (System.in); //Creación de un objeto Scanner
//entradaEscaner.nextLine();
//jugador.setNombre(entradaEscaner); //Invocamos un método sobre un objeto Scanner
g.drawImage(gifMenu,0,0,null);//gino
if (gano){//gino
g.setFont(new Font("Arkanoid", Font.BOLD, 20));//gino
g.drawString("¡Ganaste!",100,30);//gino
}
g.setFont(new Font("Arkanoid", Font.BOLD, 10));//gino
for (int i=0;i<lista.size()&&i<40;i=i+4){//gino
g.drawString("Jgr"+lista.get(i),70,posYGano);//gino
g.drawString("Nivel: "+lista.get(i+1),105,posYGano);//gino
g.drawString(lista.get(i+2),150,posYGano);//gino
g.drawString(lista.get(i+3),200,posYGano);//gino
posYGano+=10;
}//gino
posYGano=60;
g.drawString("Espacio para continuar...",90,fondoAlto/2+100);//gino
if (keyboard.isKeyPressed(KeyEvent.VK_SPACE)){//gino
ranking=false;//gino
menu=true;//gino
SistemaDeSonidos.pararSonidos();
}//gino
}else
{
if (pausaNivel){
if ((tiempoActual+4)>diffSeconds){
pausaNivel=true;
}
else{
pausaNivel=false;
this.pausar();
pausarBola=true;
}
}
g.drawImage(img_fondo,0,1,null);// imagen de fondo
if (bypass){
g.drawImage(habreSalida,fondoAncho/2+76,fondoAlto/2+78,null);
//System.out.println(diffSeconds+" "+tiempoActual);
if (diffSeconds>(tiempoActual+0.5)){
g.drawImage(bucleSalida,fondoAncho/2+76,fondoAlto/2+78,null);
}
}else{
g.drawImage(salida,fondoAncho/2+76,fondoAlto/2+78,null);
}
g.setColor(Color.white);
g.drawString("Tiempo: "+diffMinutes+":"+diffSeconds,180,50);
g.drawString("FPS: "+FPS,180,65);
g.drawString("Puntaje: "+jugador.getPuntajeJugador(),180,80);
g.drawString("Vidas: "+jugador.getVidas(),180,95);
if (pausaNivel){
g.setFont(new Font("Arkanoid", Font.BOLD, 20));
g.drawString("Nivel "+nivel.getNivelActualArkanoid(),fondoAncho/3,fondoAlto-20);
}
//System.out.println(g+" "+bola);
//g.drawString("Posicion X: "+bola.getX(),200,80);
//g.drawString("Posicion Y: "+bola.getY(),200,90);
nave.draw(g);
for (int i=0;i<vectorBola.size();i++){
//vectorBola.get(i).draw(g);
/*g.setColor(Color.red);
//g.fillRect((int)vectorBola.get(i).getX()+2, (int)vectorBola.get(i).getY(), 2, 5);
g.fillRect((int)vectorBola.get(i).getX()+2, (int)vectorBola.get(i).getY(), 1, 1);
g.setColor(Color.red);
g.fillRect((int)vectorBola.get(i).getX(), (int)vectorBola.get(i).getY()+2, 1, 1);
g.fillRect((int)vectorBola.get(i).getX()+2, (int)vectorBola.get(i).getY()+4, 1, 1);
g.setColor(Color.red);
g.fillRect((int)vectorBola.get(i).getX()+4, (int)vectorBola.get(i).getY()+2, 1, 1);*/
vectorBola.get(i).draw(g);
}
//Disposicion Bloques (1 es Azul,2 es Rosa,3 es Roja,4 es Amarilla)
for(int i=0;i<nivel.getCantBloques();i++){
//if (nivel.getObj(i).getX()<=)
//(nivel.getObj(i)).draw(g);
/*g.setColor(Color.GREEN);
g.fillRect((int)nivel.getObj(i).getX(), (int)nivel.getObj(i).getY(), 3, 7);
g.setColor(Color.BLUE);
g.fillRect((int)nivel.getObj(i).getX()+3, (int)nivel.getObj(i).getY(), 12, 7);
g.setColor(Color.GREEN);
g.fillRect((int)nivel.getObj(i).getX()+12, (int)nivel.getObj(i).getY(), 3, 7);
g.setColor(Color.BLUE);*/
//g.fillRect((int)nivel.getObj(i).getX(), (int)nivel.getObj(i).getY()+6, 15, 1);
(nivel.getObj(i)).draw(g);
}
if (!vectorBonus.isEmpty()){
for (int i=0;i<vectorBonus.size();i++){
//g.setColor(Color.YELLOW);
//g.fillRect((int)vectorBonus.get(i).getX(), (int)vectorBonus.get(i).getY(), 20, 10);
vectorBonus.get(i).draw(g);
}
}
if (gameOver){
pararJuego=true;//gino
g.setFont(new Font("Arkanoid", Font.BOLD, 20)); //gino
g.drawString("Game Over",fondoAncho/3-25,fondoAlto-20);
if ((tiempoActual+5)<diffSeconds){
vectorBola.clear();
gameOver=false;
ranking=true;//gino
pararJuego=false;
//SistemaDeSonidos.pararSonidos();
}
/*//rdb.borrarRanking();
Scanner entradaEscaner = new Scanner (System.in); //Creación de un objeto Scanner
System.out.println("Fin: Su puntaje es de "+jugador.getPuntajeJugador());
System.out.println("Ingrese su nombre, por favor");
jugador.setNombre(entradaEscaner.nextLine()); //Invocamos un método sobre un objeto Scanner
rdb.insertarJugadorAlRanking(jugador.getNombre(),jugador.getPuntajeJugador(),nivel.getNivelActualArkanoid());
rdb.mostrarRanking();
String prueba= entradaEscaner.nextLine();*/
}
}
}
}
@Override
public void gameShutdown() {
Log.info(getClass().getSimpleName(), "Shutting down game");
}
}
| true |
59e590c4bb6a6a2d5a54857b2f53271b5d6867f8
|
Java
|
PetroRavlinko/concordion-markdown-extension
|
/src/test/java/spec/concordion/markdown/LegacyExample.java
|
UTF-8
| 149 | 1.523438 | 2 |
[
"Apache-2.0"
] |
permissive
|
package spec.concordion.markdown;
public class LegacyExample extends AbstractGrammar{
public LegacyExample(){
super(true);
}
}
| true |
09a03a9f4287a2593a3d0ccc3d8898846ec290b9
|
Java
|
akhilbhardwaj20/April-Leetcode-Challenge
|
/Count Binary Substrings.java
|
UTF-8
| 502 | 3.203125 | 3 |
[] |
no_license
|
class Solution {
// TC - O(n) where n is the length of the string
// TC - O(1)
public int countBinarySubstrings(String s) {
int prev = 0, curr = 1, res = 0;
for(int i = 1; i<s.length(); i++) {
if(s.charAt(i-1) != s.charAt(i)) {
res += Math.min(prev, curr);
prev = curr;
curr = 1;
} else {
curr++;
}
}
return res + Math.min(prev, curr);
}
}
| true |
c5117feb0a2ef3460f56228d85437be79cf6b307
|
Java
|
barracuda-bf/aShabanov
|
/src/com/company/lab1/Task41.java
|
UTF-8
| 500 | 2.96875 | 3 |
[] |
no_license
|
package com.company.lab1;
import java.util.Scanner;
/**
* Created by наш on 23.03.2017.
*/
public class Task41 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);// создаем сканер консоли для считывания
System.out.println("дополните фразу: \"Програмистом быть:\"");
String aa = s.next();
System.out.println("Програмистом быть " + aa + "!");
}
}
| true |
26cc3153203d5d9e5d60ff9c0b5447cfbf45dddd
|
Java
|
JoelOliveira15/LSI
|
/ProjetoLSI/src/main/java/Pojo/Permissao.java
|
UTF-8
| 67 | 1.570313 | 2 |
[] |
no_license
|
package Pojo;
public enum Permissao {
NIVEL1, NIVEL2, NIVEL3;
}
| true |
0e9e2849adb430d47369bb36268d07c72c355dac
|
Java
|
stephanenoutsa/CUIB-Cameroon
|
/app/src/main/java/com/stephnoutsa/cuib/models/Token.java
|
UTF-8
| 1,701 | 2.734375 | 3 |
[] |
no_license
|
package com.stephnoutsa.cuib.models;
import com.google.gson.annotations.SerializedName;
/**
* Created by stephnoutsa on 11/26/16.
*/
public class Token {
// Private variables
@SerializedName("id")
int id;
@SerializedName("value")
String value;
@SerializedName("school")
String school;
@SerializedName("department")
String department;
@SerializedName("level")
String level;
// Empty constructor
public Token() {
}
// Constructor
public Token(int id, String value, String school, String department, String level) {
this.id = id;
this.value = value;
this.school = school;
this.department = department;
this.level = level;
}
// Constructor
public Token(String value, String school, String department, String level) {
this.value = value;
this.school = school;
this.department = department;
this.level = level;
}
// Getter and Setter methods
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
}
| true |
07874e618a623047e9e48d51e760aad888783667
|
Java
|
jieun93/BasicJava
|
/JavaBasic/src/d_array/Array.java
|
UHC
| 5,530 | 4.375 | 4 |
[] |
no_license
|
package d_array;
import java.util.Arrays;
import java.util.Scanner;
public class Array {
public static void main(String[] args) {
/*
* <<迭 Է¹ 3>>
* int[] number = new int[5];// ⺻ ʱȭǴ.
* int[] number = new int[]{10,20,30,40,50};
* int[] number = {10,20,30,40,50};
*/
//迭 Ÿ̴.
int[]array;//迭 ּҸ .
array = new int[5];//迭 ǰ ּҰ ȴ.
//new : ο ּҹȯ
//int[5] : int ִ 5
//迭 ʱȭ ⺻ ȴ.
System.out.println(array);//ּҰ Ǿ ִ.
System.out.println(array[0]);// ϱؼ index Ѵ.
//index int ִ.(ͷ, , , )
//迭 ִ ũ int ִ밪( 20)̴.
String arrayStr = Arrays.toString(array);
//迭 ε ڿ ȯѴ.
System.out.println(arrayStr);
int[] iArray1 = new int[]{1,2,3};// 迭 ̰ .
int[] iArray2 = {1,2,3};// ʱȭ ÿ ؾѴ.
int[] iArray3;
//iArray3 = {1,2,3};//
array[0] = 10;//ε 0 Ѵ.
array[1] = 20;
array[2] = 30;
array[3] = 40;
array[4] = 50;// ε "迭 -1"̴.
// ִ ̰ 10 迭 ʱȭ ּ.
int[] array1 = new int [] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// ε ִ ּ.
array1[0] = 10;
array1[1] = 20;
array1[2] = 30;
array1[3] = 40;
array1[4] = 50;
array1[5] = 60;
array1[6] = 70;
array1[7] = 80;
array1[8] = 90;
array1[9] = 100;
// ε ִ ּ.
int sum = 0;
sum += array1[0];
sum += array1[1];
sum += array1[2];
sum += array1[3];
sum += array1[4];
sum += array1[5];
sum += array1[6];
sum += array1[7];
sum += array1[8];
sum += array1[9];
System.out.println(sum);
//index 1 ϴ Ģ־ for Բ ϱ .
for(int i=0; i < array.length; i++){
System.out.println(array[i]);
}
//迭 ̸ ˰ ִٰ ڸ ϴ ϵڵ̶ Ѵ.
//̸ ˴ length ϴ ڵ̴.
for(int i = 0; i < array.length; i++){
array[i] = i + 1;
}
System.out.println(Arrays.toString(array));
//迭 ڸ հ غ.
int[] number = new int[10];
for(int i = 0; i < number.length; i++){
number[i] = (int)(Math.random() * 100)+1;
}
System.out.println(Arrays.toString(number));
sum = 0;//հ
double avg = 0;//
for(int i = 0; i < number.length; i++){
sum += number[i];
}
avg =(double) sum / number.length;
System.out.println("հ: "+sum+" / : "+avg);
// for
for(int number1 : number){//迭 ִ ʴ ִ´.
System.out.println(number1);
}
//迭 ڵ ּҰ ִ밪 ãּ.
int min = number[0];
int max = number[0];
for(int i=0; i < number.length; i++){
if(number[i]<min){
min = number[i];
}
if(max<number[i]){
max = number[i];
}
}
System.out.println("min :"+min+" max :"+max);
// Q1.
int[]shuffle = new int[30];
for(int i = 0; i < shuffle.length; i++){
shuffle[i] = i + 1;
}
System.out.println(Arrays.toString(shuffle));
//迭 ּ.
//0 ε ε ȯѴ.
for(int i = 0; i < shuffle.length*10; i++){
int random =(int)(Math.random()*shuffle.length);
int temp =shuffle[0];
shuffle[0]=shuffle[random];
shuffle[random] = temp;
}
System.out.println(Arrays.toString(shuffle));
//1~10 500 ϰ, ڰ Ƚ ּ.
int[] counts = new int[10];
for(int i=0; i<500; i++ ){
int random =(int)(Math.random()*10)+1;
counts[random-1] ++ ;
// 1 2 3 4 5 6 7 8 9 10
// 0 1 2 3 4 5 6 7 8 9
}
for(int i = 0; i < counts.length; i++){
System.out.println(i+1+":"+counts[i]);
}
//Math.random() 0~1̸(0.99999...)
//ּҰ,ִ밪,ݺȽ Է¹ Ƚ
Scanner s = new Scanner(System.in);
System.out.println("ּҰ>");
int minNum = Integer.parseInt(s.nextLine());
System.out.println("ִ밪>");
int maxNum = Integer.parseInt(s.nextLine());
System.out.println("ݺȽ>");
int repeat = Integer.parseInt(s.nextLine());
counts = new int[maxNum - minNum +1];
for(int i = 0; i < repeat; i++){
int random = (int)(Math.random()*(maxNum - minNum +1))+minNum;
counts[random - minNum]++;
}
for(int i = 0; i < counts.length; i++ ){
System.out.println( i + 1 + ":" + counts[i]);
}
}
}
| true |
29edf88864020d6932a039e55066f71321929330
|
Java
|
Utopia1138/Design-Patterns-Training
|
/txr/DesignPatternsChapter6/src/main/java/org/txr/designpatterns/chapter6/reporters/DonaldTrumpEmbedded.java
|
UTF-8
| 442 | 2.5625 | 3 |
[] |
no_license
|
package org.txr.designpatterns.chapter6.reporters;
import org.txr.designpatterns.chapter6.Reporter;
import org.txr.designpatterns.chapter6.candidates.DonaldTrump;
public class DonaldTrumpEmbedded implements Reporter {
private DonaldTrump trump;
public DonaldTrumpEmbedded(DonaldTrump trump) {
super();
this.trump = trump;
}
public void report() {
trump.offensiveQuote();
trump.talkAboutMexico();
trump.classy();
}
}
| true |
625d0e5bc842bd41023eefeedf13d968733df739
|
Java
|
pixeleon/vagonka-kharkiv
|
/src/main/java/net/khpi/shevvaddm/vagonka/controller/ProductsController.java
|
UTF-8
| 3,514 | 2.0625 | 2 |
[] |
no_license
|
package net.khpi.shevvaddm.vagonka.controller;
import net.khpi.shevvaddm.vagonka.dto.AdminProductDto;
import net.khpi.shevvaddm.vagonka.dto.ProductMuDto;
import net.khpi.shevvaddm.vagonka.dto.ProductTypeDto;
import net.khpi.shevvaddm.vagonka.dto.SaveProductDto;
import net.khpi.shevvaddm.vagonka.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.validation.Valid;
import java.util.List;
@Controller
@RequestMapping("/admin")
public class ProductsController {
private ProductService productService;
@Autowired
public void setProductService(ProductService productService) {
this.productService = productService;
}
@GetMapping("/products")
public String showProducts(Model model) {
List<AdminProductDto> productsDto = productService
.findAllAdminProducts();
model.addAttribute("products", productsDto);
return "adminProducts";
}
@GetMapping("/edit-product")
public String showProductSaveForm(@RequestParam Long productId,
Model model) {
SaveProductDto product = productService.findSaveProductById(productId);
model.addAttribute("product", product);
populateProductSaveForm(model);
return "saveProduct";
}
@PostMapping("/edit-product")
public String processProductSaveForm(
@Valid @ModelAttribute("product") SaveProductDto productDto,
BindingResult bindingResult, Model model) {
if (bindingResult.hasErrors()) {
populateProductSaveForm(model);
return "saveProduct";
} else {
productService.saveProduct(productDto);
return "redirect:/admin/products";
}
}
@PostMapping("/delete-product")
public String processProductRemoval(
@RequestParam("productId") Long productId) {
productService.deleteProductById(productId);
return "redirect:/admin/products";
}
@GetMapping("/create-product")
public String showProductCreateForm(Model model) {
SaveProductDto product = new SaveProductDto();
model.addAttribute("product", product);
populateProductSaveForm(model);
return "saveProduct";
}
@PostMapping("/create-product")
public String processProductCreateForm(
@Valid @ModelAttribute("product") SaveProductDto productDto,
BindingResult bindingResult, Model model) {
if (bindingResult.hasErrors()) {
populateProductSaveForm(model);
return "saveProduct";
} else {
productService.saveProduct(productDto);
return "redirect:/admin/products";
}
}
private void populateProductSaveForm(Model model) {
List<ProductTypeDto> productTypes = productService
.findAllProductTypes();
List<ProductMuDto> productMus = productService.findAllProductMus();
model.addAttribute("productTypes", productTypes);
model.addAttribute("productMus", productMus);
}
}
| true |
69c1d9e0ef7e8bcca60517e323dd5ae2a69dcde2
|
Java
|
duncangaming/Guilds
|
/src/main/java/me/duncangaming/guilds/Crates/Create.java
|
UTF-8
| 2,782 | 2.34375 | 2 |
[] |
no_license
|
package me.duncangaming.guilds.Crates;
import me.duncangaming.guilds.Storage.YMLController;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import java.util.*;
public class Create implements CommandExecutor, Listener {
public Create(YMLController config) {
this.config = config;
}
YMLController config;
HashMap<UUID, String> addRewards = new HashMap<UUID, String>();
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (label.equalsIgnoreCase("crates")) {
if (sender instanceof Player) {
if (args.length != 0) {
if (args[0].equalsIgnoreCase("create")) {
if (sender.hasPermission("crates.admin")) {
if (args[1].length() != 0) {
openInv((Player) sender);
addRewards.put(((Player) sender).getPlayer().getUniqueId(), args[1]);
} else {
sender.sendMessage(ChatColor.RED + "Please name your crate");
}
} else {
sender.sendMessage(ChatColor.RED + "You don't have permission to run this command");
}
}
} else {
sender.sendMessage("");
}
} else {
sender.sendMessage(ChatColor.RED + "You must be a player to run this command");
}
return true;
}
return false;
}
public Inventory openInv(Player p) {
Inventory inv = Bukkit.createInventory(null, 36, "Crate Rewards");
p.openInventory(inv);
return inv;
}
public void closeCrate(InventoryCloseEvent e) {
if (e.getView().getTitle().equalsIgnoreCase("crate rewards")) {
config.setConfig(addRewards.get(e.getPlayer().getUniqueId()), e.getInventory().getContents());
addRewards.remove(e.getPlayer().getUniqueId());
}
}
}
| true |
e475c7e26746e0b7af002ffc571f5887932ae687
|
Java
|
nick130589/graphs_live_coding_presentation
|
/src/main/java/com/prituladima/DFSImpl.java
|
UTF-8
| 316 | 2 | 2 |
[] |
no_license
|
package com.prituladima;
import java.util.*;
public class DFSImpl {
private static final int inf = (int)1e6;
private boolean[] used = new boolean[inf];
public void dfs(int from, Map<Integer, Collection<Integer>> graph, List<Integer> ans){
// TODO: 13.10.2019 Task 3: Make tests work
}
}
| true |
8125be3c746b184f2bd0fa4bdc1a3f01f08526a4
|
Java
|
afikrim/ma-hateoas
|
/src/main/java/com/github/afikrim/flop/utils/ErrorHandler.java
|
UTF-8
| 5,921 | 2.3125 | 2 |
[] |
no_license
|
package com.github.afikrim.flop.utils;
import javax.persistence.EntityNotFoundException;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import lombok.extern.slf4j.Slf4j;
@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
@Slf4j
public class ErrorHandler extends ResponseEntityExceptionHandler {
/**
* Handle MissingServletRequestParameterException. Triggered when a 'required'
* request parameter is missing.
*
* @param ex MissingServletRequestParameterException
* @param headers HttpHeaders
* @param status HttpStatus
* @param request WebRequest
* @return
*/
@Override
protected ResponseEntity<Object> handleMissingServletRequestParameter(MissingServletRequestParameterException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
Response<Object> response = new Response<>(false, ResponseCode.BAD_REQUEST, ex.getMessage(), null);
return ResponseEntity.status(status).headers(headers).body(response);
}
/**
* Handle HttpMediaTypeNotSupportedException. This one triggers when JSON is
* invalid as well.
*
* @param ex HttpMediaTypeNotSupportedException
* @param headers HttpHeaders
* @param status HttpStatus
* @param request WebRequest
* @return
*/
@Override
protected ResponseEntity<Object> handleHttpMediaTypeNotSupported(HttpMediaTypeNotSupportedException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
Response<Object> response = new Response<>(false, ResponseCode.UNSUPPORTED_MEDIA_TYPE, ex.getMessage(), null);
return ResponseEntity.status(status).headers(headers).body(response);
}
/**
* Handles EntityNotFoundException. Created to encapsulate errors with more
* detail than javax.persistence.EntityNotFoundException.
*
* @param ex the EntityNotFoundException
* @return
*/
@ExceptionHandler(EntityNotFoundException.class)
protected ResponseEntity<Object> handleEntityNotFound(EntityNotFoundException ex) {
Response<Object> response = new Response<>(false, ResponseCode.NOT_FOUND, ex.getMessage(), null);
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
}
/**
* Handles DataIntegrityViolationException. Create
* Handles DataIntegrityViolationException. Created to encapsulate errors with more
* detail than org.springframework.dao.DataIntegrityViolationException.
*
* @param ex the DataIntegrityViolationException
* @return
*/
@ExceptionHandler(DataIntegrityViolationException.class)
protected ResponseEntity<Object> handleDataIntegrityViolation(DataIntegrityViolationException ex) {
Response<Object> response = new Response<>(false, ResponseCode.INTERNAL_SERVER_ERROR, ex.getMessage(), null);
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
}
/**
* Handle HttpMessageNotReadableException. Happens when request JSON is
* malformed.
*
* @param ex HttpMessageNotReadableException
* @param headers HttpHeaders
* @param status HttpStatus
* @param request WebRequest
* @return
*/
@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
String message = "Malformed JSON request";
Response<Object> response = new Response<>(false, ResponseCode.BAD_REQUEST, message, null);
return ResponseEntity.status(status).headers(headers).body(response);
}
/**
* Handle HttpMessageNotWritableException.
*
* @param ex HttpMessageNotWritableException
* @param headers HttpHeaders
* @param status HttpStatus
* @param request WebRequest
* @return
*/
@Override
protected ResponseEntity<Object> handleHttpMessageNotWritable(HttpMessageNotWritableException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
String message = "Error writing JSON output";
Response<Object> response = new Response<>(false, ResponseCode.BAD_REQUEST, message, null);
return ResponseEntity.status(status).headers(headers).body(response);
}
/**
* Handle HttpRequestMethodNotSupportedException.
*
* @param ex HttpMessageNotWritableException
* @param headers HttpHeaders
* @param status HttpStatus
* @param request WebRequest
* @return
*/
@Override
protected ResponseEntity<Object> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
String message = "Method not allowed";
Response<Object> response = new Response<>(false, ResponseCode.METHOD_NOT_ALLOWED, message, null);
return ResponseEntity.status(status).headers(headers).body(response);
}
}
| true |
3a53ef173716c5473a6814f613d659d406d9fbf0
|
Java
|
shahrzadav/codyze
|
/src/main/java/de/fraunhofer/aisec/codyze/crymlin/builtin/Year.java
|
UTF-8
| 2,166 | 2.515625 | 3 |
[
"LicenseRef-scancode-proprietary-license",
"Apache-2.0"
] |
permissive
|
package de.fraunhofer.aisec.codyze.crymlin.builtin;
import de.fraunhofer.aisec.codyze.analysis.*;
import de.fraunhofer.aisec.codyze.analysis.markevaluation.ExpressionEvaluator;
import de.fraunhofer.aisec.codyze.analysis.markevaluation.ExpressionHelper;
import de.fraunhofer.aisec.codyze.analysis.resolution.ConstantValue;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
/**
* Method signature: _year()
*
* Note:
* Time is represented as numeric value. The value represents the number of seconds
* since epoch (1970-01-01T00:00:00Z).
*/
public class Year implements Builtin {
private static final Logger log = LoggerFactory.getLogger(Year.class);
@NonNull
@Override
public String getName() {
return "_year";
}
@Override
public MarkIntermediateResult execute(
@NonNull AnalysisContext ctx,
@NonNull ListValue argResultList,
@NonNull Integer contextID,
@NonNull MarkContextHolder markContextHolder,
@NonNull ExpressionEvaluator expressionEvaluator) {
// arguments: int
// example:
// _year(_now()) returns 2021
try {
BuiltinHelper.verifyArgumentTypesOrThrow(argResultList, ConstantValue.class);
var epochSeconds = ExpressionHelper.asNumber(argResultList.get(0));
if (epochSeconds == null) {
log.warn("The argument for _year was not the expected type, or not initialized/resolved");
return ErrorValue.newErrorValue("The argument for _year was not the expected type, or not initialized/resolved", argResultList.getAll());
}
log.info("arg: {}", epochSeconds);
var instant = Instant.ofEpochSecond((Long) epochSeconds);
var ldt = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
var year = ldt.getYear();
log.debug("_year() -> {}", year);
ConstantValue cv = ConstantValue.of(year);
cv.addResponsibleNodesFrom((ConstantValue) argResultList.get(0));
return cv;
}
catch (InvalidArgumentException e) {
log.warn(e.getMessage());
return ErrorValue.newErrorValue(e.getMessage(), argResultList.getAll());
}
}
}
| true |
a917118a441027df5114c1652c84d8fbb6997787
|
Java
|
zendesk/android-lint-rules
|
/src/test/java/com/getbase/lint/BaseLintDetectorTest.java
|
UTF-8
| 1,067 | 1.867188 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.getbase.lint;
import com.android.tools.lint.checks.infrastructure.LintDetectorTest;
import com.android.tools.lint.detector.api.Detector;
import com.android.tools.lint.detector.api.Issue;
import com.getbase.lint.issues.EnumDetector;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableList;
import com.google.common.io.Resources;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
public abstract class BaseLintDetectorTest extends LintDetectorTest {
@Override
protected InputStream getTestResource(String relativePath, boolean expectExists) {
InputStream stream = getClass().getClassLoader().getResourceAsStream(relativePath);
if (!expectExists && stream == null) {
return null;
}
return stream;
}
protected String getExpectedError(String relativePath) throws IOException {
URL resource = getClass().getClassLoader().getResource(relativePath);
assertNotNull(resource);
return Resources.toString(resource, Charsets.UTF_8);
}
}
| true |
613e96ed85a1d98cd2bdc289f022fd4e7570e546
|
Java
|
wso2/carbon-business-process
|
/components/bpel/org.wso2.carbon.bpel.ui/src/main/java/org/wso2/carbon/bpel/ui/bpel2svg/impl/OnMessageImpl.java
|
UTF-8
| 19,213 | 2.015625 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.bpel.ui.bpel2svg.impl;
import org.apache.axiom.om.OMElement;
import org.w3c.dom.Element;
import org.w3c.dom.svg.SVGDocument;
import org.wso2.carbon.bpel.ui.bpel2svg.ActivityInterface;
import org.wso2.carbon.bpel.ui.bpel2svg.BPEL2SVGFactory;
import org.wso2.carbon.bpel.ui.bpel2svg.OnMessageInterface;
import org.wso2.carbon.bpel.ui.bpel2svg.SVGCoordinates;
import org.wso2.carbon.bpel.ui.bpel2svg.SVGDimension;
import java.util.Iterator;
import javax.xml.namespace.QName;
/**
* OnMessage tag UI implementation
*/
public class OnMessageImpl extends ActivityImpl implements OnMessageInterface {
/**
* Initializes a new instance of the OnMessageImpl class using the specified string i.e. the token
*
* @param token
*/
public OnMessageImpl(String token) {
//Variables to store the partnerLink & operation names
String partnerLink = "";
String operation = "";
// Get the Partner Link Name
int plIndex = token.indexOf("partnerLink");
int firstQuoteIndex = 0;
int lastQuoteIndex = 0;
if (plIndex >= 0) {
firstQuoteIndex = token.indexOf("\"", plIndex + 1);
if (firstQuoteIndex >= 0) {
lastQuoteIndex = token.indexOf("\"", firstQuoteIndex + 1);
if (lastQuoteIndex > firstQuoteIndex) {
partnerLink = token.substring(firstQuoteIndex + 1, lastQuoteIndex);
}
}
}
// Get the Operation Name
int opIndex = token.indexOf("operation");
if (opIndex >= 0) {
firstQuoteIndex = token.indexOf("\"", opIndex + 1);
if (firstQuoteIndex >= 0) {
lastQuoteIndex = token.indexOf("\"", firstQuoteIndex + 1);
if (lastQuoteIndex > firstQuoteIndex) {
operation = token.substring(firstQuoteIndex + 1, lastQuoteIndex);
setDisplayName(operation);
}
}
}
//Set the name by combining the partnerLink and operation Names
setName(partnerLink + "." + operation);
// Set Start and End Icon and Size
startIconPath = BPEL2SVGFactory.getInstance().getIconPath(this.getClass().getName());
endIconPath = BPEL2SVGFactory.getInstance().getEndIconPath(this.getClass().getName());
}
/**
* Initializes a new instance of the OnMessageImpl class using the specified omElement
*
* @param omElement which matches the OnMessage tag
*/
public OnMessageImpl(OMElement omElement) {
super(omElement);
//Variables to store the partnerLink & operation names
String partnerLink = null;
String operation = null;
// Get the Partner Link Name
if (omElement.getAttribute(new QName("partnerLink")) != null) {
partnerLink = omElement.getAttribute(new QName("partnerLink")).getAttributeValue();
}
// Get the operation Name
if (omElement.getAttribute(new QName("operation")) != null) {
operation = omElement.getAttribute(new QName("operation")).getAttributeValue();
}
//Set the name by combining the partnerLink and operation Names
setName(partnerLink + "." + operation);
// Set Start and End Icon and Size
startIconPath = BPEL2SVGFactory.getInstance().getIconPath(this.getClass().getName());
endIconPath = BPEL2SVGFactory.getInstance().getEndIconPath(this.getClass().getName());
}
/**
* Initializes a new instance of the OnMessageImpl class using the specified omElement
* Constructor that is invoked when the omElement type matches an OnMessage Activity when processing the
* subActivities
* of the process
*
* @param omElement which matches the OnMessage tag
* @param parent
*/
public OnMessageImpl(OMElement omElement, ActivityInterface parent) {
super(omElement);
//Set the parent of the activity
setParent(parent);
//Variables to store the partnerLink & operation names
String partnerLink = null;
String operation = null;
// Get the Partner Link Name
if (omElement.getAttribute(new QName("partnerLink")) != null) {
partnerLink = omElement.getAttribute(new QName("partnerLink")).getAttributeValue();
}
// Get the operation Name
if (omElement.getAttribute(new QName("operation")) != null) {
operation = omElement.getAttribute(new QName("operation")).getAttributeValue();
}
//Set the name by combining the partnerLink and operation Names
setName(partnerLink + "." + operation);
// Set Start and End Icon and Size
startIconPath = BPEL2SVGFactory.getInstance().getIconPath(this.getClass().getName());
endIconPath = BPEL2SVGFactory.getInstance().getEndIconPath(this.getClass().getName());
}
/**
* @return String with name of the activity
*/
@Override
public String getId() {
return getName(); // + "-OnMessage";
}
/**
* @return- String with the end tag of OnMessage Activity
*/
@Override
public String getEndTag() {
return BPEL2SVGFactory.ONMESSAGE_END_TAG;
}
/**
* At the start: width=0, height=0
*
* @return dimensions of the activity i.e. the final width and height after doing calculations by iterating
* through the dimensions of the subActivities
*/
@Override
public SVGDimension getDimensions() {
if (dimensions == null) {
int width = 0;
int height = 0;
//Set the dimensions at the start to (0,0)
dimensions = new SVGDimension(width, height);
//Dimensons of the subActivities
SVGDimension subActivityDim = null;
ActivityInterface activity = null;
//Iterates through the subActivites inside the activity
Iterator<ActivityInterface> itr = getSubActivities().iterator();
while (itr.hasNext()) {
activity = itr.next();
//Gets the dimensions of each subActivity separately
subActivityDim = activity.getDimensions();
//Checks whether the width of the subActivity is greater than zero
if (subActivityDim.getWidth() > width) {
width += subActivityDim.getWidth();
}
/*As OnMessage should increase in height when the number of subActivities increase, height of each
subActivity
is added to the height of the main activity
*/
height += subActivityDim.getHeight();
}
/*After iterating through all the subActivities and altering the dimensions of the activity
to get more spacing , Xspacing and Yspacing is added to the height and the width of the activity
*/
height += getYSpacing() + getStartIconHeight() + (getYSpacing() / 2);
width += getXSpacing();
//Set the Calculated dimensions for the SVG height and width
dimensions.setWidth(width);
dimensions.setHeight(height);
}
return dimensions;
}
/**
* Sets the layout of the process drawn
*
* @param startXLeft x-coordinate of the activity
* @param startYTop y-coordinate of the activity
*/
@Override
public void layout(int startXLeft, int startYTop) {
if (layoutManager.isVerticalLayout()) {
layoutVertical(startXLeft, startYTop);
} else {
layoutHorizontal(startXLeft, startYTop);
}
}
/**
* Sets the x and y positions of the activities
* At the start: startXLeft=0, startYTop=0
* centreOfMyLayout- center of the the SVG
*
* @param startXLeft x-coordinate
* @param startYTop y-coordinate
*/
public void layoutVertical(int startXLeft, int startYTop) {
//Aligns the activities to the center of the layout
int centreOfMyLayout = startXLeft + (dimensions.getWidth() / 2);
//Positioning the startIcon
int xLeft = centreOfMyLayout - (getStartIconWidth() / 2);
int yTop = startYTop + (getYSpacing() / 2);
ActivityInterface activity;
Iterator<ActivityInterface> itr = getSubActivities().iterator();
//Adjusting the childXLeft and childYTop positions
int childYTop = yTop + getStartIconHeight() + (getYSpacing() / 2);
int childXLeft;
//Iterates through all the subActivities
while (itr.hasNext()) {
activity = itr.next();
//Sets the xLeft position of the iterated activity : childXleft= center of the layout - (width of the
// activity icon)/2
childXLeft = centreOfMyLayout - activity.getDimensions().getWidth() / 2;
//Sets the xLeft and yTop position of the iterated activity
activity.layout(childXLeft, childYTop);
childYTop += activity.getDimensions().getHeight();
}
//Sets the xLeft and yTop positions of the start icon
setStartIconXLeft(xLeft);
setStartIconYTop(yTop);
//Sets the xLeft and yTop positions of the start icon text
setStartIconTextXLeft(startXLeft + BOX_MARGIN);
setStartIconTextYTop(startYTop + BOX_MARGIN + BPEL2SVGFactory.TEXT_ADJUST);
//Sets the xLeft and yTop positions of the SVG of the activity after setting the dimensions
getDimensions().setXLeft(startXLeft);
getDimensions().setYTop(startYTop);
}
/**
* Sets the x and y positions of the activities
* At the start: startXLeft=0, startYTop=0
*
* @param startXLeft x-coordinate
* @param startYTop y-coordinate
* centreOfMyLayout- center of the the SVG
*/
public void layoutHorizontal(int startXLeft, int startYTop) {
//Aligns the activities to the center of the layout
int centreOfMyLayout = startYTop + (dimensions.getHeight() / 2);
//Positioning the startIcon
int xLeft = startXLeft + (getYSpacing() / 2);
int yTop = centreOfMyLayout - (getStartIconHeight() / 2);
ActivityInterface activity;
Iterator<ActivityInterface> itr = getSubActivities().iterator();
//Adjusting the childXLeft and childYTop positions
int childYTop;
int childXLeft = xLeft + getStartIconWidth() + (getYSpacing() / 2);
//Iterates through all the subActivities
while (itr.hasNext()) {
activity = itr.next();
//Sets the yTop position of the iterated activity : childYTop= center of layout -(height of the activity)/2
childYTop = centreOfMyLayout - (activity.getDimensions().getHeight() / 2);
//Sets the xLeft and yTop position of the iterated activity
activity.layout(childXLeft, childYTop);
childXLeft += activity.getDimensions().getWidth();
}
//Sets the xLeft and yTop positions of the start icon
setStartIconXLeft(xLeft);
setStartIconYTop(yTop);
//Sets the xLeft and yTop positions of the start icon text
setStartIconTextXLeft(startXLeft + BOX_MARGIN);
setStartIconTextYTop(startYTop + BOX_MARGIN + BPEL2SVGFactory.TEXT_ADJUST);
//Sets the xLeft and yTop positions of the SVG of the activity after setting the dimensions
getDimensions().setXLeft(startXLeft);
getDimensions().setYTop(startYTop);
}
/**
* At the start: xLeft=0, yTop=0
* Calculates the coordinates of the arrow which enters an activity
*
* @return coordinates/entry point of the entry arrow for the activities
* After Calculations(Vertical Layout): xLeft=Xleft of Icon + (width of icon)/2 , yTop= Ytop of the Icon
*/
@Override
public SVGCoordinates getEntryArrowCoords() {
int xLeft = 0;
int yTop = 0;
if (layoutManager.isVerticalLayout()) {
xLeft = getStartIconXLeft() + (getStartIconWidth() / 2);
yTop = getStartIconYTop();
} else {
xLeft = getStartIconXLeft();
yTop = getStartIconYTop() + (getStartIconHeight() / 2);
}
//Returns the calculated coordinate points of the entry arrow
SVGCoordinates coords = new SVGCoordinates(xLeft, yTop);
return coords;
}
/**
* At the start: xLeft=0, yTop=0
* Calculates the coordinates of the arrow which leaves an activity
*
* @return coordinates/exit point of the exit arrow for the activities
*/
@Override
public SVGCoordinates getExitArrowCoords() {
//Exit arrow coordinates are calculated by invoking getStartIconExitArrowCoords()
SVGCoordinates coords = getStartIconExitArrowCoords();
//Checks for any subActivities
if (subActivities != null && subActivities.size() > 0) {
ActivityInterface activity = subActivities.get(subActivities.size() - 1);
coords = activity.getExitArrowCoords();
}
//Returns the calculated coordinate points of the exit arrow
return coords;
}
/**
* At the start: xLeft=0, yTop=0
* Calculates the coordinates of the arrow which leaves the start OnMessage Icon
*
* @return coordinates of the exit arrow for the start icon
* After Calculations(Vertical Layout): xLeft= Xleft of Icon + (width of icon)/2 , yTop= Ytop of the Icon +
* height of the icon
*/
protected SVGCoordinates getStartIconExitArrowCoords() {
int xLeft = 0;
int yTop = 0;
if (layoutManager.isVerticalLayout()) {
xLeft = getStartIconXLeft() + (getStartIconWidth() / 2);
yTop = getStartIconYTop() + getStartIconHeight();
} else {
xLeft = getStartIconXLeft() + getStartIconWidth();
yTop = getStartIconYTop() + (getStartIconHeight() / 2);
}
//Returns the calculated coordinate points of the exit arrow of the startIcon
SVGCoordinates coords = new SVGCoordinates(xLeft, yTop);
return coords;
}
/**
* @param doc SVG document which defines the components including shapes, gradients etc. of the activity
* @return Element(represents an element in a XML/HTML document) which contains the components of the OnMessage
* activity
*/
@Override
public Element getSVGString(SVGDocument doc) {
Element group = null;
group = doc.createElementNS(SVGNamespace.SVG_NAMESPACE, "g");
//Get the id of the activity
group.setAttributeNS(null, "id", getLayerId());
//Checks for the opacity of the icons
if (isAddOpacity()) {
group.setAttributeNS(null, "style", "opacity:" + getOpacity());
}
group.appendChild(getBoxDefinition(doc));
//Get the icons of the activity
group.appendChild(getImageDefinition(doc));
//Get the start image/icon text
group.appendChild(getStartImageText(doc));
// Process Sub Activities
group.appendChild(getSubActivitiesSVGString(doc));
//Get the arrow flows of the subActivities inside the OnMessage activity
group.appendChild(getArrows(doc));
return group;
}
/**
* Get the arrow coordinates of the activities
*
* @param doc SVG document which defines the components including shapes, gradients etc. of the activity
* @return An element which contains the arrow coordinates of the OnMessage activity and its subActivities
*/
protected Element getArrows(SVGDocument doc) {
Element subGroup = null;
subGroup = doc.createElementNS(SVGNamespace.SVG_NAMESPACE, "g");
//Checks for the subActivities
if (subActivities != null) {
ActivityInterface prevActivity = null;
ActivityInterface activity = null;
String id = null;
//Gets the exit coordinates of the start icon
SVGCoordinates myStartCoords = getStartIconExitArrowCoords();
SVGCoordinates exitCoords = null;
SVGCoordinates entryCoords = null;
Iterator<ActivityInterface> itr = subActivities.iterator();
//Iterates through all the subActivities
while (itr.hasNext()) {
activity = itr.next();
//Checks whether the previous activity is null
if (prevActivity != null) {
//Get the exit arrow coordinates of the previous activity
exitCoords = prevActivity.getExitArrowCoords();
//Get the entry arrow coordinates of the current activity
entryCoords = activity.getEntryArrowCoords();
// id is assigned with the id of the previous activity + id of the current activity
id = prevActivity.getId() + "-" + activity.getId();
/*If the previous activity is not null, then arrow flow is from the previous activity to the
current activity
This gives the coordinates of the start point and the end point
*/
subGroup.appendChild(getArrowDefinition(doc, exitCoords.getXLeft(), exitCoords.getYTop(),
entryCoords.getXLeft(), entryCoords.getYTop(), id));
} else {
//Get the entry arrow coordinates of the current activity
entryCoords = activity.getEntryArrowCoords();
/*If the previous activity is null, then arrow flow is directly from the startIcon to the activity
This gives the coordinates of the start point and the end point
*/
subGroup.appendChild(getArrowDefinition(doc, myStartCoords.getXLeft(), myStartCoords.getYTop(),
entryCoords.getXLeft(), entryCoords.getYTop(), id));
}
prevActivity = activity;
}
}
return subGroup;
}
/**
* Adds opacity to icons
*
* @return true or false
*/
@Override
public boolean isAddOpacity() {
return isAddCompositeActivityOpacity();
}
/**
* @return String with the opacity value
*/
@Override
public String getOpacity() {
return getCompositeOpacity();
}
}
| true |
41b3e2da5007cd23c9b5846ef8114a42bda9bdd9
|
Java
|
ClareBee/FlowYogaApp
|
/app/src/main/java/com/example/clareblackburne/yogaapp/Set.java
|
UTF-8
| 3,977 | 2.34375 | 2 |
[] |
no_license
|
package com.example.clareblackburne.yogaapp;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import static com.example.clareblackburne.yogaapp.DBHelper.POSES_COLUMN_CHAKRA;
import static com.example.clareblackburne.yogaapp.DBHelper.POSES_COLUMN_DURATION;
import static com.example.clareblackburne.yogaapp.DBHelper.POSES_COLUMN_ID;
import static com.example.clareblackburne.yogaapp.DBHelper.POSES_COLUMN_IMAGE;
import static com.example.clareblackburne.yogaapp.DBHelper.POSES_COLUMN_NAME;
import static com.example.clareblackburne.yogaapp.DBHelper.POSES_COLUMN_SANSKRITNAME;
import static com.example.clareblackburne.yogaapp.DBHelper.POSES_TABLE_NAME;
import static com.example.clareblackburne.yogaapp.DBHelper.SET_COLUMN_ID;
import static com.example.clareblackburne.yogaapp.DBHelper.SET_POSES_ID;
import static com.example.clareblackburne.yogaapp.DBHelper.SET_SESSION_ID;
import static com.example.clareblackburne.yogaapp.DBHelper.SET_TABLE_NAME;
/**
* Created by clareblackburne on 13/11/2017.
*/
public class Set {
private int id;
private int session_id;
private int poses_id;
public Set(int id, int session_id, int poses_id){
this.id = id;
this.session_id = session_id;
this.poses_id = poses_id;
}
public Set(int session_id, int poses_id) {
this.session_id = session_id;
this.poses_id = poses_id;
}
public int getId() {
return id;
}
//left in for future extension
public static ArrayList<Set> all(DBHelper dbHelper){
ArrayList<Set> sets = new ArrayList<>();
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + SET_TABLE_NAME, null);
while(cursor.moveToNext()){
int id = cursor.getInt(cursor.getColumnIndex(SET_COLUMN_ID));
int session_id = cursor.getInt(cursor.getColumnIndex(SET_SESSION_ID));
int poses_id = cursor.getInt(cursor.getColumnIndex(SET_POSES_ID));
Set set = new Set(id, session_id, poses_id);
sets.add(set);
}
cursor.close();
return sets;
}
public ArrayList<Pose> allPosesInSet(Integer session_id, DBHelper dbHelper) {
ArrayList<Pose> allPosesInThisSet = new ArrayList<>();
String selectAllQuery = "SELECT poses.* FROM " + POSES_TABLE_NAME + " INNER JOIN " + SET_TABLE_NAME + " ON poses.id = sessions_poses.poses_id WHERE sessions_poses.session_id = ? ";
String[] values = {session_id.toString()};
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.rawQuery(selectAllQuery, values);
if (cursor != null && cursor.getCount() > 0) {
while(cursor.moveToNext()){
int id = cursor.getInt(cursor.getColumnIndex(POSES_COLUMN_ID));
String name = cursor.getString(cursor.getColumnIndex(POSES_COLUMN_NAME));
String sanskritName = cursor.getString(cursor.getColumnIndex(POSES_COLUMN_SANSKRITNAME));
String chakra = cursor.getString(cursor.getColumnIndex(POSES_COLUMN_CHAKRA));
int duration = cursor.getInt(cursor.getColumnIndex(POSES_COLUMN_DURATION));
int image = cursor.getInt(cursor.getColumnIndex(POSES_COLUMN_IMAGE));
Pose pose = new Pose(name, sanskritName, chakra, duration, image);
allPosesInThisSet.add(pose);
}
cursor.close();
} else {
allPosesInThisSet.add(null);
}
return allPosesInThisSet;
}
public boolean save(DBHelper dbHelper){
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(SET_SESSION_ID, this.session_id);
cv.put(SET_POSES_ID, this.poses_id);
db.insert(SET_TABLE_NAME, null, cv);
return true;
}
}
| true |
63f605e221eefe982c99f9c6085cb81a725446c3
|
Java
|
vladislav57/2019-11-otus-spring-naumov
|
/homework01/src/main/java/ru/otus/homework01/Main.java
|
UTF-8
| 491 | 1.859375 | 2 |
[] |
no_license
|
package ru.otus.homework01;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import ru.otus.homework01.service.EnquiryService;
public class Main {
public static void main(final String[] args) {
final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("/spring-context.xml");
final EnquiryService enquiryService = context.getBean(EnquiryService.class);
enquiryService.performEnquiryWithAllQuestions();
}
}
| true |
783952bb0fb5334141097592c1bb75a5c1e95570
|
Java
|
narendrasuthar1/Auroapp
|
/Auraapp/src/main/java/com/dhanrajapp/form/LoginForm.java
|
UTF-8
| 696 | 1.976563 | 2 |
[] |
no_license
|
package com.dhanrajapp.form;
import org.apache.struts.action.ActionForm;
public class LoginForm extends ActionForm{
private String staffId;
private String password;
private String licenseNo;
public String getLicenseNo() {
return licenseNo;
}
public void setLicenseNo(String licenseNo) {
this.licenseNo = licenseNo;
}
public LoginForm() {
// TODO Auto-generated constructor stub
}
public String getStaffId() {
return staffId;
}
public void setStaffId(String staffId) {
this.staffId = staffId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
| true |
78a6d995402d29360fb873e535c4c524b2dd4e09
|
Java
|
rcoolboy/guilvN
|
/app/src/main/java/com/p118pd/sdk/C6065i1lL.java
|
UTF-8
| 1,858 | 2.015625 | 2 |
[] |
no_license
|
package com.p118pd.sdk;
import java.util.ArrayList;
import java.util.Enumeration;
import org.bouncycastle.cert.X509CRLHolder;
import org.bouncycastle.cert.X509CertificateHolder;
/* renamed from: com.pd.sdk.i1丨l丨L reason: invalid class name and case insensitive filesystem */
public class C6065i1lL {
public C1ILLL1 OooO00o;
public C6065i1lL(C1ILLL1 r1) {
this.OooO00o = r1;
}
public AbstractC6271iilI OooO00o() {
I11L OooO00o2 = this.OooO00o.OooO00o();
if (OooO00o2 == null) {
return new C5607LI1I1iI(new ArrayList());
}
ArrayList arrayList = new ArrayList(OooO00o2.size());
Enumeration OooO00o3 = OooO00o2.m15215OooO00o();
while (OooO00o3.hasMoreElements()) {
AbstractC6122iIlLiL OooO0O0 = ((AbstractC6854lLi1LL) OooO00o3.nextElement()).OooO0O0();
if (OooO0O0 instanceof I11li1) {
arrayList.add(new X509CRLHolder(C5190I1lIiL.OooO00o(OooO0O0)));
}
}
return new C5607LI1I1iI(arrayList);
}
/* renamed from: OooO00o reason: collision with other method in class */
public C1ILLL1 m16925OooO00o() {
return this.OooO00o;
}
public AbstractC6271iilI OooO0O0() {
I11L OooO0O0 = this.OooO00o.OooO0O0();
if (OooO0O0 == null) {
return new C5607LI1I1iI(new ArrayList());
}
ArrayList arrayList = new ArrayList(OooO0O0.size());
Enumeration OooO00o2 = OooO0O0.m15215OooO00o();
while (OooO00o2.hasMoreElements()) {
AbstractC6122iIlLiL OooO0O02 = ((AbstractC6854lLi1LL) OooO00o2.nextElement()).OooO0O0();
if (OooO0O02 instanceof I11li1) {
arrayList.add(new X509CertificateHolder(LilIiIl.OooO00o(OooO0O02)));
}
}
return new C5607LI1I1iI(arrayList);
}
}
| true |
3ae4bdfd41e43ff290a1432e7582f8f741fcbfaf
|
Java
|
hocgin/zeus
|
/zeus-gateway/src/main/java/in/hocg/zeus/gateway/filter/authorize/BaseAuthorizeFilter.java
|
UTF-8
| 2,008 | 2.15625 | 2 |
[] |
no_license
|
package in.hocg.zeus.gateway.filter.authorize;
import in.hocg.boot.utils.LangUtils;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import java.net.InetSocketAddress;
import java.util.Collections;
import java.util.List;
/**
* Created by hocgin on 2020/8/17
* email: [email protected]
*
* @author hocgin
*/
public abstract class BaseAuthorizeFilter implements GlobalFilter, Ordered {
private final PathMatcher matcher = new AntPathMatcher();
private final AuthorizeProperties properties;
public BaseAuthorizeFilter(AuthorizeProperties properties) {
this.properties = properties;
}
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE + 2;
}
/**
* IP 白名单
*
* @param request
* @return
*/
protected boolean isPermitAllWithIp(ServerHttpRequest request) {
InetSocketAddress remoteAddress = request.getRemoteAddress();
assert remoteAddress != null;
String ipAddress = remoteAddress.getAddress().getHostAddress();
return properties.getIgnoreIps().parallelStream()
.anyMatch(ipAddress::matches);
}
/**
* URI 白名单
*
* @param request
* @return
*/
protected boolean isPermitAllWithUri(ServerHttpRequest request) {
String path = request.getPath().toString();
List<String> ignoreUrls = LangUtils.getOrDefault(properties.getIgnoreUrls(), Collections.emptyList());
return ignoreUrls.parallelStream()
.anyMatch(pattern -> matcher.match(pattern, path));
}
/**
* 是否通过权限认证
*
* @param request
* @param username
* @return
*/
protected boolean isPassAuthorize(ServerHttpRequest request, String username) {
return true;
}
}
| true |
820df45b2b018baf32eefd0781a193a128603049
|
Java
|
wwowann/CSV_JSON_Parser
|
/src/test/java/EmployeeTest.java
|
UTF-8
| 1,238 | 2.703125 | 3 |
[] |
no_license
|
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.junit.Assert;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
public class EmployeeTest {
List<Employee> list = new ArrayList<>();
@BeforeEach
public void addEmployee() {
Employee emp = new Employee(1, "Inav", "Petrov", "RU", 25);
list.add(emp);
emp = new Employee(2, "John", "Smith", "USA", 23);
list.add(emp);
}
@Test
public void getFirstName() {
Assert.assertEquals("John", list.get(1).getFirstName());
}
@Test
public void firstNameBeginStartSwith() {
MatcherAssert.assertThat(list.get(1).getFirstName(), CoreMatchers.startsWith("J"));
}
@Test
public void getFirstNameMatcher() {
MatcherAssert.assertThat("Inav", CoreMatchers.equalTo(list.get(0).firstName));
}
@Test
public void containsStringInLastname() {
MatcherAssert.assertThat(list.get(1).lastName, CoreMatchers.containsString("i"));
}
@Test
public void endSwithInLastname() {
MatcherAssert.assertThat(list.get(0).lastName, CoreMatchers.endsWith("ov"));
}
}
| true |
c07ecb90dc24f82e8ac1a61686cf263248ef6bad
|
Java
|
Asisranjan/java
|
/ConcurrencyWS/src/hello/ConcurrencyDemo1.java
|
UTF-8
| 2,276 | 3.109375 | 3 |
[] |
no_license
|
package hello;
import java.util.concurrent.*;
public class ConcurrencyDemo1{
// count number of attempt
private int counter = 0;
private int heartbeattimer = 0;
public static void main(String []args){
ConcurrencyDemo1 h = new ConcurrencyDemo1();
h.start();
}
public void start()
{
CountDownLatch latch = new CountDownLatch(1);
ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);
ScheduledFuture<?> handle = exec.scheduleAtFixedRate(this.new Task(latch), 1, 5, TimeUnit.SECONDS);
try {
// block till registration success
latch.await();
handle.cancel(true);
exec.shutdownNow();
System.out.println(handle.isDone());
System.out.println(handle.isCancelled());
scheduleHeartbeatRequest();
initiateLookupOnAnyChangeOnConfig();
} catch (Throwable e) {
//Exception rootException = e.getCause();
}
}
public void initiateLookupOnAnyChangeOnConfig()
{
}
public void scheduleHeartbeatRequest()
{
ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);
ScheduledFuture<?> handle = exec.scheduleAtFixedRate(this.new HeartbeatHandler(), heartbeattimer, heartbeattimer, TimeUnit.SECONDS);
}
class Task implements Runnable
{
CountDownLatch latch;
public Task(CountDownLatch latch){
this.latch = latch;
}
public void run()
{
counter ++;
System.out.println("Hello World -"+System.currentTimeMillis()+"-"+counter);
// Lets say registation success in 4th attempt
if (counter == 4){
try {
heartbeattimer = 5;
latch.countDown();
} catch (Throwable e) {
//Exception rootException = e.getCause();
}
}
}
}
class HeartbeatHandler implements Runnable
{
public void run()
{
System.out.println("Send heart beat message - "+System.currentTimeMillis());
}
}
}
| true |
1d4e5e6fc01478a050544ece7021ecaf6a2b70c7
|
Java
|
grozeille/sonar-plugin-dotnet
|
/sonar/sonar-csharp-gendarme-plugin/src/main/java/org/sonar/plugins/csharp/gendarme/results/GendarmeResultParser.java
|
UTF-8
| 5,397 | 1.8125 | 2 |
[] |
no_license
|
/*
* Sonar C# Plugin :: Gendarme
* Copyright (C) 2010 Jose Chillan, Alexandre Victoor and SonarSource
* [email protected]
*
* This program 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 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.plugins.csharp.gendarme.results;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import javax.xml.stream.XMLStreamException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.codehaus.staxmate.SMInputFactory;
import org.codehaus.staxmate.in.SMEvent;
import org.codehaus.staxmate.in.SMHierarchicCursor;
import org.codehaus.staxmate.in.SMInputCursor;
import org.sonar.api.BatchExtension;
import org.sonar.api.rules.Rule;
import org.sonar.api.rules.RuleFinder;
import org.sonar.api.rules.RuleQuery;
import org.sonar.api.utils.SonarException;
import org.sonar.plugins.csharp.core.AbstractStaxParser;
import org.sonar.plugins.csharp.gendarme.GendarmeConstants;
/**
* Parses the reports generated by a Gendarme analysis.
*/
public class GendarmeResultParser extends AbstractStaxParser implements BatchExtension {
private RuleFinder ruleFinder;
private GendarmeViolationMaker gendarmeViolationMaker;
/**
* Constructs a @link{GendarmeResultParser}.
*
* @param project
* @param context
* @param rulesManager
* @param profile
*/
public GendarmeResultParser(RuleFinder ruleFinder, GendarmeViolationMaker gendarmeViolationMaker) {
super();
this.ruleFinder = ruleFinder;
this.gendarmeViolationMaker = gendarmeViolationMaker;
}
/**
* Parses a processed violation file.
*
* @param file
* the file to parse
*/
public void parse(File file) {
SMInputFactory inputFactory = initStax();
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
SMHierarchicCursor cursor = inputFactory.rootElementCursor(new InputStreamReader(fileInputStream, getEncoding()));
SMInputCursor rulesCursor = cursor.advance().descendantElementCursor("rule");
parseRuleBlocs(rulesCursor);
cursor.getStreamReader().closeCompletely();
} catch (XMLStreamException e) {
throw new SonarException("Error while reading Gendarme result file: " + file.getAbsolutePath(), e);
} catch (FileNotFoundException e) {
throw new SonarException("Cannot find Gendarme result file: " + file.getAbsolutePath(), e);
} finally {
IOUtils.closeQuietly(fileInputStream);
}
}
private void parseRuleBlocs(SMInputCursor cursor) throws XMLStreamException {
RuleQuery ruleQuery = RuleQuery.create().withRepositoryKey(GendarmeConstants.REPOSITORY_KEY);
// Cursor is on <rule>
while (cursor.getNext() != null) {
if (cursor.getCurrEvent().equals(SMEvent.START_ELEMENT)) {
Rule currentRule = ruleFinder.find(ruleQuery.withKey(cursor.getAttrValue("Name")));
if (currentRule != null) {
String type = cursor.getAttrValue("Type");
if (StringUtils.isEmpty(type)) {
parseRuleDefects(cursor, currentRule);
} else {
gendarmeViolationMaker.registerRuleType(currentRule, type);
}
}
}
}
}
private void parseRuleDefects(SMInputCursor cursor, Rule currentRule) throws XMLStreamException {
gendarmeViolationMaker.setCurrentRule(currentRule);
gendarmeViolationMaker.setCurrentDefaultViolationMessage("");
SMInputCursor childCursor = cursor.childElementCursor();
while (childCursor.getNext() != null) {
if ("problem".equals(childCursor.getQName().getLocalPart())) {
gendarmeViolationMaker.setCurrentDefaultViolationMessage(childCursor.collectDescendantText().trim());
} else if ("target".equals(childCursor.getQName().getLocalPart())) {
parseTargetBloc(childCursor);
}
}
}
private void parseTargetBloc(SMInputCursor cursor) throws XMLStreamException {
// Cursor is on <target>
gendarmeViolationMaker.setCurrentTargetName(cursor.getAttrValue("Name"));
gendarmeViolationMaker.setCurrentTargetAssembly(cursor.getAttrValue("Assembly"));
SMInputCursor defectCursor = cursor.childElementCursor();
while (defectCursor.getNext() != null) {
// Cursor is on <defect>
gendarmeViolationMaker.setCurrentLocation(defectCursor.getAttrValue("Location"));
gendarmeViolationMaker.setCurrentSource(defectCursor.getAttrValue("Source"));
gendarmeViolationMaker.setCurrentMessage(defectCursor.collectDescendantText().trim());
gendarmeViolationMaker.createViolation();
}
}
}
| true |
9bbe84d40e029c3a443cf9f2435f3f0a803e8b69
|
Java
|
sunjingcat/eCold
|
/app/src/main/java/com/zz/cold/business/storage/AddEquipmentActivity.java
|
UTF-8
| 7,804 | 1.8125 | 2 |
[] |
no_license
|
package com.zz.cold.business.storage;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.donkingliang.imageselector.utils.ImageSelector;
import com.donkingliang.imageselector.utils.ImageSelectorUtils;
import com.troila.customealert.CustomDialog;
import com.zz.cold.R;
import com.zz.cold.base.MyBaseActivity;
import com.zz.cold.bean.EquipmentBean;
import com.zz.cold.bean.ImageBack;
import com.zz.cold.bean.StorageBean;
import com.zz.cold.business.qualification.AddQualificationActivity;
import com.zz.cold.business.qualification.adapter.ImageDeleteItemAdapter;
import com.zz.cold.business.storage.adapter.EquipmentAdapter;
import com.zz.cold.business.storage.mvp.Contract;
import com.zz.cold.business.storage.mvp.presenter.EquipmentAddPresenter;
import com.zz.cold.business.storage.mvp.presenter.StorageAddPresenter;
import com.zz.cold.utils.PostUtils;
import com.zz.lib.commonlib.utils.ToolBarUtils;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;
/**
* 贮存设备edit
*/
public class AddEquipmentActivity extends MyBaseActivity<Contract.IsetEquipmentAddPresenter> implements Contract.IGetEquipmentAddView {
@BindView(R.id.toolbar)
Toolbar toolbar;
ArrayList<ImageBack> images = new ArrayList<>();
ImageDeleteItemAdapter adapter;
@BindView(R.id.rv_image)
RecyclerView rvImages;
String warehouseId;
String id;
@BindView(R.id.toolbar_title)
TextView toolbar_title;
@BindView(R.id.text_equipmentName)
EditText text_equipmentName;
@BindView(R.id.text_equipmentRemark)
EditText text_equipmentRemark;
@Override
protected int getContentView() {
return R.layout.activity_equipment_add;
}
@Override
public EquipmentAddPresenter initPresenter() {
return new EquipmentAddPresenter(this);
}
@Override
protected void initView() {
ButterKnife.bind(this);
rvImages.setLayoutManager(new GridLayoutManager(this, 3));
adapter = new ImageDeleteItemAdapter(this, images);
rvImages.setAdapter(adapter);
warehouseId = getIntent().getStringExtra("warehouseId");
id = getIntent().getStringExtra("id");
if (!TextUtils.isEmpty(id)){
toolbar_title.setText("修改贮存设备");
mPresenter.getData(id);
}else {
toolbar_title.setText("新增贮存设备");
}
adapter.setOnclick(new ImageDeleteItemAdapter.Onclick() {
@Override
public void onclickAdd(View v, int option) {
ArrayList<String> localPath = new ArrayList<>();
for (int i = 0; i < images.size(); i++) {
if (!TextUtils.isEmpty(images.get(i).getPath())) {
localPath.add(images.get(i).getPath());
} else {
}
}
ImageSelector.builder()
.useCamera(true) // 设置是否使用拍照
.setSingle(false) //设置是否单选
.setMaxSelectCount(9 - images.size()) // 图片的最大选择数量,小于等于0时,不限数量。
.setSelected(localPath) // 把已选的图片传入默认选中。
.setViewImage(true) //是否点击放大图片查看,,默认为true
.start(AddEquipmentActivity.this, 1101); // 打开相册
}
@Override
public void onclickDelete(View v, int option) {
images.remove(option);
adapter.notifyDataSetChanged();
}
});
}
@OnClick({R.id.toolbar_subtitle})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.toolbar_subtitle:
if (TextUtils.isEmpty(warehouseId)) {
setResult();
} else {
postData();
}
break;
}
}
void setResult() {
EquipmentBean equipmentBean = new EquipmentBean(getText(text_equipmentName), getText(text_equipmentRemark), PostUtils.getImageIds(images));
setResult(RESULT_OK, new Intent().putExtra("equipment", equipmentBean));
finish();
}
void postData() {
Map<String, Object> params = new HashMap<>();
params.put("equipmentName", getText(text_equipmentName));
params.put("equipmentRemark", getText(text_equipmentRemark));
params.put("enclosureIds", PostUtils.getImageIds(images));
params.put("warehouseId", warehouseId);
if (!TextUtils.isEmpty(id)){
params.put("id",id);
}
mPresenter.submitData(params);
}
@Override
protected void initToolBar() {
ToolBarUtils.getInstance().setNavigation(toolbar);
}
@Override
public void showEquipmentInfo(EquipmentBean data) {
text_equipmentName.setText(data.getEquipmentName()+"");
text_equipmentRemark.setText(data.getEquipmentRemark()+"");
warehouseId = data.getWarehouseId();
}
@Override
public void showResult() {
setResult();
}
@Override
public void showPostImage(String localPath, ImageBack imageBack) {
if (imageBack == null) return;
imageBack.setPath(localPath);
images.add(imageBack);
adapter.notifyDataSetChanged();
}
@Override
public void showImage(List<ImageBack> list) {
if (list == null) return;
images.clear();
images.addAll(list);
adapter.notifyDataSetChanged();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && data != null) {
switch (requestCode) {
case 1101:
ArrayList<String> selectImages = data.getStringArrayListExtra(
ImageSelectorUtils.SELECT_RESULT);
for (String path : selectImages) {
Luban.with(this)
.load(path)
.ignoreBy(100)
.setCompressListener(new OnCompressListener() {
@Override
public void onStart() {
// TODO 压缩开始前调用,可以在方法内启动 loading UI
}
@Override
public void onSuccess(File file) {
mPresenter.postImage(file.getPath(), getImageBody(file.getPath()));
}
@Override
public void onError(Throwable e) {
// TODO 当压缩过程出现问题时调用
}
}).launch();
}
break;
}
}
}
}
| true |
abcbec216dee19580a162e5a02f72f7a5c822364
|
Java
|
hymanath/PA
|
/partyanalyst-service/trunk/src/main/java/com/itgrids/partyanalyst/dto/PartyPositionsInDistrictVO.java
|
UTF-8
| 3,505 | 2.109375 | 2 |
[] |
no_license
|
/*
* Copyright (c) 2009 IT Grids.
* All Rights Reserved.
*
* IT Grids Confidential Information.
* Created on April 07,2010
*/
package com.itgrids.partyanalyst.dto;
import java.io.Serializable;
public class PartyPositionsInDistrictVO implements Serializable {
/**
*
*/
private static final long serialVersionUID = -6988911071267468461L;
private Long nthPos;
private Long SeatsWon;
private Long thirdPos;
private Long secondPos;
private Long fourthPos;
private Long districtId;
private String districtName;
private Long totalValidVotes;
private Long totalVotesEarned;
private String votesPercentage;
private Long totalConstituencies;
private Long totalConstiValidVotes;
private String completeVotesPercent;
private Double completeVotesPercentDouble;
private Long totalConstiParticipated;
//getters and setters
public Long getNthPos() {
return nthPos;
}
public void setNthPos(Long nthPos) {
this.nthPos = nthPos;
}
public Long getSeatsWon() {
return SeatsWon;
}
public void setSeatsWon(Long seatsWon) {
SeatsWon = seatsWon;
}
public Long getThirdPos() {
return thirdPos;
}
public void setThirdPos(Long thirdPos) {
this.thirdPos = thirdPos;
}
public Long getSecondPos() {
return secondPos;
}
public void setSecondPos(Long secondPos) {
this.secondPos = secondPos;
}
public Long getFourthPos() {
return fourthPos;
}
public void setFourthPos(Long fourthPos) {
this.fourthPos = fourthPos;
}
public Long getDistrictId() {
return districtId;
}
public void setDistrictId(Long districtId) {
this.districtId = districtId;
}
public String getDistrictName() {
return districtName;
}
public void setDistrictName(String districtName) {
this.districtName = districtName;
}
public Long getTotalValidVotes() {
return totalValidVotes;
}
public void setTotalValidVotes(Long totalValidVotes) {
this.totalValidVotes = totalValidVotes;
}
public Long getTotalVotesEarned() {
return totalVotesEarned;
}
public void setTotalVotesEarned(Long totalVotesEarned) {
this.totalVotesEarned = totalVotesEarned;
}
public String getVotesPercentage() {
return votesPercentage;
}
public void setVotesPercentage(String votesPercentage) {
this.votesPercentage = votesPercentage;
}
public Long getTotalConstituencies() {
return totalConstituencies;
}
public void setTotalConstituencies(Long totalConstituencies) {
this.totalConstituencies = totalConstituencies;
}
public Long getTotalConstiValidVotes() {
return totalConstiValidVotes;
}
public void setTotalConstiValidVotes(Long totalConstiValidVotes) {
this.totalConstiValidVotes = totalConstiValidVotes;
}
public String getCompleteVotesPercent() {
return completeVotesPercent;
}
public void setCompleteVotesPercent(String completeVotesPercent) {
this.completeVotesPercent = completeVotesPercent;
}
public Long getTotalConstiParticipated() {
return totalConstiParticipated;
}
public void setTotalConstiParticipated(Long totalConstiParticipated) {
this.totalConstiParticipated = totalConstiParticipated;
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
public Double getCompleteVotesPercentDouble() {
return completeVotesPercentDouble;
}
public void setCompleteVotesPercentDouble(Double completeVotesPercentDouble) {
this.completeVotesPercentDouble = completeVotesPercentDouble;
}
}
| true |
674741b83bdb0530bdf652886c522e61b248b268
|
Java
|
FitimHajredini59/RaportoUP
|
/app/src/main/java/com/FIEK/raportoup/aktivitetet/FaqjaHyrese.java
|
UTF-8
| 1,028 | 1.726563 | 2 |
[] |
no_license
|
package com.FIEK.raportoup.aktivitetet;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import androidx.appcompat.app.AppCompatActivity;
import com.FIEK.raportoup.R;
public class FaqjaHyrese extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_faqja_hyrese);
LinearLayout linearLayout = findViewById(R.id.activity_faqja_hyrese);
linearLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(FaqjaHyrese.this, Login.class);
startActivity(intent);
}
}
);
}
}
| true |
a645b26db893c83e16c3b6695bfd6a2d77944398
|
Java
|
simokhov/schemas44
|
/src/main/java/ru/gov/zakupki/oos/types/_1/ZfcsNotificationModification111Type.java
|
UTF-8
| 3,728 | 1.757813 | 2 |
[
"MIT"
] |
permissive
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2019.07.02 at 03:35:23 PM MSK
//
package ru.gov.zakupki.oos.types._1;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* Внесение изменений в извещение по ст. 111 Федерального закона № 44-ФЗ
*
* <p>Java class for zfcs_notificationModification111Type complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="zfcs_notificationModification111Type">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="modificationNumber" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="info" type="{http://zakupki.gov.ru/oos/types/1}zfcs_longTextMinType" minOccurs="0"/>
* <element name="addInfo" type="{http://zakupki.gov.ru/oos/types/1}zfcs_longTextMinType" minOccurs="0"/>
* <element name="reason" type="{http://zakupki.gov.ru/oos/types/1}zfcs_purchaseChangeType" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "zfcs_notificationModification111Type", propOrder = {
"modificationNumber",
"info",
"addInfo",
"reason"
})
public class ZfcsNotificationModification111Type {
protected int modificationNumber;
protected String info;
protected String addInfo;
protected ZfcsPurchaseChangeType reason;
/**
* Gets the value of the modificationNumber property.
*
*/
public int getModificationNumber() {
return modificationNumber;
}
/**
* Sets the value of the modificationNumber property.
*
*/
public void setModificationNumber(int value) {
this.modificationNumber = value;
}
/**
* Gets the value of the info property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getInfo() {
return info;
}
/**
* Sets the value of the info property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setInfo(String value) {
this.info = value;
}
/**
* Gets the value of the addInfo property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAddInfo() {
return addInfo;
}
/**
* Sets the value of the addInfo property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAddInfo(String value) {
this.addInfo = value;
}
/**
* Gets the value of the reason property.
*
* @return
* possible object is
* {@link ZfcsPurchaseChangeType }
*
*/
public ZfcsPurchaseChangeType getReason() {
return reason;
}
/**
* Sets the value of the reason property.
*
* @param value
* allowed object is
* {@link ZfcsPurchaseChangeType }
*
*/
public void setReason(ZfcsPurchaseChangeType value) {
this.reason = value;
}
}
| true |
660100a2441cb04f79266ac57eba78b5cb152f0a
|
Java
|
Mandersen21/dtupay
|
/merchant-service/src/test/java/beijing/merchantservice/domain/TransactionObjectTest.java
|
UTF-8
| 3,021 | 2.5 | 2 |
[] |
no_license
|
package beijing.merchantservice.domain;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.Date;
import org.junit.Test;
public class TransactionObjectTest {
@Test
public void constructorNotNullTest() {
TransactionObject trOb = new TransactionObject("123987","222666", "123123", "100", 1234333l);
assertNotNull(trOb);
}
@Test
public void getAmountTest() {
TransactionObject trOb = new TransactionObject("123987","222666", "123123", "100", 1234333l);
String actual = trOb.getAmount();
String expected = "100";
assertEquals(expected, actual);
}
@Test
public void getCustomerTest() {
TransactionObject trOb = new TransactionObject("123987","222666", "123123", "100", 1234333l);
String actual = trOb.getCustomerId();
String expected = "222666";
assertEquals(expected, actual);
}
@Test
public void getMerchantIdTest() {
TransactionObject trOb = new TransactionObject("123987","222666", "123123", "100", 123456l);
String actual = trOb.getMerchantId();
String expected = "123987";
assertEquals(expected, actual);
}
@Test
public void getTransactionIdTest() {
TransactionObject trOb = new TransactionObject("123987","222666", "123123", "100", 123456l);
String actual = trOb.getTrasactionId();
String expected = "123123";
assertEquals(expected, actual);
}
@Test
public void getDateTest() {
long l = System.currentTimeMillis();
TransactionObject trOb = new TransactionObject("123987","222666", "123123", "100",l );
long actual = trOb.getTimeOfTransaction();
long expected = l;
assertEquals(expected, actual);
}
@Test
public void setAmountTest() {
TransactionObject trOb = new TransactionObject("123987","222666", "123123", "100", 123456l);
trOb.setAmount("200");
String actual = trOb.getAmount();
String expected = "200";
assertEquals(expected, actual);
}
@Test
public void setCustomerTest() {
TransactionObject trOb = new TransactionObject("123987","222666", "123123", "100", 123456l);
trOb.setCustomerId("1234321");
String actual = trOb.getCustomerId();
String expected = "1234321";
assertEquals(expected, actual);
}
@Test
public void setMerchantIdTest() {
TransactionObject trOb = new TransactionObject("123987","222666", "123123", "100", 123456l);
trOb.setMerchantId("000");
String actual = trOb.getMerchantId();
String expected = "000";
assertEquals(expected, actual);
}
@Test
public void setTransactionIdTest() {
TransactionObject trOb = new TransactionObject("123987","222666", "123123", "100", 123456l);
trOb.setTrasactionId("111");
String actual = trOb.getTrasactionId();
String expected = "111";
assertEquals(expected, actual);
}
@Test
public void setDateTest() {
TransactionObject trOb = new TransactionObject("123987","222666", "123123", "100", 123456l);
trOb.setTimeOfTransaction(1234333l);
long actual = trOb.getTimeOfTransaction();
long expected = 1234333l;
assertEquals(expected, actual);
}
}
| true |
3eb2a598fabaebb962035d860cbbcef0b36ba362
|
Java
|
pouyanhessabi/JPotify-java-spotify
|
/UserFrame.java
|
UTF-8
| 2,625 | 2.921875 | 3 |
[] |
no_license
|
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.text.StyledEditorKit;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.TimeUnit;
/**
* The Responder class get user name from client
*
* @author omid mahyar and pouyan hesabi *
* @version 1.0 (1398/04/04)
*/
public class UserFrame extends JFrame {
private JTextField textField;
private String text;
private volatile boolean tmpCheck;
public void setTmpCheck(boolean tmpCheck) {
this.tmpCheck = tmpCheck;
}
public boolean isTmpCheck() {
return tmpCheck;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public JButton getButton1() {
return button1;
}
private JButton button1;
public JTextField getTextField() {
return textField;
}
public UserFrame() {
this.setTitle("Welcome to the Binarify");
setTmpCheck(false);
this.setSize(600, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setBackground(Color.BLACK);
panel.setSize(100, 100);
JLabel label = new JLabel(" Enter your name ");
label.setBackground(Color.BLACK);
label.setForeground(Color.green);
label.setPreferredSize(new Dimension(600, 30));
button1 = new JButton("Sing in");
button1.setBackground(Color.BLACK);
button1.setForeground(Color.green);
button1.setCursor(new Cursor(Cursor.HAND_CURSOR));
button1.setBorderPainted(false);
button1.setFocusPainted(false);
button1.setContentAreaFilled(false);
button1.setPreferredSize(new Dimension(600, 30));
button1.addActionListener(new TextListener());
textField = new JTextField();
textField.setPreferredSize(new Dimension(200, 50));
panel.add(label);
panel.add(textField);
panel.add(button1);
this.add(panel);
this.setVisible(true);
}
public void closeTheFrame() {
this.setVisible(false);
}
private class TextListener implements ActionListener {
@Override
public synchronized void actionPerformed(ActionEvent e) {
if (e.getSource() == getButton1()) {
setText(getTextField().getText());
setTmpCheck(true);
closeTheFrame();
}
}
}
}
| true |
3a600dff89996a3c560793508bdeec1b3d0d7a19
|
Java
|
wlk/XChange
|
/xchange-kucoin/src/main/java/org/knowm/xchange/kucoin/service/TradingFeeAPI.java
|
UTF-8
| 1,008 | 2.078125 | 2 |
[
"MIT"
] |
permissive
|
package org.knowm.xchange.kucoin.service;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Map;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.knowm.xchange.kucoin.dto.response.KucoinResponse;
import si.mazi.rescu.ParamsDigest;
import si.mazi.rescu.SynchronizedValueFactory;
@Path("api/v1")
@Produces(MediaType.APPLICATION_JSON)
public interface TradingFeeAPI {
/**
* Get basic fee rate of users.
*
* @return basic trading fee information
*/
@GET
@Path("/base-fee")
KucoinResponse<Map<String, BigDecimal>> getBaseFee(
@HeaderParam(APIConstants.API_HEADER_KEY) String apiKey,
@HeaderParam(APIConstants.API_HEADER_SIGN) ParamsDigest signature,
@HeaderParam(APIConstants.API_HEADER_TIMESTAMP) SynchronizedValueFactory<Long> nonce,
@HeaderParam(APIConstants.API_HEADER_PASSPHRASE) String apiPassphrase)
throws IOException;
}
| true |
2b00a73ab0a36a0c4dbb9d9c9cb26de3e116f997
|
Java
|
hsg593718753/emc
|
/emc-platform/src/main/java/com/huak/org/NodeController.java
|
UTF-8
| 8,489 | 2.046875 | 2 |
[] |
no_license
|
package com.huak.org;
import com.alibaba.fastjson.JSONObject;
import com.huak.auth.model.User;
import com.huak.common.CommonExcelExport;
import com.huak.common.Constants;
import com.huak.common.UUIDGenerator;
import com.huak.common.page.Page;
import com.huak.org.model.Node;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Created by MR-BIN on 2017/5/16.
*/
@Controller
@RequestMapping("/station")
public class NodeController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Resource
private NodeService nodeService;
@Resource
private OncenetService oncenetService;
@Resource
private SecondnetService secondnetService;
@Resource
private FeedService feedService;
@RequestMapping(value = "/list", method = RequestMethod.GET)
public String listPage() {
logger.info("转至系统热力站列表页");
return "/org/node/list";
}
@RequestMapping(value = "/list", method = RequestMethod.PATCH)
@ResponseBody
public String list(@RequestParam Map<String, Object> paramsMap, Page page) {
logger.info("热力站列表页分页查询");
JSONObject jo = new JSONObject();
try {
jo.put(Constants.LIST, nodeService.queryByPage(paramsMap, page));
} catch (Exception e) {
logger.error("热力站列表页分页查询异常" + e.getMessage());
}
return jo.toJSONString();
}
@RequestMapping(value = "/add/{pOrgId}/{comId}", method = RequestMethod.GET)
public String addPage(@PathVariable("pOrgId") Long pOrgId,@PathVariable("comId") String comId,ModelMap modelMap) {
try {
Node obj = new Node();
obj.setOrgId(pOrgId);
obj.setComId(comId);
Map<String,Object> params = new HashMap<>();
params.put("comId",comId);
params.put("orgId",pOrgId);
modelMap.put(Constants.OBJECT,obj);
modelMap.put("oncenet",nodeService.selectNetAll(params));
modelMap.put("feed",nodeService.selectFeedByMap(params));
} catch (Exception e) {
logger.error("跳转到热力站编辑页出错!");
e.printStackTrace();
}
return "/org/node/add";
}
@RequestMapping(value = "/add", method = RequestMethod.POST)
@ResponseBody
public String add(Node node, HttpServletRequest request) {
logger.info("添加热力站");
JSONObject jo = new JSONObject();
jo.put(Constants.FLAG, false);
try {
// TODO 添加session,创建者
HttpSession session = request.getSession();
User user = (User) session.getAttribute(Constants.SESSION_KEY);
node.setId(UUIDGenerator.getUUID());
boolean flag = nodeService.insertSelective(node);
if(flag){
jo.put(Constants.FLAG, true);
jo.put(Constants.MSG, "添加热力站成功");
}else{
jo.put(Constants.FLAG, false);
jo.put(Constants.MSG, "添加热力站失败");
}
} catch (Exception e) {
e.printStackTrace();
logger.error("添加热力站异常" + e.getMessage());
jo.put(Constants.MSG, "添加热力站失败");
jo.put("station",null);
}
return jo.toJSONString();
}
@RequestMapping(value = "/edit/{id}/{orgId}/{comId}", method = RequestMethod.GET)
public String editPage(Model model, @PathVariable("id") String id,@PathVariable("orgId") Long pOrgId,@PathVariable("comId") String comId) {
logger.info("跳转修改热力站页");
try {
model.addAttribute("node", nodeService.selectById(id));
Map<String,Object> params = new HashMap<>();
params.put("comId",comId);
params.put("orgId",pOrgId);
model.addAttribute("oncenet",nodeService.selectNetAll(params));
model.addAttribute("feed",nodeService.selectFeedByMap(params));
} catch (Exception e) {
logger.error("跳转修改热力站页异常" + e.getMessage());
}
return "/org/node/edit";
}
@RequestMapping(value = "/edit", method = RequestMethod.POST)
@ResponseBody
public String edit(Node node) {
logger.info("修改热力站");
JSONObject jo = new JSONObject();
jo.put(Constants.FLAG, false);
try {
nodeService.update(node);
jo.put(Constants.FLAG, true);
jo.put(Constants.MSG, "修改热力站成功");
} catch (Exception e) {
logger.error("修改热力站异常" + e.getMessage());
jo.put(Constants.MSG, "修改热力站失败");
}
return jo.toJSONString();
}
/**
* @param id
* @return
*/
@RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
@ResponseBody
public String deleteNode(@PathVariable("id") String id) {
logger.info("删除热力站");
JSONObject jo = new JSONObject();
jo.put(Constants.FLAG, false);
try {
nodeService.deleteByPrimaryKey(id);
jo.put(Constants.FLAG, true);
jo.put(Constants.MSG, "删除热力站成功");
} catch (Exception e) {
logger.error("删除热力站异常" + e.getMessage());
jo.put(Constants.MSG, "删除热力站失败");
}
return jo.toJSONString();
}
@RequestMapping(value = "/export", method = RequestMethod.GET)
public void export(@RequestParam Map<String, Object> paramsMap, HttpServletResponse response) {
logger.info("导出热力站列表EXCEL");
String workBookName = "热力站列表";//文件名
Map<String, String> cellName = new LinkedHashMap<>();//列标题(有序)
cellName.put("STATION_NAME", "热力站名称");
cellName.put("STATION_CODE", "热力站编号");
cellName.put("MANAGE_TYPE", "管理类型");
cellName.put("ADDR", "详细地址");
cellName.put("LNG", "经度");
cellName.put("LAT", "纬度");
cellName.put("HEAT_AREA", "供热面积");
List<Map<String, Object>> cellValues = null;//列值
OutputStream out = null;
try {
cellValues = nodeService.exportExcel(paramsMap);
HSSFWorkbook wb = CommonExcelExport.excelExport(cellName, cellValues);
//response输出流导出excel
String mimetype = "application/vnd.ms-excel";
response.setContentType(mimetype);
response.setCharacterEncoding("UTF-8");
String fileName = workBookName + ".xls";
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
out = response.getOutputStream();
wb.write(out);
out.flush();
out.close();
} catch (Exception e) {
logger.error("导出热力站列表EXCEL异常" + e.getMessage());
}
}
/**
*唯一性校验
* sunbinbin
* @return string
*/
@RequestMapping(value = "/check", method = RequestMethod.POST)
@ResponseBody
public String checkUnique(@RequestParam Map<String, Object> paramsMap) {
logger.info("热力站唯一性校验");
JSONObject jo = new JSONObject();
jo.put(Constants.FLAG, false);
try {
List<Map<String,Object>> data= nodeService.selectStationByMap(paramsMap);
if (data.size() == 0) {
jo.put(Constants.FLAG, true);
}else {
jo.put(Constants.FLAG, false);
}
} catch (Exception e) {
jo.put(Constants.FLAG,false);
logger.error("热源唯一性校验异常" + e.getMessage());
}
return jo.toJSONString();
}
}
| true |
0fbeec8633e52ab1fa1e0a16a2d8220972c9d2bd
|
Java
|
SweetSiin/UnionWallBe
|
/src/test/java/test/videoYoutube.java
|
WINDOWS-1250
| 2,054 | 2.71875 | 3 |
[] |
no_license
|
package test;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
public class videoYoutube {
static WebDriver driver;
static WebDriverWait wait;
// buscar un video en youtube
public static void main(String[] args) throws InterruptedException {
// *navegar a la url
navegarUrl("https://www.youtube.com/");
// *Buscar el video
buscarVideo("ZEUS, Destripando la Historia");
// -introducir el nombre del video en el buscador
// -hacer click en la lupa
// -seleccinar el video de la lista
clickCancion("ZEUS, Destripando la Historia");
Thread.sleep(4000);
ValidarVideo();
cerrarpag();
}
private static void navegarUrl(String url) {
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
wait = new WebDriverWait(driver, 15);
driver.get(url);
}
private static void buscarVideo(String nombreCancion) {
WebElement buscadorYutu = driver.findElement(By.xpath("//input[@id=\"search\"]"));
buscadorYutu.click();
buscadorYutu.sendKeys(nombreCancion);
WebElement botonBuscar = driver.findElement(By.xpath("//button[@id=\"search-icon-legacy\"]"));
botonBuscar.click();
}
private static void clickCancion(String selecCancion) {
WebElement cancionYutu = driver.findElement(By.xpath("//a[@title=\"ZEUS | Destripando la Historia | Cancin\"]"));
cancionYutu.click();
}
private static void ValidarVideo() {
WebElement tituloVideo = driver.findElement(By.xpath("//h1[@class=\"title style-scope ytd-video-primary-info-renderer\"]"));
if(tituloVideo.isDisplayed())
System.out.println("Se encontro el elemento de la validacion.");
else {
System.out.println("No se encontro el elemento.");
System.exit(-1);
}
}
private static void cerrarpag() {
driver.close();
driver.quit();
}
}
| true |
3de53fc262b04b3d3ec2d2b6191d8932089cea5e
|
Java
|
KimarenNaidoo/LeetCode-Solns
|
/LeetCode/69. Sqrt(x)/src/TestCase.java
|
UTF-8
| 623 | 3.765625 | 4 |
[] |
no_license
|
public class TestCase {
public static int mySqrt(int x) { // Easier version
double value = (double)x;
double result = Math.sqrt(value);
return (int)result;
}
public static int mySqrtv2(int x) { // Binary search
int low = 0, high = x;
while (low <= high) {
double mid = low + ((high - low)/2);
if (mid * mid == x) {
return (int)mid;
} else if (mid * mid > x) {
high = (int)mid - 1;
} else {
low = (int)mid + 1;
}
}
return high;
}
public static void main(String[] args) {
int x = 8;
System.out.println(mySqrt(x));
System.out.println(mySqrtv2(x));
}
}
| true |
bdcec8c4c5c8564dc9f185ac01e4add411d90cdd
|
Java
|
PrathyushaKanumalla/EPI_ALGORITHMS
|
/strings/PhoneMnemonics.java
|
UTF-8
| 911 | 3.46875 | 3 |
[] |
no_license
|
package strings;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
public class PhoneMnemonics {
public static final String[] Maping = {"0","1","ABC","DEF","GHI","JKL","MNO","PQRS","TUV","WXYZ"};
public static void main(String[] args) {
System.out.println("phone mnemonics: ");
int[] number = {1,2,3,4};
resursiveMnemonic(number);
}
private static void resursiveMnemonic(int[] number) {
int index = 0;
char[] string = new char[number.length];
recuresiveCall(number, index, string,0);
}
private static void recuresiveCall(int[] number, int index, char[] string, int strindex) {
if(index == number.length) {
System.out.println(string);
return;
}
String values = Maping[number[index]];
for (char i : values.toCharArray()) {
string[strindex] = i;
recuresiveCall(number, index+1, string,strindex+1);
}
}
}
| true |
d8b80db88f3e797516e2d6513948a7c97fde51e1
|
Java
|
TencentCloud/tencentcloud-sdk-java
|
/src/main/java/com/tencentcloudapi/antiddos/v20200309/models/BGPIPInstanceUsages.java
|
UTF-8
| 3,930 | 2 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencentcloudapi.antiddos.v20200309.models;
import com.tencentcloudapi.common.AbstractModel;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import java.util.HashMap;
public class BGPIPInstanceUsages extends AbstractModel{
/**
* 已使用的端口规则数,单位条
*/
@SerializedName("PortRulesUsage")
@Expose
private Long PortRulesUsage;
/**
* 已使用的域名规则数,单位条
*/
@SerializedName("DomainRulesUsage")
@Expose
private Long DomainRulesUsage;
/**
* 最近7天的攻击次数,单位次
*/
@SerializedName("Last7DayAttackCount")
@Expose
private Long Last7DayAttackCount;
/**
* Get 已使用的端口规则数,单位条
* @return PortRulesUsage 已使用的端口规则数,单位条
*/
public Long getPortRulesUsage() {
return this.PortRulesUsage;
}
/**
* Set 已使用的端口规则数,单位条
* @param PortRulesUsage 已使用的端口规则数,单位条
*/
public void setPortRulesUsage(Long PortRulesUsage) {
this.PortRulesUsage = PortRulesUsage;
}
/**
* Get 已使用的域名规则数,单位条
* @return DomainRulesUsage 已使用的域名规则数,单位条
*/
public Long getDomainRulesUsage() {
return this.DomainRulesUsage;
}
/**
* Set 已使用的域名规则数,单位条
* @param DomainRulesUsage 已使用的域名规则数,单位条
*/
public void setDomainRulesUsage(Long DomainRulesUsage) {
this.DomainRulesUsage = DomainRulesUsage;
}
/**
* Get 最近7天的攻击次数,单位次
* @return Last7DayAttackCount 最近7天的攻击次数,单位次
*/
public Long getLast7DayAttackCount() {
return this.Last7DayAttackCount;
}
/**
* Set 最近7天的攻击次数,单位次
* @param Last7DayAttackCount 最近7天的攻击次数,单位次
*/
public void setLast7DayAttackCount(Long Last7DayAttackCount) {
this.Last7DayAttackCount = Last7DayAttackCount;
}
public BGPIPInstanceUsages() {
}
/**
* NOTE: Any ambiguous key set via .set("AnyKey", "value") will be a shallow copy,
* and any explicit key, i.e Foo, set via .setFoo("value") will be a deep copy.
*/
public BGPIPInstanceUsages(BGPIPInstanceUsages source) {
if (source.PortRulesUsage != null) {
this.PortRulesUsage = new Long(source.PortRulesUsage);
}
if (source.DomainRulesUsage != null) {
this.DomainRulesUsage = new Long(source.DomainRulesUsage);
}
if (source.Last7DayAttackCount != null) {
this.Last7DayAttackCount = new Long(source.Last7DayAttackCount);
}
}
/**
* Internal implementation, normal users should not use it.
*/
public void toMap(HashMap<String, String> map, String prefix) {
this.setParamSimple(map, prefix + "PortRulesUsage", this.PortRulesUsage);
this.setParamSimple(map, prefix + "DomainRulesUsage", this.DomainRulesUsage);
this.setParamSimple(map, prefix + "Last7DayAttackCount", this.Last7DayAttackCount);
}
}
| true |
0a5a0d2bb34e159e39e1511953dddc98469b86b8
|
Java
|
locisvv/ElevatorStateMachine
|
/src/svv/com/views/ElevatorView.java
|
UTF-8
| 2,269 | 3.015625 | 3 |
[] |
no_license
|
package svv.com.views;
import svv.com.controlers.Elevator;
import javax.swing.JComponent;
import java.awt.Graphics;
import java.awt.Color;
import java.util.concurrent.TimeUnit;
public class ElevatorView extends JComponent {
private int currentFloor = 0;
private int floorValue;
private int openDoorValue;
private Elevator elevator;
public ElevatorView(Elevator elevator) {
this.elevator = elevator;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
if (elevator.getStop()) {
g.setColor(Color.RED);
}
//paint elevator box
g.drawRect(180, 400 - (floorValue * 7), 36, 50);
g.drawRect(180, 400 - (floorValue * 7), 18 - openDoorValue, 50);
g.drawRect(198 + openDoorValue, 400 - (floorValue * 7), 18 - openDoorValue, 50);
//paint cable
g.setColor(Color.black);
g.drawLine(194, 400 - (floorValue * 7), 194, 100);
g.drawLine(202, 400 - (floorValue * 7), 202, 100);
}
public void oneFloorUp() {
for (int i = 0; i <= 10; i++) {
floorValue = (currentFloor * 10) + i;
animation();
if (elevator.getStop()) {
stop();
}
}
currentFloor++;
}
public void oneFloorDown() {
for (int i = 0; i <= 10; i++) {
floorValue = (currentFloor * 10) - i;
animation();
if (elevator.getStop()) {
stop();
}
}
currentFloor--;
}
private void stop() {
try {
elevator.getCountDownLatch().await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void openDoor() {
while (openDoorValue < 10) {
openDoorValue++;
animation();
}
}
public void closeDoor() {
while (openDoorValue >= 0) {
openDoorValue--;
animation();
}
}
private void animation() {
try {
repaint();
TimeUnit.MICROSECONDS.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| true |
07fbbac4391337facc339df4500cf668b1410c73
|
Java
|
fcrepo-exts/fcrepo-camel-toolbox
|
/fcrepo-fixity/src/test/java/org/fcrepo/camel/fixity/RouteTest.java
|
UTF-8
| 5,156 | 1.554688 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree.
*/
package org.fcrepo.camel.fixity;
import org.apache.camel.CamelContext;
import org.apache.camel.EndpointInject;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.AdviceWith;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.model.ModelCamelContext;
import org.apache.camel.spring.javaconfig.CamelConfiguration;
import org.apache.commons.io.IOUtils;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import static org.apache.camel.component.mock.MockEndpoint.assertIsSatisfied;
import static org.apache.camel.util.ObjectHelper.loadResourceAsStream;
import static org.fcrepo.camel.FcrepoHeaders.FCREPO_URI;
/**
* Test the route workflow.
*
* @author Aaron Coburn
* @since 2015-06-18
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {RouteTest.ContextConfig.class}, loader = AnnotationConfigContextLoader.class)
public class RouteTest {
private static final long ASSERT_PERIOD_MS = 5000;
@EndpointInject("mock:result")
protected MockEndpoint resultEndpoint;
@Produce("direct:start")
protected ProducerTemplate template;
private static final String baseURL = "http://localhost/rest";
private static final String identifier = "/file1";
@Autowired
private CamelContext camelContext;
@Autowired
private FcrepoFixityConfig config;
@BeforeClass
public static void beforeClass() {
System.setProperty("fixity.failure", "mock:failure");
System.setProperty("fixity.success", "mock:success");
System.setProperty("fixity.input.stream", "seda:foo");
System.setProperty("fixity.enabled", "true");
}
@Test
public void testBinaryFixitySuccess() throws Exception {
final var context = camelContext.adapt(ModelCamelContext.class);
AdviceWith.adviceWith(context, "FcrepoFixity", a -> {
a.replaceFromWith("direct:start");
a.mockEndpointsAndSkip("fcrepo:*");
});
final var failureEndpoint = MockEndpoint.resolve(camelContext, config.getFixityFailure());
failureEndpoint.expectedMessageCount(0);
failureEndpoint.setAssertPeriod(ASSERT_PERIOD_MS);
final var successEndpoint = MockEndpoint.resolve(camelContext, config.getFixitySuccess());
successEndpoint.expectedMessageCount(1);
final String body = IOUtils.toString(loadResourceAsStream("fixity.rdf"), "UTF-8");
template.sendBodyAndHeader(body, FCREPO_URI, baseURL + identifier);
assertIsSatisfied(failureEndpoint, successEndpoint);
}
@Test
public void testBinaryFixityFailure() throws Exception {
final var context = camelContext.adapt(ModelCamelContext.class);
AdviceWith.adviceWith(context, "FcrepoFixity", a -> {
a.replaceFromWith("direct:start");
a.mockEndpointsAndSkip("fcrepo:*");
});
final var failureEndpoint = MockEndpoint.resolve(camelContext, "mock:failure");
failureEndpoint.expectedMessageCount(1);
final var successEndpoint = MockEndpoint.resolve(camelContext, "mock:success");
successEndpoint.expectedMessageCount(0);
successEndpoint.setAssertPeriod(ASSERT_PERIOD_MS);
final String body = IOUtils.toString(loadResourceAsStream("fixityFailure.rdf"), "UTF-8");
template.sendBodyAndHeader(body, FCREPO_URI, baseURL + identifier);
assertIsSatisfied(failureEndpoint, successEndpoint);
}
@Test
public void testNonBinary() throws Exception {
final var context = camelContext.adapt(ModelCamelContext.class);
AdviceWith.adviceWith(context, "FcrepoFixity", a -> {
a.replaceFromWith("direct:start");
a.mockEndpointsAndSkip("fcrepo:*");
});
final var failureEndpoint = MockEndpoint.resolve(camelContext, "mock:failure");
failureEndpoint.expectedMessageCount(0);
failureEndpoint.setAssertPeriod(ASSERT_PERIOD_MS);
final var successEndpoint = MockEndpoint.resolve(camelContext, "mock:success");
successEndpoint.expectedMessageCount(0);
successEndpoint.setAssertPeriod(ASSERT_PERIOD_MS);
final String body = IOUtils.toString(loadResourceAsStream("container.rdf"), "UTF-8");
template.sendBodyAndHeader(body, FCREPO_URI, baseURL + identifier);
assertIsSatisfied(failureEndpoint, successEndpoint);
}
@Configuration
@ComponentScan(resourcePattern = "**/Fcrepo*.class")
static class ContextConfig extends CamelConfiguration {
}
}
| true |
79b442d24f62e7202afbfed4bf279555b61cf1fe
|
Java
|
led-os/youban
|
/app/src/main/java/cn/bjhdltcdn/p2plive/httpresponse/SchoolOrganSwitchResponse.java
|
UTF-8
| 543 | 2.171875 | 2 |
[] |
no_license
|
package cn.bjhdltcdn.p2plive.httpresponse;
/**
* Created by xiawenquan on 18/3/8.
*/
public class SchoolOrganSwitchResponse extends BaseResponse {
private int isOpen;// 系统开关(1开启,2关闭)
private int isAuth;// 是否有发布权限(1有,2没有)
public int getIsOpen() {
return isOpen;
}
public void setIsOpen(int isOpen) {
this.isOpen = isOpen;
}
public int getIsAuth() {
return isAuth;
}
public void setIsAuth(int isAuth) {
this.isAuth = isAuth;
}
}
| true |
f15843077aecd8aeb9cd4c9a1394f99ba328a9dc
|
Java
|
viniciusfernandes/algoritmos-estrutura-dados
|
/src/main/java/br/com/viniciusfernandes/algoritmos/sort/SelectionSorter.java
|
UTF-8
| 705 | 3.59375 | 4 |
[] |
no_license
|
package br.com.viniciusfernandes.algoritmos.sort;
import br.com.viniciusfernandes.algoritmos.lista.List;
public class SelectionSorter<T extends Comparable<T>> {
public void sort(List<T> list) {
T a = null;
T b = null;
T current = null;
final int length = list.size();
int currIndex = 0;
int minIndex = -1;
while (currIndex < length) {
a = list.get(currIndex);
for (int j = currIndex; j < length; j++) {
b = list.get(j);
if (a.compareTo(b) > 0) {
minIndex = j;
a = list.get(j);
}
}
if (minIndex > 0) {
current = list.get(currIndex);
list.replace(a, currIndex);
list.replace(current, minIndex);
}
minIndex = -1;
currIndex++;
}
}
}
| true |
39bcefdeeb12146f38d9a5505620b44d289dc74f
|
Java
|
cypo721/PA165-project
|
/rest/src/main/java/config/controllers/MachineController.java
|
UTF-8
| 3,261 | 2.5625 | 3 |
[] |
no_license
|
package config.controllers;
import config.ApiUris;
import dto.MachineDTO;
import facade.MachineFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.inject.Inject;
import java.util.List;
/**
* Created by pato on 16.12.2016.
*/
@RestController
@RequestMapping(ApiUris.ROOT_URI_MACHINES)
public class MachineController {
final static Logger logger = LoggerFactory.getLogger(MachineController.class);
@Inject
private MachineFacade machineFacade;
/**
* Get list of Machines curl -i -X GET
* http://localhost:8080/rest/machines
*
* @return list of MachineDTO
*/
@RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public final List<MachineDTO> getMachines() {
logger.debug("rest getMachines()");
return machineFacade.findAllMachines();
}
/**
*
* Get Machine by identifier id curl -i -X GET
* http://localhost:8080/rest/machines/1
*
* @param id identifier for a machine
* @return MachineDTO
* @throws IllegalArgumentException
*/
@RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public final MachineDTO getMachine(@PathVariable("id") long id) throws Exception {
logger.debug("rest getMachine({})", id);
MachineDTO machineDTO = machineFacade.findById(id);
if (machineDTO != null) {
return machineDTO;
} else {
throw new IllegalArgumentException();
}
}
/**
* Delete one machine by id curl -i -X DELETE
* http://localhost:8080/rest/machines/1
*
* @param id identifier for a machine
* @throws IllegalArgumentException
*/
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
public final void deleteMachine(@PathVariable("id") long id) throws Exception {
logger.debug("rest deleteMachine({})", id);
try {
machineFacade.deleteMachine(id);
} catch (Exception ex) {
throw new IllegalArgumentException();
}
}
/**
* Create a new machine by POST method
* curl -X POST -i -H "Content-Type: application/json" --data
* '{"name":"test", "dateOfBuy":"2016-12-12","machineType":"CRANE","pricePerDay":"200",
* "dateOfLastRevision":"2016-12-12"}'
* http://localhost:8080/rest/machines/create
*
* @param machine MachineDTO with required fields for creation
* @return the created machineDTO
* @throws IllegalArgumentException
*/
@RequestMapping(value = "/create", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public final MachineDTO createMachine(@RequestBody MachineDTO machine) throws Exception {
logger.debug("rest createMachine()");
try {
Long id = machineFacade.createMachine(machine);
return machineFacade.findById(id);
} catch (Exception ex) {
throw new IllegalArgumentException();
}
}
}
| true |
a4d0daf9e39d56105419cdee0731234240047fd0
|
Java
|
cristhianhg/imagelistview
|
/IMGmodels/app/src/main/java/com/example/img_models/MainActivity.java
|
UTF-8
| 1,018 | 2.203125 | 2 |
[] |
no_license
|
package com.example.img_models;
import android.os.Bundle;
import android.widget.ListView;
import androidx.appcompat.app.AppCompatActivity;
import com.example.img_models.Adapters.ProductoAdaptador;
import com.example.img_models.Models.Producto;
import com.example.img_models.helpers.QueueUtils;
public class MainActivity extends AppCompatActivity {
QueueUtils.QueueObject queue=null;
ListView productoList;
ProductoAdaptador productoAdaptador;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
queue=QueueUtils.getInstance(this.getApplicationContext());
productoList = findViewById(R.id.productoList);
productoAdaptador = new ProductoAdaptador(this, Producto.getCollection(),queue.getImageLoader());
productoList.setAdapter(productoAdaptador);
productoAdaptador = new ProductoAdaptador(this, Producto.getCollection(),queue.getImageLoader());
}
}
| true |
2f02089883bb827265f5201cc301e51ec950cb57
|
Java
|
zqsds/develop_eureka_multiple_ports
|
/src/main/java/com/example/hcy_bridge/utils/HttpRequestUtils.java
|
UTF-8
| 2,333 | 2.140625 | 2 |
[] |
no_license
|
package com.example.hcy_bridge.utils;
import com.alibaba.fastjson.JSONObject;
import org.springframework.cloud.client.ServiceInstance;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
/**
* @program xiaofeng_test
* @description:
* @author: xiaoFeng
* @create: 2020/08/06 11:01
*/
public class HttpRequestUtils {
public static final String URI_INDEX = "/hms/hcyBridge";
/**
* 获取url请求参数
*
* @param request HttpServletRequest
* @return 映射
*/
public static Map getParams(HttpServletRequest request) {
Map map = new HashMap();
Enumeration paramNames = request.getParameterNames();
while (paramNames.hasMoreElements()) {
String paramName = (String) paramNames.nextElement();
String[] paramValues = request.getParameterValues(paramName);
if (paramValues.length == 1) {
String paramValue = paramValues[0];
if (paramValue.length() != 0) {
map.put(paramName, paramValue);
}
}
}
return map;
}
/**
* 获取body参数
*
* @param jsonObject json数据
* @return 映射
*/
public static Map<String, Object> getBody(JSONObject jsonObject) {
Map<String, Object> map = new HashMap();
for (String key : jsonObject.keySet()) {
map.put(key, jsonObject.get(key));
}
return map;
}
/**
* 获取header参数
*
* @param request HttpServletRequest
* @return 映射
*/
public static Map<String, String> getHeader(HttpServletRequest request) {
Map<String, String> map = new HashMap();
Enumeration<String> e = request.getHeaderNames();
while (e.hasMoreElements()) {
String headerName = e.nextElement();
map.put(headerName, request.getHeader(headerName));
}
return map;
}
public static String getUrl(HttpServletRequest request, ServiceInstance serviceInstance) {
String requestPort = request.getParameter("requestPort");
String requestURI = request.getRequestURI();
String url = requestURI.substring(URI_INDEX.length());
String urlParam = request.getQueryString();
return serviceInstance.getScheme()
+ "://"
+ serviceInstance.getHost()
+ ":"
+ requestPort
+ url
+ "?"
+ urlParam;
}
}
| true |
9579c882c65a2ef426283f1b7a823390117de9fd
|
Java
|
AndroidKiran/EmployeeManagement
|
/src/com/pojo/masters/TourPurposeActionPojo.java
|
UTF-8
| 933 | 2.265625 | 2 |
[] |
no_license
|
package com.pojo.masters;
import java.io.Serializable;
public class TourPurposeActionPojo implements Serializable{
private static final long serialVersionUID = 1L;
private String tourPurposeName;
private Integer tourPurposeId;
/**
* @return the tourPurposeName
*/
public String getTourPurposeName() {
return tourPurposeName;
}
/**
* @param tourPurposeName the tourPurposeName to set
*/
public void setTourPurposeName(String tourPurposeName) {
this.tourPurposeName = tourPurposeName;
}
/**
* @return the tourPurposeId
*/
public Integer getTourPurposeId() {
return tourPurposeId;
}
/**
* @param tourPurposeId the tourPurposeId to set
*/
public void setTourPurposeId(Integer tourPurposeId) {
this.tourPurposeId = tourPurposeId;
}
/**
* @return the serialversionuid
*/
public static long getSerialversionuid() {
return serialVersionUID;
}
}
| true |
26d953a60a9e9e459979e46596d4c250b3f2a8c8
|
Java
|
JellyB/code_back
|
/ztk_code/ztk-knowledge-parent/knowledge-web-server/src/main/java/com/huatu/ztk/knowledge/daoPandora/provider/KnowledgeProvider.java
|
UTF-8
| 2,649 | 2.328125 | 2 |
[] |
no_license
|
package com.huatu.ztk.knowledge.daoPandora.provider;
import lombok.extern.slf4j.Slf4j;
/**
* Created by lijun on 2018/8/22
*/
@Slf4j
public class KnowledgeProvider {
/**
* 获取某个科目下的一级知识点信息
*/
public String getFirstLevelBySubjectId(int subjectId) {
StringBuilder sql = new StringBuilder(256);
sql.append(" SELECT ");
sql.append(" knowledge.id,knowledge.`name`,knowledge.parent_id AS 'parentId',")
.append("knowledge.`level`,knowledge.is_leaf AS 'isLeaf',")
.append("knowledge.`status`,knowledge.`biz_status` AS 'bizStatus'");
sql.append(" FROM ");
sql.append(" knowledge LEFT JOIN knowledge_subject ON knowledge.id = knowledge_subject.knowledge_id AND knowledge_subject.`status` = 1 ");
sql.append(" WHERE ");
sql.append(" knowledge_subject.subject_id = ").append(subjectId)
.append(" AND knowledge.`level` = 1 ")
.append(" ORDER BY knowledge.sort_num,knowledge.id");
log.info("getFirstLevelBySubjectId sql = {}", sql.toString());
return sql.toString();
}
/**
* 查询一个知识点详情 - 附带试题数量
*/
public String getKnowledgeInfoById(int knowledgeId) {
StringBuilder sql = new StringBuilder(256);
sql.append(" SELECT ");
sql.append(" knowledge.id,knowledge.`name`,knowledge.parent_id AS `parentId`,")
.append("knowledge.`level`,knowledge.is_leaf AS `isLeaf`,")
.append("knowledge.`status`,knowledge.`biz_status` AS `bizStatus`,")
.append("COUNT(1) AS 'questionNum'");
sql.append(" FROM ");
sql.append(" knowledge LEFT JOIN base_question_knowledge bqk ON knowledge.id = bqk.knowledge_id AND bqk.`status` = 1");
sql.append(" WHERE ");
sql.append(" knowledge.id = ").append(knowledgeId);
log.info("getKnowledgeInfoById sql = {}", sql.toString());
return sql.toString();
}
/**
* 查询某个科目的用户知识点ID
*/
public String getKnowledgeBySubjectId(String knowledgeIds, int subjectId) {
StringBuffer sql = new StringBuffer();
sql.append(" SELECT k.id FROM knowledge k LEFT JOIN knowledge_subject ks on k.id=ks.knowledge_id");
sql.append(" and k.`status`=1 and ks.status=1");
sql.append(" WHERE ks.subject_id=");
sql.append(subjectId);
sql.append(" and ks.knowledge_id in( ");
sql.append(knowledgeIds);
sql.append(")");
log.info("结果是:{}", sql.toString());
return sql.toString();
}
}
| true |
57dc53c73bc148771ee1999ae513decd23fdbe49
|
Java
|
balortmor/ED_CocheMoto
|
/src/es/studium/CocheMoto/Moto.java
|
UTF-8
| 514 | 2.53125 | 3 |
[] |
no_license
|
package es.studium.CocheMoto;
public class Moto extends Vehiculo {
private String cilindrada;
public Moto() {
this.setMatricula("");
this.setNumeroRuedas(4);
this.cilindrada = "";
}
public Moto(String matricula, int numeroRuedas, String cilindrada) {
this.setMatricula(matricula);
this.setNumeroRuedas(numeroRuedas);
this.cilindrada = cilindrada;
}
public String getCilindrada() {
return cilindrada;
}
public void setCilindrada(String cilindrada) {
this.cilindrada = cilindrada;
}
}
| true |
26c09e960b2e57a32929c6ef3afff69b62b77bdf
|
Java
|
Hyungrok-Kim/Back-end
|
/testAJAXProject/src/com/kh/ajax/controller/TestServlet8.java
|
UTF-8
| 2,157 | 2.28125 | 2 |
[] |
no_license
|
package com.kh.ajax.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.kh.ajax.model.vo.Product;
/**
* Servlet implementation class TestServlet8
*/
@WebServlet("/test8.do")
public class TestServlet8 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public TestServlet8() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=UTF-8");
List<Product> list = new ArrayList<>();
// 상품 10개
list.add(new Product(1, "왕눈이깜찍이", "국내산", "음료"));
list.add(new Product(2, "밭두렁", "국내산", "과자류"));
list.add(new Product(3, "신호등", "국내산", "사탕"));
list.add(new Product(4, "차카니", "인도네시아", "과자류"));
list.add(new Product(5, "짝꿍", "국내산", "캔디류"));
list.add(new Product(6, "아폴로", "중국산" ,"과자류"));
list.add(new Product(7, "꾀돌이", "국내산" , "과자류"));
list.add(new Product(8, "쫀득이", "말레이시아", "과자류"));
list.add(new Product(9, "맥주사탕", "중국산" ,"캔디류"));
list.add(new Product(10, "라면땅", "인도네시아", "과자류"));
new Gson().toJson(list, response.getWriter());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
| true |
8e967f5775f01860799cf37f3ba77aff01ef2e03
|
Java
|
epam-debrecen-rft-2015/atsy
|
/web/src/main/java/com/epam/rft/atsy/web/controllers/DeleteApplicationsController.java
|
UTF-8
| 953 | 2.078125 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.epam.rft.atsy.web.controllers;
import com.epam.rft.atsy.service.CandidateService;
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;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
@Controller
@RequestMapping(value = "/secure/deleteApplications")
public class DeleteApplicationsController {
private static final String VIEW_NAME = "candidates";
@Resource
private CandidateService candidateService;
@RequestMapping(method = RequestMethod.GET)
public ModelAndView deleteApplications(@RequestParam Long candidateId) {
candidateService.deletePositionsByCandidate(candidateService.getCandidate(candidateId));
ModelAndView modelAndView = new ModelAndView(VIEW_NAME);
return modelAndView;
}
}
| true |
0f5042969691fb2eb359cbe7bf154010d9e64b7f
|
Java
|
Olosinsk-commits/Java
|
/Capitalizer.java
|
UTF-8
| 2,189 | 4.53125 | 5 |
[] |
no_license
|
/*
Write a static method that accepts a String object as an argument
and capitalizes the first character of each sentence in the string.
In addition it removes all extra white spaces between words.
For instance, if the string argument
is “hello. my name is Joe. what is your name?” the method should
manipulate the string so it contains “Hello. My name is Joe. What is your name?”
Assume that period, question mark, and exclamation mark are the only signals of the sentence ending.
Suggestion: convert the String into a StringBuilder object to make string modification easier.
Test the new method in main().
Requirement: Make sure to pass through the string only once. Do not use nested loops
*/
package capitalizer;
import java.io.IOException;
/**
*
* @author olga.osinskaya
*/
public class Capitalizer {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
String str = "hello. my name is Joe! what is your name?";
//String str = "";
String newstr = StrCap(str);
System.out.println(newstr);
}
/**
* The StrCap method accepts a String object as an argument and capitalizes
* the first character of each sentence in the string.
* @param str
* @return new upgraded String
*/
public static String StrCap(String str) {
boolean capitalize = true;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (Character.isWhitespace(c) && i > 0 && Character.isWhitespace(str.charAt(i - 1))) {
continue;
}
if (c == '.' || c == '?' || c == '!') {
capitalize = true;
} else if (c != ' ' && capitalize) {
//Capitalize the first letter of each sentence
c = Character.toUpperCase(c);
capitalize = false;
}
//Appends the argument to this string builder
sb.append(c);
}
//return the formatted string as a string
return sb.toString();
}
}
| true |
1e8ec548abfddab4a2aadd2a60b636ae7601dfa5
|
Java
|
pwodarczyk/registeredreviews
|
/src/main/java/com/registeredreviews/model/Promotion.java
|
UTF-8
| 1,413 | 2.015625 | 2 |
[] |
no_license
|
package com.registeredreviews.model;
import java.util.Date;
public class Promotion {
private Long id;
private Date startDate;
private Date endDate;
private String description;
private String name;
private String discountAmount;
private String type;
private String code;
private String businessId;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDiscountAmount() {
return discountAmount;
}
public void setDiscountAmount(String discountAmount) {
this.discountAmount = discountAmount;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getBusinessId() {
return businessId;
}
public void setBusinessId(String businessId) {
this.businessId = businessId;
}
}
| true |
fbedb2e5458d351ecc9ae8adf51d88c07b5b99bf
|
Java
|
dxCarl/LeetCode
|
/src/main/java/com/xiao/deng/leetcode/profit/Solution.java
|
UTF-8
| 1,504 | 3.984375 | 4 |
[
"Apache-2.0"
] |
permissive
|
package com.xiao.deng.leetcode.profit;
/**
* 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
* 如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。
* 注意你不能在买入股票前卖出股票。
* <p>
* 输入: [7,1,5,3,6,4]
* 输出: 5
* 解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
* 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
* <p>
* <p>
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class Solution {
public int maxProfit(int[] prices) {
int len = prices.length;
if (len == 0) {
return 0;
}
int min = prices[0];
int profit = 0;
for (int i = 0; i < len; i++) {
int cur = prices[i];
if (cur < min) {
min = cur;
}
int curPro = cur - min;
profit = profit > curPro ? profit : curPro;
}
return profit;
}
public static void main(String[] args) {
int[] prices = new int[]{7, 1, 5, 3, 6, 4};
int ans = new Solution().maxProfit(prices);
System.out.println(ans);
}
}
| true |
8bca63372b2048e1f8ed59ddd6a0a6fc34b4dd96
|
Java
|
zhongxingyu/Seer
|
/Diff-Raw-Data/28/28_baa32ace1ccaf3da721ea5b77aaa46229f2f37eb/ExpressionSanitizerTest/28_baa32ace1ccaf3da721ea5b77aaa46229f2f37eb_ExpressionSanitizerTest_t.java
|
UTF-8
| 3,877 | 2.03125 | 2 |
[] |
no_license
|
// Copyright (C) 2006 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.caja.plugin;
import com.google.caja.lexer.FilePosition;
import com.google.caja.parser.AncestorChain;
import com.google.caja.parser.ParseTreeNode;
import com.google.caja.parser.quasiliteral.Rewriter;
import com.google.caja.parser.quasiliteral.Rule;
import com.google.caja.parser.quasiliteral.Scope;
import com.google.caja.parser.quasiliteral.RuleDescription;
import com.google.caja.parser.js.Block;
import com.google.caja.parser.js.Identifier;
import com.google.caja.reporting.MessageQueue;
import com.google.caja.reporting.MessageLevel;
import com.google.caja.reporting.TestBuildInfo;
import com.google.caja.util.CajaTestCase;
/**
* @author [email protected] (Mike Samuel)
*/
public class ExpressionSanitizerTest extends CajaTestCase {
@Override
protected void setUp() throws Exception {
super.setUp();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
public final void testBasicRewriting() throws Exception {
assertSanitize(
" 'use strict';"
+ "'use cajita';"
+ "g[i];",
" var g = ___.readImport(IMPORTS___, 'g');"
+ "var i = ___.readImport(IMPORTS___, 'i');"
+ "___.readPub(g, i);");
}
public final void testNoSpuriousRewriteErrorFound() throws Exception {
newPassThruSanitizer().sanitize(
ac(new Identifier(FilePosition.UNKNOWN, "x")));
assertFalse(mq.hasMessageAtLevel(MessageLevel.FATAL_ERROR));
}
public final void testRewriteErrorIsDetected() throws Exception {
newPassThruSanitizer().sanitize(
ac(new Identifier(FilePosition.UNKNOWN, "x__")));
assertTrue(mq.hasMessageAtLevel(MessageLevel.FATAL_ERROR));
}
public final void testNonAsciiIsDetected() throws Exception {
newPassThruSanitizer().sanitize(
ac(new Identifier(FilePosition.UNKNOWN, "\u00e6")));
assertTrue(mq.hasMessageAtLevel(MessageLevel.FATAL_ERROR));
}
private ExpressionSanitizerCaja newPassThruSanitizer() throws Exception {
return new ExpressionSanitizerCaja(new TestBuildInfo(), mq) {
@Override
protected Rewriter newCajitaRewriter(MessageQueue mq) {
return new Rewriter(mq, true, true) {{
addRule(new Rule() {
@Override
@RuleDescription(
name="passthru",
synopsis="Pass through input vacuously 'expanded'",
reason="Dummy rule for testing")
public ParseTreeNode fire(ParseTreeNode node, Scope scope) {
return expandAll(node.clone(), scope);
}
});
}};
}
};
}
private void assertSanitize(String input, String golden)
throws Exception {
Block inputNode = js(fromString(input));
ParseTreeNode sanitized =
new ExpressionSanitizerCaja(new TestBuildInfo(), mq)
.sanitize(ac(inputNode));
String inputCmp = render(sanitized);
String goldenCmp = render(js(fromString(golden)));
assertEquals(goldenCmp, inputCmp);
assertFalse(mq.hasMessageAtLevel(MessageLevel.WARNING));
}
private static <T extends ParseTreeNode> AncestorChain<T> ac(T node) {
return AncestorChain.instance(node);
}
}
| true |
f7ebf1def077307decf37796728c8d31ae90cdd2
|
Java
|
Wilczek01/alwin-projects
|
/alwin-middleware-grapescode/alwin-test-data/src/test/java/com/codersteam/alwin/testdata/BalanceStartAndAdditionalTestData.java
|
UTF-8
| 1,234 | 2.328125 | 2 |
[] |
no_license
|
package com.codersteam.alwin.testdata;
import com.codersteam.alwin.core.api.model.balance.BalanceStartAndAdditionalDto;
import java.math.BigDecimal;
/**
* @author Tomasz Sliwinski
*/
public final class BalanceStartAndAdditionalTestData {
private static final BigDecimal BALANCE_START_PLN_1 = new BigDecimal("-496.48");
private static final BigDecimal BALANCE_ADDITIONAL_PLN_1 = new BigDecimal("0.00");
private static final BigDecimal BALANCE_START_EUR_1 = new BigDecimal("-90.23");
private static final BigDecimal BALANCE_ADDITIONAL_EUR_1 = new BigDecimal("-124.12");
private BalanceStartAndAdditionalTestData() {
}
public static BalanceStartAndAdditionalDto balanceStartAndAdditionalPLN1() {
return balanceStartAndAdditionalDto(BALANCE_START_PLN_1, BALANCE_ADDITIONAL_PLN_1);
}
public static BalanceStartAndAdditionalDto balanceStartAndAdditionalEUR1() {
return balanceStartAndAdditionalDto(BALANCE_START_EUR_1, BALANCE_ADDITIONAL_EUR_1);
}
private static BalanceStartAndAdditionalDto balanceStartAndAdditionalDto(final BigDecimal balanceStart, final BigDecimal balanceAdditional) {
return new BalanceStartAndAdditionalDto(balanceStart, balanceAdditional);
}
}
| true |
df3b8e51caf14d4a478013bafaa0577eb26b861c
|
Java
|
ElliotChen/LittleTrick
|
/trick02/src/main/java/tw/elliot/trick02/conf/BaseConfig.java
|
UTF-8
| 417 | 2.03125 | 2 |
[
"MIT"
] |
permissive
|
package tw.elliot.trick02.conf;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.support.RetryTemplate;
@Configuration
public class BaseConfig {
@Bean
public RetryTemplate buildRetryTemplate() {
RetryTemplate retryTemplate = RetryTemplate.builder()
.maxAttempts(2)
.build();
return retryTemplate;
}
}
| true |
2ceeebc0de8d96731f308b17707600f32b90bb0e
|
Java
|
zhshuai1/pangu
|
/src/main/java/com/sepism/pangu/tool/AddressInitializer.java
|
UTF-8
| 5,740 | 2.53125 | 3 |
[] |
no_license
|
package com.sepism.pangu.tool;
import com.google.gson.Gson;
import com.sepism.pangu.model.questionnaire.Choice;
import com.sepism.pangu.model.repository.ChoiceRepository;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
// Put this class instead of in a new package is because the models such as Choice are shared.
// TODO: Should also abstract the model together with the tools to a separate package.
@Log4j2
public class AddressInitializer {
public static final Gson GSON = new Gson();
private static long country;
private static final Map<String, Long> provinceMap = new HashMap<>();
private static final Map<String, Long> cityMap = new HashMap<>();
private static final long creator = 1;
private static final long root = 6;
private static final long questionId = 10;
public static void main(String[] args) throws Exception {
ApplicationContext context = new FileSystemXmlApplicationContext
("./src/main/webapp/WEB-INF/persistence-context.xml");
ChoiceRepository choiceRepository = context.getBean("choiceRepository", ChoiceRepository.class);
System.out.println("This process is not idempotent. Waiting 5 seconds for you to confirm......");
Thread.sleep(5000);
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
setupCountry(documentBuilder, choiceRepository);
setupProvinces(documentBuilder, choiceRepository);
setupCities(documentBuilder, choiceRepository);
setupDistricts(documentBuilder, choiceRepository);
}
private static void setupCountry(DocumentBuilder documentBuilder, ChoiceRepository choiceRepository)
throws Exception {
Choice choice1 = Choice.builder().creationDate(new Date()).creator(creator).root(root).parent(root)
.descriptionCn("全球").questionId(questionId).build();
choiceRepository.save(choice1);
Choice choice2 = Choice.builder().creationDate(new Date()).creator(creator).root(root).parent(choice1.getId())
.descriptionCn("中国").questionId(questionId).build();
choiceRepository.save(choice2);
country = choice2.getId();
}
private static void setupProvinces(DocumentBuilder documentBuilder, ChoiceRepository choiceRepository) throws Exception {
Document provincesDocument = documentBuilder.parse("src/main/ToolsResources/provinces.xml");
NodeList provinces = provincesDocument.getElementsByTagName("Province");
for (int i = 0; i < provinces.getLength(); ++i) {
NamedNodeMap attributes = provinces.item(i).getAttributes();
String id = attributes.getNamedItem("ID").getNodeValue();
String name = attributes.getNamedItem("ProvinceName").getNodeValue();
Choice choice = Choice.builder().creationDate(new Date()).creator(creator).root(root).parent(country)
.descriptionCn(name).questionId(questionId).build();
choiceRepository.save(choice);
provinceMap.put(id, choice.getId());
log.info("Province Id is: {}, name is {}, db id is {}", id, name, choice.getId());
}
}
private static void setupCities(DocumentBuilder documentBuilder, ChoiceRepository choiceRepository) throws Exception {
Document citiesDocument = documentBuilder.parse("src/main/ToolsResources/cities.xml");
NodeList cities = citiesDocument.getElementsByTagName("City");
for (int i = 0; i < cities.getLength(); ++i) {
NamedNodeMap attributes = cities.item(i).getAttributes();
String id = attributes.getNamedItem("ID").getNodeValue();
String name = attributes.getNamedItem("CityName").getNodeValue();
String pid = attributes.getNamedItem("PID").getNodeValue();
Choice choice = Choice.builder().creationDate(new Date()).creator(creator).root(root).parent(provinceMap.get
(pid)).descriptionCn(name).questionId(questionId).build();
choiceRepository.save(choice);
cityMap.put(id, choice.getId());
log.info("Province Id is: {}, name is {}, db id is {} and pid is {}", id, name, choice.getId(), pid);
}
}
private static void setupDistricts(DocumentBuilder documentBuilder, ChoiceRepository choiceRepository) throws Exception {
Document districtsDocument = documentBuilder.parse("src/main/ToolsResources/districts.xml");
NodeList districts = districtsDocument.getElementsByTagName("District");
for (int i = 0; i < districts.getLength(); ++i) {
NamedNodeMap attributes = districts.item(i).getAttributes();
String id = attributes.getNamedItem("ID").getNodeValue();
String name = attributes.getNamedItem("DistrictName").getNodeValue();
String pid = attributes.getNamedItem("CID").getNodeValue();
Choice choice = Choice.builder().creationDate(new Date()).creator(creator).root(root).parent(cityMap.get
(pid)).descriptionCn(name).questionId(questionId).build();
choiceRepository.save(choice);
log.info("Province Id is: {}, name is {}, db id is {} and pid is {}", id, name, choice.getId(), pid);
}
}
}
| true |
b3c2edc26a0e0a07c8b6ce1c6cac27128c414bdc
|
Java
|
adrianx30/Comunicaciones
|
/Comunicacion_Socket/src/comunicacion_socket/Cliente.java
|
UTF-8
| 1,343 | 2.734375 | 3 |
[] |
no_license
|
/*
* 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 comunicacion_socket;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.PrintStream;
import java.net.Socket;
/**
*
* @author adrian.jimenez
*/
public class Cliente {
Socket cliente;
int puerto;
String ip;
PrintStream salida;
BufferedReader entrada,teclado;
DataOutputStream salida2;
ObjectInputStream dIn;
public Cliente(int a,String ipp){
puerto=a;
ip=ipp;
}
public String[] Iniciar() {
String[] b3=new String[7];
try {
cliente = new Socket(ip,puerto);
salida2=new DataOutputStream(cliente.getOutputStream());
salida2.writeUTF("Peticion");
dIn=new ObjectInputStream(cliente.getInputStream());
b3=(String[])dIn.readObject();
entrada.close();
cliente.close();
salida.close();
} catch (Exception e) {
}
;
return b3;
}
}
| true |
d7dffa198fd1b1336536e1248fc35a757b6a0113
|
Java
|
dupreemovil/DupreeBolivia--master
|
/app/src/main/java/com/dupreeincabolnuevo/dupree/mh_fragments_menu/Reporte_SegPetQueRec_Fragment.java
|
UTF-8
| 5,767 | 2.078125 | 2 |
[] |
no_license
|
package com.dupreeincabolnuevo.dupree.mh_fragments_menu;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.CardView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.dupreeincabolnuevo.dupree.R;
import com.dupreeincabolnuevo.dupree.mh_http.Http;
import com.dupreeincabolnuevo.dupree.mh_required_api.RequiredIdenty;
import com.dupreeincabolnuevo.dupree.mh_response_api.PQR;
import com.dupreeincabolnuevo.dupree.mh_response_api.Perfil;
import com.dupreeincabolnuevo.dupree.mh_response_api.ResponsePQR;
import com.dupreeincabolnuevo.dupree.mh_adapters.MH_Adapter_SeguimientoPQR;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
*/
public class Reporte_SegPetQueRec_Fragment extends Fragment {
private final String TAG = "Reporte_PQR_Frag";
private final String BROACAST_PQR_ASESORA = "broadcast_pqr_asesora";
//ResponseFaltantes faltantesHttp;
private MH_Adapter_SeguimientoPQR adapterPQR;
private List<PQR> listPQR, listFilter;
public Reporte_SegPetQueRec_Fragment() {
// Required empty public constructor
}
CardView cardViewBackGround;
TextView tvNombreAsesora;
private Perfil perfil;
public void loadData(Perfil perfil){
this.perfil=perfil;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_reporte_seg_pet_que_rec, container, false);
cardViewBackGround = v.findViewById(R.id.cardViewBackGround);
cardViewBackGround.setVisibility(View.INVISIBLE);
tvNombreAsesora = v.findViewById(R.id.tvNombreAsesora);
tvNombreAsesora.setText("");
RecyclerView rcvSeguimientoPQR = v.findViewById(R.id.rcvSeguimientoPQR);
rcvSeguimientoPQR.setLayoutManager(new GridLayoutManager(getActivity(),1));
rcvSeguimientoPQR.setHasFixedSize(true);
//faltantesHttp = getFaltantes();
listPQR = new ArrayList<>();
listFilter = new ArrayList<>();
//listPQR = getResult();
listFilter.addAll(listPQR);
adapterPQR = new MH_Adapter_SeguimientoPQR(listPQR, listFilter, getActivity());
rcvSeguimientoPQR.setAdapter(adapterPQR);
localBroadcastReceiver = new LocalBroadcastReceiver();
checkPQR();
return v;
}
private void checkPQR(){
if(perfil != null){
if(perfil.getPerfil().equals(Perfil.ADESORA)){
searchIdenty("");
}
}
}
private void updateView(){
listPQR.clear();
listFilter.clear();
listPQR.addAll(listaPQR.getResult());
listFilter.addAll(listaPQR.getResult());
cardViewBackGround.setVisibility(View.VISIBLE);
tvNombreAsesora.setText(listaPQR.getAsesora());
adapterPQR.notifyDataSetChanged();
}
/*
public List<PQR> getResult(){
List<PQR> listPQR = new ArrayList<>();
listPQR.add(new PQR("1621732","2017-08-01 12:21:53","jacqueline_dominguez","GESTION ADICIONAL","GESTION ADICIONAL","Asesora indica que llevo unos productos a la reunión de canjes y pero aún no se ha visto reflejado el descuento se aclara la fecha y los días para que ingrese el descuento ya que la reunión fue el día 26/07/2017"));
return listPQR;
}
*/
@Override
public void onResume() {
super.onResume();
registerBroadcat();
Log.i(TAG,"onResume()");
//setSelectedItem(oldItem);
}
@Override
public void onPause() {
super.onPause();
unregisterBroadcat();
Log.i(TAG,"onPause()");
}
public void registerBroadcat(){
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(
localBroadcastReceiver,
new IntentFilter(TAG));
}
public void unregisterBroadcat(){
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(
localBroadcastReceiver);
}
ResponsePQR listaPQR;
private BroadcastReceiver localBroadcastReceiver;
private class LocalBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// safety check
Log.i(TAG, "BroadcastReceiver");
if (intent == null || intent.getAction() == null) {
return;
}
if (intent.getAction().equals(TAG)) {
switch (intent.getStringExtra(TAG)) {//pregunta cual elemento envio este broadcast
//Datos personales
case BROACAST_PQR_ASESORA:
String jsonPQR = intent.getStringExtra(Http.BROACAST_DATA);
if(jsonPQR!=null){
listaPQR = new Gson().fromJson(jsonPQR, ResponsePQR.class);
updateView();
}
break;
}
}
}
}
public void searchIdenty(String cedula){
new Http(getActivity()).getPQR(new RequiredIdenty(cedula), TAG, BROACAST_PQR_ASESORA);
}
}
| true |
701ce32fbc55837d111accccbda5c121c3ece604
|
Java
|
mngarriga/Bikestore
|
/BikeStore/src/test/java/bikestore/db/UserTest.java
|
UTF-8
| 8,602 | 2.375 | 2 |
[] |
no_license
|
package bikestore.db;
import java.security.*;
import javax.persistence.*;
import org.junit.*;
import static org.junit.Assert.*;
import java.util.*;
import java.util.logging.*;
public class UserTest {
private EntityManager em;
private User user1,user2,user3,user4,user5,user6,user7,user8,user9,user10;
@Before
public void beforeTest() {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("bikestorePU");
em = emf.createEntityManager();
emptyTable();
defineAllUsers();
}
private void emptyTable() {
String sql = "TRUNCATE TABLE users";
Query q = em.createNativeQuery(sql);
EntityTransaction et = em.getTransaction();
et.begin();
q.executeUpdate();
et.commit();
}
private void defineAllUsers() {
user1 = new User("fjmv28"
, "subeguara2009"
, "Francisco Javier Martin Villuendas"
, "[email protected]"
, "Avenida de Madrid 174"
, "Zaragoza"
, "España"
, 50017);
user2 = new User("Javier"
, "zzzzzzzz"
, "Francisco Javier Martin Villuendas 2"
, "[email protected]"
, "Avenida de Madrid 174"
, "Zaragoza"
, "España"
, 50017);
user3 = new User("login3"
, "passwd3"
, "Nombre 3"
, "[email protected]"
, "Direccion 3"
, "Ciudad 3"
, "Pais 3"
, 50003);
user4 = new User("login4"
, "passwd4"
, "Nombre 4"
, "[email protected]"
, "Direccion 4"
, "Ciudad 4"
, "Pais 4"
, 50004);
user5 = new User("login5"
, "passwd5"
, "Nombre 5"
, "[email protected]"
, "Direccion 5"
, "Ciudad 5"
, "Pais 5"
, 50005);
user6 = new User("login6"
, "passwd6"
, "Nombre 6"
, "[email protected]"
, "Direccion 6"
, "Ciudad 6"
, "Pais 6"
, 50003);
user7 = new User("login7"
, "passwd7"
, "Nombre 7"
, "[email protected]"
, "Direccion 7"
, "Ciudad 7"
, "Pais 7"
, 50003);
user8 = new User("login8"
, "passwd8"
, "Nombre 8"
, "[email protected]"
, "Direccion 8"
, "Ciudad 8"
, "Pais 8"
, 50008);
user9 = new User("login9"
, "passwd9"
, "Nombre 9"
, "[email protected]"
, "Direccion 9"
, "Ciudad 9"
, "Pais 9"
, 50009);
user10 = new User("login10"
, "passwd10"
, "Nombre 10"
, "[email protected]"
, "Direccion 10"
, "Ciudad 10"
, "Pais 10"
, 50010);
}
private void createAllUsers() {
user1.create(em);
user2.create(em);
user3.create(em);
user4.create(em);
user5.create(em);
user6.create(em);
user7.create(em);
user8.create(em);
user9.create(em);
user10.create(em);
}
private static String getSha(String s) {
try {
MessageDigest sha = MessageDigest.getInstance("SHA-1");
return new String(sha.digest(s.getBytes()));
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
return null;
} finally {
}
}
@Test
public void createUser_test() {
boolean result = user1.create(em);
result = result && user2.create(em);
assertTrue(result);
assertEquals(user1,User.findById(em, user1.getId()));
assertEquals(user2,User.findById(em, user2.getId()));
assertEquals(User.count(em),2l);
}
@Test
public void countUsers_test() {
assertTrue(User.count(em) == 0l);
createAllUsers();
assertTrue(User.count(em) == 10l);
}
@Test
public void findById_test() {
createAllUsers();
assertEquals(user1,user1.findById(em, user1.getId()));
assertEquals(user2,user2.findById(em, user2.getId()));
assertEquals(user3,user3.findById(em, user3.getId()));
assertEquals(user4,user4.findById(em, user4.getId()));
assertEquals(user5,user5.findById(em, user5.getId()));
assertEquals(user6,user6.findById(em, user6.getId()));
assertEquals(user7,user7.findById(em, user7.getId()));
assertEquals(user8,user8.findById(em, user8.getId()));
assertEquals(user9,user9.findById(em, user9.getId()));
assertEquals(user10,user10.findById(em, user10.getId()));
}
@Test
public void findAll_test() {
createAllUsers();
List<User> expected = new ArrayList<User>();
expected.add(user1);
expected.add(user2);
expected.add(user3);
expected.add(user4);
expected.add(user5);
expected.add(user6);
expected.add(user7);
expected.add(user8);
expected.add(user9);
expected.add(user10);
assertEquals(expected,User.findAll(em));
}
@Test
public void findByPage_test() {
createAllUsers();
List<User> expected = new ArrayList<User>();
expected.add(user1);
expected.add(user2);
expected.add(user3);
expected.add(user4);
expected.add(user5);
assertEquals(expected,User.findByPage(em, 1, 5));
expected.clear();
expected.add(user6);
expected.add(user7);
expected.add(user8);
expected.add(user9);
expected.add(user10);
assertEquals(expected,User.findByPage(em, 2, 5));
}
@Test
public void exists_test() {
createAllUsers();
assertTrue(User.exists(em, "fjmv28"));
assertTrue(User.exists(em, "Javier"));
assertTrue(User.exists(em, "login3"));
assertTrue(User.exists(em, "login4"));
assertTrue(User.exists(em, "login5"));
assertTrue(User.exists(em, "login6"));
assertTrue(User.exists(em, "login7"));
assertTrue(User.exists(em, "login8"));
assertTrue(User.exists(em, "login9"));
assertTrue(User.exists(em, "login10"));
assertFalse(User.exists(em, "foo"));
assertFalse(User.exists(em, "bar"));
}
@Test
public void login_test() {
createAllUsers();
assertEquals(user1,User.loginUser(em, "fjmv28", "subeguara2009"));
assertEquals(null,User.loginUser(em, "login2", "zzzzzzzz"));
assertEquals(user2,User.loginUser(em, "Javier", "zzzzzzzz"));
assertEquals(null,User.loginUser(em, "login10", "passwdNo"));
}
@Test
public void update_test() {
createAllUsers();
User userPrevio = User.findById(em, user1.getId());
userPrevio.setLogin("login1");
userPrevio.setPasswd("passwd1");
userPrevio.setFullName("Nombre 1");
userPrevio.setAddress("Direccion 1");
userPrevio.setCity("Ciudad 1");
userPrevio.setCountry("Pais 1");
userPrevio.setEmail("[email protected]");
userPrevio.setZipcode(50001);
userPrevio.update(em);
User userActual = User.findById(em, userPrevio.getId());
assertEquals("login1",userActual.getLogin());
assertEquals(getSha("passwd1"),userActual.getPasswd());
assertEquals("Nombre 1",userActual.getFullName());
assertEquals("Direccion 1",userActual.getAddress());
assertEquals("Ciudad 1",userActual.getCity());
assertEquals("Pais 1",userActual.getCountry());
assertEquals("[email protected]",userActual.getEmail());
assertEquals(50001,userActual.getZipcode());
}
@Test
public void delete_test() {
createAllUsers();
assertEquals(user5,User.findById(em, user5.getId()));
user5.remove(em);
assertEquals(null,User.findById(em, user5.getId()));
}
}
| true |
d0fd8b9bb766b8731a627b39a32320d37c5c0e38
|
Java
|
irfanazam1/quranpearls
|
/app/src/main/java/com/pureapps/quranpearls/DataContext.java
|
UTF-8
| 5,730 | 2.390625 | 2 |
[] |
no_license
|
package com.pureapps.quranpearls;
import android.content.Context;
import com.pureapps.model.Aya;
import com.pureapps.model.Quran;
import com.pureapps.model.Sura;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class DataContext {
private static volatile DataContext _instance;
private DataContext(){}
private Context context;
private Map<String, Integer> resources = new HashMap<>();
private Map<String, Quran> quranCache = new HashMap<>();
public static DataContext getInstance(Context context){
if(_instance == null){
_instance = new DataContext();
_instance.initContent();
_instance.context = context;
}
return _instance;
}
private void initContent(){
resources.put("English", R.raw.english);
resources.put("Urdu", R.raw.urdu);
resources.put("Arabic", R.raw.arabic);
}
public static Quran loadQuran(InputStream inputStream) throws Exception {
ObjectInputStream objectInputStream = null;
try {
objectInputStream = new ObjectInputStream(inputStream);
Quran quran = (Quran) objectInputStream.readObject();
return quran;
}
finally {
if(objectInputStream != null){
try{
objectInputStream.close();
}
catch(Exception e){}
}
}
}
public List<Map<String, Map<String, String>>> findMatchingSuraWithAya(String query, String language){
List<Map<String, Map<String, String>>> result = new LinkedList<>();
try {
Quran englishQuran = null;
Quran arabicQuran = null;
if(quranCache.containsKey("English")){
englishQuran = quranCache.get("English");
}
else{
englishQuran = loadQuran(context.getResources().openRawResource(resources.get("English")));
quranCache.put("English", englishQuran);
}
if(quranCache.containsKey("Arabic")){
arabicQuran = quranCache.get("Arabic");
}
else{
arabicQuran = loadQuran(context.getResources().openRawResource(resources.get("Arabic")));
quranCache.put("Arabic", arabicQuran);
}
if (englishQuran != null && englishQuran.getSura() != null) {
Map<String, Map<String, String>> englishQuranMap = queryQuran(englishQuran, query);
Map<String, Map<String, String>> arabicQuranMap = convertQuranToSuraMap(arabicQuran, true);
result.add(getMatchingListOfAyasFromQuran(arabicQuranMap, englishQuranMap));
if(language.equals("English")){
result.add(englishQuranMap);
}
else {
Quran translationQuran = null;
if(quranCache.containsKey(language)){
translationQuran = quranCache.get(language);
}
else {
translationQuran = loadQuran(context.getResources().openRawResource(resources.get(language)));
quranCache.put(language, translationQuran);
}
Map<String, Map<String, String>> translationQuranMap = convertQuranToSuraMap(translationQuran, false);
result.add(getMatchingListOfAyasFromQuran(translationQuranMap, englishQuranMap));
}
}
}
catch(Exception ex){
ex.printStackTrace();
}
return result;
}
public static Map<String, Map<String, String>> convertQuranToSuraMap(Quran quran, boolean addAyaNumber){
Map<String, Map<String, String>> suraMap = new HashMap<>();
for(Sura sura : quran.getSura()){
Map<String, String> ayaMap = new HashMap<>();
for(Aya aya : sura.getAya()){
String ayaText = aya.getText();
if(addAyaNumber) {
ayaText = String.format("%s - (%s)", aya.getText(), aya.getIndex());
}
ayaMap.put(aya.getIndex(), ayaText);
}
suraMap.put(sura.getName(), ayaMap);
}
return suraMap;
}
public static Map<String, Map<String, String>> queryQuran(Quran quran , String text){
Map<String, Map<String, String>> result = new HashMap<>();
for(Sura sura : quran.getSura()){
Map<String, String> ayaMap = new HashMap<>();
for(Aya aya : sura.getAya()){
if(aya.getText().contains(text)){
ayaMap.put(aya.getIndex(), aya.getText());
}
}
if(ayaMap != null && ayaMap.size() > 0) {
result.put(sura.getName(), ayaMap);
}
}
return result;
}
public static Map<String, Map<String, String>> getMatchingListOfAyasFromQuran(Map<String, Map<String, String>> fullQuran, Map<String, Map<String, String>> referenceQuran ){
Map<String, Map<String, String>> result = new HashMap<>();
for(String sura : referenceQuran.keySet()){
Map<String, String> ayaMap = referenceQuran.get(sura);
Map<String, String> matchingAyaMap = new HashMap<>();
for(String aya : ayaMap.keySet()){
matchingAyaMap.put(aya, fullQuran.get(sura).get(aya));
}
result.put(sura, matchingAyaMap);
}
return result;
}
}
| true |
b07876ce6fabc37fd9fe7cf241437352ade3a0aa
|
Java
|
zjt0428/emms_GXDD
|
/emms_GXDD/.svn/pristine/6f/6ff5ba2eb12621652d9d2cd99ec95babef49a25c.svn-base
|
UTF-8
| 982 | 1.976563 | 2 |
[] |
no_license
|
/**
*====================================================
* 文件名称: SecureProtocolService.java
* 修订记录:
* No 日期 作者(操作:具体内容)
* 1. 2014-4-20 chenxy(创建:创建文件)
*====================================================
* 类描述:(说明未实现或其它不应生成javadoc的内容)
*/
package com.knight.emms.service;
import java.util.List;
import com.knight.core.filter.QueryFilter;
import com.knight.emms.core.service.BaseBusinessModelService;
import com.knight.emms.model.SecureProtocol;
/**
* @ClassName: SecureProtocolService
* @Description: TODO(这里用一句话描述这个类的作用)
* @author chenxy
* @date 2014-4-20 上午8:30:23
*/
public interface SecureProtocolService extends BaseBusinessModelService<SecureProtocol> {
public List<SecureProtocol> queryTranslateAllFull(QueryFilter filter);
public SecureProtocol getTranslateFull(Long protocolId);
public void delete(Long protocolId);
}
| true |
a372802eb726830dc317045fc38b0cfcd1b210aa
|
Java
|
nttv/C1120G1-NguyenThiTuongVi
|
/Module-2/src/Vehicle-Management/src/models/Truck.java
|
UTF-8
| 1,126 | 3.140625 | 3 |
[] |
no_license
|
package models;
public class Truck extends Vehicle {
private int payload;
public Truck() {
}
public Truck(String noPlate, String brand, int yearOfProduction, String owner, int payload) {
super(noPlate, brand, yearOfProduction, owner);
this.payload = payload;
}
public Truck(String[] truckInfo) {
super(truckInfo[0], truckInfo[1], Integer.parseInt(truckInfo[2]), truckInfo[3]);
this.payload = Integer.parseInt(truckInfo[4]);
}
public int getPayload() {
return payload;
}
public void setPayload(int payload) {
this.payload = payload;
}
@Override
public String toString() {
return super.toString() + ',' + payload;
}
@Override
public void showInfo() {
System.out.println("Truck{" +
"noPlate='" + super.getNoPlate() + '\'' +
", brand='" + super.getBrand() + '\'' +
", yearOfProduction=" + super.getYearOfProduction() +
", owner='" + super.getOwner() + '\'' +
", payload=" + payload +
'}');
}
}
| true |
cd027b8d98f37e30d202357be2c2ecf7118c17ad
|
Java
|
cebu4u/Trickplay
|
/server/gameservice/src/main/java/com/trickplay/gameservice/dao/GamePlaySummaryDAO.java
|
UTF-8
| 265 | 1.90625 | 2 |
[] |
no_license
|
package com.trickplay.gameservice.dao;
import com.trickplay.gameservice.domain.GamePlaySummary;
public interface GamePlaySummaryDAO extends GenericDAO<GamePlaySummary, Long> {
public GamePlaySummary findByGameAndUser(Long gameId, Long userId);
}
| true |
e0d6916fd1c6d922808db44cb68b60cfdab74856
|
Java
|
aniltelaprolu/InventryAngular
|
/Inventory-17-Jan-2018/inventory-parent/inventory-web/src/main/java/com/inventory/web/event/listeners/InvSessionCreateListener.java
|
UTF-8
| 711 | 2.125 | 2 |
[] |
no_license
|
package com.inventory.web.event.listeners;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.session.MapSession;
import org.springframework.session.events.SessionCreatedEvent;
import org.springframework.stereotype.Component;
@Component
public class InvSessionCreateListener implements ApplicationListener<SessionCreatedEvent> {
private static Logger logger = LoggerFactory.getLogger(InvSessionCreateListener.class);
@Override
public void onApplicationEvent(SessionCreatedEvent event) {
logger.info("Start Session created");
MapSession session = event.getSession();
logger.info("End Session created");
}
}
| true |
8ccdfb9a29bf867587e952ac17ef036d8467527a
|
Java
|
fireformoney/fire
|
/leyou/src/main/java/com/hxbreak/leyou/GameDownloadActivity.java
|
UTF-8
| 14,933 | 1.710938 | 2 |
[] |
no_license
|
package com.hxbreak.leyou;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google2hx.gson.Gson;
import com.hxbreak.Bean.AppInfo;
import com.hxbreak.Bean.AppListResult;
import com.hxbreak.leyou.Adapter.AppListAdapter;
import com.hxbreak.leyou.Data.UserData;
import com.hxbreak.leyou.Provider.MyFileProvider;
import com.hxbreak.leyou.Task.DownloadTask;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import okhttp2hx.Call;
import okhttp2hx.Callback;
import okhttp2hx.HttpUrl;
import okhttp2hx.OkHttpClient;
import okhttp2hx.Request;
import okhttp2hx.Response;
/**
* Created by HxBreak on 2017/7/28.
*/
public class GameDownloadActivity extends BaseActivity implements Callback, AppListAdapter.OnItemClick, DownloadTask.DownloadListener{
private final String applisturl = "http://112.126.66.190/games.php";
private final String FileStorePath = "/gamecache";
private final String TAG = "HxBreak";
private final String FILEPROVIDER = "com.hxbreak.leyou.fileprovider";
private final String CHANNEL_ID = "20019a";
private final String APP_ID = "b1019a";
private static final String APP_SECRET = "D9IIkKvFYA8q8f0gsHxSpccWyOKT4dAp";
private UserData mUserData;
private Toolbar toolbar;
private RecyclerView recyclerView;
private ProgressBar progressBar;
private OkHttpClient okHttpClient;
private AppListResult appListResult;
private AppListAdapter appListAdapter;
private BroadcastReceiver broadcastReceiver;
private HashMap<Integer, DownloadTask> hashMap = new HashMap<>();
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case 1:
initList(); break;
case 2:
Toast.makeText(GameDownloadActivity.this, "列表加载失败", Toast.LENGTH_LONG).show();break;
case 90:
//Setup apk size
appListAdapter.setItemSize(msg.arg1, msg.arg2);
break;
case 100:
appListAdapter.updateItemDownloadProgess(msg.arg1, msg.arg2);
if(appListAdapter.shouldLaunchInstall(msg.arg1)){
requestInstallPackage(String.format("/%s.apk", appListAdapter.requestPackageName(msg.arg1)));
}
break;
case 101:
Toast.makeText(GameDownloadActivity.this, "下载任务出错", Toast.LENGTH_LONG).show();break;
case 200:
Toast.makeText(getApplicationContext(), "奖励已经添加", Toast.LENGTH_SHORT).show();
appListAdapter.listAdd(msg.getData().getString("package", ""));break;
case 201:
appListAdapter.listRemove(msg.getData().getString("package", ""));break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
okHttpClient = new OkHttpClient();
mUserData = new UserData(this);
toolbar = (Toolbar) findViewById(R.id.hb_toolbar);
recyclerView = (RecyclerView)findViewById(R.id.hb_app_recylerview);
progressBar = (ProgressBar)findViewById(R.id.hx_progressBar);
initToolbar();
dowloadAppList();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
intentFilter.addDataScheme("package");
broadcastReceiver = new GameDownloadActivity.PackageListener(handler);
registerReceiver(broadcastReceiver, intentFilter);
}
private void initToolbar(){
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
public List<String> getInstalledAppList(){
List<String> list = new ArrayList<>();
for (PackageInfo pinfo : getPackageManager().getInstalledPackages(0)){
list.add(pinfo.packageName);
}
return list;
}
@Override
protected void onDestroy() {
unregisterReceiver(broadcastReceiver);
super.onDestroy();
}
/**
* 展示列表内容
*/
private void initList(){
progressBar.setVisibility(View.GONE);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(OrientationHelper.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setItemAnimator(null);
appListAdapter = new AppListAdapter(this, appListResult.content.list, this, new File(getFilesDir(), FileStorePath).listFiles(), getInstalledAppList(), true);
recyclerView.setAdapter(appListAdapter);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
finish();
break;
}
return super.onOptionsItemSelected(item);
}
/**
* 下载app列表
*/
private void dowloadAppList(){
HashMap<String, String> hashMap = new HashMap<>();
// hashMap.put("from_client", "server");
// hashMap.put("channel_id", CHANNEL_ID);
// hashMap.put("app_id", APP_ID);
// hashMap.put("pn", "1");
// hashMap.put("rn", "10");
// hashMap.put("timestamp", String.valueOf((int)(System.currentTimeMillis() / 1000)));
HttpUrl.Builder httpUrlBuilder = HttpUrl.parse(applisturl).newBuilder();
// Iterator iterator = hashMap.entrySet().iterator();
StringBuilder sign = new StringBuilder();
//排序
List<Map.Entry<String, String>> hashMap2 = new ArrayList<Map.Entry<String, String>>(hashMap.entrySet());
Collections.sort(hashMap2, new Comparator<Map.Entry<String, String>>() {
@Override
public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
return o1.getKey().compareTo(o2.getKey());
}
});
Iterator iterator = hashMap2.iterator();
while(iterator.hasNext()){
Map.Entry<String, String> entry = (Map.Entry<String, String>)iterator.next();
httpUrlBuilder.addQueryParameter(entry.getKey(), entry.getValue());
sign.append(entry.getKey());
sign.append("=");
sign.append(entry.getValue());
if (iterator.hasNext()) {
sign.append("&");
}
}
Request request = new Request.Builder().url(httpUrlBuilder.build()).build();
okHttpClient.newCall(request).enqueue(this);
}
@Override
public void onFailure(Call call, IOException e) {
handler.sendEmptyMessage(2);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if(response.code() == 200){
Gson gson = new Gson();
try{
AppInfo[] appInfos = gson.fromJson(new StringReader(response.body().string()), AppInfo[].class);
appListResult = new AppListResult();
appListResult.content.list = appInfos;
appListResult.content.has_more = 0;
appListResult.content.total_cnt = appInfos.length;
handler.sendEmptyMessage(1);//数据下载完毕
}catch (Exception e){
handler.sendEmptyMessage(2);
}
}else{
handler.sendEmptyMessage(2);
}
}
@Override
public void OnClick(View view, int position) {
switch (view.getId()){
case R.id.hb_btn_download:
switch (appListAdapter.getItemStatus(position)){
case 0:
startDownloadPackage(appListResult.content.list[position].apk_url, position);
appListAdapter.setItemStatus(position, 1, true);
break;
case 1:
hashMap.get(position).requestShutdown();
appListAdapter.setItemStatus(position, 2, true);
break;
case 2:
startDownloadPackage(appListResult.content.list[position].apk_url, position);
appListAdapter.setItemStatus(position, 1, true);
break;
case 3:
requestInstallPackage(String.format("/%s.apk", appListAdapter.requestPackageName(position)));break;
case 4:
requestLaunchPackage(appListAdapter.requestPackageName(position));break;
}
break;
}
}
/**
* 开始下载应用包
* @param url
* @param position
*/
public void startDownloadPackage(String url, int position){
try {
File file = new File(this.getFilesDir(), FileStorePath);
if (!file.exists()){
file.mkdir();
}
// File targetFile = new File(file, String.format("/%s.apk", appListAdapter.requestPackageName(position)));
File targetFile = new File(this.getFilesDir(), String.format("%s/%s.apk",FileStorePath, appListAdapter.requestPackageName(position)));
FileOutputStream fos = new FileOutputStream(targetFile, true);
DownloadTask downloadTask = new DownloadTask(this,
url, position, (int)targetFile.length(), this, fos);
hashMap.put(position, downloadTask);
downloadTask.requestDownload();
Message msg = new Message();
msg.what = 100;
msg.arg1 = position;
msg.arg2 = 0;
handler.sendMessage(msg);
Toast.makeText(this, "下载任务即将开始", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, "创建下载任务时发生意外 " + e.toString(), Toast.LENGTH_LONG).show();
}
}
public boolean requestLaunchPackage(String IPackage){
try {
Intent intent = getPackageManager().getLaunchIntentForPackage(IPackage);
startActivity(intent);
return true;
}catch (Exception e){
return false;
}
}
/**
* 兼容Android 7.0及以上版本
* @param path
*/
public void requestInstallPackage(String path){
boolean passed = false;
File file = new File(getFilesDir(), FileStorePath + path);
String DataType = "application/vnd.android.package-archive";
Log.e("HxBreak", String.format("file:%s-%s", String.valueOf(file.exists()), file.getAbsolutePath()));
try{
Intent intent = new Intent();
Runtime.getRuntime().exec("chmod 777 " + file.getAbsolutePath());
Runtime.getRuntime().exec("chmod 777 " + file.getParent());
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), DataType);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Log.e(TAG, String.format("Intent Test1: %s", intent.toString()));
startActivity(intent);
passed = true;
}catch (Exception e){
Log.e(TAG, e.toString());
}
if (!passed){
try {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MyFileProvider myFileProvider = new MyFileProvider();
intent.setDataAndType(myFileProvider.getUriForFile(this, FILEPROVIDER, file), DataType);
Log.e(TAG, String.format("Intent Test2: %s", intent.toString()));
startActivity(intent);
passed = true;
}catch (Exception e){
Log.e(TAG, e.toString());
}
}
if(!passed){
Toast.makeText(this, "安装程序无法正常启动", Toast.LENGTH_SHORT).show();
}
}
/**
* 下载进度更新
* @param buffered
* @param id
*/
@Override
public void onUpdate(int buffered, int id) {
Message msg = new Message();
msg.what = 100;
msg.arg1 = id;
msg.arg2 = buffered;
handler.sendMessage(msg);
}
@Override
public void onInit(long length, int id) {
Message msg = new Message();
msg.what = 90;
msg.arg1 = id;
msg.arg2 = (int)length;
handler.sendMessage(msg);
}
public class PackageListener extends BroadcastReceiver
{
private Handler handler;
public PackageListener(Handler handler) {
this.handler = handler;
}
@Override
public void onReceive(Context context, Intent intent) {
Message msg = new Message();
Log.e("HxBreak", "package active :" + intent.getDataString() );
if(intent.getAction().equals(Intent.ACTION_PACKAGE_ADDED)){
Bundle bundle = new Bundle();
bundle.putString("package", intent.getDataString().substring(8));
msg.what = 200;
msg.setData(bundle);
if(appListAdapter.hasPackageInList(intent.getDataString().substring(8))){
handler.sendMessage(msg);
int x = (int)(Math.random() * 20) + 30;
mUserData.setUserMoney(mUserData.getUserMoney() + (float) (x / 100.0));
}
}else if(intent.getAction().equals(Intent.ACTION_PACKAGE_REMOVED)){
Bundle bundle = new Bundle();
bundle.putString("package", intent.getDataString().substring(8));
msg.what = 201;
msg.setData(bundle);
handler.sendMessage(msg);
}
}
}
}
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.