text
stringlengths 10
2.72M
|
|---|
package ee.ttu.tarkvaratehnika.selveleidja;
import java.util.List;
import org.springframework.web.bind.annotation.*;
@RestController
public class CommentController {
private CommentService commentService;
public CommentController(CommentService commentService){
this.commentService = commentService;
}
@CrossOrigin(origins = "http://localhost:8080")
@RequestMapping(value="/comments/add", method = RequestMethod.POST, consumes = "application/json")
public Comment addComment(@RequestBody Comment comment){
return commentService.addComment(comment);
}
@RequestMapping(value="/comments", method=RequestMethod.GET)
public List<Comment> getAllComments() {
return commentService.getAllComments();
}
@RequestMapping(value = "/comments/{id}", method=RequestMethod.GET)
public Comment getComment(@PathVariable("id") long commentId) {
return commentService.getCommentById(commentId);
}
}
|
package com.example.marek.komunikator.userSettings.activities;
import android.os.Bundle;
import android.view.View;
import com.example.marek.komunikator.MyBaseActivity;
import com.example.marek.komunikator.R;
import com.example.marek.komunikator.userSettings.fields.Field;
import com.example.marek.komunikator.userSettings.tasks.ResponseTask;
public abstract class UserActivity extends MyBaseActivity {
protected ResponseTask mAuthTask = null;
protected Field focusView = null;
private View mProgressView;
private View mLoginFormView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
}
protected void showProgress(final boolean show) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
public void resetDataAfterResponse(){
mAuthTask = null;
showProgress(false);
}
public abstract void executeAfterResponse(boolean success);
protected abstract void executeRequest();
}
|
/**
*
*/
package ucl.cs.testingEmulator.contexNotifierScripts;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.RemoteDevice;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileSystemRegistry;
import javax.swing.JFrame;
import javax.swing.JPanel;
import ucl.cs.testingEmulator.connection.file.EmulatedFileSystem;
import ucl.cs.testingEmulator.core.Script;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import javax.swing.JCheckBox;
import java.awt.GridBagConstraints;
import java.io.File;
import java.io.IOException;
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
import javax.swing.BorderFactory;
import javax.swing.border.TitledBorder;
import javax.swing.JButton;
import org.microemu.app.Common;
/**
* @author -Michele Sama- aka -RAX-
*
* University College London
* Dept. of Computer Science
* Gower Street
* London WC1E 6BT
* United Kingdom
*
* Email: M.Sama (at) cs.ucl.ac.uk
*
* Group:
* Software Systems Engineering
*
*/
public class Demo26March2007 extends JPanel implements Script {
EmulatedFileSystem _lastConnected=null;
EmulatedFileSystem _notificationFileSystem=new EmulatedFileSystem("/Users/rax/Documents/demoFakeRoots/notification","/E:",Connector.READ); // @jve:decl-index=0:
EmulatedFileSystem _gcFileSystem=new EmulatedFileSystem("/Users/rax/Documents/demoFakeRoots/gc","/E:",Connector.READ); // @jve:decl-index=0:
EmulatedFileSystem _meetingFileSystem=new EmulatedFileSystem("/Users/rax/Documents/demoFakeRoots/meeting","/E:",Connector.READ); // @jve:decl-index=0:
RemoteDevice _btMyComputer=new RemoteDevice("00:00:00:00:01"); // @jve:decl-index=0:
RemoteDevice _btMyBossComputer=new RemoteDevice("00:00:00:00:02"); // @jve:decl-index=0:
RemoteDevice _btMyBossMobile=new RemoteDevice("00:00:00:00:03"); // @jve:decl-index=0:
RemoteDevice _btBlackhole=new RemoteDevice("00:00:00:00:04"); // @jve:decl-index=0:
/**
*
*/
private static final long serialVersionUID = -8917166797291773754L;
public static String JARLOCATION = "/Users/rax/APPZ/TestingEmulator/ContextNotifier/dist/ContextNotifier.jad"; // @jve:decl-index=0:
private JPanel jPanelFileSystem = null;
private JRadioButton jRadioButtonNotification = null;
private JRadioButton jRadioButtonGarbageCollection = null;
private JRadioButton jRadioButtonMeeting = null;
private ButtonGroup buttonGroupFileSystem = null; // @jve:decl-index=0:visual-constraint="694,18"
private JPanel jPanelBlueTooth = null;
private JCheckBox jCheckBoxBTBlackhole = null;
private JCheckBox jCheckBoxMyOffice = null;
private JCheckBox jCheckBoxBTBossOffice = null;
private JCheckBox jCheckBoxBTBossDevice = null;
private JRadioButton jRadioButtonNone = null;
private JButton jButtonRestart = null;
/**
* This method initializes
*
*/
public Demo26March2007() {
super();
initialize();
}
/**
* This method initializes this
*
*/
private void initialize() {
this._btMyComputer.setFriendlyName("MyComputer");
this._btMyBossComputer.setFriendlyName("MyBossComputer");
this._btMyBossMobile.setFriendlyName("MyBossMobile");
this._btBlackhole.setFriendlyName("Blackhole");
this.getButtonGroupFileSystem();
this.setSize(new Dimension(527, 233));
this.add(getJPanelFileSystem(), null);
this.add(getJPanelBlueTooth(), null);
this.add(getJButtonRestart(), null);
}
/* (non-Javadoc)
* @see ucl.cs.testingEmulator.core.Script#getName()
*/
public String getName() {
return "Demo26March2007";
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
public void run() {
JFrame frame=new JFrame(this.getName());
frame.getContentPane().add(this);
frame.pack();
frame.setVisible(true);
}
/**
* This method initializes jPanelFileSystem
*
* @return javax.swing.JPanel
*/
private JPanel getJPanelFileSystem() {
if (jPanelFileSystem == null) {
GridBagConstraints gridBagConstraints11 = new GridBagConstraints();
gridBagConstraints11.gridx = 0;
gridBagConstraints11.gridy = 0;
GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
gridBagConstraints2.gridx = 0;
gridBagConstraints2.gridy = 3;
GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
gridBagConstraints1.gridx = 0;
gridBagConstraints1.gridy = 2;
GridBagConstraints gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
jPanelFileSystem = new JPanel();
jPanelFileSystem.setLayout(new GridBagLayout());
jPanelFileSystem.setBorder(BorderFactory.createTitledBorder(null, "FileSystem", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null));
jPanelFileSystem.add(getJRadioButtonNotification(), gridBagConstraints);
jPanelFileSystem.add(getJRadioButtonGarbageCollection(), gridBagConstraints1);
jPanelFileSystem.add(getJRadioButtonMeeting(), gridBagConstraints2);
jPanelFileSystem.add(getJRadioButtonNone(), gridBagConstraints11);
}
return jPanelFileSystem;
}
/**
* This method initializes jRadioButtonNotification
*
* @return javax.swing.JRadioButton
*/
private JRadioButton getJRadioButtonNotification() {
if (jRadioButtonNotification == null) {
jRadioButtonNotification = new JRadioButton();
jRadioButtonNotification.setText("Notification");
jRadioButtonNotification.setPreferredSize(new Dimension(150, 22));
jRadioButtonNotification.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
if(jRadioButtonNotification.isSelected())
{
FileSystemRegistry.getInstance().removeFileSystem(_lastConnected);
FileSystemRegistry.getInstance().addFileSystem(_notificationFileSystem);
_lastConnected=_notificationFileSystem;
}else
{
//FileSystemRegistry.getInstance().removeFileSystem(_notificationFileSystem);
}
}
});
}
return jRadioButtonNotification;
}
/**
* This method initializes jRadioButtonGarbageCollection
*
* @return javax.swing.JRadioButton
*/
private JRadioButton getJRadioButtonGarbageCollection() {
if (jRadioButtonGarbageCollection == null) {
jRadioButtonGarbageCollection = new JRadioButton();
jRadioButtonGarbageCollection.setText("GarbageCollection");
jRadioButtonGarbageCollection.setPreferredSize(new Dimension(150, 22));
jRadioButtonGarbageCollection
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
if(jRadioButtonGarbageCollection.isSelected())
{
FileSystemRegistry.getInstance().removeFileSystem(_lastConnected);
FileSystemRegistry.getInstance().addFileSystem(_gcFileSystem);
_lastConnected=_gcFileSystem;
}else
{
//FileSystemRegistry.getInstance().removeFileSystem(_gcFileSystem);
}
}
});
}
return jRadioButtonGarbageCollection;
}
/**
* This method initializes jRadioButtonMeeting
*
* @return javax.swing.JRadioButton
*/
private JRadioButton getJRadioButtonMeeting() {
if (jRadioButtonMeeting == null) {
jRadioButtonMeeting = new JRadioButton();
jRadioButtonMeeting.setText("Meeting");
jRadioButtonMeeting.setPreferredSize(new Dimension(150, 22));
jRadioButtonMeeting.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
if(jRadioButtonMeeting.isSelected())
{
FileSystemRegistry.getInstance().removeFileSystem(_lastConnected);
FileSystemRegistry.getInstance().addFileSystem(_meetingFileSystem);
_lastConnected=_meetingFileSystem;
}else
{
//FileSystemRegistry.getInstance().removeFileSystem(_meetingFileSystem);
}
}
});
}
return jRadioButtonMeeting;
}
/**
* This method initializes buttonGroupFileSystem
*
* @return javax.swing.ButtonGroup
*/
private ButtonGroup getButtonGroupFileSystem() {
if (buttonGroupFileSystem == null) {
buttonGroupFileSystem = new ButtonGroup();
buttonGroupFileSystem.add(this.getJRadioButtonNone());
buttonGroupFileSystem.add(this.getJRadioButtonGarbageCollection());
buttonGroupFileSystem.add(this.getJRadioButtonNotification());
buttonGroupFileSystem.add(this.getJRadioButtonMeeting());
}
return buttonGroupFileSystem;
}
/**
* This method initializes jPanelBlueTooth
*
* @return javax.swing.JPanel
*/
private JPanel getJPanelBlueTooth() {
if (jPanelBlueTooth == null) {
GridBagConstraints gridBagConstraints6 = new GridBagConstraints();
gridBagConstraints6.gridx = 0;
gridBagConstraints6.gridy = 3;
GridBagConstraints gridBagConstraints5 = new GridBagConstraints();
gridBagConstraints5.gridx = 0;
gridBagConstraints5.gridy = 2;
GridBagConstraints gridBagConstraints4 = new GridBagConstraints();
gridBagConstraints4.gridx = 0;
gridBagConstraints4.gridy = 1;
GridBagConstraints gridBagConstraints3 = new GridBagConstraints();
gridBagConstraints3.gridx = 0;
gridBagConstraints3.gridy = 0;
jPanelBlueTooth = new JPanel();
jPanelBlueTooth.setLayout(new GridBagLayout());
jPanelBlueTooth.setBorder(BorderFactory.createTitledBorder(null, "BlueTooth", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null));
jPanelBlueTooth.add(getJCheckBoxBTBlackhole(), gridBagConstraints3);
jPanelBlueTooth.add(getJCheckBoxMyOffice(), gridBagConstraints4);
jPanelBlueTooth.add(getJCheckBoxBTBossOffice(), gridBagConstraints5);
jPanelBlueTooth.add(getJCheckBoxBTBossDevice(), gridBagConstraints6);
}
return jPanelBlueTooth;
}
/**
* This method initializes jCheckBoxBTBlackhole
*
* @return javax.swing.JCheckBox
*/
private JCheckBox getJCheckBoxBTBlackhole() {
if (jCheckBoxBTBlackhole == null) {
jCheckBoxBTBlackhole = new JCheckBox();
jCheckBoxBTBlackhole.setText("Blackhole");
jCheckBoxBTBlackhole.setPreferredSize(new Dimension(100, 22));
jCheckBoxBTBlackhole.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
if(jCheckBoxBTBlackhole.isSelected())
{
DiscoveryAgent.getInstance().addRemoteDevice(_btBlackhole,new DeviceClass(8*256));
}else
{
DiscoveryAgent.getInstance().removeRemoteDevice(_btBlackhole);
}
}
});
}
return jCheckBoxBTBlackhole;
}
/**
* This method initializes jCheckBoxMyOffice
*
* @return javax.swing.JCheckBox
*/
private JCheckBox getJCheckBoxMyOffice() {
if (jCheckBoxMyOffice == null) {
jCheckBoxMyOffice = new JCheckBox();
jCheckBoxMyOffice.setText("MyComputer");
jCheckBoxMyOffice.setPreferredSize(new Dimension(100, 22));
jCheckBoxMyOffice.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
if(jCheckBoxMyOffice.isSelected())
{
DiscoveryAgent.getInstance().addRemoteDevice(_btMyComputer,new DeviceClass(1*256));
}else
{
DiscoveryAgent.getInstance().removeRemoteDevice(_btMyComputer);
}
}
});
}
return jCheckBoxMyOffice;
}
/**
* This method initializes jCheckBoxBTBossOffice
*
* @return javax.swing.JCheckBox
*/
private JCheckBox getJCheckBoxBTBossOffice() {
if (jCheckBoxBTBossOffice == null) {
jCheckBoxBTBossOffice = new JCheckBox();
jCheckBoxBTBossOffice.setText("MyBossComputer");
jCheckBoxBTBossOffice.setPreferredSize(new Dimension(100, 22));
jCheckBoxBTBossOffice.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
if(jCheckBoxBTBossOffice.isSelected())
{
DiscoveryAgent.getInstance().addRemoteDevice(_btMyBossComputer,new DeviceClass(1*256));
}else
{
DiscoveryAgent.getInstance().removeRemoteDevice(_btMyBossComputer);
}
}
});
}
return jCheckBoxBTBossOffice;
}
/**
* This method initializes jCheckBoxBTBossDevice
*
* @return javax.swing.JCheckBox
*/
private JCheckBox getJCheckBoxBTBossDevice() {
if (jCheckBoxBTBossDevice == null) {
jCheckBoxBTBossDevice = new JCheckBox();
jCheckBoxBTBossDevice.setText("MyBossDevice");
jCheckBoxBTBossDevice.setPreferredSize(new Dimension(100, 22));
jCheckBoxBTBossDevice.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
if(jCheckBoxBTBossDevice.isSelected())
{
DiscoveryAgent.getInstance().addRemoteDevice(_btMyBossMobile,new DeviceClass(2*256));
}else
{
DiscoveryAgent.getInstance().removeRemoteDevice(_btMyBossMobile);
}
}
});
}
return jCheckBoxBTBossDevice;
}
/**
* This method initializes jRadioButtonNone
*
* @return javax.swing.JRadioButton
*/
private JRadioButton getJRadioButtonNone() {
if (jRadioButtonNone == null) {
jRadioButtonNone = new JRadioButton();
jRadioButtonNone.setPreferredSize(new Dimension(150, 22));
jRadioButtonNone.setSelected(true);
jRadioButtonNone.setText("None");
jRadioButtonNone.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
if(jRadioButtonNone.isSelected()==true){
FileSystemRegistry.getInstance().removeFileSystem(_lastConnected);
_lastConnected=null;
}
}
});
}
return jRadioButtonNone;
}
/**
* This method initializes jButtonRestart
*
* @return javax.swing.JButton
*/
private JButton getJButtonRestart() {
if (jButtonRestart == null) {
jButtonRestart = new JButton();
jButtonRestart.setText("Restart");
jButtonRestart.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
Common.openJadUrlSafe(new File(JARLOCATION).toURL().toString());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
}
return jButtonRestart;
}
} // @jve:decl-index=0:visual-constraint="10,10"
|
package org.motechproject.server.svc.impl;
import org.motechproject.server.model.IncomingMessage;
import org.motechproject.server.model.MessageProcessorURL;
import org.motechproject.server.model.db.MessageProcessorDAO;
import org.motechproject.server.svc.IncomingMessageProcessor;
import org.motechproject.server.svc.SupportCaseService;
import org.motechproject.server.svc.WebClient;
import org.motechproject.server.util.MailingConstants;
import org.motechproject.ws.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.io.UnsupportedEncodingException;
public class IncomingMessageProcessorImpl implements IncomingMessageProcessor {
@Autowired
private MessageProcessorDAO dao;
@Autowired
private WebClient webClient;
@Transactional
public Response process(IncomingMessage incomingMessage) throws UnsupportedEncodingException {
log(incomingMessage);
return responseFromMappedURL(incomingMessage);
}
private Response responseFromMappedURL(IncomingMessage incomingMessage) throws UnsupportedEncodingException {
MessageProcessorURL processorURL = dao.urlFor(incomingMessage.getKey());
if(processorURL != null){
StringBuilder url = new StringBuilder(processorURL.getUrl());
url.append(incomingMessage.requestParameters());
return webClient.get(url.toString());
}
return new Response(MailingConstants.KEY_NOT_SUPPORTED);
}
private void log(IncomingMessage incomingMessage) {
dao.save(incomingMessage);
}
public void setDao(MessageProcessorDAO dao) {
this.dao = dao;
}
public void setWebClient(WebClient webClient) {
this.webClient = webClient;
}
}
|
package com.bbb.composite.product.details.dto;
import java.io.Serializable;
/**
* BrandCompositeDTO attributes specified here.
*
* @author psh111
*/
public class BrandCompositeDTO implements Serializable{
private static final long serialVersionUID = -8275780178068737878L;
private String brandId;
private String brandName;
private String brandDescription;
private String brandImage;
private Boolean displayFlag;
public String getBrandId() {
return brandId;
}
public void setBrandId(String brandId) {
this.brandId = brandId;
}
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public String getBrandDescription() {
return brandDescription;
}
public void setBrandDescription(String brandDescription) {
this.brandDescription = brandDescription;
}
public String getBrandImage() {
return brandImage;
}
public void setBrandImage(String brandImage) {
this.brandImage = brandImage;
}
public Boolean getDisplayFlag() {
return displayFlag;
}
public void setDisplayFlag(Boolean displayFlag) {
this.displayFlag = displayFlag;
}
}
|
package com.ibai.patterns.decorator;
/**
* @author baizhizhen
*/
public class Soy extends CondimentDecorator {
public Soy(Beverage beverage) {
super(beverage);
}
@Override
public float cost() {
return beverage.cost() + 1.21f;
}
@Override
public String getDescription() {
return String.format("%s,%s", beverage.getDescription(), "Soy");
}
}
|
package com.lowes.lowesapp.rest.response;
/**
* Created by George on 1/23/2016.
*/
public class ImageUrls {
private String sm;
private String xl;
private String lg;
public String getSm ()
{
return sm;
}
public void setSm (String sm)
{
this.sm = sm;
}
public String getXl ()
{
return xl;
}
public void setXl (String xl)
{
this.xl = xl;
}
public String getLg ()
{
return lg;
}
public void setLg (String lg)
{
this.lg = lg;
}
@Override
public String toString()
{
return "ClassPojo [sm = "+sm+", xl = "+xl+", lg = "+lg+"]";
}
}
|
package br.com.slack.fabrica;
public interface FabricaDeArquivo {
public Arquivo criarArquivo(String nome);
}
|
package org.timesheet.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.timesheet.service.GenericDao;
public class InMemoryDao<E, K> implements GenericDao<E, K> {
static final Logger logger = Logger.getLogger(InMemoryDao.class);
private List<E> entities = new ArrayList<E>();
@Override
public void add(E entity) {
logger.info("=== InMemoryDao === method:add --- start: " + entity);
entities.add(entity);
logger.info("=== InMemoryDao === method:add --- end: " + entity);
}
@Override
public void update(E entity) {
logger.info("=== InMemoryDao === method:update --- : " + entity);
throw new UnsupportedOperationException("Not supported in dummy in-memory impl!");
}
@Override
public void remove(E entity) {
logger.info("=== InMemoryDao === method:remove --- start: " + entity);
entities.remove(entity);
logger.info("=== InMemoryDao === method:remove --- end: " + entity);
}
@Override
public E find(K key) {
logger.info("=== InMemoryDao === method:find --- start: " + key);
if (entities.isEmpty()) {
return null;
}
logger.info("=== InMemoryDao === method:find --- end: " + entities.get(0));
// just return the first one sice we are not using any keys ATM
return entities.get(0);
}
@Override
public List<E> list() {
logger.info("=== InMemoryDao === method:list --- : " + entities);
return entities;
}
@Override
public List<E> findAllSorted(String sortBy, String sortOrder) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public List<E> searchAll(String[] sortBy, String[] word) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public List<E> findAllSorted(String[] sortByField, String[] word, String sortBy, String sortOrder) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public List<E> findAllPaginated(int page, int size) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Long countTotalItems() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public List<E> findAllPaginatedAndSorted(String[] sortByField, String[] word, int page, int size, String sortBy, String sortOrder) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public List<E> findAllPaginatedAndSorted(int page, int size, String sortBy, String sortOrder) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
|
package rent.common.projection;
import org.springframework.data.rest.core.config.Projection;
import rent.common.entity.AccountRegisteredEntity;
import java.time.LocalDate;
@Projection(types = {AccountRegisteredEntity.class})
public interface AccountRegisteredMinimal {
CitizenMinimalForAccount getCitizen();
LocalDate getDateStart();
LocalDate getDateEnd();
}
|
import java.util.ArrayList;
import java.util.List;
public class CloneTest {
/**
* @param args
*/
public static void main(String[] args) {
ArrayList<String> l = new ArrayList<String>();
l.add("one");
l.add("two");
List<String> l1 = (List<String>)l.clone();
System.out.println(l1 == l);
System.out.println(l1.equals(l));
l1.add("three");
System.out.println(l1.equals(l));
}
}
|
package custom_binary_tree;
import java.io.Serializable;
import java.util.*;
/*
Построй дерево(1)
*/
public class CustomTree extends AbstractList<String> implements Cloneable, Serializable {
Entry<String> root;
List<Entry<String>> listOfElements = new LinkedList<>();
List<Entry<String>> listForRemove = new ArrayList<>();
public CustomTree() {
root = new Entry<>("0");
listOfElements.add(root);
}
@Override
public String get(int index) {
throw new UnsupportedOperationException();
}
@Override
public int size() {
return listOfElements.size() - 1;
}
@Override
public String set(int index, String element) {
throw new UnsupportedOperationException();
}
@Override
public void add(int index, String element) {
throw new UnsupportedOperationException();
}
@Override
public String remove(int index) {
throw new UnsupportedOperationException();
}
@Override
public List<String> subList(int fromIndex, int toIndex) {
throw new UnsupportedOperationException();
}
@Override
protected void removeRange(int fromIndex, int toIndex) {
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(int index, Collection<? extends String> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean add(String s) {
boolean elementAdded = false;
if (listOfElements.size() > 0) {
for (Entry<String> entry: listOfElements) {
if (entry.availableToAddLeftChildren) {
entry.leftChild = new Entry<>(s);
entry.leftChild.parent = entry;
elementAdded = listOfElements.add(entry.leftChild);
entry.availableToAddLeftChildren = false;
break;
} else if (entry.availableToAddRightChildren) {
entry.rightChild = new Entry<>(s);
entry.rightChild.parent = entry;
elementAdded = listOfElements.add(entry.rightChild);
entry.availableToAddRightChildren = false;
break;
}
}
}
return elementAdded;
}
public String getParent(String s) {
String parent = null;
if (listOfElements.size() > 1) {
for (Entry<String> entry: listOfElements) {
if (entry.elementName.equals(s)) {
parent = entry.parent.elementName;
}
}
}
return parent;
}
@Override
public boolean remove(Object o) {
if (!(o instanceof String)) throw new UnsupportedOperationException();
boolean elementRemoved = false;
for (Entry<String> entry: listOfElements) {
if (!entry.elementName.equals(o.toString())) {
continue;
}
listForRemove.add(entry);
searchElements(entry);
}
for (Entry<String> entry: listForRemove) {
elementRemoved = listOfElements.remove(entry);
}
listForRemove.clear();
return elementRemoved;
}
public void searchElements(Entry<String> entry) {
for (Entry<String> element: listOfElements) {
if (element.equals(entry)) {
if (!element.availableToAddLeftChildren) {
listForRemove.add(element.leftChild);
}
if (!element.availableToAddRightChildren) {
listForRemove.add(element.rightChild);
}
if (isLeftChild(element.parent, element)) {
element.parent.availableToAddLeftChildren = true;
} else element.parent.availableToAddRightChildren = true;
searchElements(element.leftChild);
searchElements(element.rightChild);
}
}
}
public boolean isLeftChild(Entry<String> parent, Entry<String> child) {
return parent.leftChild.elementName.equals(child.elementName);
}
public boolean isRightChild(Entry<String> parent, Entry<String> child) {
return parent.rightChild.elementName.equals(child.elementName);
}
static class Entry<T> implements Serializable {
String elementName;
boolean availableToAddLeftChildren, availableToAddRightChildren;
Entry<T> parent, leftChild, rightChild;
public Entry(String elementName) {
this.elementName = elementName;
availableToAddLeftChildren = true;
availableToAddRightChildren = true;
}
public boolean isAvailableToAddChildren() {
return availableToAddLeftChildren || availableToAddRightChildren;
}
}
}
|
package com.service.proxy;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import com.pojo.CardRecord;
import com.pojo.Proxy;
import com.service.base.BaseService;
public interface ProxyService extends BaseService<Proxy> {
/**
* 注意要和Employeer.xml的方法名对应
*/
public Proxy findProxyByID(int id);
/**
* 注意要和Employeer.xml的方法名对应
*/
public int addProxy(Proxy proxy);
/**
* 注意要和Employeer.xml的方法名对应
*/
public void deleteProxy(String proxyId);
/**
* 注意要和Employeer.xml的方法名对应
*/
public int updateProxy(Proxy proxy);
/**
* 代理买卡
* @param proxyId
* @param type
* @param cardCount
* @param cardLTime
* @return
*/
public int updateCardCount(int triggerId,String sellerName,int proxyId,int type,int cardCount,Date cardLTime);
public List<Proxy> getProxysByRecommendID(int recommendId,int startIndex,int length);
public List<Proxy> getProxysByPioneerID(int pioneerId,int startIndex,int length);
public List<Proxy> getAllProxys(int startIndex,int length);
public List<Proxy> getAllProxys(Date startTime,Date endTime);
/**
* 代理售卡
* @param userId
* @param edUserId
* @param type
* @param toType
* @param count
* @param income
* @param cardLTime
* @return
*/
public int sellCardCount(int userId,int edUserId,int type,int toType,int count,int income);
/**
* 单纯更新房卡数
* @param proxyId
* @param type
* @param cardCount
* @return
*/
public int updateCardCount(int proxyId,int type,int cardCount);
public int updateCardCountWithProxy(Proxy proxy, int type,int cardCount);
public int clearCardCount(int proxyId,int type);
public int removeProxy(int proxyId);
public List<Integer> getProxyIdsByRecommendID(int recommendPerson);
public List<Proxy> getProxysByRecommendID(int recommendPerson);
public List<Integer> getProxyIdsByPioneerID(int pioneerPerson);
public List<Proxy> getProxysByTime(int id,Date crTime,Date enTime);
public List<Proxy> getProxysByIndex(int id,int startIndex,int length);
public int getProxysCountByRecommendID(int recommendId);
public int getProxysCountByPioneerID(int pioneerId);
//-----------------------------------
public int getAllProxysCount();
public boolean handleThreeClassBonus(int id,String sellerName,int addCardCount);
public boolean exchangeCardwithBonus(int id,int exchangeClass);
public int editProxyForGameUid(int id,int curGameUid);
}
|
abstract class AbstractSoupFactory {
String factoryLocation;
public String getFactoryLocation() {
return factoryLocation;
}
public ChickenSoup makeChickenSoup() {
return new ChickenSoup();
}
public FishChowder makeFishChowder() {
return new FishChowder();
}
public ClamChowder makeClamChowder() {
return new ClamChowder();
}
}
|
package com.tencent.mm.plugin.address.ui;
public interface InvoiceEditView$b {
}
|
package com.workorder.ticket.persistence.dao;
import java.util.Date;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.workorder.ticket.controller.vo.common.HistogramItem;
import com.workorder.ticket.persistence.dto.workorder.WorkOrderQueryDto;
import com.workorder.ticket.persistence.dto.workorder.WorkOrderWithCreatorDto;
import com.workorder.ticket.persistence.entity.WorkOrder;
public interface WorkOrderDao {
int deleteByPrimaryKey(Long id);
int insert(WorkOrder record);
int insertSelective(WorkOrder record);
WorkOrder getByPrimaryKey(Long id);
WorkOrderWithCreatorDto getWithCreator(Long id);
List<WorkOrderWithCreatorDto> getListByParam(
WorkOrderQueryDto workOrderQueryDto);
int getCountByParam(WorkOrderQueryDto workOrderQueryDto);
int updateByPrimaryKeySelective(WorkOrder record);
int updateByPrimaryKeyWithBLOBs(WorkOrder record);
int updateByPrimaryKey(WorkOrder record);
List<HistogramItem> statisticByDay(@Param("startTime") Date start,
@Param("endTime") Date end);
List<HistogramItem> statisticByWeek(@Param("startTime") Date start,
@Param("endTime") Date end);
List<HistogramItem> statisticByMonth(@Param("startTime") Date start,
@Param("endTime") Date end);
}
|
package com.lei.utils.xml;
public class Element
{
private String actionPath;
private Class<?> handlerClass;
private String handlerMethod;
private Class<?> handlerRequest;
public String getActionPath()
{
return actionPath;
}
public void setActionPath(String actionPath)
{
this.actionPath = actionPath;
}
public Class<?> getHandlerClass()
{
return handlerClass;
}
public void setHandlerClass(Class<?> handlerClass)
{
this.handlerClass = handlerClass;
}
public String getHandlerMethod()
{
return handlerMethod;
}
public void setHandlerMethod(String handlerMethod)
{
this.handlerMethod = handlerMethod;
}
public Class<?> getHandlerRequest()
{
return handlerRequest;
}
public void setHandlerRequest(Class<?> handlerRequest)
{
this.handlerRequest = handlerRequest;
}
}
|
//递归方式:k sum -> k-1 sum
//同时结合一些过滤手段
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> ans = new ArrayList<>();
int size = nums.length;
if(size < 4){
return ans;
}
Arrays.sort(nums);
List<Integer> sol = new ArrayList<>();
for(int i = 0; i < size - 3; i++){
//avoid duplicate
if(i != 0 && nums[i] == nums[i - 1]){
continue;
}
//too small
if(nums[i] + 3 * nums[size - 1] < target){
continue;
}
//too big
if(nums[i] * 4 > target){
break;
}
sol.add(nums[i]);
//System.out.format("4sum:%d%n", nums[i]);
threeSum(ans, sol, nums, i + 1, target - nums[i], size);
sol.remove(sol.size() - 1);
}
return ans;
}
private void threeSum(List<List<Integer>> ans, List<Integer> sol, int[] nums, int low, int target, int size){
for(int i = low; i < size - 2; i++){
if(i != low && nums[i] == nums[i - 1]){
continue;
}
if(nums[i] + 2 * nums[size - 1] < target){
continue;
}
if(nums[i] * 3 > target){
break;
}
sol.add(nums[i]);
//System.out.format("3sum:%d%n", nums[i]);
twoSum(ans, sol, nums, i + 1, target - nums[i], size);
sol.remove(sol.size() - 1);
}
}
private void twoSum(List<List<Integer>> ans, List<Integer> sol, int[] nums, int low, int target, int size){
int start = low;
int end = size - 1;
while(start < end){
if(start != low && nums[start] == nums[start - 1]){
start++;
continue;
}
if(nums[start] + nums[end] == target){
sol.add(nums[start]);
sol.add(nums[end]);
ans.add(new ArrayList<Integer>(sol));
sol.remove(sol.size() - 1);
sol.remove(sol.size() - 1);
//sol.removeRange(sol.size() - 2, sol.size());
start++;
}
else if(nums[start] + nums[end] < target){
start++;
}
else{
end--;
}
}
}
}
|
package com.kps.dsk;
import java.awt.Canvas;
import java.util.List;
public interface IDSKController {
void play();
void pause();
void stop();
double getTime();
void setTime(double time);
void setStopTime(double time);
double getStopTime();
DSKState getState();
double getDuration();
Canvas getCanvas();
void addListener(IDSKListener listener);
void removeListener(IDSKListener listener);
List<IDSKListener> getListeners();
}
|
package com.binary.mindset.tasklistmanagement.crud.repository;
import com.binary.mindset.tasklistmanagement.crud.entity.TaskEntity;
import com.binary.mindset.tasklistmanagement.model.Task;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
@Repository
public interface TaskRepository extends CrudRepository<TaskEntity, Integer> {
List<TaskEntity> findAllByProjectId(Integer projectId);
Optional<TaskEntity> findByIdAndProjectId(Integer taskId, Integer projectId);
void deleteAllByProjectId(Integer projectId);
void deleteByIdAndProjectId(Integer taskId, Integer projectId);
}
|
package prog5황인호;
import java.util.Scanner;
/**
* 아래와 같은 모양의 삼각형을 그리는 프로그램.
* 삼각형의 크기는 사용자가 지정해 준다.
* *****
* ****
* ***
* **
* *
* @author 황인호
*
*/
public class Triangle3
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("삼각형을 그리는 프로그램입니다.");
System.out.print("삼각형의 크기를 얼마로 할까요? ");
int number = input.nextInt(); // 삼각형의 크기
for (int i = 1; i<=number; i++)
{
for (int j = 1; j<i; j++) // 앞의 빈공간
{
System.out.print(" ");
}
for (int k = number; i<=k; k--) // *문자
{
System.out.print('*');
}
System.out.println();
}
}
}
|
package com.joseph.beer.Controller;
import com.joseph.beer.domain.BeerEntry;
import com.joseph.beer.service.BeerService;
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.*;
import javax.validation.Valid;
@Controller
public class BeerWebController {
@Autowired
private BeerService beerService;
private static final String BEER_TEMPLATE = "beer";
private static final String ENTRIES_TEMPLATE_ID = "entries";
private static final String HOMEPAGE_REDIRECT = "redirect:/";
private static final String NEW_PAGE_TEMPLATE_ID = "newEntry";
private static final String BEER_FORM_HEADER_ID = "formHeader";
@GetMapping("/")
public String displayBeer (Model model) {
model.addAttribute(BEER_FORM_HEADER_ID, "Add A New Beer");
model.addAttribute(ENTRIES_TEMPLATE_ID, this.beerService.findAllEntries());
model.addAttribute("newEntry", new BeerEntry());
return BEER_TEMPLATE;
}
@GetMapping ("/delete/{id}")
public String deleteBeer (@PathVariable Integer id) {
this.beerService.deleteBeerEntryById (id);
return HOMEPAGE_REDIRECT;
}
@PostMapping ("/")
public String addBeer (Model model, @Valid @ModelAttribute (NEW_PAGE_TEMPLATE_ID) BeerEntry newEntry, BindingResult bindingResult) {
if (!bindingResult.hasErrors()) {
this.beerService.save(newEntry);
return HOMEPAGE_REDIRECT;
} else {
model.addAttribute(BEER_FORM_HEADER_ID, "Please Correct The Data");
model.addAttribute (ENTRIES_TEMPLATE_ID, this.beerService.findAllEntries());
return BEER_TEMPLATE;
}
}
@GetMapping ("update/{id}")
public String editBeer (Model model, @PathVariable Integer id) {
model.addAttribute(ENTRIES_TEMPLATE_ID, this.beerService.findAllEntries());
model.addAttribute(BEER_FORM_HEADER_ID, "Please Change the Data");
model.addAttribute(NEW_PAGE_TEMPLATE_ID, this.beerService.findOne(id));
return BEER_TEMPLATE;
}
@PostMapping ("update/{id}")
public String saveBeer (Model model, @PathVariable Integer id, @Valid @ModelAttribute (NEW_PAGE_TEMPLATE_ID) BeerEntry newEntry, BindingResult bindingResult) {
if (!bindingResult.hasErrors()) {
BeerEntry current = this.beerService.findOne(id);
current.setBeer(newEntry.getBeer());
current.setComment(newEntry.getComment());
current.setCountry(newEntry.getCountry());
current.setPercent(newEntry.getPercent());
current.setTime(newEntry.getTime());
this.beerService.save(current);
return HOMEPAGE_REDIRECT;
} else {
model.addAttribute(BEER_FORM_HEADER_ID, "Please Correct The Data");
model.addAttribute(ENTRIES_TEMPLATE_ID, this.beerService.findAllEntries());
return BEER_TEMPLATE;
}
}
}
|
package com.tencent.mm.ui.tools;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
class ShareScreenImgUI$2 implements OnCancelListener {
final /* synthetic */ ShareScreenImgUI uBX;
ShareScreenImgUI$2(ShareScreenImgUI shareScreenImgUI) {
this.uBX = shareScreenImgUI;
}
public final void onCancel(DialogInterface dialogInterface) {
}
}
|
package org.fuserleer.ledger.atoms;
import java.util.Objects;
import org.fuserleer.crypto.Hash;
import org.fuserleer.exceptions.ValidationException;
public class AtomNotFoundException extends ValidationException
{
/**
*
*/
private static final long serialVersionUID = 6964432881299046502L;
private final Hash atom;
public AtomNotFoundException(String message, Hash atom)
{
super(message);
Hash.notZero(atom, "Atom hash is ZERO");
this.atom = atom;
}
public AtomNotFoundException(Hash atom)
{
this("The atom "+Objects.requireNonNull(atom)+" is not found", atom);
}
public Hash getAtom()
{
return this.atom;
}
}
|
package com.tencent.mm.plugin.webview.model;
import com.tencent.mm.plugin.webview.modeltools.e;
import com.tencent.mm.protocal.c.ant;
import com.tencent.mm.protocal.c.apz;
import com.tencent.mm.sdk.platformtools.bi;
import java.util.LinkedList;
import java.util.List;
public final class f {
public int pRe;
public int pRf;
public int pRg;
public final List<apz> pRh;
public int pRi;
public long pRj;
/* synthetic */ f(byte b) {
this();
}
private f() {
this.pRe = 20480;
this.pRf = 30720;
this.pRg = 51200;
this.pRh = new LinkedList();
this.pRi = 0;
this.pRj = 0;
}
public static void cM(List<ant> list) {
if (!bi.cX(list)) {
for (ant ant : list) {
e.bUZ().pRc.s(Integer.valueOf(ant.rQv), Long.valueOf(bi.VE() + ((long) ant.rQw)));
}
e.bUZ().bTV();
}
}
}
|
package com.somethinglurks.jbargain.api;
import com.somethinglurks.jbargain.api.node.teaser.Teaser;
import java.util.List;
public interface Search {
Search sortBy(SortOption sortOption);
Search forumTopicOnly();
Search dealsOnly(boolean noExpired);
Search competitionsOnly();
List<Teaser> getResults();
enum SortOption {
RELEVANCE,
POST_DATE,
LAST_COMMENT
}
}
|
package com.tencent.tinker.loader;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.SystemClock;
import com.tencent.tinker.loader.app.TinkerApplication;
import com.tencent.tinker.loader.hotplug.ComponentHotplug;
import com.tencent.tinker.loader.shareutil.ShareIntentUtil;
import com.tencent.tinker.loader.shareutil.SharePatchFileUtil;
import com.tencent.tinker.loader.shareutil.SharePatchInfo;
import com.tencent.tinker.loader.shareutil.ShareSecurityCheck;
import com.tencent.tinker.loader.shareutil.ShareTinkerInternals;
import java.io.File;
public class TinkerLoader extends AbstractTinkerLoader {
private static final String TAG = "Tinker.TinkerLoader";
private SharePatchInfo patchInfo;
public Intent tryLoad(TinkerApplication tinkerApplication) {
Intent intent = new Intent();
long elapsedRealtime = SystemClock.elapsedRealtime();
tryLoadPatchFilesInternal(tinkerApplication, intent);
ShareIntentUtil.a(intent, SystemClock.elapsedRealtime() - elapsedRealtime);
return intent;
}
private void tryLoadPatchFilesInternal(TinkerApplication tinkerApplication, Intent intent) {
int tinkerFlags = tinkerApplication.getTinkerFlags();
if (!ShareTinkerInternals.In(tinkerFlags)) {
ShareIntentUtil.a(intent, -1);
} else if (ShareTinkerInternals.id(tinkerApplication)) {
ShareIntentUtil.a(intent, -1);
} else {
File hV = SharePatchFileUtil.hV(tinkerApplication);
if (hV == null) {
ShareIntentUtil.a(intent, -2);
return;
}
String absolutePath = hV.getAbsolutePath();
if (hV.exists()) {
File acT = SharePatchFileUtil.acT(absolutePath);
if (acT.exists()) {
File acU = SharePatchFileUtil.acU(absolutePath);
this.patchInfo = SharePatchInfo.n(acT, acU);
if (this.patchInfo == null) {
ShareIntentUtil.a(intent, -4);
return;
}
String str = this.patchInfo.vvF;
String str2 = this.patchInfo.vvG;
String str3 = this.patchInfo.vsJ;
if (str == null || str2 == null || str3 == null) {
ShareIntentUtil.a(intent, -4);
return;
}
intent.putExtra("intent_patch_old_version", str);
intent.putExtra("intent_patch_new_version", str2);
boolean ic = ShareTinkerInternals.ic(tinkerApplication);
Object obj = !str.equals(str2) ? 1 : null;
Object obj2 = (str3.equals("changing") && ic) ? 1 : null;
str3 = ShareTinkerInternals.bS(tinkerApplication, str3);
intent.putExtra("intent_patch_oat_dir", str3);
if (obj == null || !ic) {
str2 = str;
}
if (ShareTinkerInternals.oW(str2)) {
ShareIntentUtil.a(intent, -5);
return;
}
str = SharePatchFileUtil.acV(str2);
if (str == null) {
ShareIntentUtil.a(intent, -6);
return;
}
absolutePath = absolutePath + "/" + str;
File file = new File(absolutePath);
if (file.exists()) {
String acW = SharePatchFileUtil.acW(str2);
File file2 = acW != null ? new File(file.getAbsolutePath(), acW) : null;
if (SharePatchFileUtil.ah(file2)) {
ShareSecurityCheck shareSecurityCheck = new ShareSecurityCheck(tinkerApplication);
int a = ShareTinkerInternals.a(tinkerApplication, tinkerFlags, file2, shareSecurityCheck);
if (a != 0) {
intent.putExtra("intent_patch_package_patch_check", a);
ShareIntentUtil.a(intent, -8);
return;
}
intent.putExtra("intent_patch_package_config", shareSecurityCheck.cHd());
boolean Ij = ShareTinkerInternals.Ij(tinkerFlags);
if (Ij && !TinkerDexLoader.a(absolutePath, shareSecurityCheck, str3, intent)) {
return;
}
if (!ShareTinkerInternals.Ik(tinkerFlags) || TinkerSoLoader.a(absolutePath, shareSecurityCheck, intent)) {
boolean Il = ShareTinkerInternals.Il(tinkerFlags);
if (!Il || TinkerResourceLoader.a(tinkerApplication, absolutePath, shareSecurityCheck, intent)) {
boolean z = ShareTinkerInternals.cHe() && ShareTinkerInternals.acZ(this.patchInfo.vvH) && VERSION.SDK_INT >= 21 && !ShareTinkerInternals.cHg();
intent.putExtra("intent_patch_system_ota", z);
if ((ic && obj != null) || obj2 != null) {
this.patchInfo.vvF = str2;
this.patchInfo.vsJ = str3;
if (!SharePatchInfo.a(acT, this.patchInfo, acU)) {
ShareIntentUtil.a(intent, -19);
return;
} else if (obj2 != null) {
SharePatchFileUtil.co(absolutePath + "/interpet");
}
}
if (checkSafeModeCount(tinkerApplication)) {
if (Ij) {
boolean a2 = TinkerDexLoader.a(tinkerApplication, absolutePath, str3, intent, z);
if (z) {
this.patchInfo.vvH = Build.FINGERPRINT;
this.patchInfo.vsJ = a2 ? "interpet" : "odex";
obj2 = null;
if (SharePatchInfo.a(acT, this.patchInfo, acU)) {
intent.putExtra("intent_patch_oat_dir", this.patchInfo.vsJ);
} else {
ShareIntentUtil.a(intent, -19);
return;
}
}
if (!a2) {
return;
}
}
if (!Il || TinkerResourceLoader.a(tinkerApplication, absolutePath, intent)) {
if (Ij && Il) {
ComponentHotplug.a(tinkerApplication, shareSecurityCheck);
}
if (obj2 != null) {
ShareTinkerInternals.ie(tinkerApplication);
}
ShareIntentUtil.a(intent, 0);
return;
}
return;
}
intent.putExtra("intent_patch_exception", new TinkerRuntimeException("checkSafeModeCount fail"));
ShareIntentUtil.a(intent, -25);
return;
}
return;
}
return;
}
ShareIntentUtil.a(intent, -7);
return;
}
ShareIntentUtil.a(intent, -6);
return;
}
new StringBuilder("tryLoadPatchFiles:patch info not exist:").append(acT.getAbsolutePath());
ShareIntentUtil.a(intent, -3);
return;
}
ShareIntentUtil.a(intent, -2);
}
}
private boolean checkSafeModeCount(TinkerApplication tinkerApplication) {
String str = "tinker_own_config_" + ShareTinkerInternals.aC(tinkerApplication);
SharedPreferences sharedPreferences = tinkerApplication.getSharedPreferences(str, 0);
int i = sharedPreferences.getInt("safe_mode_count", 0) + 1;
new StringBuilder("tinker safe mode preferName:").append(str).append(" count:").append(i);
if (i >= 3) {
sharedPreferences.edit().putInt("safe_mode_count", 0).commit();
return false;
}
tinkerApplication.setUseSafeMode(true);
sharedPreferences.edit().putInt("safe_mode_count", i).commit();
return true;
}
}
|
package com.jk.jkproject.ui.entity;
import android.os.Parcel;
import android.os.Parcelable;
import androidx.annotation.NonNull;
import com.jk.jkproject.utils.GsonUtils;
public class LiveGiftInfo implements Parcelable, Comparable {
public static final Creator<LiveGiftInfo> CREATOR = new Creator<LiveGiftInfo>() {
@Override
public LiveGiftInfo createFromParcel(Parcel in) {
return new LiveGiftInfo(in);
}
@Override
public LiveGiftInfo[] newArray(int size) {
return new LiveGiftInfo[size];
}
};
public int giftID; // 礼物id
public int price; // 礼物价格
public int type; // 礼物类型
public String icon; // 礼物名称
public String animateType; // 礼物动画
public String image; // 礼物图片网络资源
public String avatarPath = ""; // 本地图片地址
public String name; // 礼物名称
public String desc; // 礼物说明
public String intro; // 中奖倍数
public int state; // 礼物状态 0:隐藏 1:正常 2:禁用
public int remain_num; // 剩余免费次数
public int remain_ttl; // 剩余倒计时 -1:不改变 0:不显示
public int give_number=1; //赠送数量
public boolean select_item = false; //选中item
public int select_position; //选中礼物的位置
public String select_tab = "shop";//选中的tab的位置
public Long lastTime = 0L; //点击送礼最后的时间
public LiveGiftInfo() {
}
protected LiveGiftInfo(Parcel in) {
giftID = in.readInt();
price = in.readInt();
type = in.readInt();
icon = in.readString();
animateType = in.readString();
image = in.readString();
name = in.readString();
desc = in.readString();
state = in.readInt();
remain_num = in.readInt();
remain_ttl = in.readInt();
give_number = in.readInt();
select_item = in.readByte() != 0;
select_position = in.readInt();
lastTime = in.readLong();
select_tab = in.readString();
intro = in.readString();
avatarPath = in.readString();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(giftID);
dest.writeInt(price);
dest.writeInt(type);
dest.writeString(icon);
dest.writeString(animateType);
dest.writeString(image);
dest.writeString(name);
dest.writeInt(state);
dest.writeInt(remain_num);
dest.writeInt(remain_ttl);
dest.writeInt(give_number);
dest.writeByte(select_item ? (byte) 1 : (byte) 0);
dest.writeInt(select_position);
dest.writeLong(lastTime);
dest.writeString(select_tab);
dest.writeString(intro);
dest.writeString(avatarPath);
}
@Override
public int describeContents() {
return 0;
}
@Override
public String toString() {
return GsonUtils.get().toJson(this);
}
@Override
public int compareTo(@NonNull Object o) {
if (this == o) {
return 0;
}
if (o == null || getClass() != o.getClass()) {
return 1;
}
LiveGiftInfo liveGiftInfo = (LiveGiftInfo) o;
if (liveGiftInfo.giftID != this.giftID) {
return 1;
}
if (liveGiftInfo.type != this.type) {
return 1;
}
if (!liveGiftInfo.name.equals(this.name)) {
return 1;
}if (liveGiftInfo.remain_num != this.remain_num) {
return 1;
}if (liveGiftInfo.remain_ttl != this.remain_ttl) {
return 1;
}
return 0;
}
}
|
package fr.jmini.htmlchecker.cli;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import com.google.common.base.Charsets;
import com.google.common.io.Resources;
import com.selesse.jxlint.cli.CommandLineOptions;
import fr.jmini.htmlchecker.settings.HtmlCheckerProgramSettings;
public class MainTest {
@Test
public void testHelpMessage() throws Exception {
String helpMessage = CommandLineOptions.getHelpMessage(new HtmlCheckerProgramSettings());
String expected = Resources.toString(Resources.getResource("htmlchecker-help.txt"), Charsets.UTF_8);
assertThat(normalizeLineEnds(helpMessage)).isEqualTo(normalizeLineEnds(expected));
}
private static String normalizeLineEnds(String s) {
return s.replace("\r\n", "\n").replace('\r', '\n');
}
}
|
package Algorithm;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Stack;
//请根据每日 气温 列表,重新生成一个列表。对应位置的输出为:要想观测到更高的气温,至少需要等待的天数。如果气温在这之后都不会升高,请在该位置用 0 来代替。
public class a739 {
public int[] dailyTemperatures(int[] T) {
Stack<Integer> stack =new Stack<>();
int[] res= new int[T.length];
for (int i=0;i<T.length;i++){
if (stack.isEmpty()){
stack.add(i);
continue;
}
while (!stack.isEmpty()&&T[i]>T[stack.peek()]){
int out=stack.pop();
res[out]=i-out;
}
stack.add(i);
}
return res;
}
}
|
package User;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public abstract class Account {
protected float Amount;
protected String Account_id;
protected String Pname;
protected String Branch;
protected char Status;
private ArrayList<Transaction> tlist;
protected float initial;
final String JDBC_DRIVER = "oracle.jdbc.driver.OracleDriver";
final String DB_URL = "jdbc:oracle:thin:@cloud-34-133.eci.ucsb.edu:1521:XE";
final String USERNAME = "fliang";
final String PASSWORD = "123455";
Connection conn = null;
Statement stmt = null;
Account(){
this.Amount = 0;
this.Account_id = "";
this.Pname = "";
this.Branch = "";
this.Status = '1';
}
Account(String Account_id, String TaxID, float Amount, String Branch, char status){
this.Amount = Amount;
this.Account_id = Account_id;
this.Pname = TaxID;
this.Branch = Branch;
this.Status = status;
this.initial = initial;
tlist = new ArrayList<Transaction>();
try {
// STEP 2: Register JDBC driver
Class.forName(JDBC_DRIVER);
// STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD);
System.out.println("Connected database successfully...");
// STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String query = "SELECT * FROM Record_Transaction T WHERE T.Aid_1 = '"+Account_id+"'"+" UNION "+" SELECT * FROM Record_Transaction T WHERE T.Aid_2 = '"+Account_id+"'";
PreparedStatement accountQuery = conn.prepareStatement(query);
ResultSet rs = accountQuery.executeQuery();
while(rs.next()) {
String tid = rs.getString("Tid");
String date = rs.getString("TransactionDate");
String aid1 = rs.getString("Aid_1");
String aid2 = rs.getString("Aid_2");
String type = rs.getString("TypeTransaction");
float num = rs.getFloat("Amount");
tlist.add(new Transaction(tid, date,aid1, aid2,type,num));
}
query = "SELECT I.Amount FROM Account A, initialAmount I WHERE A.Aid = I.Aid AND A.Aid = '"+Account_id+"'";
accountQuery = conn.prepareStatement(query);
rs = accountQuery.executeQuery();
if(rs.next()) {
this.initial = rs.getFloat("Amount");
}
} catch (SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
} catch (Exception ea) {
// Handle errors for Class.forName
ea.printStackTrace();
} finally {
// finally block used to close resources
try {
if (stmt != null)
conn.close();
} catch (SQLException se) {
} // do nothing
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} // end finally try
}
}
public float getAmount() {
return this.Amount;
}
public ArrayList<Transaction> getList(){
return tlist;
}
public String getAccount() {
return this.Account_id;
}
public String getPname() {
return this.Pname;
}
public String getBranch() {
return this.Branch;
}
public char getStatus() {
return this.Status;
}
public void setAmount(float Amount) {
this.Amount = Amount;
}
public void setAccount(String Account_id) {
this.Account_id = Account_id;
}
public void setPname(String Pname) {
this.Pname = Pname;
}
public void setBranch(String Branch) {
this.Branch = Branch;
}
public void setStatus(char Status) {
this.Status = Status;
}
public float getInitial(){
return initial;
}
}
|
package webdriver.screen.cloud.exception;
public class ElementNotEnabledException extends Exception {
public ElementNotEnabledException() {
}
public ElementNotEnabledException(String message) {
super(message);
}
public ElementNotEnabledException(String message, Throwable cause) {
super(message, cause);
}
public ElementNotEnabledException(Throwable cause) {
super(cause);
}
}
|
package com.bw.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.bw.base.service.RegistService;
import com.bw.base.util.ResultJSON;
@Controller
public class RegistController {
@Autowired
private RegistService registService;
@RequestMapping("/checkUsername")
@ResponseBody
public ResultJSON checkUsername(String username){
ResultJSON rs=registService.checkUsername(username);
return rs;
}
/***
* 注册
* @param username
* @param password
* @return
*/
@RequestMapping("/register")
@ResponseBody
public ResultJSON register(String username,String password) {
//1.调用service,保存用户名和密码
ResultJSON rs = registService.register(username,password);
//2.返回成功注册信息
return rs;
}
}
|
package org.example;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import org.assertj.core.api.SoftAssertions;
import org.example.api.AuthApi;
import org.example.model.AuthRequest;
import org.example.model.AuthResponse;
import org.junit.jupiter.api.*;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;
import java.io.IOException;
import static org.apache.http.HttpStatus.*;
import static org.assertj.core.api.Assertions.assertThat;
class AuthenticateTests {
@Test
void shouldGetToken() throws IOException {
AuthRequest authRequest = new AuthRequest()
.password("u7ljdajLNo7PsVw7")
.username("admin")
.rememberMe(true);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(JacksonConverterFactory.create())
.baseUrl("http://31.131.249.140:8080/")
.client(httpClient.build())
.build();
AuthApi authApi = retrofit.create(AuthApi.class);
Response<AuthResponse> call = authApi.authenticate(authRequest).execute();
assertThat(call.code()).isEqualTo(SC_OK);
assertThat(call.body()).isNotNull();
SoftAssertions.assertSoftly(softly -> {
assertThat(call.body().getIdToken()).isNotEmpty();
assertThat(call.body().getAdditionalProperties()).isEmpty();
});
}
}
|
package org.usfirst.frc.team1165.robot.commands.auto;
import edu.wpi.first.wpilibj.command.CommandGroup;
/**
*
*/
public class CrossAutoLineCenter extends CommandGroup
{
public CrossAutoLineCenter()
{
addSequential(new DriveStraightSpeed(0.75, 0), 1.65);
}
}
|
package com.xiaoxiao.search.service.impl;
import com.xiaoxiao.pojo.vo.XiaoxiaoArticleVo;
import com.xiaoxiao.search.mapper.SearchArticleMapper;
import com.xiaoxiao.search.pojo.SolrArticleDocument;
import com.xiaoxiao.search.service.ArticleSolrService;
import com.xiaoxiao.utils.Result;
import com.xiaoxiao.utils.StatusCode;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.CollectionParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.solr.core.SolrTemplate;
import org.springframework.data.solr.core.query.*;
import org.springframework.data.solr.core.query.result.HighlightEntry;
import org.springframework.data.solr.core.query.result.HighlightPage;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* _ooOoo_
* o8888888o
* 88" . "88
* (| -_- |)
* O\ = /O
* ____/`---'\____
* .' \\| |// `.
* / \\||| : |||// \
* / _||||| -:- |||||- \
* | | \\\ - /// | |
* | \_| ''\---/'' | |
* \ .-\__ `-` ___/-. /
* ___`. .' /--.--\ `. . __
* ."" '< `.___\_<|>_/___.' >'"".
* | | : `- \`.;`\ _ /`;.`/ - ` : | |
* \ \ `-. \_ __\ /__ _/ .-` / /
* ======`-.____`-.___\_____/___.-`____.-'======
* `=---='
* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* 佛祖保佑 永无BUG
* 佛曰:
* 写字楼里写字间,写字间里程序员;
* 程序人员写程序,又拿程序换酒钱。
* 酒醒只在网上坐,酒醉还来网下眠;
* 酒醉酒醒日复日,网上网下年复年。
* 但愿老死电脑间,不愿鞠躬老板前;
* 奔驰宝马贵者趣,公交自行程序员。
* 别人笑我忒疯癫,我笑自己命太贱;
* 不见满街漂亮妹,哪个归得程序员?
*
* @project_name:xiaoxiao_final_blogs
* @date:2019/12/13:14:00
* @author:shinelon
* @Describe:
*/
@Service
public class ArticleSolrServiceImpl implements ArticleSolrService
{
@Autowired
private SearchArticleMapper articleMapper;
@Autowired
private SolrTemplate solrTemplate;
/**
* 核心库
*/
@Value("${spring.data.core}")
private String core;
@Override
public Result importArticleToSolr()
{
List<XiaoxiaoArticleVo> allArticle = this.articleMapper.findAllArticle();
try
{
insertToSolr(allArticle);
return Result.ok(StatusCode.OK,Result.MARKED_WORDS_SUCCESS);
} catch (Exception e)
{
e.printStackTrace();
}
return Result.error(StatusCode.ERROR, Result.MARKED_WORDS_FAULT);
}
public void insertToSolr(List<XiaoxiaoArticleVo> list){
try
{
for (XiaoxiaoArticleVo x:list
)
{
SolrInputDocument document = new SolrInputDocument();
document.setField("article_id", x.getArticleId());
document.setField("user_id", x.getUserId());
document.setField("article_views", x.getArticleViews());
document.setField("article_comment_count", x.getArticleCommentCount());
document.setField("article_date", x.getArticleDate());
document.setField("article_like_count", x.getArticleLikeCount());
document.setField("article_bk_sorts_id", x.getArticleBkSortsId());
document.setField("article_bk_first_img", x.getArticleBkFirstImg());
document.setField("article_recommend", x.getArticleRecommend());
document.setField("user_profile_photo", x.getUserProfilePhoto());
document.setField("user_nickname", x.getUserNickname());
document.setField("article_title", x.getArticleTitle());
document.setField("article_desc", x.getArticleDesc());
document.setField("article_type", x.getArticleType());
this.solrTemplate.saveDocument(core, document).wait(10000);
}
} catch (Exception e)
{
e.printStackTrace();
}
}
@Override
@SuppressWarnings("all")
public Result searchArticle(String q, Long page, Integer rows)
{
//设置高亮查询条件
try
{
HighlightQuery query = new SimpleHighlightQuery();
//设置检索域
Criteria criteria = new Criteria("item_keywords");
criteria.is(q); //放入查询关键字
query.addCriteria(criteria);
//设置高亮属性
HighlightOptions highlightOptions = new HighlightOptions();
highlightOptions.addField("article_title");//设置高亮显示的域
highlightOptions.setSimplePrefix("<em style='color:red'>");//设置高亮的样式的前缀
highlightOptions.setSimplePostfix("</em>");
query.setHighlightOptions(highlightOptions);
//分页
query.setOffset((page -1) * rows);
query.setRows(rows);
//设置高亮设置
HighlightPage<SolrArticleDocument> highlightPage = this.solrTemplate.queryForHighlightPage(this.core, query, SolrArticleDocument.class);
List<HighlightEntry<SolrArticleDocument>> highlighted = highlightPage.getHighlighted();
for (HighlightEntry<SolrArticleDocument> tbItemHighlightEntry : highlighted)
{
SolrArticleDocument entity = tbItemHighlightEntry.getEntity();//实体对象,原始的实体对象
List<HighlightEntry.Highlight> highlights = tbItemHighlightEntry.getHighlights();
//如果有高亮,就取高亮 主要的方法是getSnipplets用于获取高亮数据
if (highlights != null && highlights.size() > 0 && highlights.get(0).getSnipplets().size() > 0)
{
//将高亮数据设置的到实体列
entity.setArticle_title(highlights.get(0).getSnipplets().get(0));
}
}
//返回数据
List<SolrArticleDocument> list = highlightPage.getContent();
return Result.ok(StatusCode.OK,true,Result.MARKED_WORDS_SUCCESS,list);
} catch (Exception e)
{
e.printStackTrace();
}
return Result.error(StatusCode.ERROR, Result.MARKED_WORDS_FAULT);
}
@Override
public void insertArticleToSolr(Long articleId) throws Exception
{
List<XiaoxiaoArticleVo> articleById = this.articleMapper.findArticleById(articleId);
insertToSolr(articleById);
this.solrTemplate.commit(this.core);
}
@Override
public void deleteArticleToSolr(Long articleId) throws Exception
{
Criteria criteria = new Criteria("article_id");
criteria.is(articleId);
this.solrTemplate.delete(this.core,new SimpleQuery(criteria));
this.solrTemplate.commit(this.core);
}
}
|
/**
* Establishes the Triangle class and constructor!
*
* @author C. Thurston
* @version 5/1/2014
*/
public class Triangle extends IsoscelesTriangle
{
private double sideC;
/**
* Constructor for objects of class Triangle
*/
public Triangle(double A, double B, double C)
{
super(A,B);
this.sideC = C;
}
public double getC()
{
return sideC;
}
}
|
package com.tencent.mm.plugin.appbrand.dynamic.g;
class a$1 implements Runnable {
final /* synthetic */ a fxp;
public a$1(a aVar) {
this.fxp = aVar;
}
public final void run() {
this.fxp.KM();
}
}
|
package org.team3128.redobot.subsystems;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.kauailabs.navx.frc.AHRS;
import org.team3128.common.NarwhalRobot;
import org.team3128.common.control.trajectory.Trajectory;
import org.team3128.common.drive.DriveCommandRunning;
import org.team3128.common.utility.units.Angle;
import org.team3128.common.utility.units.Length;
import org.team3128.redobot.subsystems.FalconDrive;
import org.team3128.common.utility.Log;
import org.team3128.common.listener.ListenerManager;
import org.team3128.common.listener.controllers.ControllerExtreme3D;
import org.team3128.common.listener.controltypes.Button;
import org.team3128.common.listener.controltypes.POV;
import org.team3128.common.narwhaldashboard.NarwhalDashboard;
import org.team3128.common.hardware.misc.Piston;
import org.team3128.common.hardware.motor.LazyCANSparkMax;
import org.team3128.common.utility.units.Length;
import com.revrobotics.CANSparkMaxLowLevel.MotorType;
import com.revrobotics.CANEncoder;
import edu.wpi.first.wpilibj.DriverStation;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.PowerDistributionPanel;
import edu.wpi.first.wpilibj.RobotBase;
import edu.wpi.first.wpilibj.RobotController;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import edu.wpi.first.wpilibj.DigitalInput;
import org.team3128.common.generics.ThreadScheduler;
import org.team3128.common.generics.Threaded;
public class Claw extends Threaded {
public static final Claw instance = new Claw();
Piston pushPiston;
boolean isPushing = false;
boolean isDone = false;
double passedTime;
private Claw() {
configPistons();
}
public static Claw getInstance() {
return instance;
}
private void configPistons() {
pushPiston = new Piston(1, 2);
pushPiston.setPistonOff();
}
public void Push() {
isPushing = true;
isDone = false;
}
public void Retract() {
isPushing = false;
isDone = false;
}
public void update() {
if(isPushing && !isDone) {
pushPiston.setPistonOn();
isDone = true;
} else if(!isPushing && !isDone) {
pushPiston.setPistonOff();
isDone = true;
}
}
}
|
package genscript.types;
import genscript.parse.SearchGraph;
import scriptinterface.ScriptComplexType;
import scriptinterface.ScriptSystemInterface;
import scriptinterface.ScriptType;
import scriptinterface.TypeCast;
import scriptinterface.defaulttypes.GComplexType;
import scriptinterface.defaulttypes.GVector;
import scriptinterface.execution.returnvalues.ExecutionResult;
import java.util.ArrayList;
import java.util.HashMap;
public abstract class DefaultTypeSystem {
protected ArrayList<ScriptType> scriptTypes;
protected HashMap<String, ScriptComplexType> complexTypeMap;
protected HashMap<String, ScriptType> typeMap;
private SearchGraph casts;
public DefaultTypeSystem() {
scriptTypes = new ArrayList<>(64);
scriptTypes.add(new ScriptType("ComplexType", "Complex"));
complexTypeMap = new HashMap<>(128);
typeMap = new HashMap<>(128);
casts = new SearchGraph();
casts.setName("Casts");
}
public ScriptType getScriptType(String typeName) {
return typeMap.get(typeName.toUpperCase());
}
public ScriptType getScriptType(int typeId) {
return scriptTypes.get(typeId);
}
public int getTypeCount() {
return scriptTypes.size();
}
public Iterable<ScriptType> getScriptTypes() {
return this.scriptTypes;
}
public void clearTypes() {
scriptTypes.clear();
}
public boolean checkExecutionTypeExistence(ScriptType executionType) {
ScriptType pre = typeMap.get(executionType.getName().toUpperCase());
return (pre != null && pre != executionType);
}
public void registerType(ScriptType executionType) {
if (executionType == null) return;
if (checkExecutionTypeExistence(executionType))
throw new RuntimeException("Type name already set for another type.");
typeMap.put(executionType.getName().toUpperCase(), executionType);
executionType.setId(scriptTypes.size());
scriptTypes.add(executionType);
}
public void registerType(Class<? extends ExecutionResult<?>> instanceClass) {
try {
registerType(instanceClass.newInstance().getType());
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
public void registerComplexType(ScriptComplexType complexType) {
String typeName = complexType.getComplexName().toUpperCase();
if (typeMap.get(typeName) != null) throw new RuntimeException("Type name already set.");
complexTypeMap.put(typeName, complexType);
typeMap.put(typeName, complexType);
}
public ScriptComplexType getComplexType(String typeName) {
return complexTypeMap.get(typeName.toUpperCase());
}
public void registerSynonym(String original, String synonym) {
ScriptType pre = typeMap.get(original.toUpperCase());
if (pre == null) throw new RuntimeException("Type not found: " + original);
typeMap.put(synonym.toUpperCase(), pre);
}
public void registerSynonym(ScriptType original, String synonym) {
registerSynonym(original.getName(), synonym);
}
public void registerSynonym(Class<? extends ExecutionResult<?>> original, String synonym) {
try {
registerSynonym(original.newInstance().getType(), synonym);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
//TYPECASTS
public TypeCast<?, ?> getTypeCast(ScriptType fromType, ScriptType toType) {
SearchGraph.Node node = casts.getRoot().getChild(fromType.getId());
if (node == null) return null;
node = node.getChild(toType.getId());
if (node == null) return null;
return (TypeCast<?, ?>) node.getValue();
}
@SuppressWarnings({"unchecked", "rawtypes"})
public ExecutionResult<?> cast(ExecutionResult<?> value, ScriptType toType) {
if ((value instanceof GVector) && toType.isComplex()) {
return new GComplexType((ScriptComplexType) toType, ((GVector) value).getValue());
} else {
ScriptType valueType = value.getType();
if (valueType == toType || toType == ScriptSystemInterface.ANY) return value;
TypeCast typeCast = getTypeCast(valueType, toType);
if (typeCast == null) return null;
else return typeCast.cast(value);
}
}
public void putTypeCast(ScriptType fromType, ScriptType toType, TypeCast<?, ?> typeCast) {
TypeCast<?, ?> pre = getTypeCast(fromType, toType);
if (pre != null) {
if (pre.getClass() == typeCast.getClass()) return;
else throw new RuntimeException("TypeCast already set");
}
casts.getRoot().insert(fromType.getId()).insert(toType.getId()).setValue(typeCast);
}
public void putTypeCast(String fromType, String toType, TypeCast<?, ?> typeCast) {
putTypeCast(getScriptType(fromType), getScriptType(toType), typeCast);
}
public void putTypeCast(String[] fromTypes, String toType, TypeCast<?, ?> typeCast) {
for (String fromType : fromTypes)
putTypeCast(getScriptType(fromType), getScriptType(toType), typeCast);
}
public void putTypeCast(String fromType, String[] toTypes, TypeCast<?, ?> typeCast) {
for (String toType : toTypes)
putTypeCast(getScriptType(fromType), getScriptType(toType), typeCast);
}
}
|
package com;
import java.util.Scanner;
/**
* 十进制数转为任意进制数(考虑了小数点)
*
* @author walkerwang
*
*/
public class DecimalToNbinary {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(scanner.hasNextLine()){
String string = scanner.nextLine();
String[] strs = string.split(" ");
double input = Double.valueOf(strs[0]);
int n = Integer.valueOf(strs[1]);
System.out.println(decimal2Binary(input, n));
}
}
public static String decimal2Binary(double value, int n){
int in = (int) value;
double r = value - in;
StringBuilder stringBuilder = new StringBuilder();
int remainder = 0;
int quotient = 0;
while (in != 0) {
quotient = in / n;
remainder = in % n;
stringBuilder.append(remainder);
in = quotient;
}
stringBuilder.reverse();
stringBuilder.append(".");
// 将小数部分转化为二进制
int count = 32; // 限制小数部分位数最多为32位,如果超过32为则抛出异常
double num = 0;
while (r > 0.0000000001) {
count--;
if (count == 0) {
}
num = r * n;
if (num >= 1) {
stringBuilder.append(1);
r = num - 1;
} else {
stringBuilder.append(0);
r = num;
}
}
String res = String.valueOf(value);
if (res.substring(res.length()-1) == "0" ) {
return stringBuilder.toString();
}else {
return stringBuilder.toString().substring(0,stringBuilder.toString().length()-1);
}
}
}
|
package com.tencent.mm.ui.chatting.f;
import com.tencent.mm.R;
import com.tencent.mm.model.au;
import com.tencent.mm.model.c;
import com.tencent.mm.modelsimple.t;
import com.tencent.mm.sdk.platformtools.ad;
import com.tencent.mm.sdk.platformtools.x;
class a$1 implements Runnable {
final /* synthetic */ a tXT;
a$1(a aVar) {
this.tXT = aVar;
}
public final void run() {
this.tXT.bXQ.setType(10002);
t.a(ad.getContext().getString(R.l.chatting_revoke_msg_tips), "", this.tXT.bXQ, "");
au.HU();
c.FT().a(this.tXT.bXQ.field_msgId, this.tXT.bXQ);
x.i("MicroMsg.InvokeMessageNewXmlMsg", "checkExpired:%s", new Object[]{Long.valueOf(this.tXT.bXQ.field_msgId)});
}
}
|
package com.decrypt.beeglejobsearch.di.scopes;
//@Scope
//@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE)
//public @interface Screen {
// int value();
//}
|
package com.xrigau.droidcon.espresso.presentation;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.widget.TextView;
import com.xrigau.droidcon.espresso.R;
import static com.xrigau.droidcon.espresso.presentation.WorldDestructionCountdown.COUNTDOWN_FINISHED;
import static com.xrigau.droidcon.espresso.presentation.WorldDestructionCountdown.COUNTDOWN_STARTED;
import static com.xrigau.droidcon.espresso.presentation.WorldDestructionCountdown.COUNTDOWN_UPDATED;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
public class IdlingResourceActivity extends Activity {
private TextView timer;
private WorldDestructionCountdown countdown = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_idling_resource);
findViews();
Handler handler = makeHandler();
setCountdown(new WorldDestructionCountdown(handler));
}
private void findViews() {
timer = (TextView) findViewById(R.id.timer);
}
Handler makeHandler() {
return new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case COUNTDOWN_STARTED:
onStartCountdown();
break;
case COUNTDOWN_UPDATED:
onUpdate(msg.arg1);
break;
case COUNTDOWN_FINISHED:
onEndCountdown();
break;
}
}
};
}
private void onStartCountdown() {
timer.setText(getString(R.string.countdown_started));
}
private void onUpdate(long remainingMs) {
timer.setText(getString(R.string.countdown_update, (int) SECONDS.convert(remainingMs, MILLISECONDS)));
}
private void onEndCountdown() {
timer.setText(getString(R.string.countdown_finished));
}
public void setCountdown(WorldDestructionCountdown countdown) {
cancelPreviousCountdownIfExists();
this.countdown = countdown;
startCountdown();
}
private void cancelPreviousCountdownIfExists() {
if (this.countdown != null) {
this.countdown.stop();
}
}
private void startCountdown() {
countdown.startCounting();
}
}
|
package com.sudipatcp.stacknqueue;
import java.util.Stack;
public class DesignMinStack {
private Stack<Integer> stack;
private int min;
public DesignMinStack() {
stack = new Stack<>();
min = Integer.MAX_VALUE;
}
public void push(int x) {
if(x < min){
min = x;
}
stack.push(x);
}
public void pop() {
if(!stack.isEmpty()){
int key = stack.pop();
if(key == min){
min = Integer.MAX_VALUE;
Stack<Integer> tempStack = new Stack<>();
while(!stack.isEmpty()){
int val = stack.pop();
if(val <= min){
min = val;
}
tempStack.push(val);
}
while(!tempStack.isEmpty()){
stack.push(tempStack.pop());
}
}
}
}
public int top() {
if(stack.isEmpty()){
return -1;
}
return stack.peek();
}
public int getMin() {
if(stack.isEmpty()){
return -1;
}else{
return min;
}
}
public static void main(String[] args) {
DesignMinStack minStack = new DesignMinStack();
minStack.push(19);
minStack.push(10);
minStack.push(9);
System.out.println(minStack.getMin());
minStack.pop();
System.out.println(minStack.getMin());
minStack.push(8);
System.out.println(minStack.getMin());
minStack.push(7);
}
}
|
package com.actitime.excelsheets;
import org.testng.Reporter;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class DemoTest
{
@Parameters({"city","area"})
@Test
public void testA(String city,String area)
{
Reporter.log(city,true);
Reporter.log(area,true);
}
}
|
/*
* 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 quicksort;
/**
*
* @author maikol
*/
//herncia de la clase Molde
public class Peine extends Molde {
//contrcutor
public Peine(int numero, String nombre) {
//reutilizar el constructor de la clase padre
super(numero, nombre);
}
// metodo de ordenacion que recibe el array a ordenar
public int[] ordenar(int[] array) {
//se define la variable i y j con el tamaño del array
int i = 0;
int j = array.length - 1;
//se valida si j > 1 para que el repita el ciclo de ordenacion del array
while (j > 1) {
//se disminulle la variable j--;
j--;
//if para que recorra todo el array sin problema
if (j < 1) {
j = 1;
}
//ciclo for que nos permitira evaluar el array dependiendo su posicion
for (int k = 0; k < array.length - j; k++) {
/*al recorrer el ciclo se evalua cada vez el array[k] es mAyor para
ordenar el array de menor a mayor xd
*/
if (array[k] > array[k + j]) {
int tem = array[k];
array[k] = array[k + j];
array[k + j] = tem;
}
}
}
//se retorna el array ordenado
return array;
}
}
|
package com.ljw.util;
import java.util.LinkedList;
import java.util.List;
/**
* @Description:
* @Author Created by liangjunwei on 2018/8/2 17:09
*/
public class TitleUtil {
private static List<String> getGoodsBaseInfoStrList(){
List<String> list = new LinkedList<String>();
list.add("商品名称");
list.add("图片地址");
list.add("库存");
list.add("售价");
list.add("商品单位");
list.add("是否热销(0:否;1:是)");
list.add("品牌分类编号");
list.add("纯度编号");
list.add("地域");
list.add("排序(Num降序)");
list.add("CAS");
list.add("自定义属性");
list.add("SEO优化-标题");
list.add("SEO优化-关键字");
list.add("SEO优化-描述");
return list;
}
public static List<String> getGoodsChemAttributeList(){
List<String> goodsInfoStrList = getGoodsBaseInfoStrList();
goodsInfoStrList.add("规格");
goodsInfoStrList.add("货期(时间格式)");
goodsInfoStrList.add("仓库");
goodsInfoStrList.add("品牌商户号");
goodsInfoStrList.add("分子量");
goodsInfoStrList.add("精确量");
goodsInfoStrList.add("化学商品种类编号");
return goodsInfoStrList;
}
public static List<String> getChemClassList(){
List<String> chemClassList = new LinkedList<String>();
chemClassList.add("二级栏目编号");
chemClassList.add("名称");
chemClassList.add("中文别名");
chemClassList.add("英文名称");
chemClassList.add("图片");
chemClassList.add("CAS号");
chemClassList.add("分子式");
chemClassList.add("是否热销(0:否;1:是)");
chemClassList.add("排序(越大越靠前)");
chemClassList.add("第一属性(品牌分类)编号集");
chemClassList.add("第二属性(纯度)编号集");
chemClassList.add("SEO优化-标题");
chemClassList.add("SEO优化-关键字");
chemClassList.add("SEO优化-描述");
return chemClassList;
}
}
|
package com.bbyopen.mongodb;
import java.net.UnknownHostException;
import org.json.simple.JSONValue;
import org.netkernel.layer0.nkf.INKFRequestContext;
import org.netkernel.layer0.nkf.INKFResponse;
import org.netkernel.module.standard.endpoint.StandardAccessorImpl;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
public class MongoDB extends StandardAccessorImpl {
public MongoDB(){
this.declareThreadSafe();
}
@Override
public void onSource(INKFRequestContext context) throws Exception{
String dbserver = context.source("arg:dbserver", String.class);
String dbname = context.source("arg:dbname", String.class);
String collection = context.source("arg:collection", String.class);
String action = context.source("arg:action", String.class);
String data = "";
if(context.getThisRequest().argumentExists("data")){
data = context.source("arg:data", String.class);
}
insert(dbserver,dbname,collection,data);
INKFResponse response = context.createResponseFrom("hals");
}
public void insert(String server, String name, String collection, String thedata){
Object s = JSONValue.parse(thedata);
Mongo m;
try {
m = new Mongo(server);
DB database = m.getDB(name);
DBCollection coll = database.getCollection(collection);
BasicDBObject doc = new BasicDBObject();
doc.put("data",s);
coll.insert(doc);
m.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(Exception ex){
ex.printStackTrace();
}
}
public void delete(String server, String name, String collection){
System.out.println("delete!");
}
}
|
package at.technikum.sfrexercise2.corebankingservice.service;
import at.technikum.sfrexercise2.corebankingservice.model.Customer;
import at.technikum.sfrexercise2.corebankingservice.model.Transaction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Service;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
@Service
@Slf4j
public class MessageSender {
@Value(value = "${customer.topic.name}")
private String customerTopicName;
@Value(value = "${transaction.topic.name}")
private String transactionTopicName;
KafkaTemplate<String, Customer> kafkaCustomerTemplate;
KafkaTemplate<String, Transaction> kafkaTransactionTemplate;
public MessageSender(KafkaTemplate<String, Customer> kafkaCustomerTemplate,
KafkaTemplate<String, Transaction> kafkaTransactionTemplate) {
this.kafkaCustomerTemplate = kafkaCustomerTemplate;
this.kafkaTransactionTemplate = kafkaTransactionTemplate;
}
public void sendCustomer(Customer customer) {
ListenableFuture<SendResult<String, Customer>> future = kafkaCustomerTemplate
.send(customerTopicName, customer);
future.addCallback(new ListenableFutureCallback<SendResult<String, Customer>>() {
@Override
public void onSuccess(SendResult<String, Customer> result) {
log.info("Sent customer={} with offset {}",
customer.toString(),
result.getRecordMetadata().offset());
}
@Override
public void onFailure(Throwable ex) {
log.error("Unable to send message \"{}\" due to: ",
customer.toString(),
ex.getMessage());
}
});
}
public void sendTransaction(Transaction transaction) {
ListenableFuture<SendResult<String, Transaction>> future = kafkaTransactionTemplate
.send(transactionTopicName, transaction);
future.addCallback(new ListenableFutureCallback<SendResult<String, Transaction>>() {
@Override
public void onSuccess(SendResult<String, Transaction> result) {
log.info("Sent transaction={} with offset {}",
transaction.toString(),
result.getRecordMetadata().offset());
}
@Override
public void onFailure(Throwable ex) {
log.error("Unable to send message \"{}\" due to: ",
transaction.toString(),
ex.getMessage());
}
});
}
}
|
package com.voksel.electric.pc.service;
import com.voksel.electric.pc.component.MenuTreeItem;
import com.voksel.electric.pc.configuration.ServiceConfiguration;
import com.voksel.electric.pc.domain.entity.Role;
import com.voksel.electric.pc.domain.entity.User;
import com.voksel.electric.pc.domain.entity.UserRole;
import com.voksel.electric.pc.security.AuthenticationService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import static org.junit.Assert.assertTrue;
/**
* Created by edsarp on 8/14/16.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {ServiceConfiguration.class})
public class UserandPrivilegeServiceTest {
@Autowired
UserAndPrivilegeService userAndPrivilegeService;
@Test
public void saveUserAndPrivilege() throws Exception{
User user=new User();
UserRole userRole=new UserRole();
user.setUserName("edwars");
user.setEmail("edwar@email.com");
user.setEnabled(1);
user.setPassword("edwar");
/* userRole.setRoleId("XX");
userRole.setUserId(2);
List<UserRole> userRoles=new ArrayList<UserRole>();
userRoles.add(userRole);
user.setRoles(userRoles);*/
user=userAndPrivilegeService.saveUser(user);
assertTrue(user.getUserId()!=null);
}
@Test
public void deleteuser() throws Exception{
userAndPrivilegeService.deleteUser(2);
//assertTrue(user.getUserid()!=null);
}
}
|
//
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7 generiert
// Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2016.05.11 um 01:33:35 PM CEST
//
package com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml;
import java.math.BigInteger;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java-Klasse für GLUEHENIstdatenType complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType name="GLUEHENIstdatenType">
* <complexContent>
* <extension base="{http://www-fls.thyssen.com/xml/schema/qcs}ArbeitsvorgangIstdatenType">
* <sequence>
* <element name="GluehKz" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="GluehVerfahren" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="Gluehstapel" type="{http://www-fls.thyssen.com/xml/schema/qcs}GluehstapelIdentType" minOccurs="0"/>
* <element name="LageImGluehstapel" type="{http://www.w3.org/2001/XMLSchema}integer" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "GLUEHENIstdatenType", propOrder = {
"gluehKz",
"gluehVerfahren",
"gluehstapel",
"lageImGluehstapel"
})
public class GLUEHENIstdatenType
extends ArbeitsvorgangIstdatenType
{
@XmlElement(name = "GluehKz")
protected String gluehKz;
@XmlElement(name = "GluehVerfahren")
protected String gluehVerfahren;
@XmlElement(name = "Gluehstapel")
protected GluehstapelIdentType gluehstapel;
@XmlElement(name = "LageImGluehstapel")
protected BigInteger lageImGluehstapel;
/**
* Ruft den Wert der gluehKz-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getGluehKz() {
return gluehKz;
}
/**
* Legt den Wert der gluehKz-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setGluehKz(String value) {
this.gluehKz = value;
}
/**
* Ruft den Wert der gluehVerfahren-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getGluehVerfahren() {
return gluehVerfahren;
}
/**
* Legt den Wert der gluehVerfahren-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setGluehVerfahren(String value) {
this.gluehVerfahren = value;
}
/**
* Ruft den Wert der gluehstapel-Eigenschaft ab.
*
* @return
* possible object is
* {@link GluehstapelIdentType }
*
*/
public GluehstapelIdentType getGluehstapel() {
return gluehstapel;
}
/**
* Legt den Wert der gluehstapel-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link GluehstapelIdentType }
*
*/
public void setGluehstapel(GluehstapelIdentType value) {
this.gluehstapel = value;
}
/**
* Ruft den Wert der lageImGluehstapel-Eigenschaft ab.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getLageImGluehstapel() {
return lageImGluehstapel;
}
/**
* Legt den Wert der lageImGluehstapel-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setLageImGluehstapel(BigInteger value) {
this.lageImGluehstapel = value;
}
}
|
package utils;
public class Configs {
// static resource
public static final String HOME_PATH = "/views/fxml/home.fxml";
public static final String SPLASH_SCREEN_PATH = "/views/fxml/splash.fxml";
public static final String CARD_PATH = "/views/fxml/card_1.fxml";
public static final String DOCK_HOME_PATH = "/views/fxml/dock_item.fxml";
public static final String DOCK_PATH = "/views/fxml/dock_detail.fxml";
public static final String DOCK_BIKE_PATH = "/views/fxml/dock_bike_1.fxml";
public static final String BIKE_INFO_PATH = "/views/fxml/bike_detail.fxml";
public static final String VIEW_RENTING_BIKE_PATH = "/views/fxml/view_renting_bike_1.fxml";
public static final String HISTORY_PATH = "/views/fxml/history_1.fxml";
public static final String RETURN_POPUP_PATH = "/views/fxml/return_popup_1.fxml";
public static final String LOGIN_PATH = "/views/fxml/login.fxml";
public static final String ACCOUNT_PATH = "/views/fxml/account_info.fxml";
public static final String INVOICE_PATH = "/views/fxml/invoice.fxml";
public static final String POPUP_PATH = "/views/fxml/popup.fxml";
public static final String IMAGE_PATH = "assets/images";
public static final String HISTORY_ITEM_PATH = "/views/fxml/history_item_1.fxml";
public static final String POPUP_RETURN_FAIL_PATH = "/views/fxml/fail_return.fxml";
public static final String GET_BALANCE_URL = "https://ecopark-system-api.herokuapp.com/api/card/balance/118609_group1_2020";
public static final String GET_VEHICLECODE_URL = "https://ecopark-system-api.herokuapp.com/api/get-vehicle-code/1rjdfasdfas";
public static final String PROCESS_TRANSACTION_URL = "https://ecopark-system-api.herokuapp.com/api/card/processTransaction";
public static final String RESET_URL = "https://ecopark-system-api.herokuapp.com/api/card/reset-balance";
// demo data
public static final String POST_DATA = "{"
+ " \"secretKey\": \"BpW3BCBzuRo=\" ,"
+ " \"transaction\": {"
+ " \"command\": \"pay\" ,"
+ " \"cardCode\": \"121319_group2_2020\" ,"
+ " \"owner\": \"Group 2\" ,"
+ " \"cvvCode\": \"228\" ,"
+ " \"dateExpried\": \"1125\" ,"
+ " \"transactionContent\": \" Pay money\" ,"
+ " \"amount\": 1000000 "
+ "}"
+ "}";
public static final String TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiIxMTg2MDlfZ3JvdXAxXzIwMjAiLCJpYXQiOjE1OTkxMTk5NDl9.y81pBkM0pVn31YDPFwMGXXkQRKW5RaPIJ5WW5r9OW-Y";
// database Configs
public static final String DB_NAME = "ecobike";
public static final String DB_USERNAME = System.getenv("DB_USERNAME");
public static final String DB_PASSWORD = System.getenv("DB_PASSWORD");
public static String CURRENCY = "VND";
public static float PERCENT_VAT = 10;
public static int BATTERY_CAPACITY = 600;
public static int DOCK_SLOT = 10;
public static int STANDARD_PAYMENT = 1;
public static int SPECIAL_PAYMENT = 2;
}
|
package com.github.dmstocking.putitonthelist.grocery_list.items.add;
import android.support.annotation.NonNull;
import com.github.dmstocking.putitonthelist.Color;
import com.google.auto.value.AutoValue;
import java.net.URI;
@AutoValue
public abstract class ListItemViewModel {
public static ListItemViewModel create(@NonNull String id,
@NonNull URI image,
@NonNull String name,
@NonNull Color textColor,
@NonNull Color backgroundColor,
@NonNull CategoryDocument categoryDocument) {
return new AutoValue_ListItemViewModel(id, image, name, textColor, backgroundColor, categoryDocument);
}
@NonNull public abstract String id();
@NonNull public abstract URI image();
@NonNull public abstract String name();
@NonNull public abstract Color textColor();
@NonNull public abstract Color backgroundColor();
@NonNull public abstract CategoryDocument category();
}
|
package offer;
// 操作给定的二叉树,将其变换为源二叉树的镜像。
public class 二叉树的镜像 {
public static void main(String[] args) {
TreeNode root = new TreeNode(8);
root.left = new TreeNode(6);
root.right = new TreeNode(10);
root.left.left = new TreeNode(5);
root.left.right = new TreeNode(7);
root.right.left = new TreeNode(9);
root.right.right = new TreeNode(11);
Mirror(root);
System.out.println(root.left.right.right);
}
public static void Mirror(TreeNode root) {
if(root == null) return;
// 交换左右孩子
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
// 左结点为头的进行上述操作
Mirror(root.left);
// 右结点为头的进行上述操作
Mirror(root.right);
}
}
|
package org.sagebionetworks.repo.manager.table;
import java.util.HashMap;
import java.util.Map;
import org.sagebionetworks.repo.model.EntityType;
import org.sagebionetworks.util.ValidateArgument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Simple mapping of entity types to transaction managers.
*
*/
@Service
public class TableUpdateRequestManagerProviderImpl implements TableUpdateRequestManagerProvider {
private Map<EntityType, TableUpdateRequestManager> managerMap;
@Autowired
public void configureMapping(TableEntityUpdateRequestManager tableEntityUpdateManager, TableViewUpdateRequestManager tableViewUpdateManager) {
managerMap = new HashMap<>();
managerMap.put(EntityType.table, tableEntityUpdateManager);
managerMap.put(EntityType.entityview, tableViewUpdateManager);
managerMap.put(EntityType.submissionview, tableViewUpdateManager);
managerMap.put(EntityType.dataset, tableViewUpdateManager);
}
@Override
public TableUpdateRequestManager getUpdateRequestManagerForType(EntityType type) {
ValidateArgument.required(type, "type");
TableUpdateRequestManager manager = managerMap.get(type);
if (manager == null){
throw new IllegalArgumentException("Unknown type: "+type);
}
return manager;
}
}
|
package com.tencent.mm.plugin.mmsight.ui;
import com.tencent.mm.plugin.mmsight.ui.SightCaptureUI.14;
class SightCaptureUI$14$1 implements Runnable {
final /* synthetic */ 14 lqx;
SightCaptureUI$14$1(14 14) {
this.lqx = 14;
}
public final void run() {
SightCaptureUI.U(this.lqx.lqr);
}
}
|
package com.g53mdp.cw1_3.recipebook;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private RecipeDBAdapter dbAdapter;
private SimpleCursorAdapter dataAdapter;
private final String
CLA = "RRS01 MainActivity",
NO_DATA_MSG = "Wow! Your recipe book is empty. \n\n Add a new recipe.",
TAG_ACTION = "actionToDo";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(CLA,"onCreate");
}
@Override
protected void onStart() {
super.onStart();
Log.d(CLA,"onStart");
dbAdapter = new RecipeDBAdapter(this);
dbAdapter.open();
setWidgets();
}
private void setWidgets() {
final Cursor cursor = dbAdapter.db.query(
RecipeDBAdapter.TABLE_NAME,
new String[]{
RecipeDBAdapter.KEY_ROWID,
RecipeDBAdapter.KEY_TITLE
},
null,null,null,null,null);
String[] columns = new String[]{
RecipeDBAdapter.KEY_ROWID,
RecipeDBAdapter.KEY_TITLE
};
int[] to = new int[]{
R.id.idView,
R.id.titleView
};
dataAdapter = new SimpleCursorAdapter(this, R.layout.db_item_layout,cursor, columns, to,0);
final ListView lv = (ListView) findViewById(R.id.lv_recipes);
lv.setAdapter(dataAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter,
View myView,
int myItemInt,
long mylng) {
//String itemSelected = (String) (lv.getItemAtPosition(myItemInt));
Cursor c1 = (Cursor) lv.getAdapter().getItem(myItemInt);
Log.d(CLA,"" + c1.getInt(0));
//Do something with each recipe here
//showRecipeDetails(itemSelected);
}
});
}
private void showRecipeDetails(String selectedFromList) {
Toast.makeText(this,selectedFromList,Toast.LENGTH_SHORT).show();
}
public void onAddBtn(View view){
Log.d(CLA,"onAddBtn");
Bundle b = new Bundle();
b.putInt(TAG_ACTION,1);
Intent i = new Intent(MainActivity.this, CrudActivity.class);
i.putExtras(b);
startActivity(i);
}
@Override
protected void onStop() {
super.onStop();
Log.d(CLA,"onStop");
dbAdapter.close();
}
}
|
package controller.front;
import controller.FrontController;
import library.utils.Func;
import model.beans.NewsItemBean;
import model.beans.UserBean;
import model.models.NewsModel;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
/**
* 新闻模块
*/
@SuppressWarnings("serial")
@WebServlet(name = "News", urlPatterns = {"/news/*"})
public class NewsController extends FrontController {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
request.setCharacterEncoding("UTF-8");
if (req.getRequestURI().endsWith("/news/")) {
index();
} else if (!hasPage()) {
response.sendError(404, "访问未知名网页");
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
if (req.getRequestURI().endsWith("/news/")) {
index();
} else if (!hasPage()) {
response.sendError(404, "访问未知名网页");
}
}
/**
* 新闻详情页
*/
public void details() {
String id = request.getParameter("id");
NewsItemBean news = new NewsModel().getNewsDetails(id);
if (news != null) {
request.setAttribute("html_title", "新闻详情页 | " + news.getTitle());
request.setAttribute("news", news);
this.display("Details.jsp");
} else {
try {
response.sendError(404);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 新闻默认页
*/
public void index() {
request.setAttribute("html_title", "资讯中心-查看最新资讯");
NewsModel newsModel = new NewsModel();
int news_count = newsModel.getNewsCount();
String size = request.getParameter("size");
String str_page_now = request.getParameter("page");
int page_size = Func.getPageSize(size);
int page_now = Func.getPageNow(str_page_now);
int page_total = (news_count + page_size - 1) / page_size;
List<NewsItemBean> newsList = newsModel.getNewsItems((page_now - 1) * page_size, page_size);
List<NewsItemBean> hotNews = newsModel.getHotNews();
request.setAttribute("newsList", newsList);
request.setAttribute("hotNews", hotNews);
request.setAttribute("news_total", news_count);
request.setAttribute("page_now", page_now);
request.setAttribute("page_size", page_size);
request.setAttribute("page_total", page_total);
this.display("Index.jsp");
}
/**
* 新增新闻
*/
public void add() {
if (!isLogin()) {
markHere();
request.setAttribute("msg", "请登录后再进行操作!");
this.userLogin();
return;
}
if ("POST".equals(request.getMethod().toUpperCase())) {
doAdd();
} else {
request.setAttribute("html_title", "添加资讯");
this.display("Add.jsp");
}
}
/**
* 处理添加文章世界无
*/
public void doAdd() {
if (!isLogin()) {
userLogin();
return;
}
String title = request.getParameter("title");
String content = request.getParameter("content");
String abst = request.getParameter("abstract");
NewsItemBean news = new NewsItemBean();
news.setTitle(title);
news.setContent(content);
news.setCtime(System.currentTimeMillis());
news.setAbst(abst);
news.setUid(((UserBean) session.getAttribute("user")).getUid());
int result = new NewsModel().addNews(news);
if (result == 1) {
request.setAttribute("html_title", "新闻添加成功");
request.setAttribute("status", "success");
request.setAttribute("link", "返回资讯");
request.setAttribute("url", "/news/index.html");
request.setAttribute("msg", "新闻添加成功");
} else {
request.setAttribute("html_title", "新闻添加失败");
request.setAttribute("status", "danger");
request.setAttribute("link", "返回资讯");
request.setAttribute("url", "/news/index.html");
request.setAttribute("msg", "新闻添加失败");
}
this.display("Result.jsp", "/front/");
}
}
|
package com.tencent.mm.g.a;
public final class op$b {
public String Yy;
public int actionType;
public String bZA;
}
|
package p9.entity;
import java.io.File;
import p9.CoreGame;
import p9.Direction;
import p9.InputClass;
import p9.MapScreen;
import p9.server.netpaks.CharacterDataPackage;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.math.Vector3;
public class Mob {
public Animation[] animation; // holds 4 animations for 4 directions
private TextureRegion[][] regions; //hold the regions for the animation
private TextureAtlas texAt;
public Sprite[] sprites; //the non-walking sprites
public Direction direction; //holds the current direction, as well as usefull statics and methods for deatecting/changin direction
public CharacterDataPackage cdp;
private Float speed = 1f; //the speed of the mob
public Boolean moving = false; //use to detect if mob is moving or not
private Boolean walking = true; //used to detect is the mob i walkign or running.
private CoreGame parent;
public Vector3 position = new Vector3(0,0,0);
public Mob(CoreGame p, CharacterDataPackage cds) {
cdp =cds;
parent = p;
regions = new TextureRegion[4][3];
animation = new Animation[4];
direction = new Direction(Direction.DOWN);
//must varify that the file exists
String path = "res/CharData/" + cds.classData.name + "/" + cds.atlasName;
if((new File(path)).exists()){
texAt= new TextureAtlas(Gdx.files.local(path));
}
else{
System.out.println("\nCould not find the character information for " + cds.name + " at: " + path);
}
//Make sure the the texture atlas is not null.
if(texAt != null){
regions[Direction.UP][0] = texAt.findRegion("char",1);
regions[Direction.UP][1] = texAt.findRegion("char",2); //set regions for up
regions[Direction.UP][2] = texAt.findRegion("char",3);
animation[Direction.UP]= new Animation(1/6f, regions[Direction.UP]) ;
regions[Direction.DOWN][0] = texAt.findRegion("char",4);
regions[Direction.DOWN][1] = texAt.findRegion("char",5); //set regions for down
regions[Direction.DOWN][2] = texAt.findRegion("char",6);
animation[Direction.DOWN]= new Animation(1/6f, regions[Direction.DOWN]) ;
regions[Direction.LEFT][0] = texAt.findRegion("char",7);
regions[Direction.LEFT][1] = texAt.findRegion("char",8); //set regions for left
regions[Direction.LEFT][2] = texAt.findRegion("char",9);
animation[Direction.LEFT]= new Animation(1/6f, regions[Direction.LEFT]) ;
regions[Direction.RIGHT][0] = texAt.findRegion("char",10);
regions[Direction.RIGHT][1] = texAt.findRegion("char",11); //set regions for right
regions[Direction.RIGHT][2] = texAt.findRegion("char",12);
animation[Direction.RIGHT]= new Animation(1/6f, regions[Direction.RIGHT]) ;
sprites = new Sprite[4];
sprites[Direction.UP] = new Sprite(texAt.findRegion("char",1));
sprites[Direction.DOWN] = new Sprite(texAt.findRegion("char",4));
sprites[Direction.LEFT] = new Sprite(texAt.findRegion("char",7));
sprites[Direction.RIGHT] = new Sprite(texAt.findRegion("char",10));
//check all our regions to make sure there all not null.
Boolean regionsOK = true;
for(int i = 0; i < 4; i++){
for(int a = 0; a < 3; a++){
if(regions[i][a] == null){
regionsOK = false;
}
}
}
if(!regionsOK){
System.out.println("\nWarning! Regions were not all loaded!");
}
//test the atlas, to make sure it has been loaded. and if it has, process it into animations.
}
}
/**
* Override the meathod so that scales and rotations are performed on the actor.
*/
/* @Override
public void draw(Batch batch, float parentAlpha) {
super.draw(batch, parentAlpha);
elapTime += Gdx.graphics.getDeltaTime();
Color color = getColor();
batch.setColor(color.r, color.g, color.b, color.a * parentAlpha);
//draw the moving or non moving animation only if the sprite is visible
if(moving && isVisible()){
batch.draw(animation[direction.looking()].getKeyFrame(elapTime, true), getX(), getY(), getOriginX(), getOriginY(),
getWidth(), getHeight(), getScaleX(), getScaleY(), getRotation());
}
if(!moving && isVisible()){
batch.draw(sprites[direction.looking()], getX(), getY(), getOriginX(), getOriginY(),
getWidth(), getHeight(), getScaleX(), getScaleY(), getRotation());
}
this.setBounds(getX(), getY(), 32, 32);
}*/
/*
* returns the gird32 cords of the camera(or sprite);
*/
public float gridCords(char c){
if(c == 'x'){
return (float) Math.floor((getX()+5)/32);
}
if(c=='y'){
return (float) Math.floor((getY()+5)/32);
}
else{
return -1f;
}
}
/**
* Check to see if the mob should be visible or not.
* @return
*/
public boolean isVisible(){
TiledMapTileLayer colLayer = (TiledMapTileLayer) parent.getTiledMap().getLayers().get("col");
return !colLayer.getCell((int)gridCords('x'),(int) gridCords('y')).getTile().getProperties().containsKey("under");
}
/**
* Set the direction the mob
* @param up
*/
public void setDirection(int i) {
direction.setDirection(i);
}
public void setMoving(boolean b) {
moving = b;
}
public void setPosition(float x, float y){
position.x = x;
position.y = y;
}
/**
* @return the speed
*/
public Float getSpeed() {
return speed;
}
/**
* @param i the speed to set
*/
public void setSpeed(Float i) {
this.speed = i;
}
/**
* @return the walking
*/
public Boolean getWalking() {
return walking;
}
/**
*
* @return mob X position
*/
public float getX(){
return position.x;
}
/**
*
* @return mob Y position
*/
public float getY(){
return position.y;
}
/**
* @param walking the walking to set
*/
public void setWalking(Boolean walking) {
this.walking = walking;
}
public int looking(){
return direction.looking();
}
}
|
package com.example.demo;
public class TestData {
}
|
package kz.sagrad.ufix;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import java.util.ArrayList;
public class DetailsActivity extends AppCompatActivity {
public static String TAG = "DetailsActivity";
OrderItem orderItem;
DetailsActivity thisActivity = this;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
String id = getIntent().getExtras().getString("id");
for (OrderItem item : UFix.orderItems) {
if (item.id.equals(id))
orderItem = item;
}
if (orderItem == null)
return;
// for (String photoID : orderItem.photos)
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ArrayList<String> items = (orderItem.photos.size() > 0) ?
orderItem.photos : null;
ImageView photosLL = (ImageView) findViewById(R.id.photos_ll);
if (orderItem.photos.size() > 0) {
CameraAndPictures.getPicFromFirebase(orderItem.photos.get(0), photosLL);
} else {
viewPager.setAdapter(new ImageScrollFragmentAdapter(getSupportFragmentManager(), items));
photosLL.setImageResource(R.drawable.tire_wrench);
}
viewPager.setAdapter(new ImageScrollFragmentAdapter(getSupportFragmentManager(),
items));
viewPager.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(thisActivity, PhotoMasterActivity.class);
intent.putExtra("PHOTOS", orderItem.photos);
startActivity(intent);
// startActivity(new Intent(thisActivity, PhotoMasterActivity.class));
// Toast.makeText(thisActivity, "Photo is clicked", Toast.LENGTH_SHORT).show();
}
});
//orderItem
((TextView) findViewById(R.id.form_name1)).setText(orderItem.ownerName);
((TextView) findViewById(R.id.form_auto1)).setText(orderItem.autoBrand + " , " + orderItem.year);
((TextView) findViewById(R.id.form_description1)).setText(orderItem.details);
((TextView) findViewById(R.id.form_phone1)).setText(orderItem.phone);
findViewById(R.id.form_phone1).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String uri = "tel:" + orderItem.phone;
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(uri));
if (ActivityCompat.checkSelfPermission(thisActivity, android.Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
startActivity(intent);
}
}
});
((TextView) findViewById(R.id.form_city1)).setText(orderItem.city);
(findViewById(R.id.button_make_offer)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
makeAnOffer(thisActivity, (LinearLayout) findViewById(R.id.priceLL));
}
});
readOffers();
}
private void readOffers() {
UFix.ref.child("youfix/offers/" + orderItem.id).addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
try {
Offer offer = dataSnapshot.getValue(Offer.class);
addOffer(offer, (LinearLayout) findViewById(R.id.priceLL));
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void makeAnOffer(final Context context, final LinearLayout priceLL) {
final String phone = UFix.sharedPref.getString("phone", "");
final String name = UFix.sharedPref.getString("name", "");
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
final ScrollView filterScrollView = new ScrollView(context);
final LinearLayout ll = new LinearLayout(context);
ll.setOrientation(LinearLayout.VERTICAL);
filterScrollView.addView(ll);
final EditText priceEditText = new EditText(context);
priceEditText.setRawInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);
priceEditText.setHint("Цена в тенге");
final EditText phoneEditText = new EditText(context);
phoneEditText.setRawInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);
phoneEditText.setHint("Ваш номер телефона");
phoneEditText.setText(phone);
final EditText commentEditText = new EditText(context);
commentEditText.setHint("Комментарий");
ll.addView(priceEditText);
ll.addView(phoneEditText);
ll.addView(commentEditText);
builder
.setMessage("Сделайте своё предложение по ремонту")
.setView(filterScrollView)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
if (!("" + phoneEditText.getText()).trim().equals(""))
UFix.savePref("phone", "" + phoneEditText.getText());
Offer offer = new Offer();
offer.price = "" + priceEditText.getText();
offer.phone = UFix.sharedPref.getString("phone", "");
offer.comment = "" + commentEditText.getText();
offer.email = UFix.sharedPref.getString("email", "");
offer.name = UFix.sharedPref.getString("name", "");
UFix.ref.child("youfix/offers/" + orderItem.id + "/").push().setValue(offer);
}
}).show();
}
public void addOffer(final Offer offer, LinearLayout oll) {
LayoutInflater li = (LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
FrameLayout frameLayout = (FrameLayout) li.inflate(R.layout.bubble, null);
TextView anotherOffer = (TextView) frameLayout.findViewById(R.id.textInBubble);
anotherOffer.setText(offer.name + ":" + offer.price + " тенге\n" + offer.comment);
ImageView call = (ImageView) frameLayout.findViewById(R.id.user_img);
call.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String uri = "tel:" + offer.phone;
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(uri));
if (ActivityCompat.checkSelfPermission(thisActivity, android.Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
startActivity(intent);
}
}
});
oll.addView(frameLayout);
}
public void showMaster(View view){
Intent intent = new Intent(thisActivity, PhotoMasterActivity.class);
intent.putExtra("PHOTOS", orderItem.photos);
startActivity(intent);
}
}
|
/*
* Copyright (C) 2013-2014 The CyanogenMod Project
*
* 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.fantasy.systemui.quicksettings;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.view.View;
import android.view.ViewGroup.MarginLayoutParams;
import android.widget.ImageView;
import com.android.internal.util.fantasy.QSUtils;
import com.android.systemui.statusbar.phone.QuickSettingsController;
import com.android.systemui.statusbar.phone.ResourceUtils;
import com.android.systemui.statusbar.policy.NetworkController;
public class MobileNetworkTile extends NetworkTile {
private static final int NO_OVERLAY = 0;
private static final int DISABLED_OVERLAY = -1;
private boolean mEnabled;
private String mDescription;
private int mDataTypeIconId = NO_OVERLAY;
private String mDataContentDescription;
private String mSignalContentDescription;
private boolean mWifiOn = false;
private ConnectivityManager mCm;
public MobileNetworkTile(Context context, QuickSettingsController qsc,
NetworkController controller) {
super(context, qsc, controller, ResourceUtils.getResLayout(context, "quick_settings_tile_rssi"));
mCm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
mOnClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!mCm.getMobileDataEnabled()) {
// None, onMobileDataSignalChanged will set final overlay image
updateOverlayImage(NO_OVERLAY);
mCm.setMobileDataEnabled(true);
} else {
updateOverlayImage(DISABLED_OVERLAY);
mCm.setMobileDataEnabled(false);
}
}
};
mOnLongClick = new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Intent intent = new Intent();
intent.setComponent(new ComponentName(
"com.android.settings",
"com.android.settings.Settings$DataUsageSummaryActivity"));
startSettingsActivity(intent);
return true;
}
};
}
@Override
protected void updateTile() {
Resources r = mContext.getResources();
mDataContentDescription = mEnabled && mDataTypeIconId > 0 && !mWifiOn
? mDataContentDescription
: r.getString(ResourceUtils.getResString(mContext, "accessibility_no_data"));
mLabel = mEnabled
? mDescription
: r.getString(ResourceUtils.getResString(mContext, "quick_settings_rssi_emergency_only"));
}
@Override
public void onWifiSignalChanged(boolean enabled, int wifiSignalIconId,
boolean activityIn, boolean activityOut,
String wifiSignalContentDescriptionId, String description) {
mWifiOn = enabled;
}
@Override
public void onMobileDataSignalChanged(boolean enabled,
int mobileSignalIconId, String mobileSignalContentDescriptionId,
int dataTypeIconId, boolean activityIn, boolean activityOut,
String dataTypeContentDescriptionId, String description) {
if (!QSUtils.deviceSupportsMobileData(mContext)) {
return;
}
// TODO: If view is in awaiting state, disable
Resources r = mContext.getResources();
mDrawable = enabled && mobileSignalIconId > 0
? mobileSignalIconId
: ResourceUtils.getResDrawable(mContext, "ic_qs_signal_no_signal");
mSignalContentDescription = enabled && mobileSignalIconId > 0
? mSignalContentDescription
: r.getString(ResourceUtils.getResString(mContext, "accessibility_no_signal"));
// Determine the overlay image
if (enabled && dataTypeIconId > 0 && !mWifiOn) {
mDataTypeIconId = dataTypeIconId;
} else if (!mCm.getMobileDataEnabled()) {
mDataTypeIconId = DISABLED_OVERLAY;
} else {
mDataTypeIconId = NO_OVERLAY;
}
mEnabled = enabled;
mDescription = removeTrailingPeriod(description);
setActivity(activityIn, activityOut);
updateResources();
}
@Override
public void onAirplaneModeChanged(boolean enabled) {
}
@Override
protected View getImageView() {
return mTile.findViewById(ResourceUtils.getResId(mContext, "rssi_image"));
}
@Override
void updateQuickSettings() {
super.updateQuickSettings();
updateOverlayImage(mDataTypeIconId);
mTile.setContentDescription(mContext.getResources().getString(
ResourceUtils.getResString(mContext, "accessibility_quick_settings_mobile"),
mSignalContentDescription, mDataContentDescription,
mLabel));
}
void updateOverlayImage(int dataTypeIconId) {
ImageView iov = (ImageView) mTile.findViewById(ResourceUtils.getResId(mContext, "rssi_overlay_image"));
if (dataTypeIconId > 0) {
iov.setImageResource(dataTypeIconId);
} else if (dataTypeIconId == DISABLED_OVERLAY) {
iov.setImageResource(ResourceUtils.getResDrawable(mContext, "ic_qs_signal_data_off"));
} else {
iov.setImageDrawable(null);
}
}
// Remove the period from the network name
private static String removeTrailingPeriod(String string) {
if (string == null) return null;
final String aux = string.trim();
if (aux.endsWith(".")) {
return aux.substring(0, aux.length() - 1);
}
return aux;
}
// MobileNetworkTile use an internal frame, so we need to restrict frame margins
// instead of image margin
@Override
public void setImageMargins(int margin) {
View image = mTile.findViewById(ResourceUtils.getResId(mContext, "image"));
if (image != null) {
MarginLayoutParams params = (MarginLayoutParams) image.getLayoutParams();
params.topMargin = params.bottomMargin = margin;
image.setLayoutParams(params);
}
}
}
|
package com.myapp.accountsManagement;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import org.json.JSONObject;
public class RegistrationDao {
public boolean RegisterUser(
String userName,
String password,
String firstname,
String lastname,
String email,
String adress,
String bdate) {
String url = "http://localhost:8080/services/webapi/";
String url_param = "user/createUser";
System.out.println("\nConnection to " + url+url_param);
URL post_url;
String string = "\n"
+ "{\n"
+ " \"newUser\": {\n"
+ " \"userName\": "+userName+",\n"
+ " \"password\": "+password+",\n"
+ " \"firstname\": "+firstname+",\n"
+ " \"lastname\": "+lastname+",\n"
+ " \"email\": "+email+",\n"
+ " \"adress\": "+adress+",\n"
+ " \"bdate\": "+bdate+"\n"
+ " }\n"
+ "}";
try {
JSONObject jsonObject = new JSONObject(string);
// Step2: Now pass JSON File Data to REST Service
try {
post_url = new URL(url+url_param);
URLConnection connection = post_url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(jsonObject.toString());
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while (in.readLine() != null) {
}
System.out.println("\nREST Service Invoked Successfully..");
in.close();
} catch (Exception e) {
System.out.println("\nError while calling REST Service");
System.out.println(e);
}
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
}
|
/*
* Property of Will Stevens
* All rights reserved.
*/
package chapter_2_;
import java.util.ArrayList;
import java.util.List;
/**
* @author wstevens
*/
public class FilterScratch {
interface Predicate<T> {
boolean test(T subject);
}
public static <T> List<T> filter(List<T> subjects, Predicate<T> test) {
List<T> filteredList = new ArrayList<>();
for (T subject : subjects) {
if (test.test(subject)) {
filteredList.add(subject);
}
}
return filteredList;
}
}
|
package com.tencent.mm.plugin.webview.ui.tools;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.plugin.webview.ui.tools.WebViewDownloadWithX5UI.2;
class WebViewDownloadWithX5UI$2$1 implements OnClickListener {
final /* synthetic */ 2 pWQ;
WebViewDownloadWithX5UI$2$1(2 2) {
this.pWQ = 2;
}
public final void onClick(DialogInterface dialogInterface, int i) {
h.mEJ.h(14217, new Object[]{"", Integer.valueOf(5), this.pWQ.pWG, this.pWQ.val$url, Integer.valueOf(1)});
WebViewDownloadWithX5UI.a(this.pWQ.pWO, this.pWQ.val$url, this.pWQ.pWG);
dialogInterface.dismiss();
}
}
|
package SvgPac;
import java.awt.Color;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
public final class SvgHelper {
public static String floatToString(final float f) {
return String.format("%.1f", f).replace(',', '.');
}
public static String colorToString(final Color col) {
return String.format("rgb(%d,%d,%d)",
col.getRed(), col.getGreen(), col.getBlue());
}
public static void writeColor(DataOutputStream out, Color color) throws IOException {
out.writeInt(color.getRed());
out.writeInt(color.getGreen());
out.writeInt(color.getBlue());
}
public static Color readColor(DataInputStream in) throws IOException {
return new Color(in.readInt(), in.readInt(), in.readInt());
}
}
|
package com.hedong.hedongwx.utils.yinlian;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQTextMessage;
/**
* 消息队列的发送者
* @author zz
*
*/
public class QueueSender {
public static void main(String[] args) {
//创建连接工厂
ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://192.168.3.2:61616");
try {
//从工厂对象中获得连接
Connection connection = factory.createConnection();
//开启一个会话
Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
//创建一个队列
Queue queue = session.createQueue("my");
//创建一个生产者
MessageProducer producer = session.createProducer(queue);
//创建消息
TextMessage message = new ActiveMQTextMessage();
//写入消息
while(true){
message.setText("nihiuahihaihaihiahaihai");
//发送消息
producer.send(message);
System.out.println("生生生生生生生生生生生生生生生生");
}
//producer.close();
//session.close();
//connection.close();
//System.out.println("oooooooooooooooooo");
} catch (JMSException e) {
e.printStackTrace();
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.gui.asma;
import com.codename1.components.ImageViewer;
import com.codename1.ui.Button;
import com.codename1.ui.Container;
import com.codename1.ui.EncodedImage;
import com.codename1.ui.Form;
import com.codename1.ui.Image;
import com.codename1.ui.Label;
import com.codename1.ui.TextField;
import com.codename1.ui.Toolbar;
import com.codename1.ui.URLImage;
import com.codename1.ui.layouts.BoxLayout;
import com.codename1.ui.util.Resources;
import com.mycompany.entities.asma.Feed;
import com.mycompany.services.asma.ServiceFeed;
import java.util.ArrayList;
/**
*
* @author User
*/
public class ShowListFeed {
private Form current;
private TextField nom,prenom;
private Button valider;
private Container ctn,ctn2;
private ImageViewer img;
private Label titre;
private EncodedImage encodedImage;
private Image urlImage;
private ImageViewer imageviewer;
private Toolbar tb;
private Form form;
public ShowListFeed() {
}
public ShowListFeed(Resources theme) {
form=new Form("Actualite",BoxLayout.y());
ServiceFeed sp1=new ServiceFeed();
ArrayList<Feed> list=sp1.showList();
int i=0;
//********************************Parcourir la liste****************************************************************
for(Feed f : list)
{
i++;
Container ctn = new Container(BoxLayout.x());
encodedImage=EncodedImage.createFromImage(theme.getImage("round.png"), false);
urlImage = URLImage.createToStorage(encodedImage, "brha"+i,"http://localhost"+f.getImage(),URLImage.RESIZE_SCALE_TO_FILL);
img =new ImageViewer(urlImage);
ctn.add(img);
titre= new Label(f.getTitle());
ctn.add(titre);
titre.addPointerPressedListener((e)-> {
ShowDetailFeed sda =new ShowDetailFeed(theme ,f);
sda.getForm().show();
});
ctn.setLeadComponent(titre);
form.add(ctn);
}
}
public Form getForm() {
return form;
}
public void setForm(Form form) {
this.form = form;
}
}
|
/* Directions:
* Write a program that implements a stack class that is based on the Deque
* class in Programming Project 4.2. This stack class should have the same
* methods and capabilities as the StackX class in the stack.java program
* (Listing 4.1).
*/
package chapter4;
public class Project4_3 {
public static void main(String[] args) {
final int SIZE = 8;
DequeStack stack = new DequeStack(SIZE);
try {
for (int i = 0; i < SIZE; i++) {
stack.insertLeft(i);
}
stack.display();
stack.removeLeft();
stack.insertLeft(5);
stack.display();
System.out.println(stack.peekFront());
stack.display();
}
catch (Exception ex) {
System.out.println(ex);
}
}
}
class DequeStack {
private int maxSize;
private int[] dequeArray;
private int left;
private int right;
private int numberOfItems;
public DequeStack(int max) {
maxSize = max;
dequeArray = new int[maxSize];
left = 1;
right = 0;
numberOfItems = 0;
}
// push
public void insertLeft(int value)
throws Exception {
if (isFull()) {
throw new Exception("Stack is full");
}
else {
if (left == 0) {
left = maxSize;
}
dequeArray[--left] = value;
numberOfItems++;
}
}
// pop
public int removeLeft()
throws Exception {
if (isEmpty()) {
throw new Exception("Queue is empty");
}
else {
int temp = dequeArray[left++];
if (left == maxSize) {
left = 0;
}
numberOfItems--;
return temp;
}
}
// peek
public int peekFront() {
return dequeArray[left];
}
public boolean isEmpty() {
return numberOfItems == 0;
}
public boolean isFull() {
return numberOfItems == maxSize;
}
public int getsSize() {
return numberOfItems;
}
public void display() {
if (isEmpty()) {
System.out.println("--");
}
else {
for (int i = 0; i < numberOfItems; i++) {
System.out.print(dequeArray[(i + left) % maxSize] + " ");
}
System.out.println();
}
}
}
|
package com.woncheol.restapi.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.Date;
@Data
@AllArgsConstructor
public class Member {
String userId;
String name;
int age;
String address;
Date createdAt;
String companyName;
public Member() {
}
public Member(String userId, String name, int age, String address, Date createAt, String companyName) {
// TODO Auto-generated constructor stub
this.userId = userId;
this.name = name;
this.age = age;
this.address = address;
this.createdAt = createAt;
this.companyName = companyName;
}
public String getUserId() {
return this.userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return this.age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getCreatedAt() {
return this.createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public String getCompanyName() {
return this.companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
}
|
package com.chilkens.timeset.domain;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.*;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Created by hoody on 2017-08-02.
*/
/*
pick 테이블과 pick_detail 테이블 조인한 Entity
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Entity(name = "pick")
@EntityListeners(value = { AuditingEntityListener.class })
public class PickJoin {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="pickId")
private Long pickId;
@Column(name="tableId")
private Long tableId; // Foreign Key
@Column
private String createdBy; // 작성한 사람
@Column(insertable = false)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createdAt; // 작성 날짜
@Column
private boolean deleted; // 삭제 여부
@OneToMany(fetch=FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name="pickId")
private List<PickDetail> pickDetails = new ArrayList<>();
/*
sample result
PickJoin(pickId=3, tableId=2, createdBy=은영, createdAt=2017-07-30 05:53:56.0, deleted=false, pick_detail=[PickDetail(detailId=26, pickId=3, pickDate=2017-08-01 00:00:00.0, pickTime=22)])
PickJoin(pickId=4, tableId=2, createdBy=나연, createdAt=2017-07-30 05:53:56.0, deleted=false, pick_detail=[PickDetail(detailId=33, pickId=4, pickDate=2017-08-02 00:00:00.0, pickTime=12|18)])
PickJoin(pickId=5, tableId=2, createdBy=병찬, createdAt=2017-07-30 05:53:56.0, deleted=false, pick_detail=[PickDetail(detailId=28, pickId=5, pickDate=2017-08-05 00:00:00.0, pickTime=18), PickDetail(detailId=29, pickId=5, pickDate=2017-08-06 00:00:00.0, pickTime=15)])
*/
}
|
package com.bowlong.third.assist;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface A2Class {
String type() default A2G.DATA; // Server, Client, Data
String namespace() default "";
String name() default "";
String remark() default "";
boolean constant() default false;
}
|
package com.example.cryptocoffee.blockchainapi.domain;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
@Getter
@Setter
@ToString
public class User {
@Id
private String rfid;
private String corporateKey;
private String firstName;
private String lastName;
private String ingMail;
private String walletAddress;
private String googleMail;
}
|
package marche.traitement.Produit;
import java.time.LocalDate;
/**
*
*/
public abstract class Produit implements Cloneable{
protected int quantite;
protected LocalDate dateDePeremption;
protected String unite;
protected Produit(){}
/**
*
* @return une copie d'un Produit mais pas par référence
*/
public Produit clone() {
Produit produit = null;
try
{
produit = (Produit) super.clone();
}catch(CloneNotSupportedException c){
System.out.println("erreur dans la segmentation du produit");
}
return produit;
}
/**
* Constructeur
*/
public Produit(int quantite, LocalDate dateDePeremption, String unite) {
this.quantite = quantite;
this.dateDePeremption = dateDePeremption;
this.unite = unite;
}
/**
* Renvoi la quantité d'un produit
* @return int
*/
public int getQuantite() {
return quantite;
}
/**
* Initialise la quantité d'un produit
* @param quantite int
*/
public void setQuantite(int quantite) {
this.quantite = quantite;
}
/**
* Renvoi la date d'un peremption d'un produit
* @return boolean
*/
public LocalDate getDateDePeremption() {
return dateDePeremption;
}
/**
* Renvoi l'unité d'un produit
* @return boolean
*/
public String getUnite() {
return unite;
}
/**
* Renvoi si un produit est validé , en fonction de sa date de peremption
* @return boolean
*/
public boolean valider() {
return (dateDePeremption.isAfter(LocalDate.now().plusDays(1)));
}
/**
* Enleve une quantité passée en paramètre a un produit
* @param quantite int
*/
public void enleverQuantite(int quantite){
this.quantite -= quantite;
}
/**
* Ajoute une quantité passée en paramètre a un produit
* @param quantite int
*/
public void ajouterQuantite(int quantite){
this.quantite += quantite;
}
public abstract String getNom();
}
|
package io.bega.kduino.activities;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.afollestad.materialdialogs.MaterialDialog;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.squareup.otto.Bus;
import com.squareup.otto.Subscribe;
import org.adw.library.widgets.discreteseekbar.DiscreteSeekBar;
import org.osmdroid.util.GeoPoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import io.bega.kduino.IClickable;
import io.bega.kduino.R;
import io.bega.kduino.SettingsManager;
import io.bega.kduino.api.KdUINOMessages;
import io.bega.kduino.datamodel.Analysis;
import io.bega.kduino.datamodel.DataSet;
import io.bega.kduino.datamodel.KDUINOBuoy;
import io.bega.kduino.datamodel.KdUINOOperations;
import io.bega.kduino.datamodel.Status;
import io.bega.kduino.datamodel.events.KdUinoAnalysisMessageBusEvent;
import io.bega.kduino.datamodel.events.KdUinoDataFileMessageBusEvent;
import io.bega.kduino.datamodel.events.KdUinoMessageBusEvent;
import io.bega.kduino.datamodel.events.KdUinoOperationMessageBusEvent;
import io.bega.kduino.datamodel.BuoyDefinition;
import io.bega.kduino.datamodel.events.KdUinoSendAnalysisDataMessageBusEvent;
import io.bega.kduino.datamodel.events.KdUinoSendDataMessageBusEvent;
import io.bega.kduino.fragments.AnalysisFragment;
import io.bega.kduino.fragments.KdUINOControlFragment;
//import io.bega.kduino.fragments.ALoginDialogFragment;
import io.bega.kduino.fragments.MapDialogFragment;
import io.bega.kduino.fragments.bluetooth.BluetoothActivityFragment;
import io.bega.kduino.fragments.bluetooth.BluetoothManagerFragment;
import io.bega.kduino.fragments.bluetooth.RegisterBuoyFragment;
import io.bega.kduino.fragments.bluetooth.SelectKdUINOModelFragment;
import io.bega.kduino.fragments.make.DefineBuoyFragment;
import io.bega.kduino.kdUINOApplication;
import io.bega.kduino.services.BluetoothManager;
import io.bega.kduino.services.BluetoothService;
import io.bega.kduino.services.ConnectBluetooth;
import io.bega.kduino.services.IDeviceDiscoveryNameService;
import io.bega.kduino.services.StorageService;
import io.bega.kduino.utils.DisplayUtilities;
public class BluetoothActivity extends BaseActivity implements AdapterView.OnItemClickListener,
IClickable, IDeviceDiscoveryNameService {
public static final int DIALOG_FRAGMENT = 1;
protected MaterialDialog connectingDialog;
private BluetoothService bluetoothService;
private BluetoothManager bluetoothManager;
private Context ctx;
private LineChart mChart;
ConnectBluetooth connectBluetooth;
DataSet dataset;
private final String stackName = "bluetooth";
ListView listViewDevices;
public ArrayAdapter<String> devices;
TextView tv;
private String buoyID = "0";
private String macAddress;
Menu mMenu;
Bus bus;
private ProgressDialog progressDialog;
AnalysisFragment analysisFragment;
private IClickable fragment;
View view;
public BluetoothService getBluetoothService()
{
return this.bluetoothService;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth);
this.ctx = this;
setActionNavigation();
this.bus = ((kdUINOApplication) this.getApplication()).getBus();
this.devices = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
this.setTitle(getString(R.string.title_activity_bluetooth));
view = findViewById(R.id.main_layout_linear);
this.bluetoothService = new BluetoothService(this, this.bus, this.devices, this, view);
this.bluetoothManager = new BluetoothManager(this, this.bluetoothService,
new StorageService(this, view), this.bus);
this.setTitle("");
this.moveToSearch();
}
@Override
protected void onStart() {
this.bluetoothService.registerReciever();
this.bus.register(this);
super.onStart();
}
@Override
protected void onStop() {
this.bluetoothService.unregisterReciever();
this.bus.unregister(this);
super.onStop();
}
@Subscribe
public void getMessage(KdUinoAnalysisMessageBusEvent message) {
this.setData(message.getData());
if (message.getData().Type.equals(DataSet.TYPE_ALL)) {
this.displayData(message.getData());
// this.launchAnalysisFragment();
} else {
this.sendDataToTask(message.getData());
}
}
@Subscribe
public void getMessage(KdUinoSendAnalysisDataMessageBusEvent event)
{
this.sendDataToTask(event.getData());
}
@Subscribe
public void getMessage(KdUinoDataFileMessageBusEvent event)
{
this.sendFileToTask(event.getPath());
}
@Subscribe
public void getMessage(KdUinoMessageBusEvent event)
{
switch (event.getMessage())
{
case KdUINOMessages.RECIEVE_INFO:
Status status = (Status)event.getData();
this.setTitle(status.Name);
break;
case KdUINOMessages.REFRESH_INFO:
this.sendInfoMessage();
break;
case KdUINOMessages.BLUETOOTH_CONNECT_TO_KDUINO:
this.sendInfoMessage();
this.invalidateOptionsMenu();
if (event.getData() != null) {
String id = Long.toString(((KDUINOBuoy) event.getData()).getId());
this.moveToControl(id, this.macAddress);
}
break;
case KdUINOMessages.CONNECT_BLUETOOTH:
if (!this.bluetoothService.isEnabled()) {
this.bluetoothService.enableBluetooth(this);
}
else
{
this.connectToDevice((KDUINOBuoy) event.getData());
}
this.invalidateOptionsMenu();
break;
case KdUINOMessages.SEARCH_DEVICES:
if (event.getData() != null) {
String code = event.getData().toString();
if (code.equals("MENU"))
{
return;
}
}
if (bluetoothService.isConnected())
{
return;
}
if (!bluetoothService.isEnabled())
{
bluetoothService.enableBluetooth((Activity)ctx);
}
else
{
if (bluetoothService.isConnected())
{
bluetoothService.disconnect();
bluetoothService.searchDevices();
}
else
{
bluetoothService.searchDevices();
}
}
break;
case KdUINOMessages.DISCONNECT_KDUINO:
if (this.bluetoothService.isConnected()) {
this.bluetoothService.disconnect();
}
this.invalidateOptionsMenu();
break;
case KdUINOMessages.SEND_COMMAND_KDUINO:
break;
case KdUINOMessages.BLUETOOTH_ON:
this.invalidateOptionsMenu();
break;
case KdUINOMessages.CONNECT_KDUINO:
this.connectToDevice((KDUINOBuoy) event.getData());
break;
case KdUINOMessages.BLUETOOTH_ERROR:
KDUINOBuoy buoy = (KDUINOBuoy) event.getData();
if (buoy != null) {
if (buoy.Name != null && buoy.Maker != null) {
if (buoy.Name.length() == 0 && buoy.Maker.length() == 0) {
buoy.delete();
}
}
}
DisplayUtilities.ShowLargeMessage("Error connecting to Bluetooth device.",
"", this.getWindow().getDecorView(), false,
null);
break;
case KdUINOMessages.ADD_MAKE_KDUINO:
finish();
break;
default:
this.processNavigationMessage(event.getMessage());
}
}
private void sendInfoMessage() {
if (this.bluetoothService.isConnected()) {
this.bluetoothManager.ExecuteOperation(KdUINOOperations.INFO_KdUINO, "");
}
if (connectingDialog != null) {
connectingDialog.dismiss();
}
}
@Subscribe
public void getMessage(KdUinoOperationMessageBusEvent message) {
if (message.getData() != null && message.getData() instanceof String)
{
String extracommand = new String();
extracommand = (String)message.getData();
this.bluetoothManager.ExecuteOperation(message.getMessage(), extracommand);
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (!this.bluetoothService.isConnected()) {
//for ()
//parent.getChildAt()
// ((TextView) view).setTextColor(getResources().getColor(R.color.white_pressed));
BluetoothDevice device = this.bluetoothService.getBTDevices().get(position);
this.macAddress = device.getAddress();
List<KDUINOBuoy> list = KDUINOBuoy.find(KDUINOBuoy.class, "mac_address= ?", this.macAddress);
if (list.size() > 0) {
buoyID = list.get(0).getId().toString();
try {
this.connectToDevice(list.get(0));
}
catch(Exception ex)
{
return;
}
// this.moveToControl(buoyID, this.macAddress);
}
else {
SettingsManager manager = new SettingsManager(this);
KDUINOBuoy buoy = new KDUINOBuoy(
"0",
"",
"",
manager.getUsername(),
this.macAddress,
0,0, 0);
buoy.save();
try {
this.connectToDevice(buoy);
}
catch(Exception ex)
{
return;
}
// this.moveToControl(Long.toString(buoy.getId()), this.macAddress);
//this.moveToKduinoModelSelection();
}
}
}
private void moveToKduinoModelSelection() {
SelectKdUINOModelFragment buoyFragment = SelectKdUINOModelFragment.newInstance(this.macAddress);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setCustomAnimations(
android.R.anim.slide_in_left,
android.R.anim.slide_out_right,
android.R.anim.slide_in_left,
android.R.anim.slide_out_right
);
ft.replace(R.id.fragment_container_bluetooth, buoyFragment);
ft.setTransition(FragmentTransaction.TRANSIT_NONE);
ft.addToBackStack(stackName);
ft.commit();
fragment = buoyFragment;
}
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == BluetoothService.REQUEST_ENABLE_BT) {
/*bus.post(new KdUinoMessageBusEvent(
KdUINOMessages.BLUETOOTH_ON, null)
); */
//this.moveToSearch();
if (resultCode == 0)
{
finish();
return;
}
bus.post(new KdUinoMessageBusEvent(KdUINOMessages.SEARCH_DEVICES, null));
this.invalidateOptionsMenu();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.getItem(0).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
if (bluetoothService.isConnected())
{
closeDialog();
}
return false;
}
});
return true;
}
public boolean onPrepareOptionsMenu (Menu menu)
{
if (this.bluetoothService.isConnected()) {
menu.getItem(0).setIcon(getResources().getDrawable(R.drawable.ic_action_connect_white));
}
else
{
menu.getItem(0).setIcon(getResources().getDrawable(R.drawable.ic_action_disconnect_white_off));
}
super.onPrepareOptionsMenu(menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_menu_connect_device)
{
if (this.bluetoothService.isConnected())
{
this.closeDialog();
}
}
//noinspection SimplifiableIfStatement
/*if (id == R.id.action_bluetooth_search) {
}
else if (id == R.id.action_bluetooth_activate)
{
this.bluetoothService.enableBluetooth();
supportInvalidateOptionsMenu();
}
else if (id == R.id.action_bluetooth_disconnect)
{
this.bluetoothService.disconnect();
this.tv.setText("Not Connected");
supportInvalidateOptionsMenu();
}*/
return super.onOptionsItemSelected(item);
}
private void connectToDescription(String id)
{
BluetoothManagerFragment bluetoothManagerFragment =
BluetoothManagerFragment.newInstance(id, this.macAddress);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setCustomAnimations(
android.R.anim.slide_in_left,
android.R.anim.slide_out_right,
android.R.anim.slide_in_left,
android.R.anim.slide_out_right
);
ft.replace(R.id.fragment_container_bluetooth, bluetoothManagerFragment);
ft.setTransition(FragmentTransaction.TRANSIT_NONE);
ft.addToBackStack(stackName);
ft.commit();
fragment = bluetoothManagerFragment;
}
private void moveToSearch()
{
BluetoothActivityFragment fragment = new BluetoothActivityFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setCustomAnimations(
android.R.anim.slide_in_left,
android.R.anim.slide_out_right,
android.R.anim.slide_in_left,
android.R.anim.slide_out_right
);
ft.replace(R.id.fragment_container_bluetooth, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_NONE);
ft.commit();
}
private void moveToControl(String id, String mac)
{
BluetoothManagerFragment bluetoothManagerFragment
= BluetoothManagerFragment.newInstance(id, mac);
fragment = bluetoothManagerFragment;
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setCustomAnimations(
android.R.anim.slide_in_left,
android.R.anim.slide_out_right,
android.R.anim.slide_in_left,
android.R.anim.slide_out_right
);
ft.replace(R.id.fragment_container_bluetooth, bluetoothManagerFragment);
ft.setTransition(FragmentTransaction.TRANSIT_NONE);
ft.addToBackStack(stackName);
ft.commit();
}
private void connectToDevice(KDUINOBuoy buoy)
{
if (buoy == null)
{
return;
}
if (!this.bluetoothService.isConnected()) {
if (connectBluetooth == null) {
connectBluetooth = new ConnectBluetooth(this.bus, this, this.bluetoothService, buoy);
connectBluetooth.execute(this.macAddress);
// this.bluetoothService.connect(this.macAddress);
}
else
{
if (connectBluetooth.getStatus() == AsyncTask.Status.FINISHED)
{
connectBluetooth = new ConnectBluetooth(this.bus, this, this.bluetoothService, buoy);
connectBluetooth.execute(this.macAddress);
}
}
}
this.invalidateOptionsMenu();
}
@Override
public void clickView(View v) {
if (fragment != null)
{
fragment.clickView(v);
}
}
@Override
public void onBackPressed() {
int count = getSupportFragmentManager().getBackStackEntryCount();
if (count == 0) {
super.onBackPressed();
}
else {
if (this.bluetoothService.isConnected()) {
this.closeDialog();
/* new AlertDialog.Builder(this)
.setMessage("Are you sure to disconnect?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("No", null)
.show(); */
}
else
{
getSupportFragmentManager().popBackStack(stackName, FragmentManager.POP_BACK_STACK_INCLUSIVE);
super.onBackPressed();
}
}
}
private void closeDialog() {
MaterialDialog dialog = new MaterialDialog.Builder(this)
.title("Confirm disconnect")
.content("You will disconnect from the kduino buoy.")
.positiveColorRes(R.color.colorPrimaryDark)
.neutralColorRes(R.color.colorPrimary)
.negativeColorRes(R.color.colorPrimary)
.positiveText(R.string.ok_dialog)
.negativeText(R.string.cancel_dialog)
.callback(new MaterialDialog.ButtonCallback() {
@Override
public void onPositive(MaterialDialog dialog) {
((BaseActivity) ctx).clearStack();
if (analysisFragment != null && analysisFragment.isVisible()) {
analysisFragment.dismissAllowingStateLoss();
}
bus.post(
new KdUinoMessageBusEvent(
KdUINOMessages.DISCONNECT_KDUINO, null)
);
finish();
}
}).build();
dialog.show();
}
@Override
public String foundDevice(String mac, String name) {
List<KDUINOBuoy> list = KDUINOBuoy.find(KDUINOBuoy.class, "mac_address= ?", mac);
if (list.size() > 0)
{
return list.get(0).Name;
}
return name;
}
private void displayData(DataSet dataset)
{
MaterialDialog dialog = new MaterialDialog.Builder(this)
.title(R.string.dialog_kd_r2_title)
.customView(R.layout.fragment_analysis, false)
.positiveColorRes(R.color.colorPrimaryDark)
.neutralColorRes(R.color.colorPrimary)
.negativeColorRes(R.color.colorPrimary)
.callback(new MaterialDialog.ButtonCallback() {
@Override
public void onPositive(MaterialDialog dialog) {
View view = dialog.getCustomView();
dialog.dismiss();
}
@Override
public void onNeutral(MaterialDialog dialog)
{
SettingsManager manager = new SettingsManager(dialog.getContext());
String nameFile = manager.getLastTotalFileName();
bus.post(new KdUinoDataFileMessageBusEvent(nameFile));
dialog.dismiss();
}
@Override
public void onNegative(MaterialDialog dialog) {
}
})
.neutralText(R.string.action_send_data_to_server)
.positiveText(R.string.ok_dialog)
// .negativeText(R.string.cancel_dialog)
.build();
View view = dialog.getCustomView();
mChart = (LineChart) view.findViewById(R.id.chart1);
mChart.setOnChartGestureListener(null);
mChart.setOnChartValueSelectedListener(null);
mChart.setDrawGridBackground(false);
// no description text
mChart.setDescription("");
mChart.setNoDataTextDescription("You need to provide data for the chart.");
// enable value highlighting
mChart.setHighlightEnabled(true);
// enable touch gestures
mChart.setTouchEnabled(true);
// enable scaling and dragging
mChart.setDragEnabled(false);
mChart.setScaleEnabled(false);
// mChart.setScaleXEnabled(true);
// mChart.setScaleYEnabled(true);
// if disabled, scaling can be done on x- and y-axis separately
mChart.setPinchZoom(false);
/*DiscreteSeekBar discreteSeekBar = (DiscreteSeekBar)view.findViewById(R.id.sample_r2_data);
discreteSeekBar.setMin(2);
discreteSeekBar.setMax(dataset.getAnalysises().size());
discreteSeekBar.setOnProgressChangeListener(new DiscreteSeekBar.OnProgressChangeListener() {
@Override
public void onProgressChanged(DiscreteSeekBar seekBar, int value, boolean fromUser) {
setData(mChart, value, getData());
}
@Override
public void onStartTrackingTouch(DiscreteSeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(DiscreteSeekBar seekBar) {
}
}); */
/*DiscreteSeekBar discreteSeekBar =
(DiscreteSeekBar)view.findViewById(R.id.sample_time_dsb);
discreteSeekBar.setMin(1);
discreteSeekBar.setMax(59); */
/* int sampleTime = 0;
if (statusData.SampleTime > 1000)
{
sampleTime = statusData.SampleTime / 1000;
} */
//discreteSeekBar.setProgress(statusData.SampleTime);
dialog.show();
setData(mChart, dataset);
}
private void setData(LineChart mChart, DataSet dataSet)
{
ArrayList<Analysis> analysises = dataSet.getAnalysises();
ArrayList<String> xVals = new ArrayList<String>();
ArrayList<Entry> kdVals = new ArrayList<Entry>();
ArrayList<Entry> r2Vals = new ArrayList<Entry>();
int i = 0;
for (Analysis analysis : analysises)
{
if (Double.isNaN(analysis.R2))
{
continue;
}
if (Double.isNaN(analysis.Kd))
{
continue;
}
xVals.add(analysis.date.replace("_", " "));
kdVals.add(new Entry((float)analysis.Kd, i));
r2Vals.add(new Entry((float)analysis.R2, i));
i++;
}
LineDataSet set1 = new LineDataSet(kdVals, "Kd data");
LineDataSet set2 = new LineDataSet(r2Vals, "R2 data");
set1.setColor(Color.RED);
set1.setCircleColor(Color.RED);
set1.setLineWidth(1f);
set1.setCircleSize(3f);
set1.setDrawCircleHole(false);
set1.setValueTextSize(9f);
set1.setFillAlpha(65);
set1.setFillColor(Color.RED);
set2.setColor(Color.BLUE);
set2.setCircleColor(Color.BLUE);
set2.setLineWidth(1f);
set2.setCircleSize(3f);
set2.setDrawCircleHole(false);
set2.setValueTextSize(9f);
set2.setFillAlpha(65);
set2.setFillColor(Color.BLUE);
ArrayList<LineDataSet> dataSets = new ArrayList<LineDataSet>();
dataSets.add(set1); // add the datasets
dataSets.add(set2);
// create a data object with the datasets
LineData data = new LineData(xVals, dataSets);
// set data
mChart.setData(data);
mChart.setVisibleXRange(4); // allow 20 values to be displayed at once on the x-axis, not more
mChart.moveViewToX(kdVals.size() - 5); // se
//mChart.setVisibleYRange(3, null);
//mChart.moveViewToY(kdVals.get(kdVals.size() - 1).getVal(), null);
}
private void launchAnalysisFragment()
{
System.gc();
//Mater
FragmentManager fm = getSupportFragmentManager();
analysisFragment = AnalysisFragment.newInstance("", "");
analysisFragment.show(fm, "map fragment");
}
public void setData(DataSet dataset)
{
this.dataset = dataset;
}
public DataSet getData()
{
return dataset;
}
}
|
//package com.hedong.hedongwx;
//
//import java.util.List;
//import java.util.Map;
//
//import org.junit.Test;
//import org.junit.runner.RunWith;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.boot.test.context.SpringBootTest;
//import org.springframework.test.context.junit4.SpringRunner;
//
//import com.alibaba.fastjson.JSON;
//import com.hedong.hedongwx.dao.CollectStatisticsDao;
//import com.hedong.hedongwx.entity.Parameters;
//import com.hedong.hedongwx.service.CollectStatisticsService;
//
//@RunWith(SpringRunner.class)
//@SpringBootTest
//public class HedongwxApplicationTests {
//
// @Autowired
// private CollectStatisticsDao collectStatisticsDao;
//
// @Test
// public void dealerIncomeCollect(){
// Parameters parame = new Parameters();
// String str = "2020-08-11";
// parame.setStartTime(str + " 00:00:00");
// parame.setEndTime(str + " 23:59:59");
// List<Map<String,Object>> dealerIncomeCollect = collectStatisticsDao.dealerIncomeCollect(parame);
// System.out.println(JSON.toJSON(dealerIncomeCollect));
// }
//
//}
|
package com.vilio.plms.service;
import com.vilio.plms.dao.HouseDao;
import com.vilio.plms.dao.PlmsContractInfoDao;
import com.vilio.plms.dao.RepaymentScheduleDao;
import com.vilio.plms.exception.ErrorException;
import com.vilio.plms.glob.ReturnCode;
import com.vilio.plms.pojo.House;
import com.vilio.plms.service.base.BaseService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
/**
* 类名: Plms000011<br>
* 功能:合同信息信息查询<br>
* 版本: 1.0<br>
* 日期: 2017年7月19日<br>
* 作者: zx<br>
* 版权:vilio<br>
* 说明:<br>
*/
@Service
public class Plms000011 extends BaseService {
private static final Logger logger = Logger.getLogger(Plms000011.class);
@Resource
private HouseDao houseDao;
@Resource
PlmsContractInfoDao plmsContractInfoDao;
@Resource
private RepaymentScheduleDao repaymentScheduleDao;
/**
* 参数验证
*
* @param body
*/
public void checkParam(Map<String, Object> body) throws ErrorException {
checkField(ObjectUtils.toString(body.get("contractCode")), "合同编码", null, null);
}
/**
* 主业务流程空实现
*
* @param head
* @param body
*/
public void busiService(Map<String, Object> head, Map<String, Object> body, Map<String, Object> resultMap) throws ErrorException, Exception {
String contractCode = (String) body.get("contractCode");
//查询贷款业务信息
Map contractInfo = plmsContractInfoDao.queryContractInfoByCode(contractCode);
if (contractInfo == null) {
throw new ErrorException(ReturnCode.CONTRACT_INFO_FAIL, "");
}
//收集抵押物信息
List<House> houseList = houseDao.qryHouseForContract(contractCode);
if (houseList == null || houseList.size() < 1) {
throw new ErrorException(ReturnCode.HOUSE_INFO_FAIL, "");
}
//拼装产证地址
StringBuffer strTotalHouse = new StringBuffer();
for(int i = 0; i < houseList.size(); i++){
House house = houseList.get(i);
if(i>0){
strTotalHouse.append(",");
}
strTotalHouse.append(house.getCertificateAddress());
}
contractInfo.put("certificateAddress", strTotalHouse.toString());
//计算期数,还款计划表中大于今天,小于等于本金归还日,统计条数
String loanCount = repaymentScheduleDao.qryLoanCount(contractInfo);
if (loanCount == null || "".equals(loanCount) || Integer.parseInt(loanCount) == 0) {
//最高期数为0,不能进行借款操作
throw new ErrorException(ReturnCode.LOAN_COUNT_FAIL, "");
}
contractInfo.put("loanCount", loanCount);
resultMap.putAll(contractInfo);
}
}
|
package com.smxknife.servlet.springboot.demo01.servlet;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
/**
* @author smxknife
* 2018-12-26
*/
@WebServlet(name = "def", value = "/def/*", initParams = {
@WebInitParam(name = "msg", value = "default servlet")
})
public class MyServletDef extends AbsMyServlet {
}
|
package uns.ac.rs.hostplatserver.controller;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
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;
import uns.ac.rs.hostplatserver.dto.MilestoneDTO;
import uns.ac.rs.hostplatserver.dto.ProjectDTO;
import uns.ac.rs.hostplatserver.dto.StatisticBackDTO;
import uns.ac.rs.hostplatserver.dto.StatisticsDTO;
import uns.ac.rs.hostplatserver.dto.TaskDTO;
import uns.ac.rs.hostplatserver.dto.UserDTO;
import uns.ac.rs.hostplatserver.dto.UserProjectDTO;
import uns.ac.rs.hostplatserver.dto.UserTaskDTO;
import uns.ac.rs.hostplatserver.exception.ResourceNotFoundException;
import uns.ac.rs.hostplatserver.mapper.MilestoneMapper;
import uns.ac.rs.hostplatserver.mapper.ProjectMapper;
import uns.ac.rs.hostplatserver.mapper.TaskMapper;
import uns.ac.rs.hostplatserver.mapper.UserMapper;
import uns.ac.rs.hostplatserver.model.LabelEntity;
import uns.ac.rs.hostplatserver.model.Milestone;
import uns.ac.rs.hostplatserver.model.Project;
import uns.ac.rs.hostplatserver.model.Task;
import uns.ac.rs.hostplatserver.model.User;
import uns.ac.rs.hostplatserver.resource.LabelResource;
import uns.ac.rs.hostplatserver.service.ProjectService;
import uns.ac.rs.hostplatserver.service.TaskService;
import uns.ac.rs.hostplatserver.service.UserService;
import uns.ac.rs.hostplatserver.util.DateUtil;
@RestController
@RequestMapping("/api/project")
public class ProjectController {
@Autowired
private ProjectService projectService;
@Autowired
private UserService userService;
@Autowired
private TaskService taskService;
@GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ProjectDTO> getProject(@PathVariable("id") Long id) throws ResourceNotFoundException {
Project project = projectService.findOne(id);
return new ResponseEntity<>(ProjectMapper.toDTO(project), HttpStatus.OK);
}
@GetMapping(value = "/getAll", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<ProjectDTO>> getProjects() {
List<Project> projects = projectService.findAll();
List<ProjectDTO> projectsDTO = new ArrayList<ProjectDTO>();
for (Project project: projects) {
projectsDTO.add(ProjectMapper.toDTO(project));
}
return new ResponseEntity<>(projectsDTO, HttpStatus.OK);
}
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ProjectDTO> createProject(@RequestBody ProjectDTO projectDTO) throws Exception {
Project savedProject = projectService.create(ProjectMapper.toProject(projectDTO));
return new ResponseEntity<>(ProjectMapper.toDTO(savedProject), HttpStatus.CREATED);
}
@PutMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ProjectDTO> updateProject(@RequestBody ProjectDTO projectDTO) throws Exception {
Project updatedProject = projectService.update(ProjectMapper.toProject(projectDTO));
return new ResponseEntity<>(ProjectMapper.toDTO(updatedProject), HttpStatus.OK);
}
@DeleteMapping(value = "/{id}")
public ResponseEntity<Project> deleteProject(@PathVariable("id") Long id) {
projectService.delete(id);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@GetMapping(value = "/allForUser/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<ProjectDTO>> getProjectsForUser(@PathVariable("id") Long id) {
List<Project> projects = projectService.findAllForUser(id);
List<ProjectDTO> projectsDTO = new ArrayList<ProjectDTO>();
for (Project project: projects) {
projectsDTO.add(ProjectMapper.toDTO(project));
}
return new ResponseEntity<>(projectsDTO, HttpStatus.OK);
}
@GetMapping(value = "/allPublic", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<Project>> getPublic() {
List<Project> projects = projectService.findAllPublic();
List<ProjectDTO> projectsDTO = new ArrayList<ProjectDTO>();
for (Project project: projects) {
projectsDTO.add(ProjectMapper.toDTO(project));
}
return new ResponseEntity<>(projects, HttpStatus.OK);
}
@GetMapping(value = "/allUserForProject/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<UserDTO>> getUsersForProject(@PathVariable("id") Long id) {
Set<User> users = projectService.findOne(id).getUsers();
List<UserDTO> usersDTO = new ArrayList<UserDTO>();
for (User user: users) {
usersDTO.add(UserMapper.toDTO(user));
}
System.out.println("MILICA");
System.out.println(usersDTO.size());
return new ResponseEntity<>(usersDTO, HttpStatus.OK);
}
@GetMapping(value = "/allMilestoneForProject/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<MilestoneDTO>> getMilestoneForProjectWithTask(@PathVariable("id") Long id) {
List<Milestone> milestones = projectService.findAllMilestonesForProjectWithTask(id);
List<MilestoneDTO> milestonesDTO = new ArrayList<MilestoneDTO>();
for (Milestone milestone: milestones) {
milestonesDTO.add(MilestoneMapper.toDTO(milestone));
}
return new ResponseEntity<>(milestonesDTO, HttpStatus.OK);
}
@GetMapping(value = "/updatePrivateProject/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ProjectDTO> updatePrivateProject(@PathVariable("id") Long id) throws ResourceNotFoundException {
Project project = projectService.findOne(id);
if(project.isPrivate_project()) {
project.setPrivate_project(false);
}else {
project.setPrivate_project(true);
}
return new ResponseEntity<>(ProjectMapper.toDTO(project), HttpStatus.OK);
}
@GetMapping(value = "/allMilestone/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<MilestoneDTO>> getMilestoneForProject(@PathVariable("id") Long id) {
List<Milestone> milestones = projectService.findAllMilestonesForProject(id);
List<MilestoneDTO> milestonesDTO = new ArrayList<MilestoneDTO>();
for (Milestone milestone: milestones) {
milestonesDTO.add(MilestoneMapper.toDTO(milestone));
}
return new ResponseEntity<>(milestonesDTO, HttpStatus.OK);
}
@GetMapping(value = "/getAllNewUserForProject/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<UserDTO>> getAllNewUserForProject(@PathVariable("id") Long id, boolean list) {
Set<User> users = projectService.findAllUsersForProject(id);
List<UserDTO> allUser = userService.findAll();
List<UserDTO> usersDTO = new ArrayList<UserDTO>();
for (User user: users) {
usersDTO.add(UserMapper.toDTO(user));
}
allUser.removeAll(usersDTO);
return new ResponseEntity<>(allUser, HttpStatus.OK);
}
@PostMapping(value = "/setUsersToProject", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Set<UserDTO>> setUsersToProject(@RequestBody UserProjectDTO dto) {
Project project = projectService.findOne(dto.getProject_id());
Set<User> usersOnProject = project.getUsers();
Set<User> usersSaFronta = new HashSet<>();
for (UserDTO user: dto.getUsers()) {
usersSaFronta.add(UserMapper.toUser(user));
}
Set<User> users = projectService.setUsersToProject(dto.getProject_id(), usersOnProject, usersSaFronta);
Set<UserDTO> returnDTO = new HashSet<>();
for (User user : users) {
returnDTO.add(UserMapper.toDTO(user));
}
return new ResponseEntity<>(returnDTO, HttpStatus.OK);
}
@GetMapping(value = "/allUserForTask/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<UserDTO>> getUsersForTask(@PathVariable("id") Long id) {
Set<User> users = projectService.findAllUsersForProject(id);
List<UserDTO> usersDTO = new ArrayList<UserDTO>();
for (User user: users) {
usersDTO.add(UserMapper.toDTO(user));
}
return new ResponseEntity<>(usersDTO, HttpStatus.OK);
}
@PostMapping(value = "/statistics", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<StatisticBackDTO> statistics(@RequestBody StatisticsDTO dto) {
StatisticBackDTO back = projectService.statistic(dto);
return new ResponseEntity<>(back, HttpStatus.OK);
}
}
|
package com.accenture.flowershop.fe.dto;
public class UserDTO {
private String login;
private String password;
private String name;
private String address;
private String phoneNumber;
private double score;
private int sale;
private String role;
public UserDTO(){
}
public UserDTO(String login, String password, String name,
String address, String phoneNumber, double score, int sale, String role){
this.login = login;
this.password = password;
this.name = name;
this.address = address;
this.phoneNumber = phoneNumber;
this.score = score;
this.sale = sale;
this.role = role;
}
public String getLogin() {
return login;
}
public String getPassword() {
return password;
}
public double getScore() {
return score;
}
public int getSale() {
return sale;
}
public String getAddress() {
return address;
}
public String getName() {
return name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setLogin(String login) {
this.login = login;
}
public void setPassword(String password) {
this.password = password;
}
public void setAddress(String address) {
this.address = address;
}
public void setName(String name) {
this.name = name;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setSale(int sale) {
this.sale = sale;
}
public void setScore(double score) {
this.score = score;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
|
package com.uzabase.schema;
import javax.xml.bind.annotation.*;
public class Item {
@XmlElement(name="title")
private String title;
@XmlElement(name="link")
private String link;
@XmlElement(name="description")
private String description;
@XmlElement(name="pubDate")
private String pubDate;
@XmlElement(name="guid")
private Guid guid;
@XmlElement(name="enclosure")
private Enclosure enclosure;
public Item(){}
public Item(String pTitle, String pLink, String pDescription,
String pPubDate, Guid pGuid, Enclosure pEnclosure){
title = pTitle;
link = pLink;
description = pDescription;
pubDate = pPubDate;
guid = pGuid;
enclosure = pEnclosure;
}
public String getTitle() {
return title;
}
public String getLink() {
return link;
}
public String getDescription() {
return description;
}
public String getPubDate() {
return pubDate;
}
public Guid getGuid() {
return guid;
}
public Enclosure getEnclosure() {
return enclosure;
}
@Override
public String toString() {
return "Item [title=" + title + ", link=" + link + ", description=" + description.toString() + ", pubDate=" + pubDate
+ ", guid=" + guid.toString() + ", enclosure=" + enclosure.toString() + "]";
}
}
|
package task164;
import common.Watch;
import java.util.Arrays;
import java.util.HashMap;
/**
* @author Igor
*/
public class Main164 {
static final HashMap<Number, Long> counts = new HashMap<>();
public static void main(String[] args) {
Watch.start();
long count = 0;
for (int i = 1; i <= 9; i++)
count += count(new Number(19, new int[]{0, 0, i}));
System.out.println(count);
Watch.stop();
}
private static long count(Number number) {
if (counts.get(number) != null) return counts.get(number);
long count = 0;
if (number.getSum() > 9) return 0;
if (number.digitCount > 0)
for (int i = 0; i <= 9; i++)
count += count(new Number(number.digitCount - 1, new int[]{number.digits[1], number.digits[2], i}));
else count++;
counts.put(number, count);
return count;
}
private static class Number {
int digitCount, digits[] = new int[3];
private Number(int digitCount, int[] digits) {
this.digitCount = digitCount;
this.digits = digits;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Number)) return false;
Number that = (Number) o;
return digitCount == that.digitCount && Arrays.equals(digits, that.digits);
}
@Override
public int hashCode() {
return 31 * digitCount + Arrays.hashCode(digits);
}
public int getSum() {
return digits[0] + digits[1] + digits[2];
}
}
}
|
package org.houstondragonacademy.archer.services;
import org.hibernate.validator.internal.xml.mapping.MappingXmlParser;
import org.houstondragonacademy.archer.dao.CoursePeriodRepository;
import org.houstondragonacademy.archer.dao.CourseRepository;
import org.houstondragonacademy.archer.dao.SemesterRepository;
import org.houstondragonacademy.archer.dao.entity.Account;
import org.houstondragonacademy.archer.dao.entity.Course;
import org.houstondragonacademy.archer.dao.entity.CoursePeriod;
import org.houstondragonacademy.archer.dao.entity.Semester;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
//@DataMongoTest
//@Import(CourseServiceImpl.class)
class CourseServiceImplTest {
@InjectMocks
private CourseServiceImpl courseService;
// mock AccountRepository of AccountServiceImpl
@Mock
private CourseRepository courseRepository;
@Mock
private SemesterRepository semesterRepository;
@Mock
private CoursePeriodRepository periodRepository;
private static Course course1;
private static Course course2;
private static final String courseNameCourse1 = "english101";
private static String courseID;
private static Semester semesterForCourse1;
private static final String campusForCourse1 = "online";
private static CoursePeriod coursePeriod1;
private static CoursePeriod coursePeriod2;
private static List<CoursePeriod> listCoursePeriod1;
private static Account teacherAccount;
private static LocalDate classStartTime;
private static List<LocalDate> listClassStart;
//private static final String coursePeriodCampus = "onLine";
@BeforeEach
void setUp() {
MockitoAnnotations.initMocks(this);
listClassStart = new ArrayList<>();
classStartTime= LocalDate.now().minusDays(1);
listClassStart.add(classStartTime);
semesterForCourse1 = Semester.builder().startDateTime(LocalDateTime.now().minusDays(1)).endDateTime(LocalDateTime.now().plusDays(1)).name("fall2020").build();
coursePeriod1 = CoursePeriod.builder().campus(campusForCourse1).parentCourseId("110").classStartDateTimes(listClassStart).build();
coursePeriod2 = CoursePeriod.builder().campus("katy").parentCourseId("111").classStartDateTimes(listClassStart).build();
listCoursePeriod1 = new ArrayList<>();
teacherAccount = Account.builder()
.email("cat.@tamu.edu")
.phone("111-111-1111")
.name("Zhicong Zhang")
.build();
listCoursePeriod1.add(coursePeriod1);
listCoursePeriod1.add(coursePeriod2);
course1 = Course.builder()
.courseTitle(courseNameCourse1)
.semester(semesterForCourse1)
.periods(listCoursePeriod1)
.displayCategory("reading exercies")
.minGradeLevel(Course.GradeLevel.Grade1)
.maxGradeLevel(Course.GradeLevel.Grade12)
.pricingPlan("500")
.teacherAccount(teacherAccount)
.build();
course1.setId("11100");
courseID = course1.getId();
course2 = Course.builder()
.courseTitle("math151")
.semester(semesterForCourse1)
.periods(listCoursePeriod1)
.displayCategory("reading exercies")
.minGradeLevel(Course.GradeLevel.Grade9)
.maxGradeLevel(Course.GradeLevel.Grade12)
.pricingPlan("500")
.teacherAccount(teacherAccount)
.build();
course2.setId("11101");
Mono<Course> courseMono = Mono.just(course1);
Flux<Course> courseFlux = Flux.just(course1,course2);
Flux<Semester> semesterFlux = Flux.just(semesterForCourse1);
Mono<CoursePeriod> periodMono = Mono.just(coursePeriod1);
Mockito.when(courseRepository.insert(Mockito.any(Course.class))).thenReturn(courseMono);
Mockito.when(courseRepository.save(Mockito.any(Course.class))).thenReturn(courseMono);
Mockito.when(courseRepository.findAll()).thenReturn(courseFlux);
Mockito.when(courseRepository.findById(Mockito.anyString())).thenReturn(courseMono);
Mockito.when(courseRepository.findByCourseTitle("english101")).thenReturn(courseMono);
Mockito.when(semesterRepository.findSemestersByNameStartsWith("fall2020")).thenReturn(semesterFlux);
Mockito.when(courseRepository.findBySemester(semesterForCourse1)).thenReturn(courseFlux);
Mockito.when(semesterRepository.findAll()).thenReturn(semesterFlux);
Mockito.when(periodRepository.findByParentCourseIdAndCampus("110","online")).thenReturn(periodMono);
Mockito.when(periodRepository.insert(Mockito.any(CoursePeriod.class))).thenReturn(periodMono);
Mockito.when(periodRepository.save(Mockito.any(CoursePeriod.class))).thenReturn(periodMono);
Mockito.when(periodRepository.findById(Mockito.anyString())).thenReturn(periodMono);
}
@Test
void createCourse() {
Mono<Course> courseMono = courseService.createCourse(course1);
Course course = courseMono.block();
assertNotNull(course);
assertEquals(courseNameCourse1, course.getCourseTitle());
}
@Test
void updateCourse() {
Mono<Course> courseMono = courseService.updateCourse(course1);
Course course = courseMono.block();
assertNotNull(course);
assertEquals(courseNameCourse1, course.getCourseTitle());
}
@Test
void deleteCourse() {
Mono<Boolean> courseMono = courseService.deleteCourse(courseID);
Boolean isDeleted = courseMono.block();
assert isDeleted != null;
assertTrue(isDeleted);
}
@Test
void findOne() {
Mono<Course> courseMono = courseService.findOne(courseNameCourse1,courseID);
Course course = courseMono.block();
assertNotNull(course);
assertEquals(courseNameCourse1, course.getCourseTitle());
}
@Test
void findAll() {
Flux<Course> courseFlux = courseService.findAll("fall2020",campusForCourse1);
List<Course> courses = new ArrayList<>();
courseFlux.subscribe(courses::add);
assertEquals(2, courses.size());
}
@Test
void availableCourses() {
List<Course> courseFlux = courseService.availableCourses("fall2020",campusForCourse1);
assertEquals(2, courseFlux.size());
}
@Test
void createCoursePeriod() {
Mono<CoursePeriod> coursePeriodMono = courseService.createCoursePeriod(coursePeriod1);
CoursePeriod coursePeriod = coursePeriodMono.block();
assertNotNull(coursePeriod);
assertEquals(campusForCourse1, coursePeriod.getCampus());
}
@Test
void deleteCoursePeriod() {
Mono<Boolean> coursePeriodMono = courseService.deleteCoursePeriod(courseID);
Boolean isDeleted = coursePeriodMono.block();
assert isDeleted != null;
assertTrue(isDeleted);
}
@Test
void updateCoursesBySemesterBulk() {
Flux<Course> courseFlux = courseService.updateCoursesBySemesterBulk();
List<Course> courses = new ArrayList<>();
courseFlux.subscribe(courses::add);
assertEquals(2, courses.size());
}
}
|
package com.usecasepoint.model;
import lombok.Getter;
import lombok.Setter;
@Getter @Setter
public class AktorRequest {
private String nama;
private String kategori;
private String proyekId;
}
|
package com.cheforder;
import android.app.Application;
import android.content.Context;
import android.support.multidex.MultiDex;
import com.facebook.react.ReactApplication;
import com.github.kevinejohn.keyevent.KeyEventPackage;
import com.microsoft.codepush.react.CodePush;
import com.horcrux.svg.SvgPackage;
import com.reactnative.ivpusic.imagepicker.PickerPackage;
import com.evollu.react.fcm.FIRMessagingPackage;
import com.oblador.vectoricons.VectorIconsPackage;
import com.brentvatne.react.ReactVideoPackage;
import com.reactnative.photoview.PhotoViewPackage;
import com.devfd.RNGeocoder.RNGeocoderPackage;
import com.joshblour.reactnativepermissions.ReactNativePermissionsPackage;
import com.reactlibrary.RNThumbnailPackage;
import com.wix.interactable.Interactable;
import com.learnium.RNDeviceInfo.RNDeviceInfo;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import java.util.Arrays;
import java.util.List;
public class MainApplication extends Application implements ReactApplication {
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
protected String getJSBundleFile() {
return CodePush.getJSBundleFile();
}
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new KeyEventPackage(),
new CodePush(getResources().getString(R.string.reactNativeCodePush_androidDeploymentKey), getApplicationContext(), BuildConfig.DEBUG),
new SvgPackage(),
new PickerPackage(),
new FIRMessagingPackage(),
new VectorIconsPackage(),
new ReactVideoPackage(),
new PhotoViewPackage(),
new RNGeocoderPackage(),
new ReactNativePermissionsPackage(),
new RNThumbnailPackage(),
new Interactable(),
new RNDeviceInfo()
);
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
}
}
|
package cn.chinaunicom.monitor.viewholders;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import cn.chinaunicom.monitor.R;
/**
* Created by yfYang on 2017/8/16.
*/
public class MainframeDetailViewHolder extends BaseViewHolder {
public TextView monitorItem;
public TextView monitorTime;
public TextView monitorData;
public Button chartBtn;
public MainframeDetailViewHolder(View view) {
super(view);
monitorItem = (TextView) view.findViewById(R.id.monitorItem);
monitorTime = (TextView) view.findViewById(R.id.monitorTime);
monitorData = (TextView) view.findViewById(R.id.monitorData);
//chartBtn = (Button) view.findViewById(R.id.chartBtn);
}
}
|
package com.nta.lc_server.ui.discount;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.database.FirebaseDatabase;
import com.nta.lc_server.R;
import com.nta.lc_server.adapter.MyDiscountAdapter;
import com.nta.lc_server.common.Common;
import com.nta.lc_server.common.MySwipeHelper;
import com.nta.lc_server.eventbus.ToastEvent;
import com.nta.lc_server.model.DiscountModel;
import org.greenrobot.eventbus.EventBus;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import dmax.dialog.SpotsDialog;
public class DiscountFragment extends Fragment {
@BindView(R.id.recycler_discount)
RecyclerView recycler_discount;
AlertDialog dialog;
LayoutAnimationController layoutAnimationController;
MyDiscountAdapter adapter;
List<DiscountModel> discountModelList;
MySwipeHelper swipeButton;
private DiscountViewModel discountViewModel;
private Unbinder unbinder;
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
discountViewModel = new ViewModelProvider(this).get(DiscountViewModel.class);
View root = inflater.inflate(R.layout.fragment_discount, container, false);
unbinder = ButterKnife.bind(this, root);
initViews();
discountViewModel.getMessageError().observe(getViewLifecycleOwner(), s -> {
Toast.makeText(getContext(), s, Toast.LENGTH_SHORT).show();
dialog.dismiss();
});
discountViewModel.getDiscountMutableLiveData().observe(getViewLifecycleOwner(), list -> {
dialog.dismiss();
if (list == null)
discountModelList = new ArrayList<>();
else
discountModelList = list;
adapter = new MyDiscountAdapter(getContext(), discountModelList);
recycler_discount.setAdapter(adapter);
recycler_discount.setLayoutAnimation(layoutAnimationController);
});
return root;
}
private void initViews() {
dialog = new SpotsDialog.Builder().setContext(getContext()).setCancelable(false).build();
setHasOptionsMenu(true);
layoutAnimationController = AnimationUtils.loadLayoutAnimation(getContext(), R.anim.layout_item_from_left);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
recycler_discount.setLayoutManager(layoutManager);
recycler_discount.addItemDecoration(new DividerItemDecoration(getContext(), layoutManager.getOrientation()));
swipeButton = new MySwipeHelper(getContext(), recycler_discount, 200) {
@Override
public void instantiateMyButton(RecyclerView.ViewHolder viewHolder, List<MyButton> buf) {
buf.add(new MyButton(getContext(), "Xoá", 35, 0, Color.parseColor("#333639"),
pos -> {
Common.discountSelected = discountModelList.get(pos);
showDeleteDialog();
}));
buf.add(new MyButton(getContext(), "Cập nhật", 35, 0, Color.parseColor("#414243"),
pos -> {
Common.discountSelected = discountModelList.get(pos);
showUpdateDialog();
}));
}
};
}
private void showAddDialog() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
Calendar selectedDate = Calendar.getInstance();
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("TẠO MÃ GIẢM GIÁ");
builder.setMessage("Hãy điền thông tin bên dưới");
View itemView = LayoutInflater.from(getContext()).inflate(R.layout.layout_update_discount, null);
EditText edt_code = itemView.findViewById(R.id.edt_code);
EditText edt_percent = itemView.findViewById(R.id.edt_percent);
EditText edt_valid = itemView.findViewById(R.id.edt_valid);
ImageView img_calendar = itemView.findViewById(R.id.pickDate);
//Create don't have set default data
//Event
DatePickerDialog.OnDateSetListener listener = ((view, year, month, dayOfMonth) -> {
selectedDate.set(Calendar.YEAR, year);
selectedDate.set(Calendar.MONTH, month);
selectedDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
edt_valid.setText(simpleDateFormat.format(selectedDate.getTime()));
});
img_calendar.setOnClickListener(view -> {
Calendar calendar = Calendar.getInstance();
new DatePickerDialog(getContext(), listener, calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH))
.show(); //Don't forget it
});
builder.setNegativeButton("Đóng", (dialogInterface, i) -> dialogInterface.dismiss())
.setPositiveButton("Thêm", (dialogInterface, i) -> {
String code = edt_code.getText().toString().trim();
try {
int percent = Integer.parseInt(edt_percent.getText().toString().trim());
String noWhiteSpace = "\\A\\w{3,10}\\z";
DiscountModel discountModel = new DiscountModel();
discountModel.setKey(edt_code.getText().toString());
discountModel.setPercent(Integer.parseInt(edt_percent.getText().toString().trim()));
discountModel.setUntilDate(selectedDate.getTimeInMillis()); //fix v103
//discountModel.setKey(edt_code.getText().toString().toLowerCase()); //fix v103
discountModel.setKey(edt_code.getText().toString().toUpperCase());
if (!code.matches(noWhiteSpace)) {
Toast.makeText(getContext(), "Hãy kiểm tra lại mã giảm giá", Toast.LENGTH_SHORT).show();
return;
} else if (percent > 80) {
Toast.makeText(getContext(), "Mã giảm giá không được vượt quá 80%", Toast.LENGTH_LONG).show();
return;
}
createDiscount(discountModel);
} catch (Exception e) {
Toast.makeText(getContext(), "Bạn chưa điền đủ thông tin!", Toast.LENGTH_SHORT).show();
}
});
builder.setView(itemView);
AlertDialog dialog = builder.create();
dialog.show();
}
private void createDiscount(DiscountModel discountModel) {
FirebaseDatabase.getInstance()
.getReference(Common.DISCOUNT_REF)
.child(discountModel.getKey())
.setValue(discountModel)
.addOnFailureListener(e -> {
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
})
.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
discountViewModel.loadDiscount();
adapter.notifyDataSetChanged();
EventBus.getDefault().postSticky(new ToastEvent(Common.ACTION.CREATE, true));
}
});
}
private void showUpdateDialog() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
Calendar selectedDate = Calendar.getInstance();
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("CẬP NHẬT MÃ GIẢM GIÁ");
builder.setMessage("Hãy điền thông tin bên dưới");
View itemView = LayoutInflater.from(getContext()).inflate(R.layout.layout_update_discount, null);
EditText edt_code = itemView.findViewById(R.id.edt_code);
EditText edt_percent = itemView.findViewById(R.id.edt_percent);
EditText edt_valid = itemView.findViewById(R.id.edt_valid);
ImageView img_calendar = itemView.findViewById(R.id.pickDate);
//Set data
edt_code.setText(Common.discountSelected.getKey());
edt_code.setEnabled(false); //Lock key
edt_percent.setText(new StringBuilder().append(Common.discountSelected.getPercent()));
edt_valid.setText(simpleDateFormat.format(Common.discountSelected.getUntilDate()));
//Event
DatePickerDialog.OnDateSetListener listener = ((view, year, month, dayOfMonth) -> {
selectedDate.set(Calendar.YEAR, year);
selectedDate.set(Calendar.MONTH, month);
selectedDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
edt_valid.setText(simpleDateFormat.format(selectedDate.getTime()));
});
img_calendar.setOnClickListener(view -> {
Calendar calendar = Calendar.getInstance();
new DatePickerDialog(getContext(), listener, calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH))
.show(); //Don't forget it
});
builder.setNegativeButton("Đóng", (dialogInterface, i) -> dialogInterface.dismiss())
.setPositiveButton("Cập nhật", (dialogInterface, i) -> {
Map<String, Object> updateData = new HashMap<>();
updateData.put("percent", Integer.parseInt(edt_percent.getText().toString()));
updateData.put("untilDate", selectedDate.getTimeInMillis());
updateDiscount(updateData);
});
builder.setView(itemView);
AlertDialog dialog = builder.create();
dialog.show();
}
private void updateDiscount(Map<String, Object> updateData) {
FirebaseDatabase.getInstance()
.getReference(Common.DISCOUNT_REF)
.child(Common.discountSelected.getKey())
.updateChildren(updateData)
.addOnFailureListener(e -> {
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
})
.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
discountViewModel.loadDiscount();
adapter.notifyDataSetChanged();
EventBus.getDefault().postSticky(new ToastEvent(Common.ACTION.UPDATE, true));
}
});
}
private void showDeleteDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("XOÁ VẬT MÃ GIẢM GIÁ");
builder.setMessage("Bạn có muốn xoá code này?");
builder.setNegativeButton("Đóng", (dialogInterface, i) -> dialogInterface.dismiss());
builder.setPositiveButton("Xoá", (dialogInterface, i) -> deleteDiscount());
AlertDialog dialog = builder.create();
dialog.show();
}
private void deleteDiscount() {
FirebaseDatabase.getInstance()
.getReference(Common.DISCOUNT_REF)
.child(Common.discountSelected.getKey())
.removeValue()
.addOnFailureListener(e -> {
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
})
.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
discountViewModel.loadDiscount();
adapter.notifyDataSetChanged();
EventBus.getDefault().postSticky(new ToastEvent(Common.ACTION.DELETE, true));
}
});
}
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
inflater.inflate(R.menu.discount_menu, menu);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_create)
showAddDialog();
return super.onOptionsItemSelected(item);
}
}
|
package com.cnk.travelogix.core.livesupporti.client.dto;
import org.codehaus.jackson.annotate.JsonAutoDetect;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
public class Visitor {
@JsonProperty("Name")
public String name;
@JsonProperty("Email")
public String email;
@JsonProperty("Phone")
public String phone;
@JsonIgnore
public String getName() {
return name;
}
@JsonIgnore
public void setName(String name) {
this.name = name;
}
@JsonIgnore
public String getEmail() {
return email;
}
@JsonIgnore
public void setEmail(String email) {
this.email = email;
}
@JsonIgnore
public String getPhone() {
return phone;
}
@JsonIgnore
public void setPhone(String phone) {
this.phone = phone;
}
}
|
package br.com.allerp.allbanks.entity.conta;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.ForeignKey;
import br.com.allerp.allbanks.entity.Endereco;
import br.com.allerp.allbanks.entity.pessoa.Pessoa;
import br.com.allerp.allbanks.entity.user.User;
@Entity
@Table(name = "TITULAR")
@ForeignKey(name = "FK_PES_COD")
@PrimaryKeyJoinColumn(name = "tit_cod", referencedColumnName = "codigo")
public class Titular extends Pessoa {
private static final long serialVersionUID = -8605819128606661027L;
@OneToMany(mappedBy = "titular", cascade = CascadeType.REMOVE)
@Column(nullable = false)
private List<Conta> contas;
@OneToOne(cascade = CascadeType.REMOVE)
@JoinColumn(name = "id_user", nullable = false, unique = true)
@ForeignKey(name = "FK_ID_USER")
private User user;
@Column(length = 200)
private String ie;
@Column(length = 16)
private String celular;
@Column(length = 14, unique = true)
private String cpfCnpj;
@Column
@Temporal(TemporalType.DATE)
private Date dtNasc;
@Column(nullable = false, length = 200)
private String nome;
@Column(length = 20)
private String rg;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "end_codigo")
@ForeignKey(name = "FK_PESS_END")
private Endereco endereco;
@Column(nullable = false)
private String tipoPessoa;
@OneToMany(mappedBy = "titular", cascade = CascadeType.REMOVE)
private List<Contato> contato;
@Override
public boolean equals(Object titular) {
if (this == titular) {
return true;
}
if (!(titular instanceof Titular)) {
return false;
}
Titular titular2 = (Titular) titular;
return this.getCodigo() == titular2.getCodigo();
}
public String getTipoPessoa() {
return tipoPessoa;
}
public boolean isPf() {
if (tipoPessoa.equals("Pessoa Física")) {
return true;
}
return false;
}
public boolean isPj() {
if (tipoPessoa.equals("Pessoa Jurídica")) {
return true;
}
return false;
}
public void setTipoPessoa(String tipoPessoa) {
this.tipoPessoa = tipoPessoa;
}
public String getCpfCnpj() {
return cpfCnpj;
}
public void setCpfCnpj(String cpfCnpj) {
this.cpfCnpj = cpfCnpj;
}
public String getNome() {
if (nome == null) {
return "";
}
return nome;
}
public void setNome(String razaoSocial) {
this.nome = razaoSocial;
}
public String getIe() {
return ie;
}
public void setIe(String ie) {
this.ie = ie;
}
public String getCelular() {
return celular;
}
public void setCelular(String celular) {
this.celular = celular;
}
public Date getDtNasc() {
return dtNasc;
}
public void setDtNasc(Date dtNasc) {
this.dtNasc = dtNasc;
}
public String getRg() {
return rg;
}
public void setRg(String rg) {
this.rg = rg;
}
public List<Conta> getContas() {
return contas;
}
public void addContas(Conta conta) {
this.contas.add(conta);
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<Contato> getContato() {
if (contato == null) {
contato.add(new Contato());
return contato;
}
return contato;
}
public void setContato(List<Contato> contato) {
this.contato = contato;
}
public Endereco getEndereco() {
return endereco;
}
public void setEndereco(Endereco endereco) {
this.endereco = endereco;
}
}
|
package com.advpro2.basone.kongmalaew.pushservice;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import com.urbanairship.AirshipConfigOptions;
import com.urbanairship.Autopilot;
import com.urbanairship.UAirship;
/**
* Created by bason on 04-Nov-17.
*/
public class AppAutopilot extends Autopilot {
private static final String NO_BACKUP_PREFERENCES = "com.urbanairship.sample.no_backup";
public static final String CHANNEL_ID="com.advpro2.basone.kongmalaew";
private static final String FIRST_RUN_KEY = "first_run";
static String chId;
@Override
public void onAirshipReady(UAirship airship) {
SharedPreferences preferences = UAirship.getApplicationContext().getSharedPreferences(NO_BACKUP_PREFERENCES, Context.MODE_PRIVATE);
boolean isFirstRun = preferences.getBoolean(FIRST_RUN_KEY, true);
if (isFirstRun) {
preferences.edit().putBoolean(FIRST_RUN_KEY, false).apply();
// Enable user notifications on first run
airship.getPushManager().setUserNotificationsEnabled(true);
}
if (Build.VERSION.SDK_INT >= 26) {
Context context = UAirship.getApplicationContext();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Log.d("APPPPPPPPPPPPPPPPPP", "onAirshipReady: "+AppAutopilot.chId);
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
AppAutopilot.chId,
NotificationManager.IMPORTANCE_DEFAULT);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
}
}
// Create a customized default notification factory
CustomNotificationFactory notificationFactory;
notificationFactory = new CustomNotificationFactory(UAirship.getApplicationContext());
// Set the factory on the PushManager
airship.getPushManager().setNotificationFactory(notificationFactory);
}
@Nullable
@Override
public AirshipConfigOptions createAirshipConfigOptions(@NonNull Context context) {
/*
Optionally, customize your config at runtime:
AirshipConfigOptions options = new AirshipConfigOptions.Builder()
.setInProduction(!BuildConfig.DEBUG)
.setDevelopmentAppKey("Your Development App Key")
.setDevelopmentAppSecret("Your Development App Secret")
.setProductionAppKey("Your Production App Key")
.setProductionAppSecret("Your Production App Secret")
.setGcmSender("Your GCM/Firebase Sender ID")
.setNotificationAccentColor(ContextCompat.getColor(context, R.color.color_accent))
.setNotificationIcon(R.drawable.ic_notification)
.build();
return options;
*/
// defaults to loading config from airshipconfig.properties file
return super.createAirshipConfigOptions(context);
}
}
|
package lk.ijse.pos.dao;
import java.util.List;
public interface CrudDAO {
}
|
package cn.joyfollow.k21smartplayer;
import io.flutter.plugin.common.PluginRegistry.Registrar;
/**
* SmartplayerNativeViewPlugin
*/
public class SmartplayerNativeViewPlugin {
static {
System.loadLibrary("SmartPlayer");
}
/**
* Plugin registration.
*/
public static void registerWith(Registrar registrar) {
registrar
.platformViewRegistry()
.registerViewFactory(
"smartPlayerView", new SmartPlayerViewFactory(registrar));
}
}
|
package com.tencent.mm.plugin.appbrand.jsapi.video;
import com.tencent.mm.plugin.appbrand.page.p;
import com.tencent.mm.plugin.appbrand.page.p$d;
import com.tencent.mm.plugin.appbrand.page.p.e;
import com.tencent.mm.plugin.appbrand.page.p.f;
import com.tencent.mm.sdk.platformtools.x;
class a$4 implements e {
final /* synthetic */ p fJO;
final /* synthetic */ f fRJ;
final /* synthetic */ p$d fRK;
final /* synthetic */ AppBrandVideoView gbm;
final /* synthetic */ a gbn;
a$4(a aVar, AppBrandVideoView appBrandVideoView, p pVar, f fVar, p$d p_d) {
this.gbn = aVar;
this.gbm = appBrandVideoView;
this.fJO = pVar;
this.fRJ = fVar;
this.fRK = p_d;
}
public final void onDestroy() {
AppBrandVideoView appBrandVideoView = this.gbm;
x.i("MicroMsg.AppBrandVideoView", "onUIDestroy");
appBrandVideoView.clean();
this.fJO.b(this.fRJ);
this.fJO.b(this.fRK);
this.fJO.b(this);
}
}
|
package com.tencent.mm.plugin.freewifi.b;
import com.tencent.mm.plugin.freewifi.m;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
public final class a {
private boolean jjc;
private Map<String, b> jjd;
/* synthetic */ a(byte b) {
this();
}
private a() {
this.jjc = false;
this.jjd = new LinkedHashMap<String, b>() {
protected final boolean removeEldestEntry(Entry entry) {
return size() > 512;
}
};
}
private static String cN(String str, String str2) {
return str + "-" + str2;
}
public final synchronized void d(String str, String str2, String str3, int i) {
if (!(m.isEmpty(str) || m.isEmpty(str2) || m.isEmpty(str3) || (i != 4 && i != 31))) {
b bVar = new b();
bVar.bIQ = str3;
bVar.jie = i;
this.jjd.put(cN(str, str2), bVar);
}
}
public final synchronized b cO(String str, String str2) {
b bVar;
if (m.isEmpty(str) || m.isEmpty(str2)) {
bVar = null;
} else {
bVar = (b) this.jjd.get(cN(str, str2));
}
return bVar;
}
public final synchronized int size() {
return this.jjd.size();
}
}
|
package dropbox;
import dropbox.GUI.FilesUI;
import static dropbox.GUI.FilesUI.contentArea;
import static dropbox.GUI.FilesUI.pathLabel;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
public class TextFile extends AbstractFile
{
public TextFile(String id , String name , String parentFolderID , String creationDate , String url)
{
super(id , name , parentFolderID , creationDate , url);
}
public static boolean editTextFile(String oldName , String fileName , String currFolder , String fileID , String content) throws SQLException, IOException
{
if(fileName.isEmpty())
{
Toast t = new Toast("Enter file name!" , 495 , 505);
t.showtoast();
return false;
}
if(!oldName.equals(fileName))
{
ResultSet conatinerIDs = Storage.getInstance().loadContainerUsingFileName(fileName);
while(conatinerIDs.next())
{
if(currFolder.equals(conatinerIDs.getString("container_id")))
{
Toast t = new Toast("Current folder has file with same name!" , 495 , 505);
t.showtoast();
return false;
}
}
}
File cloudFile = new File("./src/CloudStorage/" + fileID + ".txt");
if(cloudFile.exists())
{
BufferedWriter writer = new BufferedWriter(new FileWriter(cloudFile));
writer.write(content);
writer.close();
}
if(!oldName.equals(fileName))
{
Storage.getInstance().updateFileName(fileID , fileName);
HashMap folderInfo = Storage.getInstance().loadFolder(pathLabel.getName());
Folder f = new Folder((String)folderInfo.get("id") , (String)folderInfo.get("name") , (String)folderInfo.get("container_id") , (String)folderInfo.get("creation_date"));
Authentication.online_user.getUserAccount().displayFiles(f);
}
return true;
}
public static boolean createTextFile(String fileName , String folderID)
{
try
{
if(fileName.isEmpty())
{
Toast t = new Toast("Enter file name!" , 495 , 505);
t.showtoast();
return false;
}
ResultSet conatinerIDs = Storage.getInstance().loadContainerUsingFileName(fileName);
while(conatinerIDs.next())
{
if(folderID.equals(conatinerIDs.getString("container_id")))
{
Toast t = new Toast("Current folder has file with same name!" , 495 , 505);
t.showtoast();
return false;
}
}
AbstractFile absFile = new TextFile(UUID.randomUUID().toString() , fileName , folderID , Folder.dateFormat.format(new Date()).toString() , "url");
Storage.getInstance().saveFile(absFile.getId(), fileName, "text", absFile.getParentFolderID(), absFile.getUrl() , absFile.getCreationDate() , Authentication.online_user.getEmail());
File cloudFile = new File("./src/CloudStorage/" + absFile.getId() + ".txt");
if(!cloudFile.exists())
{
cloudFile.createNewFile();
BufferedWriter writer = new BufferedWriter(new FileWriter(cloudFile));
writer.write(contentArea.getText());
writer.close();
}
HashMap folderInfo = Storage.getInstance().loadFolder(folderID);
Folder f = new Folder((String)folderInfo.get("id") , (String)folderInfo.get("name") , (String)folderInfo.get("container_id") , (String)folderInfo.get("creation_date"));
Authentication.online_user.getUserAccount().displayFiles(f);
return true;
}
catch (SQLException ex)
{
Logger.getLogger(FilesUI.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex) {
Logger.getLogger(FilesUI.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
public void upload(String uploadPath) throws Exception
{
Storage.getInstance().saveFile(id , name , "text" , parentFolderID , url , creationDate , Authentication.online_user.getEmail());
InputStream is = new FileInputStream(new File(uploadPath));
OutputStream os = new FileOutputStream(new File("./src/CloudStorage/" + id + ".txt"));
byte[] buffer = new byte[3096];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
is.close();
os.close();
HashMap folderInfo = Storage.getInstance().loadFolder(parentFolderID);
Folder f = new Folder((String)folderInfo.get("id") , (String)folderInfo.get("name") , (String)folderInfo.get("container_id") , (String)folderInfo.get("creation_date"));
Authentication.online_user.getUserAccount().displayFiles(f);
}
public void download(String receivedID)
{
try
{
Storage.getInstance().saveFile(id, name,"text" , parentFolderID , url , creationDate, Authentication.online_user.getEmail());
InputStream is = new FileInputStream(new File("./src/CloudStorage/" + receivedID + ".txt"));
OutputStream os = new FileOutputStream(new File("./src/CloudStorage/" + id + ".txt"));
byte[] buffer = new byte[3096];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
is.close();
os.close();
}
catch (SQLException ex)
{
Logger.getLogger(TextFile.class.getName()).log(Level.SEVERE, null, ex);
} catch (FileNotFoundException ex) {
Logger.getLogger(TextFile.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(TextFile.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
|
package example.nz.org.take.compiler.userv.generated;
import nz.org.take.rt.*;
/**
* Class generated by the take compiler.
* @version Mon Feb 11 13:49:17 NZDT 2008
*/
@SuppressWarnings("unchecked")
class KBFragement_not_contains_11 {
/**
* Method generated for query contains[in,in]
* @param slot1 input parameter generated from slot 0
* @param slot2 input parameter generated from slot 1
* @return an iterator for instances of not_contains
*/
public static ResultSet<not_contains> not_contains_11(
final java.util.Collection slot1, final java.lang.Object slot2) {
DerivationController _derivation = new DefaultDerivationController();
ResultSet<not_contains> _result = new ResultSet(KBFragement_not_contains_11.not_contains_11(
slot1, slot2, _derivation), _derivation);
return _result;
}
/**
* Method generated for query contains[in,in]
* @param source
* @param target
* @return an iterator
* code generated using velocity template JPredicate_11_neg.vm
*/
static ResourceIterator<not_contains> not_contains_11(
final java.util.Collection slot1, final java.lang.Object slot2,
final DerivationController _derivation) {
_derivation.log("public abstract boolean java.util.Collection.contains(java.lang.Object)",
DerivationController.JAVA_METHOD);
if (!slot1.contains(slot2)) {
not_contains result = new not_contains();
result.slot1 = slot1;
result.slot2 = slot2;
return new SingletonIterator<not_contains>(result);
}
return EmptyIterator.DEFAULT;
}
}
|
package repositorytests;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
//import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import com.qa.spring.application.UFCApplication;
import com.qa.spring.application.model.UFCDataModelFighter;
import com.qa.spring.application.repository.UFCFighterRepository;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = UFCApplication.class)
//@SpringBootTest(classes = { UFCApplication.class })
@DataJpaTest
public class RepositoryTest {
@Autowired
private TestEntityManager entityManager;
@Autowired
private UFCFighterRepository myRepository;
@Test
public void retrieveByIdTest() {
UFCDataModelFighter model1 = new UFCDataModelFighter("Daniel", "Cormier", "Lafayette | Louisiana", "Daniel Cormier is an American mixed martial artist and former Olympic wrestler. He is reigning champion of the heavyweight division. He is the #1 ranked pound-for-pound fighter in the UFC.", "Heavyweight", "Date of Birth - 20/03/1979", "Style - Wrestling");
entityManager.persist(model1);
entityManager.flush();
assertTrue(myRepository.findById(model1.getfighter_id()).isPresent());
}
}
|
import java.util.Arrays;
/**
* 希尔排序也是一种插入排序,它是简单插入排序经过改进之后的一个更高效的版本,也称为缩小增量排序
*
* <p>同时该算法是冲破O(n2)的第一批算法之一
*
* <p>基本思想 希尔排序是把记录按下标的一定增量分组,对每组使用直接插入排序算法排序;随着增量逐渐减少,每组包含的关键词越来越多,当增量减至1时,整个文件恰被分成一组,算法便终止
*
* 在此我们选择增量gap=length/2,缩小增量继续以gap = gap/2的方式,这种增量选择我们可以用一个序列来表示,{n/2,(n/2)/2...1},称为增量序列
*/
public class ShellSort {
public static void main(String[] args) {
int[] arr = {2, 6, 9, 3, 1, 0, 4, 7, 8};
sort(arr);
System.out.println("排序结果:" + Arrays.toString(arr));
}
private static void sort(int[] arr) {
for (int gap = (arr.length) / 2; gap > 0; gap /= 2) {
for (int i = gap; i < arr.length; i++) {
int j = i;
while (j - gap >= 0 && arr[j] < arr[j - gap]) {
swap(arr, j, j-gap);
j -= gap;
}
}
}
}
private static void swap(int[] arr, int l, int r) {
int temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.