text stringlengths 10 2.72M |
|---|
package it.polimi.se2019.rmi;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface ServerLobbyInterface extends Remote {
/**
* Make the connection to the server
* The server will lookup for an RMI registry on the ip the
* client used to connect (see {@link #getIp()}), on the port
* passed as parameter, at the reference passed as parameter.
*
* @param ref The reference the server should use to retrieve a view to
* interact with.
* @param port Port the registry is exposed on
*
* @throws RemoteException If something goes wrong with RMI
*/
void connect(String ref, int port) throws RemoteException;
/**
* @return The ip (viewed by the server) of the connecting client. This
* can then be used to properly create an RMI Registry.
* Null if for some reason the ip can not retrived
* @throws RemoteException If something goes wrong with RMI
*/
String getIp() throws RemoteException;
}
|
/**
* Vertex.java Klasse zur Repraesentation eines Knoten
* Klasse zur Repraesentation eines Knoten
*/
/** Klasse zur Repraesentation eines Knoten */
import java.util.LinkedList;
import java.util.List;
public class Vertex implements Comparable<Vertex> { // wegen Priority-Queue
public String name; // Name des Knoten (fix)
public List<Edge> edges; // Nachbarn als Kantenliste (fix)
public int nr; // Knotennummer (errechnet)
public int indegree; // Eingangsgrad (errechnet)
public double dist; // Kosten fuer diesen Knoten (errechnet)
public boolean seen; // Besuchs-Status (errechnet)
public Vertex prev; // Vorgaenger fuer diesen Knoten (errechnet)
public Vertex(String s) { // Konstruktor fuer Knoten
name = s; // initialisiere Name des Knoten
edges = new LinkedList<Edge>(); // initialisiere Nachbarschaftsliste
}
public boolean hasEdge(Vertex w) {// testet, ob Kante zu w besteht
for (Edge e : edges) // fuer jede ausgehende Nachbarkante pruefe
if (e.dest == w) // falls Zielknoten mit w uebereinstimmt
return true; // melde Erfolg
return false; // ansonsten: melde Misserfolg
}
public int compareTo(Vertex other) { // vergl. Kosten mit anderem Vertex
return (int) (dist - other.dist); // liefert Ergebnis des Vergleichs
}
} |
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package com.hybris.backoffice.workflow.renderer.actionexecutors;
import static org.fest.assertions.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.verify;
import de.hybris.platform.workflow.model.WorkflowModel;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;
import com.hybris.backoffice.widgets.notificationarea.DefaultNotificationService;
import com.hybris.backoffice.widgets.notificationarea.event.NotificationEvent;
import com.hybris.backoffice.workflow.WorkflowConstants;
import com.hybris.backoffice.workflow.WorkflowEventPublisher;
import com.hybris.backoffice.workflow.WorkflowFacade;
@RunWith(MockitoJUnitRunner.class)
public class WorkflowStartActionExecutorTest
{
@Spy
@InjectMocks
private WorkflowStartActionExecutor workflowStartActionExecutor;
@Mock
private WorkflowFacade workflowFacade;
@Mock
private WorkflowEventPublisher workflowEventPublisher;
@Spy
private DefaultNotificationService notificationService;
@Mock
private WorkflowModel data;
@Test
public void shouldStartingWorkflowPublishGlobalEventAndNotifyUserAboutSuccess()
{
// given
doReturn(Boolean.TRUE).when(workflowFacade).startWorkflow(data);
// when
final Boolean result = workflowStartActionExecutor.apply(data);
// then
assertThat(result).isTrue();
verify(workflowEventPublisher).publishWorkflowUpdatedEvent(data);
verify(notificationService).notifyUser(WorkflowConstants.HANDLER_NOTIFICATION_SOURCE,
WorkflowConstants.EVENT_TYPE_WORKFLOW_STARTED, NotificationEvent.Level.SUCCESS, workflowStartActionExecutor.getReferenceObject(data));
}
@Test
public void shouldStartingWorkflowWithAProblemNotifyUserAboutFailure()
{
// given
doReturn(Boolean.FALSE).when(workflowFacade).startWorkflow(data);
// when
final Boolean result = workflowStartActionExecutor.apply(data);
// then
assertThat(result).isFalse();
verify(notificationService).notifyUser(WorkflowConstants.HANDLER_NOTIFICATION_SOURCE,
WorkflowConstants.EVENT_TYPE_WORKFLOW_STARTED, NotificationEvent.Level.FAILURE, workflowStartActionExecutor.getReferenceObject(data));
}
}
|
package ba.ih_sonification.headsetx;
import java.util.List;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.Toast;
import com.gn.ihs.android.examples.headsetx.R;
import com.gn.intelligentheadset.IHS;
import com.gn.intelligentheadset.IHSDevice;
import com.gn.intelligentheadset.IHSDevice.IHSDeviceConnectionState;
import com.gn.intelligentheadset.IHSDevice.IHSDeviceListener;
import com.gn.intelligentheadset.IHSDeviceDescriptor;
import com.gn.intelligentheadset.IHSListener;
import com.gn.intelligentheadset.helpers.IHSDeviceListFragment;
import com.gn.intelligentheadset.helpers.IHSDeviceListFragment.DeviceSelectionListener;
import com.gn.intelligentheadset.helpers.IHSHelper;
import com.gn.intelligentheadset.subsys.IHSSensorPack;
import com.gn.intelligentheadset.subsys.IHSSensorPack.IHSSensorsListener;
/**
* Primary Activity for HeadsetX.
* The activity owns two fragments, one with a map, and one with a list of data from the IHSDevice.
*/
public class MainActivity extends Activity {
private boolean mCanShowDiscoveryDialog;
private boolean mIsShowingDiscoveryDialog = false;
private String mLastSelectedTabTag = null;
private IHS mIHS;
private IHSDevice mMyDevice = null;
private IHSDeviceListFragment mDeviceListFragment = null;
private List<IHSDeviceDescriptor> mLastReceivedDeviceList = null;
private final String mKey_ShowSelectionDialog = "mShowDiscoveryDialog";
private final String mKey_LastSelectedTabTag = "mLastSelectedTabTag";
private final static boolean MAP_FRAGMENT_ENABLED = true;
private Button buttonTrigger;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// buttonTrigger = (Button) findViewById(R.id.button1);
// buttonTrigger.setOnClickListener(new View.OnClickListener() {
//
// @Override
// public void onClick(View v) {
// Log.v("MeinTest", "buttonTrigger pressed");
// }
// });
Log.d("meinTest", "Oncreate in der Mainactivity");
ActionBar ab = getActionBar();
ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab infoTab = ab.newTab().setTabListener(new MyTabListener<InfoFragment>(R.id.fragmentContainer, InfoFragment.fragmentTag, InfoFragment.class))
.setText(R.string.tabtitle_info);
ab.addTab(infoTab);
Tab osmTab = null;
if (MAP_FRAGMENT_ENABLED) {
osmTab = ab.newTab().setTabListener(new MyTabListener<OsmFragment>(R.id.fragmentContainer, OsmFragment.fragmentTag, OsmFragment.class))
.setText(R.string.tabtitle_map);
ab.addTab(osmTab);
ab.setDisplayShowTitleEnabled(false);
}
if (savedInstanceState != null) {
// Recreation (possibly due to device orientation change), restore
// state
mCanShowDiscoveryDialog = savedInstanceState.getBoolean(mKey_ShowSelectionDialog, true);
mLastSelectedTabTag = savedInstanceState.getString(mKey_LastSelectedTabTag, null);
} else {
// Plain creation, ok to show a dialog
mCanShowDiscoveryDialog = true;
}
if (InfoFragment.fragmentTag.equals(mLastSelectedTabTag))
ab.selectTab(infoTab);
else if (MAP_FRAGMENT_ENABLED && osmTab != null && OsmFragment.fragmentTag.equals(mLastSelectedTabTag))
ab.selectTab(osmTab);
mDeviceListFragment = new IHSDeviceListFragment();
mIHS = new IHS(this, Constants.APIKEY, mIHSListener);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(mKey_ShowSelectionDialog, mCanShowDiscoveryDialog);
outState.putString(mKey_LastSelectedTabTag, mLastSelectedTabTag);
}
@Override
protected void onResume() {
super.onResume();
if (mMyDevice != null) {
mMyDevice.addListener(mIHSDeviceListener);
}
}
@Override
protected void onPause() {
super.onPause();
if (mMyDevice != null) {
mMyDevice.removeListener(mIHSDeviceListener);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.findItem(R.id.action_discover_ble).setEnabled(mCanShowDiscoveryDialog && !mIsShowingDiscoveryDialog);
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case R.id.action_discover_ble:
mDeviceListFragment.show(getFragmentManager(), mLastReceivedDeviceList, new DeviceSelectionListener() {
@Override
public void onDialogDismissed() {
}
@Override
public void onDeviceSelected(IHSDeviceDescriptor dev) {
if (dev != null) {
mIHS.selectDevice(dev);
}
}
});
return true;
default:
return super.onMenuItemSelected(featureId, item);
}
}
@Override
public void onBackPressed() {
mIHS.stopService();
super.onBackPressed();
}
private void enableSelectionDialog() {
if (!mDeviceListFragment.isVisible() && !mCanShowDiscoveryDialog) {
mCanShowDiscoveryDialog = true;
invalidateOptionsMenu();
Toast.makeText(MainActivity.this, "Select a suitable device", Toast.LENGTH_LONG).show();
}
}
private void hideSelectionDialog() {
if (mDeviceListFragment.isVisible())
mDeviceListFragment.dismiss();
mCanShowDiscoveryDialog = false;
invalidateOptionsMenu();
}
// Listener for top-level IHS API
private IHSListener mIHSListener = new IHSListener() {
@Override
public void onAPIstatus(APIStatus apiStatus) {
if (apiStatus == APIStatus.READY) {
// We want it to stay alive until explicitly stopped (in onBackPressed)
mIHS.enableBackgroundOperation();
mIHS.connectHeadset(); // May already be connected, but that doesn't matter
}
}
@Override
public void onAudioRouteSet(boolean isBluetoothToIH, String routeName) {
// Audio routing may change independently of our connections, you way want to keep the user aware
// of changes.
// Typical causes are switching between a BT headset and a wired headset.
// In this example, we just show a message.
Toast.makeText(
MainActivity.this,
isBluetoothToIH ? "Audio is routed via Bluetooth to an IntelligentHeadset"
: "Audio is NOT routed via Bluetooth to an Intelligent Headset, but to " + routeName,
Toast.LENGTH_SHORT).show();
}
@Override
public void onIHSDeviceSelectionRequired(List<IHSDeviceDescriptor> list) {
// You might get the IHSListener callback
// after a device has been selected and a connection initiated.
// To cover that, hide the selection UI here.
if (mMyDevice != null
&& ((mMyDevice.getConnectionState() == IHSDeviceConnectionState.IHSDeviceConnectionStateConnected) || (mMyDevice
.getConnectionState() == IHSDeviceConnectionState.IHSDeviceConnectionStateConnecting))) {
hideSelectionDialog();
} else {
// Some devices are found, but the API is unable to determine which one to use.
// Ask the user.
mLastReceivedDeviceList = list;
if (mDeviceListFragment.isVisible()) {
mDeviceListFragment.updateList(list);
} else {
enableSelectionDialog();
}
}
}
@Override
public void onIHSDeviceSelected(IHSDevice device) {
hideSelectionDialog();
mMyDevice = device;
mMyDevice.addListener(mIHSDeviceListener);
mMyDevice.getSensorPack().addListener(mSensorpackListener);
}
};
private IHSDeviceListener mIHSDeviceListener = new IHSDeviceListener() {
@Override
public void connectedStateChanged(IHSDevice dev, IHSDeviceConnectionState state) {
invalidateOptionsMenu();
switch (state) {
case IHSDeviceConnectionStateBluetoothOff: {
IHSHelper.showMessage(MainActivity.this, com.gn.intelligentheadset.hsapi.R.string.bt_is_off);
break;
}
case IHSDeviceConnectionStateConnectionTakesTooLong: {
IHSHelper.showMessage(MainActivity.this, R.string.connection_takes_too_long);
break;
}
case IHSDeviceConnectionStateConnected: {
hideSelectionDialog();
break;
}
default:
// Never mind the rest
break;
}
};
};
private IHSSensorsListener mSensorpackListener = new IHSSensorsListener() {
@Override
public void fusedHeadingChanged(IHSSensorPack arg0, float heading) {
// Do not rely on the UI here, as we may be between onPause() and onResume()
// mMyDevice.getAudio3DPlayer().setHeading(heading);
}
// public void yawChanged(IHSSensorPack arg0, float heading) {
// // Do not rely on the UI here, as we may be between onPause() and onResume()
// mMyDevice.getAudio3DPlayer().setHeading(heading);
// };
};
/**
*
* Helper class for tying Fragment instances to ActionBar tabs.
* <p>
* Uses MainActivity.this.
* <p>
* Inspired by http://developer.android.com/guide/topics/ui/actionbar.html
*
* @param <F>
* fragment derivative to represent
*/
private class MyTabListener<F extends Fragment> implements TabListener {
private Fragment mFragment;
private final String mTag;
private final Class<F> mClass;
private final int mContainerId;
/**
* Constructor used each time a new tab is created.
*
* @param tag
* The identifier tag for the fragment
* @param clz
* The fragment's Class, used to instantiate the fragment
*/
public MyTabListener(int containerId, String tag, Class<F> clz) {
mTag = tag;
mClass = clz;
mContainerId = containerId;
}
// ActionBar.TabListener callbacks
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// Check if the fragment is already initialized
if (mFragment == null)
mFragment = getFragmentManager().findFragmentByTag(mTag);
if (mFragment == null) {
// If not, instantiate and add it to the activity
mFragment = Fragment.instantiate(MainActivity.this, mClass.getName());
ft.add(mContainerId, mFragment, mTag);
} else {
// If it exists, simply attach it in order to show it
ft.attach(mFragment);
}
mLastSelectedTabTag = mTag;
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (mFragment != null) {
// Detach the fragment, because another one is being attached
ft.detach(mFragment);
}
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// User selected the already selected tab. No action
}
}
}
|
package com.beiyelin.person.service;
import com.beiyelin.commonsql.jpa.BaseDomainCRUDService;
import com.beiyelin.person.entity.Nation;
import java.util.List;
/**
* @Description:
* @Author: newmann
* @Date: Created in 22:29 2018-02-21
*/
public interface NationService extends BaseDomainCRUDService<Nation> {
}
|
package View;
import java.awt.Color;
import java.awt.Font;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import Model.PlayerStatisticsInformation;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
public class PlayersStatisticsWindow extends JFrame
{
ArrayList<PlayerStatisticsInformation> players = new ArrayList<PlayerStatisticsInformation>();
JLabel lblTitle;
/**
*
*/
private static final long serialVersionUID = -8349447643209966154L;
private JTable table;
DefaultTableModel model;
public PlayersStatisticsWindow()
{
players = Controller.PlayerStatisticsSingleton.GetInstance().GetPlayersStatistics();
setResizable(false);
setLocationByPlatform(true);
setBounds(new Rectangle(1000, 1000, 1000, 1000));
this.setLocationRelativeTo(null);
getContentPane().setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setBackground(new Color(46,46,46));
lblTitle = new JLabel("Players Statistics");
lblTitle.setFont(new Font("Snap ITC", Font.PLAIN, 20));
lblTitle.setForeground(new Color(255, 255, 255));
lblTitle.setBounds(376, 55, 227, 62);
getContentPane().add(lblTitle);
table = new JTable();
table.setForeground(Color.WHITE);
table.setBackground(new Color(46,46,46));
table.setShowHorizontalLines(false);
table.setShowVerticalLines(false);
table.setBorder(null);
table.setFont(new Font("Snap ITC", Font.PLAIN, 20));
table.setModel(new DefaultTableModel(
new Object[][] {
{"No.","Player Name", "Wins /", " Losess"},
},
new String[] {
"Number","Name", "Wins ", " Losess"
}
) {
/**
*
*/
private static final long serialVersionUID = -527233726797028950L;
boolean[] columnEditables = new boolean[] {
false, false, false
};
public boolean isCellEditable(int row, int column) {
return columnEditables[column];
}
});
table.getColumnModel().getColumn(0).setResizable(false);
table.getColumnModel().getColumn(0).setPreferredWidth(20);
table.getColumnModel().getColumn(1).setResizable(false);
table.getColumnModel().getColumn(1).setPreferredWidth(67);
table.getColumnModel().getColumn(2).setResizable(false);
table.getColumnModel().getColumn(2).setPreferredWidth(39);
table.getColumnModel().getColumn(3).setResizable(false);
table.getColumnModel().getColumn(3).setPreferredWidth(42);
table.setBounds(215, 128, 531, 513);
getContentPane().add(table);
model = (DefaultTableModel) table.getModel();
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
DefaultTableCellRenderer leftRenderer = new DefaultTableCellRenderer();
DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer();
table.getColumnModel().getColumn(0).setCellRenderer( leftRenderer );
table.getColumnModel().getColumn(1).setCellRenderer( leftRenderer );
table.getColumnModel().getColumn(2).setCellRenderer( rightRenderer );
table.getColumnModel().getColumn(3).setCellRenderer( leftRenderer );
centerRenderer.setHorizontalAlignment( JLabel.CENTER );
leftRenderer.setHorizontalAlignment( JLabel.LEFT );
rightRenderer.setHorizontalAlignment( JLabel.RIGHT );
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
model.addRow(new Object[]{"","","",""});
model.addRow(new Object[]{"","","",""});
int index = 1;
for(PlayerStatisticsInformation player: players)
{
model.addRow(new Object[]{index++ , player.getName(), player.getWins() + " /", " " + player.getLosses()});
model.addRow(new Object[]{"","","",""});
}
JButton NextPlayers = new JButton("Next 15 Players");
NextPlayers.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(model.getRowCount() > 30) {
for (int i = 0 ; i < 30 ; i++)
{
model.removeRow(2);
}
}
else {
JOptionPane.showMessageDialog(null, "No more players");
}
}
});
NextPlayers.setFont(new Font("Snap ITC", Font.BOLD, 17));
NextPlayers.setBackground(new Color(255, 127, 80));
NextPlayers.setBounds(464, 688, 210, 62);
getContentPane().add(NextPlayers);
JButton Back = new JButton("Back");
Back.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
setVisible(false);
ScreenManagement.ShowMenuWindow();
}
});
Back.setFont(new Font("Snap ITC", Font.BOLD, 17));
Back.setBackground(new Color(255, 127, 80));
Back.setBounds(225, 688, 190, 62);
getContentPane().add(Back);
}
public void NewPlayersStatisticsWindow()
{
players = Controller.PlayerStatisticsSingleton.GetInstance().GetPlayersStatistics();
while (table.getRowCount() > 3) {
model.removeRow(3);
}
int index = 1;
for(PlayerStatisticsInformation player: players)
{
model.addRow(new Object[]{index++ , player.getName(), player.getWins() + " /", " " + player.getLosses()});
model.addRow(new Object[]{"","","",""});
}
}
}
|
package pieces;
import java.util.ArrayList;
import chess.Board;
public class Knight extends Piece {
public Knight(Colour colour) {
super(colour);
}
public String getName()
{
return "n";
}
public double getBaseStrength()
{
return 2.5;
}
public ArrayList<String> getPossibleMoves(Board board)
{
String from = board.findPiece(this);
ArrayList<String> moves = new ArrayList<String>();
for(int x=-1; x<=1; x+=2){
for(int y=-3; y<=3; y+=6){
if ( board.isValidDirection(from, x, y) ) moves.add(board.getMoveDirection(from, x, y));
}
}
for(int y=-1; y<=1; y+=2){
for(int x=-3; x<=3; x+=6){
if ( board.isValidDirection(from, x, y) ) moves.add(board.getMoveDirection(from, x, y));
}
}
return moves;
}
}
|
package wx.realware.grp.pt.pb.condition;
import java.io.Serializable;
/**
* 条件类
* edit by liufegnqiang
* time 201808823
*/
public class ConditionPart implements Serializable,Operator ,Comparable<ConditionPart>{
/**
* 数据库类型
* 0 :mysql
* 1 :oracle
* 2 : Sybase
* 3 :db
*/
private int DataSourceType =0;
/**
/**
* 运算符
* 默认值 and
* @param o
* @return
*/
private String LogicalOperator="and";
private Boolean isOperator =false;
/**
* 字段名
* @param o
* @return
*/
private String fieldName;
/**
* 字段值
* @param o
* @return
*/
private String fieldValue;
/**
* 字段类型
* 0:字符型
* 1:整形
* 2:日期
* 3:金额
*
* @return
*/
private int fieldType;
/**
* 是否格式化
*
* @param
* @return
*/
private Boolean isFormate=false;
/**
* 格式化表达式
* @param o
* @return
*/
private String formatModel;
/**
* 排序(1,2,3,4)升序
* @param o
* @return
*/
private Long discOrder;
@Override
public int compareTo(ConditionPart part) {
if(this.discOrder>part.discOrder){
return 1;
}else if(this.discOrder==part.discOrder){
return 0;
}else{
return -1;
}
}
public int getDataSourceType() {
return DataSourceType;
}
public void setDataSourceType(int dateSourceType) {
DataSourceType = dateSourceType;
}
public String getLogicalOperator() {
return LogicalOperator;
}
public void setLogicalOperator(String logicalOperator) {
LogicalOperator = logicalOperator;
}
public Boolean getOperator() {
return isOperator;
}
public void setOperator(Boolean operator) {
isOperator = operator;
}
public String getFieldName() {
return fieldName;
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
public String getFieldValue() {
return fieldValue;
}
public void setFieldValue(String fieldValue) {
this.fieldValue = fieldValue;
}
public int getFieldType() {
return fieldType;
}
public void setFieldType(int fieldType) {
this.fieldType = fieldType;
}
public Boolean getFormate() {
return isFormate;
}
public void setFormate(Boolean formate) {
isFormate = formate;
}
public String getFormatModel() {
return formatModel;
}
public void setFormatModel(String formatModel) {
this.formatModel = formatModel;
}
public Long getDiscOrder() {
return discOrder;
}
public void setDiscOrder(Long discOrder) {
this.discOrder = discOrder;
}
}
|
package com.packers.movers.service.mapper;
import com.packers.movers.datalayer.entities.order.OrderPlaced;
import com.packers.movers.datalayer.entities.service.Service;
import com.packers.movers.service.contracts.AddressContract;
import com.packers.movers.service.contracts.OrderContract;
import com.packers.movers.service.contracts.ServiceContract;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class EntityToContractMapper {
Logger LOG = LoggerFactory.getLogger(EntityToContractMapper.class);
public OrderContract mapOrderEntityToContract(OrderPlaced orderPlaced) throws Exception {
List<ServiceContract> serviceContractList = new ArrayList<>();
if (orderPlaced == null ) {
throw new Exception("Order project is null.");
}
for(Service service : orderPlaced.getServices()) {
ServiceContract serviceContract = new ServiceContract(
service.getServiceId().toString(),
service.getServiceType(),
service.getPacketsQuantity(),
service.getStartDate(),
service.getServiceCost().intValue()
);
serviceContractList.add(serviceContract);
}
AddressContract fromAddress = fromStringToAddressContract(orderPlaced.getFromAddress());
AddressContract toAddress = fromStringToAddressContract(orderPlaced.getToAddress());
OrderContract orderContract = new OrderContract(
orderPlaced.getOrderId().toString(),
orderPlaced.getName(),
orderPlaced.getPhone(),
orderPlaced.getEmail(),
orderPlaced.getSpecialNote(),
fromAddress,
toAddress,
serviceContractList
);
LOG.debug("Mapper has contract constructed as : {}", orderContract);
System.out.println(orderContract.toJson());
return orderContract;
}
private AddressContract fromStringToAddressContract(String address) {
List<String> addressList = Arrays.asList(address.split("\\s*,\\s*"));
if (addressList.size() == 4) {
String street = addressList.get(0);
String post = addressList.get(1);
String city = addressList.get(2);
String country = addressList.get(3);
return new AddressContract(street, post, city, country);
}
return null;
}
}
|
package com.example.user.simplelife;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Created by User on 2015/6/18.
*/
public class Air_ListAdapter extends BaseAdapter {
private Context mContext;
private static LayoutInflater inflater = null;
public Air_ListAdapter(Context c) {
mContext = c;
inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return list.length;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
view = inflater.inflate(R.layout.light_list_item, null);
TextView text = (TextView) view.findViewById(R.id.text_listitem_light);
ImageView image2 = (ImageView) view.findViewById(R.id.image_listitem_light);
text.setText(list[position]);
image2.setImageResource(R.drawable.right_icon2);
return view;
}
private String[] list = new String[] {
"Time Setting","Proximity Setting","Energy Saver", "Ideal Temperature"
};
public void setList(int index,String text)
{
list[index] = text;
}
}
|
package cn.tjust.test;
public class Triangle{
public int Case(int a,int b,int c){
if(a<=0||b<=0||c<=0||a+b<=c||a+c<=b||b+c<=a)
return 0;//不是三角形
else {
if(a==b&&a==c&&b==c)
return 1;//等边
else if(a==b||b==c||a==c)
return 2;//等腰
else
return 3;//不等边
}
}
} |
package com.developer.ashwoolford.moviesfreak.details_activity.FragmentForDetailsActivity;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.developer.ashwoolford.moviesfreak.R;
import com.squareup.picasso.Picasso;
import java.util.List;
/**
* Created by ashwoolford on 1/14/2017.
*/
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
List<ImagesData> mImagesDataList;
Context context;
public CustomAdapter(Context context , List<ImagesData> imagesDataList) {
mImagesDataList = imagesDataList;
this.context = context;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.swipeee,parent,false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
//Glide.with(context).load(mImagesDataList.get(position).getPath()).into(holder.mImageView);
Picasso.with(context).load(mImagesDataList.get(position).getPath())
.fit()
.into(holder.mImageView);
holder.mTextView.setText(mImagesDataList.get(position).getCastNames());
}
@Override
public int getItemCount() {
return mImagesDataList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView mImageView;
TextView mTextView;
public ViewHolder(View itemView) {
super(itemView);
mImageView = (ImageView) itemView.findViewById(R.id.itemImage_forFragment);
mTextView = (TextView) itemView.findViewById(R.id.castNames);
}
}
}
|
package org.jboss.perf.test.server.model;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
@NamedQueries({
@NamedQuery(name="testSuiteRunsByProjectIdByStartTimeDesc", query="select ts from TestSuiteRun ts, TestSuite t, Build b, Project p where p.id = :projectId and p.id = b.project.id and b.id = t.build.id and t.id = ts.testSuite.id order by ts.startTime desc"),
@NamedQuery(name="lastFinishedTestSuiteRunByTestSuiteAndByProjectAndByBuild", query="select tr from TestSuiteRun tr, TestSuite t, Project p, Build b where p.name = :project and p.id = b.project.id and b.name = :build and b.id = t.build.id and t.name = :testSuite and t.id = tr.testSuite.id and tr.endTime != null order by tr.startTime desc"),
@NamedQuery(name="actuallyTestedTestSuiteRunsByStartTimeDesc", query="select ts from TestSuiteRun ts, TestSuite t, Build b, Project p where p.id = b.project.id and b.id = t.build.id and t.id = ts.testSuite.id and ts.endTime = null order by ts.startTime desc"),
@NamedQuery(name="finishedTestSuiteRunsInTimeRangeByStartTimeDesc", query="select ts from TestSuiteRun ts where ts.endTime != null and ts.endTime >= :start and ts.endTime <= :end order by ts.startTime desc"),
@NamedQuery(name="finishedTestSuiteRunsFromDateByStartTimeDesc", query="select ts from TestSuiteRun ts where ts.endTime != null and ts.endTime >= :start order by ts.startTime desc"),
@NamedQuery(name="testSuiteRunsByProjectIdAndByBuildAndByTestSuiteAndByHwByStartTimeDesc", query="select tr from TestSuiteRun tr, TestSuite t, Project p, Build b where p.id = :projectId and p.id = b.project.id and b.name = :build and b.id = t.build.id and t.name = :testSuite and tr.testSuite.id = t.id and tr.hw.id in :chosenHws order by tr.hw.id, tr.startTime desc"),
@NamedQuery(name="testSuiteRunsByProjectIdAndByBuildAndByTestSuiteByStartTimeDesc", query="select tr from TestSuiteRun tr, TestSuite t, Project p, Build b where p.id = :projectId and p.id = b.project.id and b.name = :build and b.id = t.build.id and t.name = :testSuite and tr.testSuite.id = t.id order by tr.startTime desc"),
@NamedQuery(name="testSuiteRunsByProjectIdAndByTestSuite", query="select tr from TestSuiteRun tr, TestSuite t, Project p, Build b where p.id = :projectId and p.id = b.project.id and b.id = t.build.id and t.name = :testSuite and tr.testSuite.id = t.id")
})
public class TestSuiteRun {
private Long id;
private Date startTime;
private Date endTime;
private Hw hw;
private TestSuite testSuite;
private List<TestRun> testRuns = new LinkedList<TestRun>();
public TestSuiteRun() {
}
public TestSuiteRun(Date startTime, Hw hw, TestSuite testSuite) {
this.startTime = startTime;
this.hw = hw;
this.testSuite = testSuite;
}
public TestSuiteRun(Date startTime, Date endTime, Hw hw, TestSuite testSuite) {
this.startTime = startTime;
this.endTime = endTime;
this.hw = hw;
this.testSuite = testSuite;
}
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Temporal(TemporalType.TIMESTAMP)
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
@Temporal(TemporalType.TIMESTAMP)
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
@OneToOne(cascade=CascadeType.DETACH, fetch=FetchType.EAGER)
@JoinColumn(name="hw_id")
public Hw getHw() {
return hw;
}
public void setHw(Hw hw) {
this.hw = hw;
}
@ManyToOne
@JoinColumn(name="testsuite_id")
public TestSuite getTestSuite() {
return testSuite;
}
public void setTestSuite(TestSuite testSuite) {
this.testSuite = testSuite;
}
@OneToMany(targetEntity=TestRun.class, mappedBy="testSuiteRun", cascade=CascadeType.ALL, fetch=FetchType.EAGER)
public List<TestRun> getTestRuns() {
return testRuns;
}
public void setTestRuns(List<TestRun> testRuns) {
this.testRuns = testRuns;
}
public void addTestRun(TestRun testRun) {
this.testRuns.add(testRun);
}
}
|
package com.tencent.mm.plugin.webview.ui.tools.bag;
class k$1 implements Runnable {
final /* synthetic */ k qcx;
k$1(k kVar) {
this.qcx = kVar;
}
public final void run() {
j.qcm.bVg();
}
}
|
package com.smile2sm.service.impl;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.smile2sm.config.MQConfig;
import com.smile2sm.constant.RedisKey;
import com.smile2sm.dao.PayOrderDao;
import com.smile2sm.dao.RedisDao;
import com.smile2sm.dao.SeckillGoodsDao;
import com.smile2sm.dto.SeckillExposer;
import com.smile2sm.entity.SeckillGoods;
import com.smile2sm.enums.SeckillStateEnum;
import com.smile2sm.exception.SeckillException;
import com.smile2sm.mq.MQProducer;
import com.smile2sm.service.SeckillGoodsService;
import com.smile2sm.utils.MD5Util;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
/**
* 秒杀处理业务
*
*/
@Component
public class SeckillGoodsServiceImpl implements SeckillGoodsService {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
JedisPool jedisPool;
@Autowired
SeckillGoodsDao seckillGoodsDao;
@Autowired
PayOrderDao payOrderDao;
@Autowired
RedisDao redisDao;
@Autowired
MQProducer mQProducer;
@Override
public List<SeckillGoods> listSeckillGoods() {
List<SeckillGoods> listSeckillGoods = redisDao.getAllSeckillGoods();
if(!StringUtils.isEmpty(listSeckillGoods)) return listSeckillGoods;
listSeckillGoods = seckillGoodsDao.listSeckillGoods();
redisDao.setAllSeckillGoods(listSeckillGoods);
return listSeckillGoods;
}
/**
* 查看单个商品详细
*/
@Override
public SeckillGoods getSeckillGoodsDetail(long seckill_id) {
Jedis jedis = jedisPool.getResource();
String string = jedis.get(RedisKey.SECKILL_ID+seckill_id);
if(!StringUtils.isEmpty(string)) {
SeckillGoods seckillGoods = JSON.parseObject(string, SeckillGoods.class);
String seckill_num = jedis.get(RedisKey.SECKILL_STOCK+seckill_id);
seckillGoods.setSeckill_num(Integer.parseInt(seckill_num));
jedis.close();
return seckillGoods;
}
return null;
}
/**
* 暴露秒杀地址
*/
@Override
public SeckillExposer exposer(long seckill_id) {
//读取出redis中对应seckill_id的商品数据
Jedis jedis = jedisPool.getResource();
String string = jedis.get(RedisKey.SECKILL_ID+seckill_id);
jedis.close();
//数据为空,秒杀没准备好或者数据已被删除
if(StringUtils.isEmpty(string)) return new SeckillExposer(false, seckill_id);
SeckillGoods seckillGoods = JSON.parseObject(string, SeckillGoods.class);
long start_time = seckillGoods.getSeckill_start_time().getTime();
long end_time = seckillGoods.getSeckill_end_time().getTime();
long now = new Date().getTime();
//秒杀未开始或者秒杀已结束
if (start_time > now || end_time < now) {
return new SeckillExposer(false, seckill_id, start_time, end_time, now);
}
return new SeckillExposer(true, seckill_id,MD5Util.getMd5(seckill_id));
}
/**
* 执行秒杀
*/
public SeckillStateEnum executeSeckill(long seckill_id, String phone,String md5) throws SeckillException{
//验证数据是否被篡改
if(MD5Util.getMd5(seckill_id).equals(md5)) {
throw new SeckillException(SeckillStateEnum.MD5_ERROR);
}
Jedis jedis = jedisPool.getResource();
String StockStr = jedis.get(RedisKey.SECKILL_STOCK + seckill_id);
int skillStock = Integer.valueOf(StockStr);
//判断是否已经秒杀到
if (jedis.sismember(RedisKey.SECKILL_USERS + seckill_id, String.valueOf(phone))) {
jedis.close();
// 重复秒杀
logger.info("SECKILL_REPEAT. seckill_id={},phone={}", seckill_id, phone);
throw new SeckillException(SeckillStateEnum.SECKILL_REPEAT);
}
//是否已经秒杀完
if (skillStock <= 0) {
jedis.close();
logger.info("SECKILL_OUT. seckill_id={},phone={}", seckill_id, phone);
throw new SeckillException(SeckillStateEnum.SECKILL_OUT);
}else {
jedis.close();
// 进入待秒杀队列,进行后续串行操作
logger.info("SECKILL_QUEUE. seckill_id={},phone={}", seckill_id, phone);
mQProducer.send(MQConfig.SECKILL_QUEUE, seckill_id+","+phone);
return SeckillStateEnum.SECKILL_QUEUE;
}
}
/**
* 在Redis中进行秒杀处理
*/
@Override
public void handleInRedis(long seckill_id, String phone) throws SeckillException {
Jedis jedis = jedisPool.getResource();
String stockKey = RedisKey.SECKILL_STOCK + seckill_id;
String boughtKey = RedisKey.SECKILL_USERS + seckill_id;
String stockStr = jedis.get(stockKey);
int skillStock = Integer.valueOf(stockStr);
//判断是否重复秒杀
if (jedis.sismember(boughtKey, phone)) {
jedis.close();
logger.info("handleInRedis SECKILL_REPEAT. seckill_id={},phone={}", seckill_id, phone);
throw new SeckillException(SeckillStateEnum.SECKILL_REPEAT);
}
//判断是否还有库存
if (skillStock <= 0) {
jedis.close();
logger.info("handleInRedis SECKILL_OUT. seckill_id={},phone={}", seckill_id, phone);
throw new SeckillException(SeckillStateEnum.SECKILL_OUT);
}
//存在问题:当前库存减一,而添加秒杀成功没有时失败了该怎么处理
jedis.decr(stockKey);
jedis.sadd(boughtKey, String.valueOf(phone));
jedis.close();
logger.info("handleInRedis SECKILL_SUCCESS. seckill_id={},phone={}", seckill_id, phone);
}
/**
* 定时轮询秒杀结果
*/
@Override
public SeckillStateEnum isGrab(long seckill_id, String phone) {
Jedis jedis = jedisPool.getResource();
try {
String boughtKey = RedisKey.SECKILL_USERS + seckill_id;
if(jedis.sismember(boughtKey,phone)){
return SeckillStateEnum.SECKILL_SUCCESS;
};
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
}
//问题:如何判断没有秒杀到呢
return SeckillStateEnum.SECKILL_QUEUE;
}
/**
* 先插入秒杀记录再减库存
*/
@Override
@Transactional
public void updateStock(long seckill_id, String phone) throws SeckillException {
Jedis jedis = jedisPool.getResource();
String boughtKey = RedisKey.SECKILL_USERS + seckill_id;
//判断是否秒杀到
if (!jedis.sismember(boughtKey, phone)) {
jedis.close();
logger.info("updateStock ORDER_ERROR. seckill_id={},phone={}", seckill_id, phone);
//没秒杀到,异常订单
throw new SeckillException(SeckillStateEnum.ORDER_ERROR);
}
jedis.close();
// //判断是否已经插入订单
// PayOrder payOrder = payOrderDao.getPayOrder(seckill_id, phone);
// if(!StringUtils.isEmpty(payOrder)) {
// //已经创建订单
// logger.info("updateStock CREATE_ORDER_SUCCESS. seckill_id={},phone={}", seckill_id, phone);
// return ;
// }
//
//插入订单
int result = payOrderDao.insertPayOrder(seckill_id, phone,1, new Date());
//创建订单失败
if(result != 1) {
logger.info("updateStock CREATE_ORDER_ERROR. seckill_id={},phone={}", seckill_id, phone);
throw new SeckillException(SeckillStateEnum.CREATE_ORDER_ERROR);
}
//减库存
result = seckillGoodsDao.reduceSeckillNum(seckill_id);
if(result != 1) {
logger.info("updateStock reduceSeckillNum. seckill_id={},phone={}", seckill_id, phone);
throw new SeckillException(SeckillStateEnum.CREATE_ORDER_ERROR);
}
logger.info("updateStock CREATE_ORDER_SUCCESS. seckill_id={},phone={}", seckill_id, phone);
}
}
|
package ru.innopolis.mputilov.expression;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
* Created by mputilov on 04.09.16.
*/
public class Term extends Expression {
private OpCode opCode;
private Expression left;
private Expression right;
public Term(OpCode op, Expression left, Expression right) {
opCode = op;
this.left = left;
this.right = right;
}
@Override
protected void recursiveToXml(Document doc, Node parent) {
Element element = doc.createElement(opCode.name());
parent.appendChild(element);
left.recursiveToXml(doc, element);
right.recursiveToXml(doc, element);
}
@Override
public String evaluate() {
java.lang.Integer leftEvaluated = java.lang.Integer.valueOf(left.evaluate());
java.lang.Integer rightEvaluated = java.lang.Integer.valueOf(right.evaluate());
switch (opCode) {
case PLUS:
return String.valueOf(leftEvaluated + rightEvaluated);
case MINUS:
return String.valueOf(leftEvaluated - rightEvaluated);
default:
return null;
}
}
public enum OpCode {PLUS, MINUS, NONE}
}
|
package com.tencent.mm.plugin.appbrand.ui;
import android.view.View;
import android.view.View.OnClickListener;
import com.tencent.mm.plugin.appbrand.e;
import com.tencent.mm.plugin.appbrand.e.c;
class g$2 implements OnClickListener {
final /* synthetic */ g gwJ;
g$2(g gVar) {
this.gwJ = gVar;
}
public final void onClick(View view) {
e.a(g.f(this.gwJ).mAppId, c.fcf);
g.f(this.gwJ).finish();
}
}
|
package things.entity.strategy.update;
import things.entity.Bullet;
public class UpdateBullet implements UpdateSprite {
private Bullet bullet;
/* The difference between the initial y position and the new y position
This is the amount of pixels the entity will move per second/update */
private static final int DELTA_Y = 5;
public UpdateBullet(Bullet bullet) {
this.bullet = bullet;
}
@Override
public void update() {
fireBullet();
bullet.notifyObservers();
}
// This method fires the bullet by reducing the the y position by Delta_y each update
private void fireBullet(){
int newTopLeftYPos;
if (bullet.isAlienBullet()) {
newTopLeftYPos = bullet.getTopLeftYPos() + DELTA_Y;
} else
newTopLeftYPos = bullet.getTopLeftYPos() - DELTA_Y;
bullet.setTopLeftYPos(newTopLeftYPos);
}
}
|
package com.isen.regardecommeilfaitbeau.api.Request;
import android.os.Build;
import androidx.annotation.RequiresApi;
import com.isen.regardecommeilfaitbeau.api.Request.darkSky.DarkSkyFuturHour;
import com.isen.regardecommeilfaitbeau.api.Request.darkSky.DarkSkyGlobalInformation;
import com.isen.regardecommeilfaitbeau.api.Request.darkSky.DarkSkyPastHour;
import com.isen.regardecommeilfaitbeau.api.Request.openStreetMap.PositionByCityName;
import com.isen.regardecommeilfaitbeau.api.Request.openStreetMap.PositionByCoordonate;
import com.isen.regardecommeilfaitbeau.typeData.Position;
import com.isen.regardecommeilfaitbeau.typeData.Time;
import com.isen.regardecommeilfaitbeau.typeData.TimeStartDay;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Request {
private Position position;
private Time actualTime;
private TimeStartDay timeStartDay;
private JSONObject currently;
private JSONArray daily;
private JSONArray alerts;
private JSONArray pastHours;
private JSONArray futurHours;
private boolean isDone;
@RequiresApi(api = Build.VERSION_CODES.O)
public Request(String cityName) throws JSONException {
Position initialPosistion = new Position(cityName);
PositionByCityName positionByCityName = new PositionByCityName(initialPosistion);
position = positionByCityName.findPositionProperties();
makeGlobalInformation();
}
@RequiresApi(api = Build.VERSION_CODES.O)
public Request(double latitude, double longitude) throws JSONException {
Position initialPosition = new Position(latitude, longitude);
PositionByCoordonate positionByCoordonate = new PositionByCoordonate(initialPosition);
position = positionByCoordonate.findPositionProperties();
makeGlobalInformation();
}
public Position getPosition() {
return position;
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void makeGlobalInformation() throws JSONException {
DarkSkyGlobalInformation globalInformation = new DarkSkyGlobalInformation(position);
currently = globalInformation.getCurrently();
daily = globalInformation.getDaily();
if(globalInformation.getAlerts() != null){
alerts = globalInformation.getAlerts();
}
actualTime = new Time(Integer.toString(currently.getInt("time")), position.getTimeZone());
timeStartDay = new TimeStartDay(Integer.toString(currently.getInt("time")), position.getTimeZone());
DarkSkyPastHour darkSkyPastHour = new DarkSkyPastHour(position, timeStartDay);
pastHours = darkSkyPastHour.getHourly();
DarkSkyFuturHour darkSkyFuturHour = new DarkSkyFuturHour(position);
futurHours = darkSkyFuturHour.getHourly();
isDone = true;
}
public Time getActualTime() {
return actualTime;
}
public JSONObject getCurrently() {
return currently;
}
public JSONArray getDaily() {
return daily;
}
public JSONArray getAlerts() {
return alerts;
}
public JSONArray getPastHours() {
return pastHours;
}
public JSONArray getFuturHours() {
return futurHours;
}
public boolean isDone() {
return isDone;
}
}
|
package pl.czyzycki.towerdef.gameplay;
import pl.czyzycki.towerdef.gameplay.entities.Bullet;
import pl.czyzycki.towerdef.gameplay.entities.Enemy;
import pl.czyzycki.towerdef.gameplay.entities.Spawn;
import pl.czyzycki.towerdef.gameplay.entities.Tower;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.utils.StringBuilder;
/**
* Klasa zarządzająca renderowaniem informacji debugowych
*
*/
class GameplayDebug {
GameplayScreen screen;
boolean base, spawns, enemies, towers, bullets, camera;
StringBuilder stringBuilder;
GameplayDebug(GameplayScreen screen) {
this.screen = screen;
stringBuilder = new StringBuilder();
}
void render() {
Gdx.gl.glEnable(GL10.GL_BLEND);
Gdx.gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
if(base) screen.base.debugDraw(screen.shapeRenderer);
if(spawns) {
screen.shapeRenderer.begin(ShapeType.Line);
for(Spawn spawn : screen.spawns) spawn.debugDraw(screen.shapeRenderer);
screen.shapeRenderer.end();
}
if(enemies) {
screen.shapeRenderer.begin(ShapeType.FilledCircle);
for(Enemy enemy : screen.groundEnemies) enemy.debugDraw(screen.shapeRenderer);
for(Enemy enemy : screen.airborneEnemies) enemy.debugDraw(screen.shapeRenderer);
screen.shapeRenderer.end();
}
if(towers) {
for(Tower tower : screen.towers) tower.debugDraw(screen.shapeRenderer);
}
if(bullets) {
screen.shapeRenderer.begin(ShapeType.FilledCircle);
for(Bullet bullet : screen.bullets) bullet.debugDraw(screen.shapeRenderer);
screen.shapeRenderer.end();
}
Gdx.gl.glDisable(GL10.GL_BLEND);
screen.batch.begin();
if(base) screen.base.debugText(screen.batch, screen.game.debugFont);
if(spawns) {
for(Spawn spawn : screen.spawns) spawn.debugText(screen.batch, screen.game.debugFont);
}
if(enemies) {
for(Enemy enemy : screen.groundEnemies) enemy.debugText(screen.batch, screen.game.debugFont);
for(Enemy enemy : screen.airborneEnemies) enemy.debugText(screen.batch, screen.game.debugFont);
}
if(towers) {
for(Tower tower : screen.towers) tower.debugText(screen.batch, screen.game.debugFont);
}
screen.batch.end();
}
void renderGUI() {
if(camera) {
screen.batch.begin();
stringBuilder.length = 0;
stringBuilder.append("Position: ");
stringBuilder.append(screen.camera.position.x);
stringBuilder.append(' ');
stringBuilder.append(screen.camera.position.y);
stringBuilder.append(" Zoom: ");
stringBuilder.append(screen.camera.zoom);
screen.game.debugFont.draw(screen.batch, stringBuilder, 15f, 30f);
screen.batch.end();
}
}
}
|
package com.tencent.mm.ui.chatting.viewitems;
import com.tencent.mm.g.a.kz;
import com.tencent.mm.sdk.b.b;
import com.tencent.mm.sdk.b.c;
class s$13 extends c<kz> {
final /* synthetic */ s ucn;
s$13(s sVar) {
this.ucn = sVar;
this.sFo = kz.class.getName().hashCode();
}
public final /* synthetic */ boolean a(b bVar) {
if (s.b(this.ucn) != null) {
s.b(this.ucn).tTq.getContext().runOnUiThread(new 1(this));
}
return true;
}
}
|
package com.best.netty;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
/**
* Created by zz1987 on 2017/7/11.
*/
public class HeartbeatServerHandler extends SimpleChannelInboundHandler<HearbeatMessage> {
private int un_rec_times = 0;
ThreadLocal<HearbeatMessage> localmessage = new ThreadLocal<HearbeatMessage>();
protected void channelRead0(ChannelHandlerContext ctx, HearbeatMessage msg) throws Exception {
System.out.println(ctx.channel().remoteAddress() + " Say : sn=" + msg.getSn()+",reqcode="+msg.getReqCode());
if(msg != null && !"".equals(msg.getSn()) && msg.getReqCode()==1){
msg.setReqCode(2);
ctx.channel().writeAndFlush(msg);
// 失败计数器清零
un_rec_times = 0;
if(localmessage.get()==null){
HearbeatMessage localMsg = new HearbeatMessage();
localMsg.setSn(msg.getSn());
localmessage.set(localMsg);
/*
* 这里可以将设备号放入一个集合中进行统一管理
*/
// TODO
}
}else{
ctx.channel().close();
}
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
IdleStateEvent event = (IdleStateEvent) evt;
if (event.state() == IdleState.READER_IDLE) {
/*读超时*/
System.out.println("===服务端===(READER_IDLE 读超时)");
// 失败计数器次数大于等于3次的时候,关闭链接,等待client重连
if(un_rec_times >= 3){
System.out.println("===服务端===(读超时,关闭chanel)");
// 连续超过N次未收到client的ping消息,那么关闭该通道,等待client重连
ctx.channel().close();
}else{
// 失败计数器加1
un_rec_times++;
}
} else if (event.state() == IdleState.WRITER_IDLE) {
/*写超时*/
System.out.println("===服务端===(WRITER_IDLE 写超时)");
} else if (event.state() == IdleState.ALL_IDLE) {
/*总超时*/
System.out.println("===服务端===(ALL_IDLE 总超时)");
}
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.out.println("错误原因:"+cause.getMessage());
if(localmessage.get()!=null){
/*
* 从管理集合中移除设备号等唯一标示,标示设备离线
*/
// TODO
}
ctx.channel().close();
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("Client active ");
super.channelActive(ctx);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
// 关闭,等待重连
ctx.close();
if(localmessage.get()!=null){
/*
* 从管理集合中移除设备号等唯一标示,标示设备离线
*/
// TODO
}
System.out.println("===服务端===(客户端失效)");
}
}
|
package com.nbu.projects.dentistappointmentsys.repositories;
import com.nbu.projects.dentistappointmentsys.models.User;
import com.nbu.projects.dentistappointmentsys.models.types.Role;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
public interface UserRepository extends JpaRepository<User, Long> {
User findById(Long id);
User findByEmail(String email);
List<User> findAllByRole(Role role);
@Transactional
@Modifying
@Query("update User u set u.password = :password where u.email = :email")
void updatePassword(@Param("password") String password, @Param("email") String email);
@Transactional
@Modifying
@Query("update User u set u.email=:email,u.firstName=:firstName,u.lastName=:lastName where u.id=:Id")
void updateUserInfo(@Param("email") String email,
@Param("firstName") String firstName,
@Param("lastName")String lastName,
@Param("Id") Long Id);
/* // CITY
List<User> findUsersByRoleAndAndCity(Role role, String city);
// NAME
@Query(value = "select u from User u\n" +
"where u.role = :role\n" +
"and (u.firstName like :name or u.lastName like :name)")
List<User> findByName(@Param("role") Role role, @Param("name") String name);
// TYPE
List<User> findUsersByDentistType(DentistType type);
//Combination searches
//Filter by: NAME + TYPE + CITY
@Query(value = "select u from User u\n" +
"where u.city = :city and u.dentistType = :type\n" +
"and (u.firstName like :name or u.lastName like :name)")
List<User> findByCityTypeAndName(@Param("city") String city, @Param("type") DentistType type, @Param("name") String name);
//Filter by: NAME + TYPE
@Query(value = "select u from User u\n" +
"where u.dentistType = :type\n" +
"and (u.firstName like :name or u.lastName like :name)")
List<User> findByNameAndType(@Param("name") String name, @Param("type") DentistType type);
//Filter by: NAME + CITY
@Query(value = "select u from User u\n" +
"where u.city = :city and u.role = :role\n" +
"and (u.firstName like :name or u.lastName like :name)")
List<User> findByNameAndCity(@Param("name") String name,@Param("city") String city, @Param("role") Role role);
//Filter by: TYPE + CITY
List<User> findUsersByCityAndDentistType(String city, DentistType type);
@Transactional
@Modifying
@Query("update User u set u.email=:email,u.firstName=:firstName,u.lastName=:lastName,u.dentistType=:dentistType,u.city=:city,u.generalInformation=:generalInformation where u.id=:Id")
void updateDentistInfo(@Param("email") String email,
@Param("firstName") String firstName,
@Param("lastName")String lastName,
@Param("dentistType")DentistType dentistType,
@Param("city") String city,
@Param("generalInformation")String generalInformation,
@Param("Id") Long Id);
*//* @Query("update User u set u.blacklist = u.blacklist + 1 where u.id = :id")
void addToBlacklist(@Param("id") Long id);*/
}
|
/*
* 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 repositorio;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.enterprise.context.Dependent;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;
import modelo.Filme;
import modelo.Sessao;
/**
*
* @author mathe
*/
@Dependent
public class SessaoRepositorio implements Serializable{
@PersistenceContext(unitName = "CinemaniaPU")
private EntityManager em;
@Resource
private UserTransaction transaction;
public void create(Sessao sessao) {
try {
transaction.begin();
Filme filme = em.find(Filme.class, sessao.getFilme().getId());
filme.addSessao(sessao);
em.persist(sessao);
transaction.commit();
} catch (IllegalStateException | SecurityException | HeuristicMixedException | HeuristicRollbackException | NotSupportedException | RollbackException | SystemException e) {
System.out.println("Erro: " + e);
}
}
public void delete(Long numero) {
try {
transaction.begin();
Sessao sessao;
sessao = em.getReference(Sessao.class, numero);
em.remove(sessao);
transaction.commit();
} catch (NotSupportedException | SystemException | RollbackException | HeuristicMixedException | HeuristicRollbackException | SecurityException | IllegalStateException ex) {
Logger.getLogger(CategoriaRepositorio.class.getName()).log(Level.SEVERE, null, ex);
}
}
public List<Sessao> findAll() {
return em.createQuery("SELECT s FROM Sessao s").getResultList();
}
public Sessao findById(Long numero) {
Sessao sessao = new Sessao();
try {
sessao = em.find(Sessao.class, numero);
} catch (Exception e) {
System.out.println("Erro ao buscar categoria por id: "+ e);
}
return sessao;
}
public List<Sessao> findByNumber(Long id) {
List<Sessao> sessoes = new ArrayList<>();;
try {
sessoes = (List<Sessao>) em.createQuery("SELECT s FROM Sessao s WHERE s.filme.id = ?1").
setParameter(1, id).setMaxResults(4).getResultList();
} catch(NoResultException nre) {
System.out.println("Erro ao buscar categoria por nome: "+ nre);
}
return sessoes;
}
public List<Sessao> findSessoesByDataFilme( Long id,Long idData){
return em.createQuery("SELECT s FROM Sessao s WHERE s.filme.id = ?1 AND s.data.id = ?2")
.setParameter(1, id).setParameter(2,idData).getResultList() ;
}
}
|
package com.minipg.fanster.armoury.object;
import android.text.Editable;
/**
* Created by Knot on 8/15/2017.
*/
public class User {
String username;
String password;
public User (String username,String password){
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
|
package com.javakc.ssm.modules.batchOut.entity;
import com.javakc.ssm.modules.booklistOut.entity.BooklistOutEntity;
import com.javakc.ssm.modules.operator.entity.OperatorEntity;
import com.javakc.ssm.modules.settlement.entity.SettlementEntity;
import lombok.Data;
import java.util.Date;
/**
* @ClassName batchOutEntity
* @Description TODO
* @Author Administrator
* @Date 2020/3/21 11:49
* @Version 1.0
**/
@Data
public class BatchOutEntity {
private String batchId ;
/** 批次名称 */
private String bathName ;
/** 批次书籍数量 */
private Integer bathBooknum ;
/** 默认运营平台 */
private String defaultPlatform ;
/** 授权开始时间 */
private Date authorizationStarttime ;
/** 授权结束时间 */
private Date authorizationEndtime ;
/** 分成比例 */
private String proportion ;
/** 逻辑删除 */
private Integer flag ;
/** 合作方id */
private String copyrightid ;
/** 合同编号 */
private String contractNumber ;
/** 类别 */
private Integer partnersCategory ;
/** 运营方 **/
private OperatorEntity operatorEntity;
/** 书单对象 **/
private BooklistOutEntity booklistOutEntity;
/** 结算管理对象 **/
private SettlementEntity settlementEntity;
}
|
package org.kuali.mobility.events.entity;
import java.util.List;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
@XStreamAlias("events")
public class UMEventReader {
@XStreamImplicit
private List<UMEvent> events;
public List<UMEvent> getEvents() {
return events;
}
public void setEvents(List<UMEvent> events) {
this.events = events;
}
}
|
package com.project.weiku.discover.ui;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.project.weiku.R;
import com.project.weiku.base.BaseActivity;
import com.project.weiku.discover.adapter.CommentAdapter;
import com.project.weiku.discover.adapter.CookingAdapter;
import com.project.weiku.discover.model.CommentEntity;
import com.project.weiku.discover.model.DetailEntity;
import com.project.weiku.discover.model.HandpickEntity;
import com.project.weiku.util.Constants;
import com.project.weiku.util.LogUtils;
import com.project.weiku.util.OkHttpUtil;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
/**
* id=22830&net=wifi&access=259eea423dee18c7b865b0777cd657cc&wid=3f110fa66586c8a945df735ac6240b64
* foreign_id=22830&net=wifi&access=259eea423dee18c7b865b0777cd657cc&type=cooking
*/
public class DetilsActivity extends BaseActivity {
@Bind(R.id.iv_det_back)
public ImageView ivDetBack;
@Bind(R.id.tv_det_title)
public TextView tvDetBigTittle;
@Bind(R.id.tv_det_more)
public TextView ivDetMore;
@Bind(R.id.rl_det_search)
public RelativeLayout rlDetSearch;
@Bind(R.id.tv_det_remark)
public TextView tvDetRemark;
@Bind(R.id.lv_det_comment)
public ListView lvDet;
@Bind(R.id.iv_avatar)
public SimpleDraweeView svDetAvatar;
@Bind(R.id.iv_bigimage)
public SimpleDraweeView svBigImage;
@Bind(R.id.tv_nickname)
public TextView tvDetNickname;
@Bind(R.id.tv_create_time)
public TextView tvDetTime;
@Bind(R.id.tv_praise_score)
public TextView tvDetscore;
@Bind(R.id.tv_title)
public TextView tvDetSmallTitle;
@Bind(R.id.tv_tag)
public TextView tvDetTag;
@Bind(R.id.tv_description)
public TextView tvDetDescription;
@Bind(R.id.tv_praise)
public TextView tvDetPraise;
@Bind(R.id.tv_comment)
public TextView tvDetComment;
@Bind(R.id.iv_share)
public ImageView ivDetShare;
//评论集合列表
private List<CommentEntity.ResultEntity.ListEntity> mList;
//评论适配器
private CommentAdapter mAdapter;
@Override
protected int getViewResid() {
return R.layout.activity_detils;
}
@Override
protected void init() {
super.init();
mList=new ArrayList<>();
mAdapter=new CommentAdapter(mList,getApplication());
lvDet.setAdapter(mAdapter);
}
@Override
protected void loadDatas() {
super.loadDatas();
Intent intent = getIntent();
//获取启动这个传过来的请求id
//HandpickFragment
String requestId = intent.getStringExtra("requestId");
final int position = intent.getIntExtra("position", 0);
/**
* 详情页请求
*/
OkHttpUtil.downJSON(Constants.URL.DETAILS_URL + "id=" + requestId + "&net=wifi&access=259eea423dee18c7b865b0777cd657cc&wid=3f110fa66586c8a945df735ac6240b64", new OkHttpUtil.OnDownDataListener() {
@Override
public void onResponse(String url, String json) {
try {
JSONObject jsonObject = new JSONObject(json);
String info = jsonObject.getString("info");
if ("success".equals(info)) {
Gson gson = new Gson();
DetailEntity detailEntity = gson.fromJson(json, DetailEntity.class);
tvDetNickname.setText(detailEntity.getResult().getAccount().getNickname());
tvDetBigTittle.setText(detailEntity.getResult().getTitle());
svDetAvatar.setImageURI(Uri.parse(detailEntity.getResult().getAccount().getAvatar()));
tvDetTime.setText(detailEntity.getResult().getCreate_time());
svBigImage.setImageURI(Uri.parse(detailEntity.getResult().getImage()));
tvDetscore.setText(detailEntity.getResult().getPraise_score());
tvDetSmallTitle.setText(detailEntity.getResult().getTitle());
tvDetTag.setText(detailEntity.getResult().getTags().toString());
tvDetDescription.setText(detailEntity.getResult().getDescription());
tvDetPraise.setText(detailEntity.getResult().getPraise());
tvDetComment.setText(detailEntity.getResult().getComment());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(String url, String error) {
}
});
/**
* 详情页评论请求
*/
OkHttpUtil.downJSON(Constants.URL.DETAILS_COMMENT_URL
+ "foreign_id=" + requestId + "&net=wifi&access=259eea423dee18c7b865b0777cd657cc&type=cooking"
, new OkHttpUtil.OnDownDataListener() {
@Override
public void onResponse(String url, String json) {
Gson gson = new Gson();
CommentEntity commentEntity = gson.fromJson(json, CommentEntity.class);
mList.addAll(commentEntity.getResult().getList());
mAdapter.notifyDataSetChanged();
setListViewHeight(lvDet);
}
@Override
public void onFailure(String url, String error) {
}
});
}
public void setListViewHeight(ListView listView) {
// 获取ListView对应的Adapter
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = 0;
for (int i = 0, len = listAdapter.getCount(); i < len; i++) { // listAdapter.getCount()返回数据项的数目
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0); // 计算子项View 的宽高
totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
}
|
/*
* 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.entidades;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author Francisco Neto
*/
@Entity
@Table(name = "mensagem")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Mensagem.findAll", query = "SELECT m FROM Mensagem m")
, @NamedQuery(name = "Mensagem.findByCod", query = "SELECT m FROM Mensagem m WHERE m.cod = :cod")
, @NamedQuery(name = "Mensagem.findByTitulo", query = "SELECT m FROM Mensagem m WHERE m.titulo = :titulo")
, @NamedQuery(name = "Mensagem.findByTexto", query = "SELECT m FROM Mensagem m WHERE m.texto = :texto")
, @NamedQuery(name = "Mensagem.findByLink", query = "SELECT m FROM Mensagem m WHERE m.link = :link")})
public class Mensagem implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "cod")
private Integer cod;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 50)
@Column(name = "titulo")
private String titulo;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 200)
@Column(name = "texto")
private String texto;
@Size(max = 300)
@Column(name = "link")
private String link;
@JoinColumn(name = "codusuario", referencedColumnName = "cod")
@ManyToOne
private Usuario codusuario;
public Mensagem() {
}
public Mensagem(Integer cod) {
this.cod = cod;
}
public Mensagem(Integer cod, String titulo, String texto) {
this.cod = cod;
this.titulo = titulo;
this.texto = texto;
}
public Integer getCod() {
return cod;
}
public void setCod(Integer cod) {
this.cod = cod;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public String getTexto() {
return texto;
}
public void setTexto(String texto) {
this.texto = texto;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public Usuario getCodusuario() {
return codusuario;
}
public void setCodusuario(Usuario codusuario) {
this.codusuario = codusuario;
}
@Override
public int hashCode() {
int hash = 0;
hash += (cod != null ? cod.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Mensagem)) {
return false;
}
Mensagem other = (Mensagem) object;
if ((this.cod == null && other.cod != null) || (this.cod != null && !this.cod.equals(other.cod))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.entidades.Mensagem[ cod=" + cod + " ]";
}
}
|
package org.machine.spring_beans_l.service.impl;
import org.machine.spring_beans_l.entity.User;
import org.machine.spring_beans_l.service.UserService;
import org.springframework.util.Assert;
public class UserServiceImpl implements UserService {
@Override
public User find(String name) {
Assert.notNull(name);
User user = new User();
user.setName(name);
if (name.equals("shao")==true) {
user.setAge(42);
} else if(name.equals("liu")==true) {
user.setAge(36);
} else {
user = null;
}
return user;
}
}
|
package com.ss.android.ugc.aweme.miniapp.f;
import com.ss.android.ugc.aweme.miniapp.MiniAppService;
import com.ss.android.ugc.aweme.miniapp_api.b.b;
import com.tt.miniapphost.process.data.CrossProcessDataEntity;
import com.tt.miniapphost.process.handler.IAsyncHostDataHandler;
import com.tt.miniapphost.process.helper.AsyncIpcHandler;
public class g implements IAsyncHostDataHandler {
public static boolean a;
public static final String b = g.class.getSimpleName();
private static b c;
public void action(CrossProcessDataEntity paramCrossProcessDataEntity, AsyncIpcHandler paramAsyncIpcHandler) {
byte b1;
CrossProcessDataEntity crossProcessDataEntity = CrossProcessDataEntity.Builder.create().build();
String str = paramCrossProcessDataEntity.getString("live_stream_action");
switch (str.hashCode()) {
default:
b1 = -1;
break;
case 1935018183:
if (str.equals("unregister_live_stream_end_listener")) {
b1 = 3;
break;
}
case 782245952:
if (str.equals("register_live_stream_end_listener")) {
b1 = 2;
break;
}
case 23018858:
if (str.equals("pause_live_stream")) {
b1 = 0;
break;
}
case -1541913311:
if (str.equals("resume_live_stream")) {
b1 = 1;
break;
}
}
if (b1 != 0) {
if (b1 != 1) {
if (b1 != 2) {
if (b1 != 3)
return;
MiniAppService.inst().getBaseLibDepend();
paramAsyncIpcHandler.callback(crossProcessDataEntity);
a = false;
return;
}
c = new b(this, paramAsyncIpcHandler, crossProcessDataEntity) {
};
MiniAppService.inst().getBaseLibDepend();
a = true;
return;
}
MiniAppService.inst().getBaseLibDepend();
paramAsyncIpcHandler.callback(crossProcessDataEntity);
return;
}
MiniAppService.inst().getBaseLibDepend();
paramAsyncIpcHandler.callback(crossProcessDataEntity);
}
public String getType() {
return "live_window_event";
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\ss\androi\\ugc\aweme\miniapp\f\g.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ |
package com.webserv.workshopmongo.config;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.TimeZone;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
import com.webserv.workshopmongo.domain.Post;
import com.webserv.workshopmongo.domain.User;
import com.webserv.workshopmongo.dto.AuthorDTO;
import com.webserv.workshopmongo.dto.CommentDTO;
import com.webserv.workshopmongo.repository.PostRepository;
import com.webserv.workshopmongo.repository.UserRepository;
@Configuration
public class Instantiation implements CommandLineRunner {
@Autowired
private UserRepository userReposiroty;
@Autowired
private PostRepository postReposiroty;
@Override
public void run(String... arg0) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
userReposiroty.deleteAll();
postReposiroty.deleteAll();
User maria = new User(null, "Maria Brown", "maria@gmail.com");
User alex = new User(null, "Alex Green", "alex@gmail.com");
User bob = new User(null, "Bob Grey", "bob@gmail.com");
userReposiroty.saveAll(Arrays.asList(maria, alex, bob));
/*- CRUD de candidato com os seguintes campos:
- Nome,
- E-mail,
- Idade,
- Url linkedin, */
/*
* - Combo múltipla escolha das tecnologias que o programador tem conhecimento. (As opções devem ser as seguintes: C#, Javascript, Nodejs, Angular, React, Ionic, Mensageria, PHP, Laravel)
*/
Post post1 = new Post(null, sdf.parse("21/03/2018"),"Analista de Sistemas / Aplicações", "C#, Javascript, Nodejs", new AuthorDTO(maria));
Post post2 = new Post(null, sdf.parse("23/03/2018"), "Programador / Desenvolvedor", "Angular, React, Ionic", new AuthorDTO(alex));
Post post3 = new Post(null, sdf.parse("23/03/2018"), "Analista de Sistemas ", "Mensageria, PHP, Laravel", new AuthorDTO(bob));
Post post4 = new Post(null, sdf.parse("23/03/2018"), "Analista de Sistemas ", "Mensageria, PHP, Laravel", new AuthorDTO(bob));
CommentDTO c1 = new CommentDTO("URL Linkedin : https://www.linkedin.com "+"Idade: 30 ", sdf.parse("21/03/2018"), new AuthorDTO(maria));
CommentDTO c2 = new CommentDTO("URL Linkedin : https://www.linkedin.com " + "Idade: 29", sdf.parse("22/03/2018"), new AuthorDTO(alex));
CommentDTO c3 = new CommentDTO("URL Linkedin : https://www.linkedin.com " + "Idade: 31 ", sdf.parse("23/03/2018"), new AuthorDTO(bob));
post1.getComments().addAll(Arrays.asList(c1));
post2.getComments().addAll(Arrays.asList(c3));
post3.getComments().addAll(Arrays.asList(c3));
postReposiroty.saveAll(Arrays.asList(post1, post2, post3));
maria.getPosts().addAll(Arrays.asList(post1, post2,post3));
userReposiroty.save(maria);
}
} |
package c.t.m.g;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Process;
import android.os.SystemClock;
public final class m {
public static String a = "null";
public static String b = "";
public static String c = "";
public static String d = "";
public static boolean e = true;
private static Context f = null;
private static String g;
private static long h;
private static int i = 0;
private static boolean j = false;
private static String k = "";
private static int l = 0;
private static String m = "3.4.1.6";
private static String n = "";
private static int o = -1;
private static boolean p = false;
private static String q = "";
private static Handler r;
private static volatile boolean s = false;
public static Context a() {
return f;
}
public static void a(int i, b bVar, String str) {
h = SystemClock.elapsedRealtime();
o = Process.myPid();
Context context = bVar.a;
f = context.getApplicationContext();
k = context.getPackageName();
i = i;
j = bVar.c;
String str2 = bVar.d;
if (ci.a(str2)) {
str2 = "";
}
c = str2;
str2 = bVar.e;
if (ci.a(str2)) {
str2 = "";
}
d = str2;
m = "3.4.1.6";
Handler handler = new Handler(f.getMainLooper());
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
a = packageInfo.versionName;
l = packageInfo.versionCode;
b = packageInfo.applicationInfo.loadLabel(context.getPackageManager()).toString();
} catch (Throwable th) {
}
n = str;
p = k.equals(n);
g = ci.d();
HandlerThread handlerThread = new HandlerThread("HalleyTempTaskThread");
handlerThread.start();
r = new Handler(handlerThread.getLooper());
p.a();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Print SDKBaseInfo on tag:" + "after initSDKBaseInfo");
stringBuilder.append("\r\nPlatformProtocalType:2");
stringBuilder.append("\r\nappContext:" + f);
stringBuilder.append("\r\nbootSessionId:" + g);
stringBuilder.append("\r\nbootTime:" + h);
stringBuilder.append("\r\nappId:" + i);
stringBuilder.append("\r\nisSDKMode:" + j);
stringBuilder.append("\r\nbundle:" + k);
stringBuilder.append("\r\nappVersionName:" + a);
stringBuilder.append("\r\nappVersionCode:" + l);
stringBuilder.append("\r\nappLabelName:" + b);
stringBuilder.append("\r\nuuid:" + c);
stringBuilder.append("\r\nchannelId:" + d);
stringBuilder.append("\r\nsdkVersion:" + m);
stringBuilder.append("\r\nsProcessName:" + n);
stringBuilder.append("\r\npid:" + o);
stringBuilder.append("\r\nsProcessNameSubfix:" + q);
stringBuilder.append("\r\nsIsMainProcess:" + p);
stringBuilder.append("\r\npsInRemoteProcess:" + e);
stringBuilder.append("\r\nisTestMode:false");
if (f != null) {
stringBuilder.append("\r\ndeviceid:" + cd.a());
}
stringBuilder.append("\r\nfinger:" + Build.FINGERPRINT);
}
public static int b() {
return i;
}
public static String c() {
return g;
}
public static int d() {
return (int) (SystemClock.elapsedRealtime() - h);
}
public static String e() {
return k;
}
public static boolean f() {
return j;
}
public static String g() {
return m;
}
public static String h() {
if (!ci.a(q)) {
return q;
}
if (ci.a(n) || !n.contains(":")) {
return "";
}
return n.substring(n.indexOf(":") + 1);
}
public static Handler i() {
return r;
}
}
|
package com.zlzkj.app.controller.cargo;
import com.zlzkj.app.model.form.StockOutForm;
import com.zlzkj.app.model.index.User;
import com.zlzkj.app.service.cargo.StockOutService;
import com.zlzkj.app.service.index.ShiroUserService;
import com.zlzkj.app.util.ExcelUtil;
import com.zlzkj.app.util.ExcelUtil.Header;
import com.zlzkj.app.util.MapUtil;
import com.zlzkj.app.util.PageView;
import com.zlzkj.core.base.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping(value = "/stock_out")
public class StockOutController extends BaseController {
@Autowired
private StockOutService stockOutService;
@Autowired
private ShiroUserService shiroUserService;
@RequestMapping(value = {"/index"})
public String index(Model model, HttpServletRequest request, HttpServletResponse response, Integer nowPage) {
Map map = MapUtil.convert(request.getParameterMap());
User curUser = shiroUserService.getLoginUser();
if(!curUser.isSuperAdmin()){
map.put("tenantId",curUser.getTenantId());
}
model.addAttribute("pageView", new PageView(stockOutService.findByMap(map, nowPage)));
return "cargo/stockout/index";
}
@RequestMapping(value = {"/view"})
public String view(Model model, HttpServletRequest request, HttpServletResponse response, Integer nowPage) {
Map map = MapUtil.convert(request.getParameterMap());
User curUser = shiroUserService.getLoginUser();
if(!curUser.isSuperAdmin()){
map.put("tenantId",curUser.getTenantId());
}
model.addAttribute("pageView", new PageView(stockOutService.findByMap(map, nowPage)));
return "cargo/stockout/view";
}
@RequestMapping(value = {"/to_create"})
public String toCreate(Model model, HttpServletRequest request, HttpServletResponse response) {
return "cargo/stockout/form";
}
@RequestMapping(value = {"/to_update"})
public String toUpdate(Model model, HttpServletRequest request, HttpServletResponse response,String index) {
model.addAttribute("obj",stockOutService.findById(index));
model.addAttribute("items",stockOutService.findItemsByOrderId(index));
return "cargo/stockout/form";
}
@RequestMapping(value = {"/excel"})
public void excel(Model model, HttpServletRequest request, HttpServletResponse response) {
try {
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
response.setContentType("application/octet-stream;");
response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode("出库单.xls","UTF-8"));
Map<String, Object> result = new HashMap();
Map map = MapUtil.convert(request.getParameterMap());
User curUser = shiroUserService.getLoginUser();
if (!curUser.isSuperAdmin()) {
map.put("tenantId", curUser.getTenantId());
}
List<Header> header = new ArrayList<Header>(){{
add(new Header("出库单编号","order_no",500));
add(new Header("出库单标题","title",800));
add(new Header("备注","description",600));
add(new Header("创建时间","created_time",400));
add(new Header("状态","status",new HashMap<String,String>(){{
put("0","未出库");
put("1","出库中");
put("2","已出库");
}}));
}};
ExcelUtil.excel(header,stockOutService.findByMap(map),response.getOutputStream());
}catch (Exception e){
e.printStackTrace();
}
}
@ResponseBody
@RequestMapping(value = {"/create"})
public int create(HttpServletRequest request,@ModelAttribute("stockOutForm") StockOutForm stockOutForm) {
User curUser = shiroUserService.getLoginUser();
return stockOutService.save(stockOutForm,curUser.getId(),curUser.getTenantId());
}
@ResponseBody
@RequestMapping(value = {"/update"})
public int update(HttpServletRequest request,@ModelAttribute("stockOutForm") StockOutForm stockOutForm) {
return stockOutService.update(stockOutForm);
}
@ResponseBody
@RequestMapping(value = {"/detail"})
public Map<String, Object> detail(HttpServletRequest request, String id) {
Map<String, Object> result = new HashMap();
result.put("obj", stockOutService.findById(id));
result.put("items", stockOutService.findItemsByOrderId(id));
return result;
}
@ResponseBody
@RequestMapping(value = {"/item_detail"})
public Map<String, Object> itemDetail(HttpServletRequest request,Integer nowPage) {
Map<String, Object> result = new HashMap();
Map parmMap = MapUtil.convert(request.getParameterMap());
result.put("pageView", new PageView(stockOutService.findCargoByMap(parmMap,nowPage)));
return result;
}
@ResponseBody
@RequestMapping(value = {"/delete"}, method = RequestMethod.POST)
public String delete(Model model, HttpServletRequest request, HttpServletResponse response, String[] id) {
return ajaxReturn(response, stockOutService.deletebyIds(id));
}
@ResponseBody
@RequestMapping(value = {"/serve"}, method = RequestMethod.POST)
public String serve(Model model, HttpServletRequest request, HttpServletResponse response, String id) {
return ajaxReturn(response, stockOutService.serve(id,shiroUserService.getLoginUser().getTenantId()));
}
@ResponseBody
@RequestMapping(value = {"/hide"}, method = RequestMethod.POST)
public String hide(Model model, HttpServletRequest request, HttpServletResponse response, String id) {
return ajaxReturn(response, stockOutService.hide(id));
}
@ResponseBody
@RequestMapping(value = {"/unhide"}, method = RequestMethod.POST)
public String unhide(Model model, HttpServletRequest request, HttpServletResponse response, String id) {
return ajaxReturn(response, stockOutService.unhide(id));
}
@ResponseBody
@RequestMapping(value = {"/list"})
public Map<String, Object> stockOutList(HttpServletRequest request, Integer nowPage) {
Map<String, Object> result = new HashMap();
Map map = MapUtil.convert(request.getParameterMap());
User curUser = shiroUserService.getLoginUser();
if (!curUser.isSuperAdmin()) {
map.put("tenantId", curUser.getTenantId());
}
result.put("pageView", new PageView(stockOutService.findByMap(map, nowPage)));
return result;
}
@ResponseBody
@RequestMapping(value = "/check_stock_out_order_no")
public boolean checkShelfNo(String name, String originalname) {
Map<String, Object> paraMap = new HashMap();
User curUser = shiroUserService.getLoginUser();
paraMap.put("orderNo", name);
paraMap.put("tenantId", curUser.getTenantId());
paraMap.put("start", 0);
paraMap.put("end", 1);
if (stockOutService.findByMap(paraMap).size() > 0 && !name.equals(originalname)) {
return false;
}
return true;
}
}
|
import java.text.NumberFormat;
import java.util.ArrayList;
/**
* Created by chenguanghe on 2/8/15.
*/
public class Experiments {
// n Number of items in the filter
// p Probability of false positives, float between 0 and 1 or a number indicating 1-in-p
// m Number of bits in the filter
// k Number of hash function
//
// m = ceil((n * log(p)) / log(1.0 / (pow(2.0, log(2.0)))));
// k = round(log(2.0) * m / n);
private final int lengthOfString = 8;
private final int ExperimentTimes = 5;
static NumberFormat numberFormat = NumberFormat.getPercentInstance();
public static void main(String[] args) {
Experiments experiments = new Experiments();
numberFormat.setMinimumFractionDigits(2);
experiments.FalsePositive1();
experiments.FalsePositive2();
experiments.FalsePositive3();
}
// Theoretically, p = 0.02, n = 1000000, m = 1017795 * 8(bit per element), k = 6
private void FalsePositive1(){
ArrayList<double[]> res = new ArrayList<double[]>();
for (int i = 0 ; i < ExperimentTimes; i++) {
FalsePositives falsePositives = new FalsePositives(1017795);
res.add(falsePositives.falsePositive(1000000, lengthOfString));
}
double averageofDie = 0.0;
double averageofRan = 0.0;
for (double[] d: res){
averageofDie +=d[0];
averageofRan +=d[1];
}
averageofDie /= ExperimentTimes;
averageofRan /= ExperimentTimes;
ShowResult(new double[]{averageofDie, averageofRan}, 0.02, "FalsePositive1");
}
// Theoretically, p = 0.2, n = 2000000, m = 1017795 * 8(bit per element), k = 6
private void FalsePositive2(){
ArrayList<double[]> res = new ArrayList<double[]>();
for (int i = 0 ; i < ExperimentTimes; i++) {
FalsePositives falsePositives = new FalsePositives(1017795);
res.add(falsePositives.falsePositive(1000000*2, lengthOfString));
}
double averageofDie = 0.0;
double averageofRan = 0.0;
for (double[] d: res){
averageofDie +=d[0];
averageofRan +=d[1];
}
averageofDie /= ExperimentTimes;
averageofRan /= ExperimentTimes;
ShowResult(new double[]{averageofDie, averageofRan}, 0.2, "FalsePositive2");
}
// Theoretically, p = 0.5, n = 1000000, m = 779403 * 8(bit per element), k = 4
private void FalsePositive3(){
ArrayList<double[]> res = new ArrayList<double[]>();
for (int i = 0 ; i < ExperimentTimes; i++) {
FalsePositives falsePositives = new FalsePositives(779403);
res.add(falsePositives.falsePositive(1000000, lengthOfString));
}
double averageofDie = 0.0;
double averageofRan = 0.0;
for (double[] d: res){
averageofDie +=d[0];
averageofRan +=d[1];
}
averageofDie /= ExperimentTimes;
averageofRan /= ExperimentTimes;
ShowResult(new double[]{averageofDie, averageofRan}, 0.05, "FalsePositive3");
}
private void ShowResult(double[] doubles, double p, String s){
System.out.println(s+": [Theoretically p is "+numberFormat.format(p)+"] [BloomFilterDet: "+numberFormat.format(doubles[0])+"] [BloomFilterRan: "+numberFormat.format(doubles[1])+"]");
}
}
|
public class A{
static int a = 0;
int b = 0;
} |
package com.tencent.mm.ui.chatting.viewitems;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.tencent.mm.R;
import com.tencent.mm.ab.e;
import com.tencent.mm.ab.o;
import com.tencent.mm.model.au;
import com.tencent.mm.model.c;
import com.tencent.mm.model.q;
import com.tencent.mm.plugin.subapp.c.h;
import com.tencent.mm.plugin.subapp.c.k;
import com.tencent.mm.pluginsdk.model.app.ac;
import com.tencent.mm.pluginsdk.model.app.ao;
import com.tencent.mm.pluginsdk.model.app.l;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.bd;
import com.tencent.mm.ui.chatting.c.a;
import com.tencent.mm.y.g;
public final class am extends b {
private e ehD;
private a tKy;
private a ufa;
public final boolean bba() {
return false;
}
public final boolean aq(int i, boolean z) {
if (i == -1879048191) {
return true;
}
return false;
}
public final View a(LayoutInflater layoutInflater, View view) {
if (view != null && view.getTag() != null) {
return view;
}
r rVar = new r(layoutInflater, R.i.chatting_item_voiceremind_sys);
rVar.setTag(new bb().dN(rVar));
return rVar;
}
public final void a(b.a aVar, int i, a aVar2, bd bdVar, String str) {
bb bbVar = (bb) aVar;
this.tKy = aVar2;
g fI = ao.cbY().fI(bdVar.field_msgId);
String str2 = bdVar.field_content;
g.a aVar3 = null;
if (!(fI == null || str2 == null)) {
aVar3 = g.a.J(str2, bdVar.field_reserved);
}
if (aVar3 != null) {
bbVar.eCn.setText(aVar3.description);
}
x.d("MicroMsg.ChattingItemVoiceRemindSys", "content sys " + bdVar.field_content);
com.tencent.mm.plugin.subapp.c.e Oj = com.tencent.mm.plugin.subapp.c.e.Oj(str2);
if (Oj != null && Oj.orp != null && Oj.orp.length() > 0 && Oj.orq > 0 && this.ehD == null && aVar3 != null && bi.oW(bdVar.field_imgPath)) {
str2 = k.nJ(q.GF());
String aY = h.aY(str2, false);
bdVar.eq(str2);
au.HU();
c.FT().a(bdVar.field_msgId, bdVar);
long j = bdVar.field_msgId;
int i2 = aVar3.sdkVer;
String str3 = aVar3.appId;
String str4 = Oj.orp;
int i3 = Oj.orq;
int i4 = aVar3.type;
String str5 = aVar3.dwK;
String a = l.a(aY, j, i2, str3, str4, i3, i4, aVar3.dws);
if (a != null) {
o DF = au.DF();
1 1 = new 1(this, bdVar, a, i);
this.ehD = 1;
DF.a(221, 1);
ac acVar = new ac(a);
acVar.cbT();
au.DF().a(acVar, 0);
}
}
bbVar.eCn.setTag(new au(bdVar, aVar2.cwr(), i, null, 0));
TextView textView = bbVar.eCn;
if (this.ufa == null) {
this.ufa = new a(this, this.tKy);
}
textView.setOnClickListener(this.ufa);
au.HU();
if (c.isSDCardAvailable()) {
bbVar.eCn.setOnLongClickListener(c(aVar2));
}
}
public final boolean a(ContextMenu contextMenu, View view, bd bdVar) {
int i = ((au) view.getTag()).position;
if (!this.tKy.cws()) {
contextMenu.add(i, 100, 0, this.tKy.tTq.getMMResources().getString(R.l.chatting_long_click_menu_delete_msg));
}
return true;
}
public final boolean a(MenuItem menuItem, a aVar, bd bdVar) {
switch (menuItem.getItemId()) {
case 100:
String str = bdVar.field_content;
g.a aVar2 = null;
if (str != null) {
aVar2 = g.a.gp(str);
}
if (aVar2 != null) {
l.fJ(bdVar.field_msgId);
}
com.tencent.mm.model.bd.aU(bdVar.field_msgId);
break;
}
return false;
}
public final boolean b(View view, a aVar, bd bdVar) {
return true;
}
}
|
package com.kingaspx.contatoswhatsapp;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
import com.google.android.material.tabs.TabLayout;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.kingaspx.contatoswhatsapp.Adapter.TabAdapter;
import com.kingaspx.contatoswhatsapp.Fragments.ContatosFragment;
import com.kingaspx.contatoswhatsapp.Fragments.SettingsFragment;
import com.kingaspx.contatoswhatsapp.Model.User;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
public class HomeActivity extends AppCompatActivity {
private List<User> userList;
private TabLayout tabLayout;
private ViewPager viewPager;
private TabAdapter adapter;
private TextView userText, idText;
private Context context;
private FirebaseDatabase database = FirebaseDatabase.getInstance();
private DatabaseReference usersRef = database.getReference("users");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
context = this;
userList = new ArrayList<>();
userText = findViewById(R.id.text_username);
idText = findViewById(R.id.text_id);
getUserInfo();
tabLayout = findViewById(R.id.tab_layout);
viewPager = findViewById(R.id.view_pager);
adapter = new TabAdapter(getSupportFragmentManager());
adapter.addFragment(new ContatosFragment(this), "Contatos");
adapter.addFragment(new SettingsFragment(this), "Configuração");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
MobileAds.initialize(this, (initializationStatus) -> {
});
AdView adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId("ca-app-pub-1508037510426777/7874007352");
adView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
}
private void getUserInfo() {
Intent intent = getIntent();
String id = intent.getStringExtra("id");
String username = intent.getStringExtra("username");
if (username != null) {
idText.setText(id);
userText.setText("@" + username);
} else {
usersRef.orderByChild("id").equalTo(id).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NotNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
idText.setText(user.getId());
userText.setText("@" + user.getUsername());
}
}
@Override
public void onCancelled(@NonNull @NotNull DatabaseError databaseError) {
}
});
}
}
private void storeDataUser(String id) {
SharedPreferences prefs = getSharedPreferences("kingaspx-login", MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = prefs.edit();
prefsEditor.clear();
prefsEditor.putString("id-main", id);
prefsEditor.commit();
}
} |
package com.ssgl.service.impl;
/*
* 功能:
* User: jiajunkang
* email:jiajunkang@outlook.com
* Date: 2018/1/16 0016
* Time: 21:31
*/
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssgl.bean.*;
import com.ssgl.mapper.CustomerUserMapper;
import com.ssgl.mapper.TUserMapper;
import com.ssgl.mapper.UserRoleMapper;
import com.ssgl.service.UserService;
import com.ssgl.util.MD5Utils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
public TUserMapper userMapper;
@Autowired
public CustomerUserMapper customerUserMapper;
@Autowired
public UserRoleMapper userRoleMapper;
/**
* 根据邮箱查找用户
*
* @param email
* @return
*/
public TUser selectUserByUsername(String email) {
TUserExample example = new TUserExample();
TUserExample.Criteria criteria = example.createCriteria().andEmailEqualTo(email);
List<TUser> users = userMapper.selectByExample(example);
return users.size() > 0 ? users.get(0) : null;
}
/**
* 用户登录方法
*
* @param user 登录的用户
* @param request
* @param j_captcha 用户输入的验证码
*/
@Override
public String login(TUser user, HttpServletRequest request, String j_captcha) {
//获取当前session中的验证码
String checkcode = (String) request.getSession().getAttribute("key");
if (null != checkcode && null != j_captcha && checkcode.equals(j_captcha)) {
//验证码匹配正确
Subject subject = SecurityUtils.getSubject();
AuthenticationToken token = new UsernamePasswordToken(user.getUsername(), MD5Utils.md5(user.getPassword()));
try {
subject.login(token);
} catch (Exception e) {
e.printStackTrace();
return "forward:toIndex.action";
}
TUser loginUser = (TUser) subject.getPrincipal();
request.getSession().setAttribute("loginUser", loginUser);
return "home";
} else {
return "login";
}
}
@Override
public Page<TUser> selectUsersPage(Integer page, Integer rows, HttpServletRequest request) throws Exception {
PageHelper.startPage(page, rows);
String username = request.getParameter("username");
List<TUser> users = customerUserMapper.selectUsers(username);
if (null != users && users.size() > 0) {
PageInfo<TUser> info = new PageInfo<TUser>(users);
Page<TUser> result = new Page<>();
result.setTotalRecord((int) info.getTotal());
result.setList(info.getList());
return result;
}
return null;
}
@Override
public Result addUser(TUser user) throws Exception {
userMapper.insertSelective(user);
UserRoleKey userRoleKey = new UserRoleKey();
userRoleKey.setUserId(user.getId());
userRoleKey.setRoleId("2");
userRoleMapper.insert(userRoleKey);
return new Result("ok", "添加成功");
}
@Override
public Result updateUser(TUser user) throws Exception {
TUser oldUser = userMapper.selectByPrimaryKey(user.getId());//获取到的数据库中的值
//更新数据
if (null != user.getPassword() && user.getPassword().equals(oldUser.getPassword())) {
oldUser.setPassword(MD5Utils.md5(user.getPassword()));
}
oldUser.setBirthday(user.getBirthday());
oldUser.setEmail(user.getEmail());
oldUser.setGender(user.getGender());
oldUser.setRemark(user.getRemark());
oldUser.setTelephone(user.getTelephone());
oldUser.setUsername(user.getUsername());
//写回到数据库中
userMapper.updateByPrimaryKey(oldUser);
return new Result("ok", "修改成功");
}
@Override
public Result deleteUsers(List<String> ids) throws Exception {
customerUserMapper.deleteUsers(ids);
return new Result("ok", "删除成功");
}
@Override
public List<TUser> exportUser() {
TUserExample example = new TUserExample();
return userMapper.selectByExample(example);
}
}
|
package java_ArrayList;
import java.util.*;
public class ArrayList4 {
public static void main(String[] args) {
//如果List<中>的数据类型是基本数据类型则他的数组会被作为集合中的元素。
int[] nums = {1,3,5};
List<int[]> list = Arrays.asList(nums);
sop(list);
}
public static void sop(Object obj){
System.out.println(obj);
}
}
|
package day45_Inheritance;
public class InheritancePractice2 extends ParentClassofInheritancePractice2{
//sub super
/*
* protected static String password="123";
public static int age=13;
protected static double salary=100000;
*/
public static void main(String[] args) {
//System.out.println(username); it is private in super class, can not be inherited
System.out.println(password); //protected
System.out.println(age); //public
System.out.println(salary);//protected
}
}
|
package mudanza.web;
import mudanza.business.ViajeBusinessBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
@RestController
public class MudanzaController {
@Autowired
private ViajeBusinessBean viajeBusinessBean;
@CrossOrigin(origins = "http://localhost:3000")
@PostMapping("/calcularViajes")
public List<Integer> calcularViajes(@RequestBody String info) {
List<Integer> viajesxDia = new ArrayList<>();
List<List<Integer>> elementosXDia = viajeBusinessBean.leerDatos(info);
for (List<Integer> elementos : elementosXDia) {
viajesxDia.add(viajeBusinessBean.calcularViajes(elementos));
}
return viajesxDia;
}
}
|
package br.org.funcate.glue.model.canvas;
import java.awt.Point;
import java.text.DecimalFormat;
import br.org.funcate.glue.main.AppSingleton;
import br.org.funcate.glue.model.CalculatorService;
public abstract class DistanceMeasuringToolService {
public static void dragDistanceTool(int mouseClickXPosition, int mouseClickYPosition) {
DistanceMeasuringGraphics distance = getDistanceGraphicsFromSingleton();
distance.setX2(mouseClickXPosition);
distance.setY2(mouseClickYPosition);
Point p = new Point(distance.getX1(), distance.getY1());
double pixelsDistance = (p.distance(distance.getX2(), distance.getY2()));
double dist = (CalculatorService.getMeterConversor(AppSingleton.getInstance().getCanvasState().getProjection())
* AppSingleton.getInstance().getCanvasState().getResolution() * pixelsDistance);
DecimalFormat df = new DecimalFormat("#,###.00");
distance.setValue(df.format(dist));
if (!distanceToolValidation()) {
cancelDistanceTool();
}
AppSingleton.getInstance().getCanvasState().getCanvasGraphicsBuffer().notifyObservers();
}
public static void cancelDistanceTool() {
DistanceMeasuringGraphics distance = getDistanceGraphicsFromSingleton();
distance.setValue("");
distance.setX1(0);
distance.setX2(0);
distance.setY1(0);
distance.setY2(0);
}
public static void pressDistanceTool(int mouseClickXPosition, int mouseClickYPosition) {
AppSingleton.getInstance().getCanvasState().getCanvasGraphicsBuffer()
.setToolGraphics(new DistanceMeasuringGraphics(mouseClickXPosition, mouseClickYPosition, 0, 0, ""));
}
public static DistanceMeasuringGraphics getDistanceGraphicsFromSingleton() {
ToolGraphics tool = AppSingleton.getInstance().getCanvasState().getCanvasGraphicsBuffer().getToolGraphics();
DistanceMeasuringGraphics distance;
if (tool instanceof DistanceMeasuringGraphics) {
distance = (DistanceMeasuringGraphics) tool;
} else {
throw new RuntimeException("Atributo toolGraphics no state não é um DistanceTool!");
}
return distance;
}
public static boolean distanceToolValidation() {
DistanceMeasuringGraphics distance = getDistanceGraphicsFromSingleton();
return !(distance.getX2() < 0 || distance.getX2() > AppSingleton.getInstance().getCanvasState().getCanvasWidth() - 3
|| distance.getY2() < 0 || distance.getY2() > AppSingleton.getInstance().getCanvasState().getCanvasHeight() - 3);
}
}
|
import java.util.ArrayList;
import java.util.Random;
public class RoomGen {
int numRoom;
ArrayList<Room> roomlist = new ArrayList();
Random dice = new Random();
int r = dice.nextInt(4) + 3;
int e = dice.nextInt(3) + 1;
/**
* Function spawns 4 types of rooms based on what the 'dice' random number generator rolls
*/
public void getroom() {
for(int i = 0; i < this.r; i++){
int type = dice.nextInt(4) + 1;
if(type == 1){
this.roomlist.add(new Room ("The entrance of an old Egyptian palace..."));
}if(type == 2){
this.roomlist.add(new Room("You fell through a trap door into a pit... "));
}if(type == 3){
this.roomlist.add(new Room("The entrance of a mysterious tunnel..."));
}if(type == 4){
this.roomlist.add(new Throne("The throne room!"));
}
}
}
/**
* toString function for RoomGen class, prints out types of rooms that are spawned
* @return String named blank defined in toString function
*/
public String toStringGen(){
String blank = "";
for(int i = 0; i < this.roomlist.size(); i++){
Room room = this.roomlist.get(i);
blank += room.toString();
}
return blank;
}
}
|
package com.tencent.mm.plugin.sns.storage.AdLandingPagesStorage;
import android.database.Cursor;
import android.os.HandlerThread;
import android.text.TextUtils;
import com.tencent.mm.ab.b;
import com.tencent.mm.ab.b.a;
import com.tencent.mm.ab.v;
import com.tencent.mm.plugin.sns.model.af;
import com.tencent.mm.plugin.sns.storage.c;
import com.tencent.mm.plugin.sns.storage.d;
import com.tencent.mm.plugin.sns.storage.y;
import com.tencent.mm.protocal.c.afl;
import com.tencent.mm.protocal.c.afm;
import com.tencent.mm.protocal.c.yw;
import com.tencent.mm.protocal.c.yx;
import com.tencent.mm.sdk.f.e;
import com.tencent.mm.sdk.platformtools.ag;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import java.util.HashMap;
import java.util.Map;
public final class i {
private static final i nIR = new i();
private Map<Long, String> jjd = new HashMap();
private d nIS = af.byp();
public y nIT = af.byq();
public Map<String, String> nIU = new HashMap();
static /* synthetic */ void a(i iVar) {
x.i("OpenCanvasMgr", "clearing old canvasInfo cache");
Cursor axc = iVar.nIS.axc();
if (axc != null) {
long currentTimeMillis = System.currentTimeMillis() - 777600000;
while (axc.moveToNext()) {
c cVar = new c();
cVar.d(axc);
if (cVar.field_createTime < currentTimeMillis) {
x.i("OpenCanvasMgr", "ad canvas eliminate %d " + cVar.field_canvasId);
iVar.nIS.a(cVar, new String[0]);
}
}
axc.close();
axc = iVar.nIT.axc();
if (axc != null) {
currentTimeMillis = System.currentTimeMillis() - 777600000;
while (axc.moveToNext()) {
com.tencent.mm.plugin.sns.storage.x xVar = new com.tencent.mm.plugin.sns.storage.x();
xVar.d(axc);
if (xVar.field_createTime < currentTimeMillis) {
x.i("OpenCanvasMgr", "ux canvas eliminate %d " + xVar.field_canvasId);
iVar.nIT.a(xVar, new String[0]);
}
}
axc.close();
}
}
}
public static i bAE() {
return nIR;
}
private i() {
HandlerThread Xs = e.Xs("OpenCanvasMgr");
Xs.start();
new ag(Xs.getLooper()).postDelayed(new Runnable() {
public final void run() {
i.a(i.this);
}
}, 5000);
}
public final String h(long j, int i, int i2) {
x.i("OpenCanvasMgr", "open pageId %d, preLoad %d", new Object[]{Long.valueOf(j), Integer.valueOf(i)});
if (j <= 0) {
return "";
}
String str = "";
if (i2 != 1) {
if (this.jjd.containsKey(Long.valueOf(j))) {
str = (String) this.jjd.get(Long.valueOf(j));
} else {
c cVar = new c();
cVar.field_canvasId = j;
this.nIS.b(cVar, new String[0]);
if (TextUtils.isEmpty(cVar.field_canvasXml)) {
str = "";
} else {
this.jjd.put(Long.valueOf(j), cVar.field_canvasXml);
str = cVar.field_canvasXml;
}
}
}
if (i != 1 || !TextUtils.isEmpty(str)) {
return str;
}
c cVar2 = new c();
cVar2.field_canvasId = j;
a aVar = new a();
aVar.dIG = new yw();
aVar.dIH = new yx();
aVar.uri = "/cgi-bin/mmoc-bin/adplayinfo/get_adcanvasinfo";
aVar.dIF = 1286;
b KT = aVar.KT();
((yw) KT.dID.dIL).rEZ = j;
v.a(KT, new 2(this, j, i, cVar2));
return "";
}
public final void p(long j, String str) {
if (!TextUtils.isEmpty(str) && j > 0) {
this.jjd.put(Long.valueOf(j), str);
c cVar = new c();
cVar.field_canvasId = j;
cVar.field_canvasXml = str;
this.nIS.a(cVar);
}
}
public final String k(String str, String str2, int i, int i2) {
x.i("OpenCanvasMgr", "open pageId %s, canvasExt %s, preLoad %d", new Object[]{str, str2, Integer.valueOf(i)});
if (bi.oW(str)) {
return "";
}
com.tencent.mm.plugin.sns.storage.x xVar;
String str3 = "";
if (i2 != 1) {
Object obj;
if (bi.oW(str2)) {
str3 = str;
} else {
obj = str + str2;
}
if (this.nIU.containsKey(obj)) {
str3 = (String) this.nIU.get(obj);
} else {
xVar = new com.tencent.mm.plugin.sns.storage.x();
xVar.field_canvasId = str;
xVar.field_canvasExt = str2;
this.nIT.b(xVar, new String[]{"canvasId", "canvasExt"});
if (TextUtils.isEmpty(xVar.field_canvasXml)) {
str3 = "";
} else {
this.nIU.put(obj, xVar.field_canvasXml);
str3 = xVar.field_canvasXml;
}
}
}
if (i != 1 || !TextUtils.isEmpty(str3)) {
return str3;
}
xVar = new com.tencent.mm.plugin.sns.storage.x();
xVar.field_canvasId = str;
a aVar = new a();
aVar.dIG = new afl();
aVar.dIH = new afm();
aVar.uri = "/cgi-bin/mmux-bin/wxaapp/mmuxwxa_getofficialcanvasinfo";
aVar.dIF = 1890;
b KT = aVar.KT();
afl afl = (afl) KT.dID.dIL;
afl.rJs = str;
afl.rJt = str2;
v.a(KT, new 3(this, str, i, xVar));
return "";
}
}
|
package app.commands;
import app.ConsoleManager;
import app.ZipFileManager;
import java.nio.file.Path;
import java.nio.file.Paths;
public abstract class ZipCommand implements Command {
public ZipFileManager getZipFileManager() throws Exception {
ConsoleManager.writeMessage("Please provide path to archive");
Path archivePath = Paths.get(ConsoleManager.readString());
return new ZipFileManager(archivePath);
}
}
|
package org.social.service;
import java.util.List;
import org.social.entities.Invitation;
import org.social.entities.User;
public interface InvitationService {
public Invitation addInvitation(Invitation invitation);
public User acceptInvitation(long idUser, long idMembre);
public void refuseInvitation(long idUser, long idMembre);
public List<User> getInvitationsOfUser(long idUser);
}
|
package com.yougou.merchant.api.monitor.service.impl;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.yougou.merchant.api.common.PageFinder;
import com.yougou.merchant.api.common.Query;
import com.yougou.merchant.api.common.UUIDGenerator;
import com.yougou.merchant.api.monitor.dao.MonitorMapper;
import com.yougou.merchant.api.monitor.dao.WarnMapper;
import com.yougou.merchant.api.monitor.service.IApiMonitorService;
import com.yougou.merchant.api.monitor.vo.MonitorAppKeyTemplate;
import com.yougou.merchant.api.monitor.vo.MonitorAppkeyWarnDetail;
import com.yougou.merchant.api.monitor.vo.MonitorConfig;
import com.yougou.merchant.api.monitor.vo.MonitorDayWarnDetail;
import com.yougou.merchant.api.monitor.vo.MonitorEarlyWarnQueryVo;
import com.yougou.merchant.api.monitor.vo.MonitorEarlyWarning;
import com.yougou.merchant.api.monitor.vo.MonitorIpBlackList;
import com.yougou.merchant.api.monitor.vo.MonitorLock;
import com.yougou.merchant.api.monitor.vo.MonitorRateWarnDetail;
import com.yougou.merchant.api.monitor.vo.MonitorSuccRateWarnDetail;
import com.yougou.merchant.api.monitor.vo.MonitorTemplate;
import com.yougou.merchant.api.monitor.vo.MonitorTemplateDetail;
@Service(value = "apiMonitorService")
public class ApiMonitorService implements IApiMonitorService {
@Resource
private MonitorMapper monitorMapper;
@Resource
private WarnMapper warnMapper;
@Override
public List<MonitorConfig> queryMonitorConfigList() throws Exception {
return monitorMapper.queryMonitorConfigList();
}
@Override
@Transactional
public boolean updateMonitorConfig(List<MonitorConfig> configs) throws Exception {
if (CollectionUtils.isEmpty(configs))
return true;
for (MonitorConfig monitorConfig : configs) {
// 需要通过Id进行删除
MonitorConfig _temp = monitorMapper.getMonitorConfigByKey(monitorConfig.getConfigKey());
if (null == _temp) {
monitorConfig.setId(UUIDGenerator.getUUID());
monitorConfig.setCreateTime(new Date());
monitorMapper.insertMonitorConfig(monitorConfig);
continue;
}
monitorConfig.setId(_temp.getId());
monitorConfig.setUpdateTime(new Date());
monitorMapper.updateMonitorConfig(monitorConfig);
}
return true;
}
@Override
public MonitorTemplate getMonitorTemplateByNo(String templateNo) throws Exception {
if (StringUtils.isBlank(templateNo))
return null;
MonitorTemplate _template = new MonitorTemplate();
_template.setTemplateNo(templateNo);
List<MonitorTemplate> _list = monitorMapper.queryMonitorTemplate(_template, new RowBounds());
if (CollectionUtils.isNotEmpty(_list)) {
MonitorTemplate obj = _list.get(0);
List<MonitorTemplateDetail> details = monitorMapper.queryTemplateDetailList(templateNo);
obj.setTemplateDetails(details);
return obj;
}
return null;
}
@Override
@Transactional
public boolean saveMonitorTemplate(MonitorTemplate template) throws Exception {
if (null == template)
return false;
if (StringUtils.isNotBlank(template.getId())) {
monitorMapper.updateTemplate(template);
} else {
template.setId(UUIDGenerator.getUUID());
template.setUpdateTime(new Date());
monitorMapper.insertTemplate(template);
}
List<MonitorTemplateDetail> details = template.getTemplateDetails();
if (CollectionUtils.isNotEmpty(details)) {
for (MonitorTemplateDetail detail : details) {
if (StringUtils.isNotBlank(detail.getId())) {
monitorMapper.updateTemplateDetail(detail);
} else {
detail.setId(UUIDGenerator.getUUID());
detail.setUpdateTime(new Date());
monitorMapper.insertTemplateDetail(detail);
}
}
}
return true;
}
@Override
@Transactional
public boolean saveAppKeyTemplate(MonitorTemplate template) throws Exception {
if (null == template)
return false;
Integer count = monitorMapper.queryMonitorTemplateCount(template);
if (count > 0) {
monitorMapper.updateTemplate(template);
} else {
template.setId(template.getId());
template.setUpdateTime(new Date());
monitorMapper.insertTemplate(template);
}
List<MonitorTemplateDetail> details = template.getTemplateDetails();
if (CollectionUtils.isNotEmpty(details)) {
for (MonitorTemplateDetail detail : details) {
if (StringUtils.isNotBlank(detail.getId())) {
monitorMapper.updateTemplateDetail(detail);
} else {
detail.setId(UUIDGenerator.getUUID());
detail.setUpdateTime(new Date());
monitorMapper.insertTemplateDetail(detail);
}
}
}
return true;
}
public boolean deleteMonitorTemplateByTemplateNo(String templateNo) throws Exception {
if (StringUtils.isEmpty(templateNo))
return false;
return monitorMapper.deleteMonitorTemplateByTemplateNo(templateNo) > 0;
}
public boolean deleteMonitorTemplateDetailByTemplateNo(String templateNo) throws Exception {
if (StringUtils.isEmpty(templateNo))
return false;
return monitorMapper.deleteMonitorTemplateDetailByTemplateNo(templateNo) > 0;
}
public boolean deleteMonitorTemplateDetailById(String id) throws Exception {
if (StringUtils.isEmpty(id))
return false;
return monitorMapper.deleteMonitorTemplateDetailById(id) > 0;
}
@Override
public PageFinder<MonitorTemplate> queryMonitorTemplateList(MonitorTemplate template, Query query) throws Exception {
// 根据模板名称和编号模糊查询
template.setTemplateNo("%" + template.getTemplateName() + "%");
template.setTemplateName("%" + template.getTemplateName() + "%");
List<MonitorTemplate> list = monitorMapper.queryMonitorTemplateByNoORName(template, new RowBounds(query.getOffset(), query.getPageSize()));
Integer count = monitorMapper.queryMonitorTemplateByNoORNameCount(template);
PageFinder<MonitorTemplate> pageFinder = new PageFinder<MonitorTemplate>(query.getPage(), query.getPageSize(), count, list);
return pageFinder;
}
@Override
public PageFinder<MonitorTemplateDetail> queryTemplateDetailList(String templateNo, Query query) throws Exception {
List<MonitorTemplateDetail> list = monitorMapper.queryTemplateDetailPage(templateNo, new RowBounds(query.getOffset(), query.getPageSize()));
Integer count = monitorMapper.queryTemplateDetailCount(templateNo);
PageFinder<MonitorTemplateDetail> pageFinder = new PageFinder<MonitorTemplateDetail>(query.getPage(), query.getPageSize(), count, list);
return pageFinder;
}
@Override
public void insertMonitorLock(MonitorLock lock) throws Exception {
monitorMapper.insertMonitorLock(lock);
}
@Override
public boolean updateMonitorLock(List<MonitorLock> locks) throws Exception {
if (CollectionUtils.isEmpty(locks))
return true;
for (MonitorLock monitorLock : locks) {
monitorMapper.updateMonitorLock(monitorLock);
}
return true;
}
@Override
public PageFinder<MonitorLock> queryMonitorLockByObj(MonitorLock lock, Query query) throws Exception {
List<MonitorLock> list = monitorMapper.queryMonitorLockByObj(lock, new RowBounds(query.getOffset(), query.getPageSize()));
Integer count = monitorMapper.queryMonitorLockCount(lock);
PageFinder<MonitorLock> pageFinder = new PageFinder<MonitorLock>(query.getPage(), query.getPageSize(), count, list);
return pageFinder;
}
@Override
@Transactional
public boolean insertIpBlackLists(List<MonitorIpBlackList> ips) throws Exception {
if (CollectionUtils.isEmpty(ips))
return true;
for (MonitorIpBlackList monitorIpBlackList : ips) {
monitorMapper.insertIpBlackList(monitorIpBlackList);
}
return true;
}
@Override
public void updateIpBlackList(MonitorIpBlackList ipBlack) throws Exception {
monitorMapper.updateIpBlackList(ipBlack);
}
@Override
public PageFinder<MonitorIpBlackList> queryMonitorIpBlacklist(String ip, String startTime, String endTime, Query query) throws Exception {
List<MonitorIpBlackList> list = monitorMapper.queryMonitorIpBlackList(ip, startTime, endTime, new RowBounds(query.getOffset(), query.getPageSize()));
Integer count = monitorMapper.queryMonitorIpBlackListCount(ip, startTime, endTime);
PageFinder<MonitorIpBlackList> pageFinder = new PageFinder<MonitorIpBlackList>(query.getPage(), query.getPageSize(), count, list);
return pageFinder;
}
public List<MonitorTemplate> queryTemplateList() {
return monitorMapper.queryTemplateList();
}
public boolean updateMonitorAppKeyTemplateByAppkeyId(MonitorAppKeyTemplate template) throws Exception {
Integer count = monitorMapper.queryAppKeyTemplateByAppKey(template.getAppkeyId());
if (count > 0) {
template.setUpdateTime(new Date());
monitorMapper.updateAppKeyTemplateByAppKey(template);
} else {
template.setId(UUIDGenerator.getUUID());
template.setCreateTime(new Date());
template.setUpdateTime(new Date());
monitorMapper.insertAppKeyTemplate(template);
}
return true;
}
@Override
@Transactional
public boolean insertMonitorEarlyWarning(List<MonitorEarlyWarning> warnVos) throws Exception {
if (CollectionUtils.isEmpty(warnVos)) {
return true;
}
for (MonitorEarlyWarning warn : warnVos) {
warnMapper.insertMonitorEarlyWarning(warn);
if (warn.getAppKeyDetail() != null) {
warnMapper.insertMonitorAppkeyWarnDetail(warn.getAppKeyDetail());
}
if (CollectionUtils.isNotEmpty(warn.getDayDetails())) {
for (MonitorDayWarnDetail daydetail : warn.getDayDetails()) {
warnMapper.insertMonitorDayWarnDetail(daydetail);
}
}
if (CollectionUtils.isNotEmpty(warn.getSuccRateDetails())) {
for (MonitorSuccRateWarnDetail succRatedetail : warn.getSuccRateDetails()) {
warnMapper.insertMonitorSuccRateWarnDetail(succRatedetail);
}
}
if (CollectionUtils.isNotEmpty(warn.getRateWarnDetails())) {
for (MonitorRateWarnDetail RateWarndetail : warn.getRateWarnDetails()) {
warnMapper.insertMonitorRateWarnDetail(RateWarndetail);
}
}
}
return true;
}
@Override
public PageFinder<MonitorEarlyWarning> queryMonitorEarlyWarning(MonitorEarlyWarnQueryVo queryVo, Query query) throws Exception {
List<MonitorEarlyWarning> list = warnMapper.queryMonitorEarlyWarning(queryVo, new RowBounds(query.getOffset(), query.getPageSize()));
Integer count = warnMapper.queryMonitorEarlyWarningCount(queryVo);
PageFinder<MonitorEarlyWarning> pageFinder = new PageFinder<MonitorEarlyWarning>(query.getPage(), query.getPageSize(), count, list);
return pageFinder;
}
@Override
public List<MonitorAppkeyWarnDetail> queryAppKeyEarlyWarningDetail(MonitorEarlyWarnQueryVo queryVo) throws Exception {
return warnMapper.queryAppKeyEarlyWarningDetail(queryVo);
}
@Override
public List<MonitorDayWarnDetail> queryApiEarlyWarningDetail(MonitorEarlyWarnQueryVo queryVo) throws Exception {
return warnMapper.queryApiEarlyWarningDetail(queryVo);
}
@Override
public List<MonitorSuccRateWarnDetail> querySuccRateWarnDetail(MonitorEarlyWarnQueryVo queryVo) throws Exception {
return warnMapper.querySuccRateWarnDetail(queryVo);
}
@Override
public List<MonitorRateWarnDetail> queryRateWarnDetail(MonitorEarlyWarnQueryVo queryVo) throws Exception {
return warnMapper.queryRateWarnDetail(queryVo);
}
/**
* 按照appkeyId查询改appkey对应的模板
* @param MonitorTemplate
* @return
*/
public List<MonitorTemplateDetail> getMonitorTemplateListByAppKeyId(String appkeyId) {
String template_no = "";
if (monitorMapper.queryAppKeyTemplateByAppKey(appkeyId) > 0) {
template_no = monitorMapper.queryAppKeyTemplateByAppKeyId(appkeyId);
} else {
template_no = monitorMapper.queryDefaultTemplate().get(0);
}
return monitorMapper.queryTemplateDetailList(template_no);
}
/**
* 按照appkey查询appkeyId
*
* @param appKey
* @return
*/
public String queryAppKeyIdByAppKey(String appKey) {
return monitorMapper.queryAppKeyIdByAppKey(appKey);
}
/**
* 查询所有已配置的appkeyId和templateNo关系的数据
*
* @return List
*/
public List<MonitorAppKeyTemplate> queryAppKeyTemplate() {
return monitorMapper.queryAppKeyTemplate();
}
/**
* 查询默认的模板信息
*
* @return List
*/
public List<String> queryDefaultTemplate() {
return monitorMapper.queryDefaultTemplate();
}
/**
* 根据模板号,查询该模板下的api接口配置明细
*
* @return List
*/
public List<MonitorTemplateDetail> queryTemplateDetailList(String templateNo) {
return monitorMapper.queryTemplateDetailList(templateNo);
}
@Override
public List<MonitorRateWarnDetail> queryApiFrequencyBynow(
MonitorEarlyWarnQueryVo queryVo) throws Exception {
return warnMapper.queryApiFrequencyBynow(queryVo);
}
}
|
package kr.ko.nexmain.server.MissingU.admin.service;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import kr.ko.nexmain.server.MissingU.admin.dao.AdminCashDao;
import kr.ko.nexmain.server.MissingU.admin.model.CashItemHistoryVO;
import kr.ko.nexmain.server.MissingU.common.Constants;
import kr.ko.nexmain.server.MissingU.common.Constants.RequestURI;
import kr.ko.nexmain.server.MissingU.common.model.Result;
import kr.ko.nexmain.server.MissingU.common.service.BaseService;
import kr.ko.nexmain.server.MissingU.common.service.CommonService;
import kr.ko.nexmain.server.MissingU.common.utils.MsgUtil;
import kr.ko.nexmain.server.MissingU.common.utils.UTL;
import kr.ko.nexmain.server.MissingU.friends.dao.FriendsDao;
import kr.ko.nexmain.server.MissingU.friends.model.FriendsEditReqVO;
import kr.ko.nexmain.server.MissingU.friends.model.SendGiftReqVO;
import kr.ko.nexmain.server.MissingU.friends.service.FriendsService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
@Transactional
public class AdminCashServiceImpl extends BaseService implements AdminCashService {
@Autowired
private MsgUtil msgUtil;
@Autowired
private AdminCashDao adminCashDao;
@Autowired
private CommonService commonService;
@Autowired
private FriendsService friendsService;
@Autowired
private FriendsDao friendsDao;
/******************************************************************
* 윙크
******************************************************************/
@Override
public Map<String, Object> sendWink(Map<String, Object> params) {
FriendsEditReqVO inputVo = new FriendsEditReqVO();
inputVo.setFriendId(UTL.convertToInt(params.get("targetMemberId"), 0));
inputVo.setGcmPass("Y".equals(params.get("gcmPass") + "") ? true : false);
inputVo.setgCountry(params.get("gCountry") + "");
inputVo.setgLang(params.get("gLang") + "");
inputVo.setgMemberId(UTL.convertToInt(params.get("memberId"), 0));
Map<String, Object> returnMap = new HashMap<String, Object>();
Result result = null;
Locale gLocale = Locale.KOREAN;
// 포인트 차감 로직 패스 하는 경우
if(params.containsKey("pointPass") && "Y".equals(params.get("pointPass"))) {
params.put("requestURI", RequestURI.SEND_WINK);
Map<String,Object> needPoint = commonService.getMemberPointAndNeedPoint(params, Locale.KOREAN.toString());
Result needPointResult = (Result)needPoint.get("result");
if(needPointResult != null && Constants.ReturnCode.SUCCESS.equals(needPointResult.getRsltCd())) {
// 윙크 발송
inputVo.setPointPass(false);
returnMap = friendsService.sendWink(inputVo);
}else{
// 포인트 부족
result = new Result(
Constants.ReturnCode.AUTH_ERROR,
msgUtil.getMsgCd("comm.authError.lackOfPoint", gLocale),
msgUtil.getMsgText("comm.authError.lackOfPoint", gLocale));
returnMap.put("result", result);
}
}else{
// 윙크 발송
inputVo.setPointPass(true);
returnMap = friendsService.sendWink(inputVo);
}
return returnMap;
}
@Override
public Map<String,Object> deleteWink(Map<String, Object> params) {
Map<String,Object> returnMap = new HashMap<String,Object>();
Map<String,Object> responseMap = new HashMap<String,Object>();
try {
int id = UTL.convertToInt(params.get("id"), 0);
// 1. 발송 이력 삭제
int count = adminCashDao.deleteCashItemHistory(id);
Map<String,Object> winkItem = new HashMap<String,Object>();
winkItem.put("senderId", params.get("senderMemberId"));
winkItem.put("receiverId", params.get("receiverMemberId"));
winkItem.put("itemCd", Constants.ItemCode.WINK);
winkItem.put("itemAmount", 1);
friendsDao.updateInventoryToDecreaseItemAmount(winkItem);
// 2. 포인트 롤백 (불가, 여성 및 관리자 무료발송 기능 있고 해당 이력이 별도로 존재하지 않음)
if(count > 0) {
Result result = new Result(
Constants.ReturnCode.SUCCESS,
msgUtil.getMsgCd("comm.success.search"),
msgUtil.getMsgText("comm.success.search"));
returnMap.put("result", result);
returnMap.put("response", responseMap);
}else{
Result result = new Result(
Constants.ReturnCode.LOGIC_ERROR,
msgUtil.getMsgCd("comm.fail.update"),
msgUtil.getMsgText("comm.fail.update"));
returnMap.put("result", result);
returnMap.put("response", responseMap);
}
}catch(Exception e) {
//조회 결과가 있는 경우
Result result = new Result(
Constants.ReturnCode.LOGIC_ERROR,
"LE",
"윙크 발송이력 롤백에 실패 했습니다.\n\n" + e.getMessage());
returnMap.put("result", result);
returnMap.put("response", responseMap);
}
return returnMap;
}
@Override
public Map<String, Object> getWinkList(Map<String, Object> params) {
Map<String,Object> returnMap = new HashMap<String,Object>();
Map<String,Object> responseMap = new HashMap<String,Object>();
//페이징 변수 int로 변환
makePaging(params);
List<Map<String,CashItemHistoryVO>> dataList = adminCashDao.selectCashItemList(params);
Integer totalCnt = adminCashDao.selectCashItemListCnt(params);
responseMap.put("totalCnt", totalCnt);
responseMap.put("dataList", dataList);
if(dataList != null && dataList.size() > 0) {
//조회 결과가 있는 경우
Result result = new Result(
Constants.ReturnCode.SUCCESS,
msgUtil.getMsgCd("comm.success.search"),
msgUtil.getMsgText("comm.success.search"));
returnMap.put("result", result);
returnMap.put("response", responseMap);
} else {
//조회 결과 없음
Result result = new Result(
Constants.ReturnCode.LOGIC_ERROR,
msgUtil.getMsgCd("comm.fail.search"),
msgUtil.getMsgText("comm.fail.search"));
returnMap.put("result", result);
returnMap.put("response", responseMap);
}
return returnMap;
}
/******************************************************************
* // 윙크
******************************************************************/
/******************************************************************
* 선물
******************************************************************/
@Override
public Map<String, Object> sendGift(Map<String, Object> params) {
SendGiftReqVO inputVo = new SendGiftReqVO();
inputVo.setFriendId(UTL.convertToInt(params.get("targetMemberId"), 0));
inputVo.setGcmPass("Y".equals(params.get("gcmPass") + "") ? true : false);
inputVo.setgCountry(params.get("gCountry") + "");
inputVo.setgLang(params.get("gLang") + "");
inputVo.setgMemberId(UTL.convertToInt(params.get("memberId"), 0));
Map<String, Object> returnMap = new HashMap<String, Object>();
Result result = null;
Locale gLocale = Locale.KOREAN;
// 포인트 차감 로직 패스 하는 경우
if(params.containsKey("pointPass") && "Y".equals(params.get("pointPass"))) {
params.put("requestURI", RequestURI.SEND_GIFT);
Map<String,Object> needPoint = commonService.getMemberPointAndNeedPoint(params, Locale.KOREAN.toString());
Result needPointResult = (Result)needPoint.get("result");
if(needPointResult != null && Constants.ReturnCode.SUCCESS.equals(needPointResult.getRsltCd())) {
// 윙크 발송
inputVo.setPointPass(false);
returnMap = friendsService.sendGift(inputVo);
}else{
// 포인트 부족
result = new Result(
Constants.ReturnCode.AUTH_ERROR,
msgUtil.getMsgCd("comm.authError.lackOfPoint", gLocale),
msgUtil.getMsgText("comm.authError.lackOfPoint", gLocale));
returnMap.put("result", result);
}
}else{
// 윙크 발송
inputVo.setPointPass(true);
returnMap = friendsService.sendGift(inputVo);
}
return returnMap;
}
@Override
public Map<String,Object> deleteGift(Map<String, Object> params) {
Map<String,Object> returnMap = new HashMap<String,Object>();
Map<String,Object> responseMap = new HashMap<String,Object>();
try {
int id = UTL.convertToInt(params.get("id"), 0);
// 1. 발송 이력 삭제
int count = adminCashDao.deleteCashItemHistory(id);
Map<String,Object> winkItem = new HashMap<String,Object>();
winkItem.put("senderId", params.get("senderMemberId"));
winkItem.put("receiverId", params.get("receiverMemberId"));
winkItem.put("itemCd", Constants.ItemCode.GIFT_FLOWER);
winkItem.put("itemAmount", 1);
friendsDao.updateInventoryToDecreaseItemAmount(winkItem);
// 2. 포인트 롤백 (불가, 여성 및 관리자 무료발송 기능 있고 해당 이력이 별도로 존재하지 않음)
if(count > 0) {
Result result = new Result(
Constants.ReturnCode.SUCCESS,
msgUtil.getMsgCd("comm.success.search"),
msgUtil.getMsgText("comm.success.search"));
returnMap.put("result", result);
returnMap.put("response", responseMap);
}else{
Result result = new Result(
Constants.ReturnCode.LOGIC_ERROR,
msgUtil.getMsgCd("comm.fail.update"),
msgUtil.getMsgText("comm.fail.update"));
returnMap.put("result", result);
returnMap.put("response", responseMap);
}
}catch(Exception e) {
//조회 결과가 있는 경우
Result result = new Result(
Constants.ReturnCode.LOGIC_ERROR,
"LE",
"선물(꽃다발) 발송이력 롤백에 실패 했습니다.\n\n" + e.getMessage());
returnMap.put("result", result);
returnMap.put("response", responseMap);
}
return returnMap;
}
@Override
public Map<String, Object> getGiftList(Map<String, Object> params) {
Map<String,Object> returnMap = new HashMap<String,Object>();
Map<String,Object> responseMap = new HashMap<String,Object>();
//페이징 변수 int로 변환
makePaging(params);
List<Map<String,CashItemHistoryVO>> dataList = adminCashDao.selectCashItemList(params);
Integer totalCnt = adminCashDao.selectCashItemListCnt(params);
responseMap.put("totalCnt", totalCnt);
responseMap.put("dataList", dataList);
if(dataList != null && dataList.size() > 0) {
//조회 결과가 있는 경우
Result result = new Result(
Constants.ReturnCode.SUCCESS,
msgUtil.getMsgCd("comm.success.search"),
msgUtil.getMsgText("comm.success.search"));
returnMap.put("result", result);
returnMap.put("response", responseMap);
} else {
//조회 결과 없음
Result result = new Result(
Constants.ReturnCode.LOGIC_ERROR,
msgUtil.getMsgCd("comm.fail.search"),
msgUtil.getMsgText("comm.fail.search"));
returnMap.put("result", result);
returnMap.put("response", responseMap);
}
return returnMap;
}
/******************************************************************
* // 선물
******************************************************************/
@Override
public Map<String, Object> getPointList(Map<String, Object> params) {
Map<String,Object> returnMap = new HashMap<String,Object>();
Map<String,Object> responseMap = new HashMap<String,Object>();
//페이징 변수 int로 변환
makePaging(params);
List<Map<String,Object>> dataList = adminCashDao.selectPointList(params);
Integer totalCnt = adminCashDao.selectPointListCnt(params);
responseMap.put("totalCnt", totalCnt);
responseMap.put("dataList", dataList);
if(dataList != null && dataList.size() > 0) {
//조회 결과가 있는 경우
Result result = new Result(
Constants.ReturnCode.SUCCESS,
msgUtil.getMsgCd("comm.success.search"),
msgUtil.getMsgText("comm.success.search"));
returnMap.put("result", result);
returnMap.put("response", responseMap);
} else {
//조회 결과 없음
Result result = new Result(
Constants.ReturnCode.LOGIC_ERROR,
msgUtil.getMsgCd("comm.fail.search"),
msgUtil.getMsgText("comm.fail.search"));
returnMap.put("result", result);
returnMap.put("response", responseMap);
}
return returnMap;
}
}
|
package cs3500.animator.model.featuremotion;
/**
* Enum to represent the attributes of the state of a feature at a given tick. This enum will be
* used to track which attributes are changed in a given motion.
*/
public enum AttributeName {
XPos, YPos, XDim, YDim, R, G, B;
}
|
package net.sf.ardengine.shapes;
import net.sf.ardengine.Core;
import net.sf.ardengine.Node;
import net.sf.ardengine.renderer.IDrawableImpl;
public class Rectangle extends Node implements IShape{
/**Used by renderer to store object with additional requirements*/
protected final IShapeImpl implementation;
protected float width;
protected float height;
/**
*
* @param x - x coord
* @param y - y coord
* @param width - width of this rectangle
* @param height - height of this rectangle
*/
public Rectangle(float x, float y, float width, float height) {
setX(x);
setY(y);
this.width = width;
this.height = height;
implementation = Core.renderer.createShapeImplementation(this);
}
@Override
public void draw() {
implementation.draw();
}
@Override
public float getWidth() {
return width;
}
public void setWidth(float width) {
this.width = width;
implementation.coordsChanged();
}
@Override
public float getHeight() {
return height;
}
public void setHeight(float height) {
this.height = height;
implementation.coordsChanged();
}
@Override
public IDrawableImpl getImplementation() {
return implementation;
}
@Override
public float[] getCoords() {
return new float[]{getX(), getY(), getX()+width, getY(), getX()+width, getY() + height, getX(), getY()+height};
}
@Override
public ShapeType getType() {
return ShapeType.RECTANGLE;
}
}
|
package com.example.demo.validator;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import javax.validation.*;
import java.util.Set;
@Component
public class ConstraintValidator<T> {
private ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
private Validator validator = factory.getValidator();
public void validate(T claz) {
validator.validate(claz);
Set<ConstraintViolation<T>> validators = validator.validate(claz);
if (validators.size() > 0) {
throw new ConstraintViolationException(validators);
}
}
}
|
package day18;
import heima.bean.Person;
import java.util.TreeSet;
public class test7 {
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args) {
//demo1();
TreeSet ts = new TreeSet();
ts.add(new Person("Achilles", 18));
ts.add(new Person("Achilles", 18));
ts.add(new Person("Forest", 19));
ts.add(new Person("Forest", 18));
ts.add(new Person("Brind", 22));
ts.add(new Person("Brind", 22));
System.out.println(ts);
}
private static void demo1() {
TreeSet ts = new TreeSet();
ts.add(3);
ts.add(3);
ts.add(2);
ts.add(1);
ts.add(1);
ts.add(2);
ts.add(3);
System.out.println(ts);
}
}
|
package org.fuusio.app.feature.test.presenter;
import org.fuusio.api.mvp.Presenter;
import org.fuusio.app.feature.test.view.TestView2;
public interface TestPresenter2 extends Presenter<TestView2, Presenter.Listener> {
void onButtonClicked();
}
|
package com.sysh.service.impl;
import com.sysh.mapper.FieldMapper;
import com.sysh.service.FieldService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
/**
* ClassName: <br/>
* Function: 字段实现<br/>
* date: 2018年06月20日 <br/>
*
* @author 苏积钰
* @since JDK 1.8
*/
@Service
public class FieldServiceImpl implements FieldService {
@Autowired
private FieldMapper fieldMapper;
@Override
public List<String> findType(String s) {
return fieldMapper.findField(s);
}
@Override
public List<Map> findTypeHelp(String s) {
return fieldMapper.findFieldHelp(s);
}
}
|
package com.shift.timer.di.components;
/**
* Created by roy on 6/8/2017.
*/
public class AppComponent {
}
|
package com.umasuo.model;
/**
* Updater.
*/
public interface Updater<E, A> {
/**
* update action handler.
*
* @param entity entity
* @param action action
*/
void handle(E entity, A action);
}
|
package switch2019.project.controllerLayer.rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.hateoas.Link;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import switch2019.project.DTO.deserializationDTO.MemberInfoDTO;
import switch2019.project.DTO.serializationDTO.AddedMemberDTO;
import switch2019.project.DTO.serializationDTO.PersonIDDTO;
import switch2019.project.DTO.serviceDTO.AddMemberDTO;
import switch2019.project.applicationLayer.US003AddMemberToGroupService;
import switch2019.project.assemblers.GroupDTOAssembler;
import java.util.Set;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn;
@RestController
public class US003AddMemberToGroupControllerRest {
@Autowired
US003AddMemberToGroupService service;
@PostMapping("/groups/{groupDescription}/members")
public ResponseEntity<Object> addMemberToGroup(@PathVariable String groupDescription,
@RequestBody MemberInfoDTO info){
AddMemberDTO addMemberDTO = GroupDTOAssembler.transformIntoAddMemberDTO(info, groupDescription);
AddedMemberDTO addedMemberDTO = service.addMemberToGroup(addMemberDTO);
Link selfLink = linkTo(methodOn(US003AddMemberToGroupControllerRest.class)
.getPersonByEmail(addMemberDTO.getGroupDescription(), addMemberDTO.getPersonEmail()))
.withSelfRel();
addedMemberDTO.add(selfLink);
return new ResponseEntity<>(addedMemberDTO, HttpStatus.CREATED);
}
@GetMapping(value = "groups/{groupDescription}/members/{personEmail:.+}")
public ResponseEntity<Object> getPersonByEmail
(@PathVariable final String groupDescription, @PathVariable final String personEmail) {
PersonIDDTO result = service.getPersonByEmail(personEmail, groupDescription);
return new ResponseEntity<>(result, HttpStatus.OK);
}
@GetMapping(value = "/groups/{groupDescription}/members")
public ResponseEntity<Object> getMembersByGroupDescription(@PathVariable final String groupDescription) {
Set<PersonIDDTO> members = service.getMembersByGroupDescription(groupDescription);
for(PersonIDDTO member : members) {
Link selfLink = linkTo(methodOn(US003AddMemberToGroupControllerRest.class)
.getPersonByEmail(groupDescription, member.getPersonID()))
.withSelfRel();
member.add(selfLink);
}
return new ResponseEntity<>(members, HttpStatus.OK);
}
@GetMapping(value = "/groups/{groupDescription}/admins")
public ResponseEntity<Object> getAdminsByGroupDescription(@PathVariable final String groupDescription) {
Set<PersonIDDTO> admins = service.getAdminsByGroupDescription(groupDescription);
for(PersonIDDTO admin : admins) {
Link selfLink = linkTo(methodOn(US003AddMemberToGroupControllerRest.class)
.getPersonByEmail(groupDescription, admin.getPersonID()))
.withSelfRel();
admin.add(selfLink);
}
return new ResponseEntity<>(admins, HttpStatus.OK);
}
} |
package com.hxsb.model.BUY_ERP_GET_DELIVERY_CREATE;
import java.util.List;
public class BUY_ERP_GET_DELIVERY_CREATE_Request {
private List<Long> erp_order_ids;
private String delivery_type;
public List<Long> getErp_order_ids() {
return erp_order_ids;
}
public void setErp_order_ids(List<Long> erp_order_ids) {
this.erp_order_ids = erp_order_ids;
}
public String getDelivery_type() {
return delivery_type;
}
public void setDelivery_type(String delivery_type) {
this.delivery_type = delivery_type;
}
@Override
public String toString() {
return "BUY_ERP_GET_DELIVERY_CREATE_Request [erp_order_ids=" + erp_order_ids + ", delivery_type="
+ delivery_type + "]";
}
}
|
package com.fillikenesucn.petcare.activities;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.fillikenesucn.petcare.R;
import com.fillikenesucn.petcare.utils.IOHelper;
import com.rscja.deviceapi.RFIDWithUHF;
import java.util.Random;
/**
* Esta clase representa a la actividad que se encargará de escanear los tags rfids asociadas a la mascotas
* @author: Marcelo Lazo Chavez
* @version: 26/03/2020
*/
public class ScannerMainFragmentActivity extends FragmentActivity {
// VARIABLES
private ImageView imageView;
// DECLARAMOS e instanciamos una variable que actuará como un indice para simular la animaciones del lector
private int countState = 4;
private Button btnLoadInfo;
// Declaramos el objeto perteneciente al lector UHF de RFID (LA PISTOLA)
public RFIDWithUHF mReader;
// Es el tipo de scannear si para el menu principal, para acontecimiento o para añadir pet
private String statusScannaer;
/**
* CONSTRUCTOR DE LA ACTIVIDAD
* @param savedInstanceState
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scanner_main_fragment);
imageView = (ImageView) findViewById(R.id.imgScanner);
btnLoadInfo = (Button) findViewById(R.id.btnLoadInfo);
// EJECUTAMOS LA ANIMACION DEL SCANNER
ExecuteTask();
// OBTENEMOS EL ESTADO ASOCIADO A LA ACTIVIDAD QUE LLAMO AL ESCANER
Intent parentIntent = getIntent();
statusScannaer = parentIntent.getStringExtra("STATUS");
// INICIALIZA EL UHF DE LA PISTOLA
InitUHF();
// DEV-BUTTON
btnLoadInfo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Random random = new Random();
switch (statusScannaer){
case "MAIN-MENU":
LoadPetInfoActivity("TAG-DE-PRUEBA-" + random.nextInt(255 - 0 + 1));
break;
case "PET-ADD":
case "PET-MODIFY":
case "EVENT-ADD":
ReturnEPCParent("TAG-DE-PRUEBA-" + random.nextInt(255 - 0 + 1));
break;
default:
break;
}
}
});
}
/**
* Método que se encarga de enviar la información asociada al EPC que se acaba de leer de un tag
* @param txtEPC Es el valor asociado al epc del tag escaneado
*/
private void LoadPetInfoActivity(String txtEPC){
// VERIFICA SI EXISTE
int resultEPC = IOHelper.CheckActiveEPC(ScannerMainFragmentActivity.this, txtEPC);
//SI EXISTE
if (resultEPC != -1){
Intent intent = new Intent(ScannerMainFragmentActivity.this, PetInfoFragmentActivity.class);
intent.putExtra("EPC",txtEPC);
startActivity(intent);
finish();
}else{ //SI NO EXISTE
Load404Error(txtEPC);
}
}
/**
* Método que se encarga de retornar el valor del EPC a la actividad padre
* (Utilizado por el agregar mascota y agregar acontecimiento global)
* @param txtEPC Es el valor asociado al epc del tag escaneado
*/
private void ReturnEPCParent(String txtEPC){
Intent resultIntent = new Intent();
resultIntent.putExtra("result",txtEPC);
setResult(RESULT_OK, resultIntent);
finish();
}
/**
* Método que se encarga de redireccionar a la vista o actividad de 404 error al falla la lectura de un tag
*/
private void Load404Error(String epc){
Intent intent = new Intent(ScannerMainFragmentActivity.this, PetNotFoundFragmentActivity.class);
intent.putExtra("EPC",epc);
startActivity(intent);
finish();
}
/**
* Método que se encarga de inicializar el lector de UHF asociada al hardware de la pistola
*/
private void InitUHF(){
try {
mReader = RFIDWithUHF.getInstance();
} catch (Exception ex) {
Toast.makeText( ScannerMainFragmentActivity.this,ex.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
if (mReader != null){
new InitTask().execute();
}
}
/**
* Metodo que se ejecuta cuando se termina la actividad del escanner, liberando la memoria asociada
* al lector RFID del celular, si es que este fue inicializado en algun momento
*/
@Override
protected void onDestroy() {
if (mReader != null) {
mReader.free();
}
super.onDestroy();
}
/**
* Método que se encarga de intercalando entre las imagenes estaticas de los resources de la aplicación
* Teniendo un total de secuencia ... -> 4 -> 3 -> 2 -> 1 -> 4 -> 3 -> 2 -> .....
* Va reducienciendo el estado de la imagen entre un rango de 1 a 4 (inclusivos)
*/
private void UpdateImageStatus(){
countState--;
if( countState < 1){
countState = 4;
}
switch (countState){
case 4:
imageView.setImageDrawable(getResources().getDrawable(R.drawable.scan4));
break;
case 3:
imageView.setImageDrawable(getResources().getDrawable(R.drawable.scan3));
break;
case 2:
imageView.setImageDrawable(getResources().getDrawable(R.drawable.scan2));
break;
case 1:
imageView.setImageDrawable(getResources().getDrawable(R.drawable.scan1));
break;
default:
break;
}
}
/**
* Método que se encarga de ejecutar la animación del escanner de la actividad
*/
private void ExecuteTask(){
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
UpdateImageStatus();
ExecuteTask();
}
},250);
}
/**
* Clase se encarga de ejecutar una tarea de forma paralela que se encarga de inicializar
* el lector de RFID, desplegando un dialog para informale al usuario de que esta incializando el lector
*/
public class InitTask extends AsyncTask<String, Integer, Boolean> {
// VARIABLES
ProgressDialog mypDialog;
/**
* Método que se encarga de mostrar el dialog de progreso de la inicialización del lector uhf
*/
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mypDialog = new ProgressDialog(ScannerMainFragmentActivity.this);
mypDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mypDialog.setMessage("Iniciando Lector UHF");
mypDialog.setCanceledOnTouchOutside(false);
mypDialog.show();
}
/**
* Método que se encarga de ejecutar la funcionalidad de inicialización del lector UHF
* @param params Conjuntos de parametros asociados al tarea paralela
* @return retorna true si la inicialización fue realizada con exito, en caso contrario retorna false
*/
@Override
protected Boolean doInBackground(String... params) {
// TODO Auto-generated method stub
return mReader.init();
}
/**
* Método que se encarga de finalizar el proceso de la tarea paralela de inicializar el lector UHF
* @param result Es un valor booleando que indica si la inicialización del lector fue completada con exito
*/
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
// CIERRA EL DIALOG
mypDialog.cancel();
if (!result) {
Toast.makeText(ScannerMainFragmentActivity.this, "FALLO AL INICIAR EL UHF",
Toast.LENGTH_SHORT).show();
}else{
String strUII = mReader.inventorySingleTag();
if(!TextUtils.isEmpty(strUII)){
String strEPC = mReader.convertUiiToEPC(strUII);
// SEGUN EL TIPO DE ACTIVIDAD QUE LLAMO AL ESCANNER LA FUNCIONALIDAD SOBRE EL EPC SERA DIFERENTE
switch (statusScannaer){
case "MAIN-MENU":
LoadPetInfoActivity(strEPC);
break;
case "PET-ADD":
case "PET-MODIFY":
case "EVENT-ADD":
ReturnEPCParent(strEPC);
break;
default:
break;
}
} else {
//NO CARGO TAG
Toast.makeText(ScannerMainFragmentActivity.this, "NO HAY TAG CERCA",
Toast.LENGTH_SHORT).show();
}
}
}
}
}
|
package com.example.mingle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;
public class ProfileActivity extends Activity {
public final static String USER_UID = "com.example.mingle.USER_SEL"; //Intent data to pass on when new Chatroom Activity started
private ViewFlipper viewFlipper;
private float lastX;
private int photo_num;
private MingleUser user;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
viewFlipper = (ViewFlipper) findViewById(R.id.view_flipper);
Intent intent = getIntent();
String uid = intent.getExtras().getString(CandidateAdapter.PROFILE_UID);
user = ((MingleApplication) this.getApplication()).getMingleUser(uid);
photo_num = user.getPhotoNum();
uid = user.getUid();
LayoutInflater inflater = getLayoutInflater();
for(int i = 0; i < photo_num; i++){
LinearLayout single_photo_layout = (LinearLayout) inflater
.inflate(R.layout.single_photo, null);
ImageView photo_view = (ImageView) single_photo_layout.findViewById(R.id.photoView);
Drawable photo_drawable = user.getPic(i);
photo_view.setImageDrawable(photo_drawable);
viewFlipper.addView(single_photo_layout);
}
TextView num_view = (TextView) findViewById(R.id.profile_user_num);
num_view.setText(String.valueOf(user.getNum()));
TextView name_view = (TextView) findViewById(R.id.profile_user_name);
name_view.setText(user.getName());
}
// Method to handle touch event like left to right swap and right to left swap
public boolean onTouchEvent(MotionEvent touchevent)
{
switch (touchevent.getAction())
{
// when user first touches the screen to swap
case MotionEvent.ACTION_DOWN:
{
lastX = touchevent.getX();
break;
}
case MotionEvent.ACTION_UP:
{
float currentX = touchevent.getX();
// if left to right swipe on screen
if (lastX < currentX)
{
// If no more View/Child to flip
if (viewFlipper.getDisplayedChild() == 0)
break;
// set the required Animation type to ViewFlipper
// The Next screen will come in form Left and current Screen will go OUT from Right
viewFlipper.setInAnimation(this, R.anim.in_from_left);
viewFlipper.setOutAnimation(this, R.anim.out_to_right);
// Show the next Screen
viewFlipper.showNext();
}
// if right to left swipe on screen
if (lastX > currentX)
{
if (viewFlipper.getDisplayedChild() == photo_num)
break;
// set the required Animation type to ViewFlipper
// The Next screen will come in form Right and current Screen will go OUT from Left
viewFlipper.setInAnimation(this, R.anim.in_from_right);
viewFlipper.setOutAnimation(this, R.anim.out_to_left);
getNewImage(viewFlipper.getDisplayedChild()/2+1);
// Show The Previous Screen
viewFlipper.showPrevious();
}
break;
}
}
return false;
}
public void getNewImage(int photo_index){
System.out.println("photo index: " + photo_index);
if(photo_index < 0 || photo_index >= photo_num) return;
if(!user.isPicAvail(photo_index)){
System.out.println("download image!");
new ImageDownloader(getApplication(), user.getUid(), photo_index);
}
}
public void updateView(int index){
LinearLayout curr_layout = (LinearLayout) viewFlipper.getCurrentView();
ImageView photo_view = (ImageView) curr_layout.findViewById(R.id.photoView);
Drawable pic_to_update = user.getPic(index);
photo_view.setImageDrawable(pic_to_update);
}
public void voteUser(View v){
String curr_uid = user.getUid();
if(!user.alreadyVoted()){
user.setVoted();
((MingleApplication) this.getApplication()).connectHelper.voteUser(curr_uid);
}
}
public void startChat(View v){
System.out.println("start chat");
MingleApplication app = ((MingleApplication) this.getApplication());
int candidate_pos = app.getCandidatePos(user.getUid());
if(candidate_pos >= 0) {
app.switchCandidateToChoice(candidate_pos);
}
// Create chatroom in local sqlite
//((MingleApplication) parent.getApplication()).dbHelper.insertNewUID(chat_user_uid);
Intent chat_intent = new Intent(this, ChatroomActivity.class);
chat_intent.putExtra(USER_UID, user.getUid());
startActivity(chat_intent);
}
}
|
package fr.polytech.al.tfc.account.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonObject;
import fr.polytech.al.tfc.account.model.Account;
import fr.polytech.al.tfc.account.model.AccountType;
import fr.polytech.al.tfc.account.model.Cap;
import fr.polytech.al.tfc.account.repository.AccountRepository;
import fr.polytech.al.tfc.profile.model.Profile;
import fr.polytech.al.tfc.profile.repository.ProfileRepository;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import static junit.framework.TestCase.assertEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class AccountControllerTest {
@Autowired
private AccountRepository accountRepository;
@Autowired
private ProfileRepository profileRepository;
@Autowired
private MockMvc mockMvc;
private ObjectMapper objectMapper = new ObjectMapper();
private Account account;
//set up is testing saveAccount
@Before
public void setUp() throws Exception {
account = new Account(800,AccountType.CHECK);
accountRepository.save(account);
}
@Test
public void viewAccount() throws Exception {
MvcResult mvcResult = this.mockMvc.perform(get("/accounts/" + account.getAccountId())
.accept(MediaType.APPLICATION_JSON_VALUE)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andReturn();
Account accountRetrieved = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), Account.class);
assertEquals(300, accountRetrieved.getAmountSlidingWindow().intValue());
assertEquals(800, accountRetrieved.getMoney().intValue());
}
@Test
public void viewCapsForAnAccount() throws Exception {
MvcResult mvcResult = this.mockMvc.perform(get("/accounts/" + account.getAccountId() + "/cap")
.accept(MediaType.APPLICATION_JSON_VALUE)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andReturn();
Cap cap = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), Cap.class);
assertEquals(300, cap.getAmountSlidingWindow().intValue());
assertEquals(800, cap.getMoney().intValue());
}
@Test
public void createAccountForProfile() throws Exception {
final String emailTest = "createAccountForProfile";
Profile profile = new Profile(emailTest);
profileRepository.save(profile);
Assert.assertEquals(0, profile.getAccounts().size());
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("money", 800);
jsonObject.addProperty("accountType", AccountType.CHECK.name());
mockMvc.perform(post("/accounts/" + emailTest + "/accounts")
.accept(MediaType.APPLICATION_JSON_VALUE)
.contentType(MediaType.APPLICATION_JSON)
.content(jsonObject.toString()))
.andExpect(status().isOk());
profile = profileRepository.findByEmail(emailTest).get();
Assert.assertEquals(1, profile.getAccounts().size());
}
} |
package daoImpl.system;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import model.Activity;
import model.ResultMessage;
import model.SystemUser;
import dao.system.WaiterDao;
import daoImpl.helper.Helper;
public class WaiterDaoImpl implements WaiterDao{
private String idStyleString = "%07d";
private WaiterDaoImpl(){
}
@Override
public ResultMessage login(String position, String id, String password) {
ResultMessage resultMessage = ResultMessage.NOTEXIST;
try {
Session session = Helper.getSessionFactory().openSession();
String hql = " from SystemUser";
Query query = session.createQuery(hql);
//默认查询出来的list里存放的是一个Object数组
List<SystemUser> userList = query.list();
for(SystemUser user : userList){
String idTemp = String.format(idStyleString,user.getId());
String passwordTemp = user.getPassword();
String positionTemp = user.getPosition();
if(idTemp.equals(id)&&passwordTemp.equals(password)&&positionTemp.equals(position)){
resultMessage = ResultMessage.EXIST;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return resultMessage;
}
@Override
public ResultMessage makeActivity(Activity activity) {
ResultMessage resultMessage = ResultMessage.FAILED;
try{
Session session = Helper.getSessionFactory().openSession();
session.beginTransaction();
session.persist(activity);
session.getTransaction().commit();
session.close();
resultMessage = ResultMessage.SUCCEED;
}catch(Exception e){
e.printStackTrace();
}
return resultMessage;
}
}
|
package scale;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
*
* @author david.charubini
*/
public class AssociativeNode<T, K> {
public static interface Timer {
public boolean isExpired();
public void clockIn();
public void start();
}
public static interface Processor<T, K> {
/**
* Returns null if the information is not relevant, a value of type K
* otherwise.
* @param t
* @return null if the information is not relevant, a value of type K
* otherwise.
*/
public K process (Collection<T> t);
}
public static interface Listener<K> {
public void notifyActive(K k);
}
private final Timer timer;
private final Processor<T, K> processor;
private Listener<K> listener;
private final List<T> currentValues = new ArrayList<T>();
public AssociativeNode(Timer timer, Processor<T, K> processor, Listener<K> listener) {
this.timer = timer;
this.processor = processor;
this.listener = listener;
}
public AssociativeNode(Timer timer, Processor<T, K> processor) {
this(timer, processor, null);
}
public synchronized void process (T t) {
if (this.timer.isExpired()) {
this.currentValues.clear();
this.timer.start();
}
this.currentValues.add(t);
this.timer.clockIn();
K result = this.processor.process(this.currentValues);
if (result != null) {
if (this.listener != null) {
this.listener.notifyActive(result);
}
}
}
public final void setListener(Listener<K> listener) {
this.listener = listener;
}
}
|
package com.pingcap.tools.cdb.binlog.instance.core;
import com.pingcap.tools.cdb.binlog.common.AbstractCDBLifeCycle;
import com.pingcap.tools.cdb.binlog.listener.CDBEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by iamxy on 2017/2/17.
*/
public abstract class AbstractCDBInstance extends AbstractCDBLifeCycle implements CDBInstance {
private static final Logger logger = LoggerFactory.getLogger(AbstractCDBInstance.class);
protected String destination;
protected CDBEventListener eventListener;
@Override
public void start() {
super.start();
}
@Override
public void stop() {
super.stop();
}
@Override
public String getDestination() {
return destination;
}
@Override
public CDBEventListener getEventListener() {
return eventListener;
}
}
|
package com.google.firebase.example.predictions;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.remoteconfig.FirebaseRemoteConfig;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void configShowAds() {
long cacheExpiration = 60L;
// [START pred_config_show_ads]
final FirebaseRemoteConfig config = FirebaseRemoteConfig.getInstance();
Map remoteConfigDefaults = new HashMap<String, Object>();
remoteConfigDefaults.put("ads_policy", "ads_never");
config.setDefaults(remoteConfigDefaults);
// ...
config.fetch(cacheExpiration)
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
config.activateFetched();
}
// Act on the retrieved parameters
// Show ads based on the ad policy retrieved with Remote Config
executeAdsPolicy();
// ...
}
});
// [END pred_config_show_ads]
}
public void executeAdsPolicy() {
// [START pred_ads_policy]
FirebaseRemoteConfig config = FirebaseRemoteConfig.getInstance();
String adPolicy = config.getString("ads_policy");
boolean will_not_spend = config.getBoolean("will_not_spend");
AdView mAdView = findViewById(R.id.adView);
if (adPolicy.equals("ads_always") ||
(adPolicy.equals("ads_nonspenders") && will_not_spend)) {
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
mAdView.setVisibility(View.VISIBLE);
} else {
mAdView.setVisibility(View.GONE);
}
FirebaseAnalytics.getInstance(this).logEvent("ads_policy_set", new Bundle());
// [END pred_ads_policy]
}
public void configPromoStrategy() {
long cacheExpiration = 60L;
// [START config_promo_strategy]
final FirebaseRemoteConfig config = FirebaseRemoteConfig.getInstance();
Map remoteConfigDefaults = new HashMap<String, Object>();
remoteConfigDefaults.put("promoted_bundle", "basic");
config.setDefaults(remoteConfigDefaults);
// ...
config.fetch(cacheExpiration)
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
config.activateFetched();
}
// Act on the retrieved parameters
String promotedBundle = getPromotedBundle();
// ...
}
});
// [END config_promo_strategy]
}
// [START pred_get_promoted_bundle]
public String getPromotedBundle() {
FirebaseAnalytics.getInstance(this).logEvent("promotion_set", new Bundle());
FirebaseRemoteConfig config = FirebaseRemoteConfig.getInstance();
String promotedBundle = config.getString("promoted_bundle");
boolean will_spend = config.getBoolean("predicted_will_spend");
if (promotedBundle.equals("predicted") && will_spend) {
return "premium";
} else {
return promotedBundle;
}
}
// [END pred_get_promoted_bundle]
public void configPreventChurn() {
long cacheExpiration = 60L;
// [START pred_config_prevent_churn]
final FirebaseRemoteConfig config = FirebaseRemoteConfig.getInstance();
Map remoteConfigDefaults = new HashMap<String, Object>();
remoteConfigDefaults.put("gift_policy", "gift_never");
config.setDefaults(remoteConfigDefaults);
// ...
config.fetch(cacheExpiration)
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
config.activateFetched();
}
// Act on the retrieved parameters
executeGiftPolicy();
// ...
}
});
// [END pred_config_prevent_churn]
}
// [START pred_execute_gift_policy]
public void executeGiftPolicy() {
FirebaseRemoteConfig config = FirebaseRemoteConfig.getInstance();
String giftPolicy = config.getString("gift_policy");
boolean willChurn = config.getBoolean("will_churn");
if (giftPolicy.equals("gift_achievement")) {
grantGiftOnLevel2();
} else if (giftPolicy.equals("gift_likelychurn") && willChurn) {
grantGiftNow();
}
FirebaseAnalytics.getInstance(this).logEvent("gift_policy_set", new Bundle());
}
// [END pred_execute_gift_policy]
public void grantGiftOnLevel2() {
// Nothing
}
public void grantGiftNow() {
// Nothing
}
}
|
package org.springframework.fom.boot.test.schedules;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.fom.Result;
import org.springframework.fom.annotation.FomSchedule;
import org.springframework.fom.boot.test.TestTask;
import org.springframework.fom.interceptor.ScheduleCompleter;
import org.springframework.fom.interceptor.ScheduleFactory;
import org.springframework.fom.interceptor.ScheduleTerminator;
import org.springframework.fom.interceptor.TaskTimeoutHandler;
/**
*
* @author shanhm1991@163.com
*
*/
@FomSchedule(cron = "0/30 * * * * ?", threadCore = 4, taskOverTime = 4, cancelTaskOnTimeout = true, remark = "定时批任务测试")
public class BatchSchedulTest implements ScheduleFactory<Long>, ScheduleCompleter<Long>, ScheduleTerminator, TaskTimeoutHandler {
private static final Logger LOG = LoggerFactory.getLogger(BatchSchedulTest.class);
@Override
public Collection<TestTask> newSchedulTasks() throws Exception {
List<TestTask> list = new ArrayList<>();
for(int i = 1; i <= 10; i++){
list.add(new TestTask(i));
}
return list;
}
@Override
public void onScheduleComplete(long schedulTimes, long schedulTime, List<Result<Long>> results) throws Exception {
String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(schedulTime);
LOG.info( "第{}次在{}提交的任务全部完成,结果为{}", schedulTimes, date, results);
}
@Override
public void onScheduleTerminate(long schedulTimes, long lastTime) {
String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(lastTime);
LOG.info("任务关闭,共执行{}次任务,最后一次执行时间为{}", schedulTimes, date);
}
@Override
public void handleTimeout(String taskId, long costTime) {
LOG.info("处理超时任务{},已经耗时{}ms", taskId, costTime);
}
}
|
package com.mmall.concurrency.example.singleton;
import com.mmall.concurrency.annotation.ThreadSafe;
/**
* @Auther: Mr.Dong
* @Date: 2019/3/1 09:59
* @Description: 饿汉模式
*/
@ThreadSafe
public class SingletonExample6 {
private static SingletonExample6 instance = null;
static {
instance = new SingletonExample6();
}
private SingletonExample6() {
}
// 静态的工厂方法
public static SingletonExample6 getInstance() {
return instance;
}
}
|
package org.fhcrc.honeycomb.metapop.experiment;
import org.fhcrc.honeycomb.metapop.environmentchanger.EnvironmentChanger;
import org.fhcrc.honeycomb.metapop.environmentchanger.StaticEnvironment;
import org.fhcrc.honeycomb.metapop.resource.Resource;
import org.fhcrc.honeycomb.metapop.resource.NullResource;
/**
* Implements a static environment.
*
* Created on 8 Apr, 2013
* @author Adam Waite
* @version $Rev: 1931 $, $Date: 2013-04-12 11:26:27 -0700 (Fri, 12 Apr 2013) $
*
*/
public abstract class LBLStaticEnv extends LinearBeforeLoad {
public LBLStaticEnv(String args[]) { super(args); }
@Override
public EnvironmentChanger makeEnvChanger() {
return new StaticEnvironment();
}
@Override
public Resource makeResource() {
return new NullResource();
}
}
|
package mapgenerator.logic;
/**
* Class is used to make simple calculations needed in the program.
*/
public class Calculator {
/**
* Returns smaller of the two values.
*
* @param val1
* @param val2
* @return
*/
public int min(int val1, int val2) {
if (val1 < val2) {
return val1;
}
return val2;
}
/**
* Returns smaller of the two values.
*
* @param val1
* @param val2
* @return
*/
public double min(double val1, double val2) {
if (val1 < val2) {
return val1;
}
return val2;
}
/**
* Returns bigger of the two values.
*
* @param val1
* @param val2
* @return
*/
public int max(int val1, int val2) {
if (val1 > val2) {
return val1;
}
return val2;
}
/**
* Returns bigger of the two values.
*
* @param val1
* @param val2
* @return
*/
public double max(double val1, double val2) {
if (val1 > val2) {
return val1;
}
return val2;
}
/**
* Raises the given value to the power of given exponent
*
* @param value
* @param exponent
* @return
*/
public int pow(int value, int exponent) {
int result = value;
if (exponent > 0) {
for (int i = 0; i < exponent - 1; i++) {
result = result * value;
}
} else if (exponent < 0) {
for (int i = 0; i < (-1) * exponent - 1; i++) {
result = result * value;
}
result = 1 / result;
} else {
result = 1;
}
return result;
}
/**
* Raises the given value to the power of given exponent
*
* @param value
* @param exponent
* @return
*/
public double pow(double value, double exponent) {
double result = value;
if (exponent > 0) {
for (int i = 0; i < exponent - 1; i++) {
result = result * value;
}
} else if (exponent < 0) {
for (int i = 0; i < (-1) * exponent - 1; i++) {
result = result * value;
}
result = 1 / result;
} else {
result = 1;
}
return result;
}
}
|
package com.tencent.mm.plugin.sns.ui;
import com.tencent.mm.g.a.gj;
import com.tencent.mm.sdk.b.b;
import com.tencent.mm.sdk.b.c;
class SnsTimeLineUI$3 extends c<gj> {
final /* synthetic */ SnsTimeLineUI odw;
SnsTimeLineUI$3(SnsTimeLineUI snsTimeLineUI) {
this.odw = snsTimeLineUI;
this.sFo = gj.class.getName().hashCode();
}
public final /* bridge */ /* synthetic */ boolean a(b bVar) {
gj gjVar = (gj) bVar;
SnsTimeLineUI.a(this.odw, gjVar.bPx.bPA, gjVar.bPx.bPz, gjVar);
return false;
}
}
|
package com.goodhealth.framework.entity.response;
import com.goodhealth.comm.exception.BaseException;
import com.goodhealth.comm.errorcode.IErrorCode;
import com.goodhealth.framework.entity.DTO;
/**
* @ClassName Response
* @Author WuDengHui
* @Description
* @Date 2019/4/249:56
**/
public class Response<T> extends DTO implements IErrorCode {
private static final long serialVersionUID = 1L;
private T data;
private boolean success;
private String errCode;
private String errMessage;
private boolean retriable;
public static <T> Response<T> of(T data) {
Response<T> singleResponse = new Response<T>();
singleResponse.setSuccess(true);
singleResponse.setData(data);
return singleResponse;
}
public static Response buildFailure(String errCode, String errMessage) {
Response response = new Response();
response.setSuccess(false);
response.setErrCode(errCode);
response.setErrMessage(errMessage);
return response;
}
public static Response buildFailure(IErrorCode IErrorCode) {
Response response = new Response();
response.setSuccess(false);
response.setErrCode(IErrorCode.getErrCode());
response.setErrMessage(IErrorCode.getErrMessage());
response.setRetriable(IErrorCode.isRetriable());
return response;
}
public static Response buildFailure(Response other) {
Response response = new Response();
response.setSuccess(false);
response.setErrCode(other.getErrCode());
response.setErrMessage(other.getErrMessage());
response.setRetriable(other.isRetriable());
return response;
}
public static Response buildFailure(BaseException bizException) {
Response response = new Response();
response.setSuccess(false);
response.setErrCode(bizException.getErrCode());
response.setErrMessage(bizException.getErrMessage());
response.setRetriable(bizException.isRetriable());
return response;
}
public static Response buildSuccess(){
Response response = new Response();
response.setSuccess(true);
return response;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
@Override
public String getErrCode() {
return errCode;
}
public void setErrCode(String errCode) {
this.errCode = errCode;
}
@Override
public String getErrMessage() {
return errMessage;
}
public void setErrMessage(String errMessage) {
this.errMessage = errMessage;
}
@Override
public boolean isRetriable() {
return retriable;
}
public void setRetriable(boolean retriable) {
this.retriable = retriable;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
|
package com.aitsuki.swipedemo;
/**
* Created by AItsuki on 2017/7/11.
* ItemTouchListener
*/
interface ItemTouchListener {
void onItemClick(String str);
void onLeftMenuClick(String str);
void onRightMenuClick(String str);
}
|
import java.util.Random;
import java.util.Scanner;
//A Program from andrew749 productions
public class decision {
// string that will capture the options
public static int[] optionvalues = new int[100];
public static Scanner scanner = new Scanner(System.in);
public static int testtimes = 0;
public static int valueof;
public static int numberofoptionarrayvalues;
public static String finalanwser;
static String[] options = new String[100];
// integer that will store the value that the user will enter to test
// method to assign values to each variable based on what number is
// generated
public static void count(int position) {
++optionvalues[position];
}
// method to run loop to generate numbers
public static void runloop(int testnumber) {
Random random = new Random();
for (int i = 0; i < testnumber; i++) {
valueof = random.nextInt(numberofoptionarrayvalues - 1);
count(valueof);
}
}
// gets input from the user to see the amount of times they want to test the
// certain option
final public static void gettesttimes() {
System.out
.println("Please enter the amount of times you want to test the options");
testtimes = scanner.nextInt();
}
public static String[] getuserinput(String[] options) {
int i = 0;
do {
numberofoptionarrayvalues = i + 1;
options[i] = scanner.nextLine();
if (options[i].equals("q")) {
break;
}
System.arraycopy(options, 0, options, 0, i);
i++;
} while (i < options.length);
return options;
}
// shows the results of the random loop
// coded for any number of options as long as numberofoptionarrayvalues is
// present
public static String results(String anwser, String[] option) {
String result = "The Results are in: ";
for (int i = 0; i < numberofoptionarrayvalues; ++i) {
result += option[i] + " has " + optionvalues[i] + " ";
anwser = result;
}
;
System.out.println(anwser);
return anwser;
}
// main loop
public static void main(String[] args) {
System.out
.println("Please enter your options and enter a \"q\" to stop entering items");
options = getuserinput(options);
gettesttimes();
runloop(testtimes);
results(finalanwser, options);
}
}
|
package pl.cwanix.opensun.agentserver.engine.npc;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;
import pl.cwanix.opensun.agentserver.engine.npc.structures.NpcInfoStructure;
import pl.cwanix.opensun.agentserver.properties.AgentServerProperties;
import pl.cwanix.opensun.utils.files.SUNFileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@Getter
@Setter
@Service
@RequiredArgsConstructor
public class NpcInfoParser implements InitializingBean {
private static final Marker MARKER = MarkerFactory.getMarker("NPC INFO PARSER");
private static final String NPC_INFO_FILE_NAME = "npcinfo.txt";
private final AgentServerProperties properties;
private Map<Integer, NpcInfoStructure> npcInfoStructureMap;
private void loadNpcInfo() throws IOException {
npcInfoStructureMap = new HashMap<>();
try (SUNFileReader reader = new SUNFileReader(properties.getDataDirectory() + "/" + NPC_INFO_FILE_NAME)) {
while (reader.readLine()) {
NpcInfoStructure field = new NpcInfoStructure();
field.setMonsterCode(reader.readNextIntValue());
field.setName(reader.readNextStringValue());
field.setLevel(reader.readNextIntValue());
npcInfoStructureMap.put(field.getMonsterCode(), field);
}
}
log.info(MARKER, "Loaded npc data: {}", npcInfoStructureMap.size());
}
@Override
public void afterPropertiesSet() throws Exception {
loadNpcInfo();
}
}
|
package juc;
import java.util.concurrent.TimeUnit;
/**
* @author wyg_edu
* @date 2020年5月21日 上午8:23:19
* @version v1.0
* 死锁是两个或者两个以上的进行在执行过程中
* 因抢夺资源而造成的相互等待的现象
* 若无外力推动则都将无法推动下去
*/
public class DeadLockDemo {
static String lockA = "A";
static String lockB = "B";
public static void main(String[] args) {
new Thread(new HoldLockThread(lockA, lockB), "ThreadAA").start();
new Thread(new HoldLockThread(lockB, lockA), "ThreadBB").start();
}
}
class HoldLockThread implements Runnable{
private String lockA;
private String lockB;
public HoldLockThread(String lockA, String lockB) {
super();
this.lockA = lockA;
this.lockB = lockB;
}
@Override
public void run() {
synchronized (lockA) {
System.out.println(Thread.currentThread().getName()+"\t持有"+lockA+"\t尝试获取"+lockB);
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lockB) {
System.out.println(Thread.currentThread().getName()+"\t持有"+lockB+"\t尝试获取"+lockA);
}
}
}
}
|
package renderer;
import android.content.Context;
import android.util.Log;
import android.view.MotionEvent;
import com.example.cc.opencvtest.MainActivity;
import com.example.cc.opencvtest.R;
import org.rajawali3d.animation.mesh.SkeletalAnimationChildObject3D;
import org.rajawali3d.lights.DirectionalLight;
import org.rajawali3d.materials.Material;
import org.rajawali3d.materials.methods.DiffuseMethod;
import org.rajawali3d.materials.textures.ATexture;
import org.rajawali3d.materials.textures.Texture;
import org.rajawali3d.math.vector.Vector3;
import org.rajawali3d.primitives.Sphere;
import org.rajawali3d.renderer.RajawaliRenderer;
import java.util.Vector;
/**
* Created by cc on 7/4/2015.
*/
public class Renderer extends RajawaliRenderer {
public interface RajawaliCallback{
void setPos();
void setData();
}
private static final String TAG = MainActivity.ALL + "_rajarenderer";
public RajawaliCallback callback;
public Context context;
private DirectionalLight directionalLight;
private Sphere earthSphere;
private SkeletalAnimationChildObject3D obj3d;
float posX = 0.8f, posY = 0.8f;
private double[] projectionMatrix;
private double[] viewMatrix;
public Renderer(Context context){
super(context);
this.context = context;
setFrameRate(60);
}
public void setPos(float x, float y){
Log.d(TAG, "setPos");
posX = x;
posY = y;
}
public void setData(double[] projectionMatrix, double[] viewMatrix){
for (int i = 0; i < this.projectionMatrix.length; i++)
this.projectionMatrix[i] = projectionMatrix[i];
for (int i = 0; i < this.viewMatrix.length; i++)
this.viewMatrix[i] = viewMatrix[i];
}
@Override
public void initScene(){
Log.d(TAG, "initScene");
directionalLight = new DirectionalLight(1f, .2f, -1.0f );
directionalLight.setColor(1.0f, 1.0f, 1.0f);
directionalLight.setPower(2);
getCurrentScene().addLight((directionalLight));
Material material = new Material();
material.enableLighting(true);
material.setDiffuseMethod(new DiffuseMethod.Lambert());
Texture earthTexture = new Texture("Earth", R.drawable.earthtruecolor_nasa_big);
try{
material.addTexture(earthTexture);
}
catch (ATexture.TextureException e){
Log.d(TAG, "Texture error");
}
earthSphere = new Sphere(0.6f, 27, 27);
earthSphere.setMaterial(material);
earthSphere.setPosition(posX, posY, 0);
getCurrentScene().addChild(earthSphere);
getCurrentCamera().setZ(4.2f);
}
@Override
public void onRender(final long elapsedTime, final double deltaTime){
//Log.d(TAG, "onRender");
super.onRender(elapsedTime, deltaTime);
callback.setPos();
// callback.setData();
//getCurrentCamera().setLookAt(0, 0, 4);
Vector3 v3 = new Vector3();
earthSphere.setPosition(posX, posY, 0);
//earthSphere.setOrientation();
Log.d(TAG, "x: " + Double.toString(earthSphere.getX()) + "y: " + Double.toString(earthSphere.getY()));
earthSphere.rotate(Vector3.Axis.Y, 1.0);
}
@Override
public void onTouchEvent(MotionEvent event){
Log.d(TAG, "onTouchEvent");
/*
float x = event.getX(), y = event.getY();
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
posX = x;
posY = y;
break;
case MotionEvent.ACTION_MOVE:
getCurrentCamera().setZ((y - posY)*0.0005f);
break;
}
*/
}
@Override
public void onOffsetsChanged(float x, float y, float z, float w, int i, int j){
Log.d(TAG, "onOffsetsChanged");
}
}
|
package com.hbj.learning.threadcoreknowledge.basicattributes;
/**
* ID从1开始,我们创建的线程id早已不是2
*
* @author hbj
* @date 2019/11/4 21:51
*/
public class ThreadId {
public static void main(String[] args) {
Thread thread = new Thread();
System.out.println("主线程的id " + Thread.currentThread().getId());
System.out.println("子线程的id " + thread.getId());
}
}
|
package com.tencent.mm.plugin.wallet.balance.ui.lqt;
import com.tencent.mm.plugin.wallet.balance.ui.lqt.WalletLqtDetailUI.4;
import com.tencent.mm.plugin.wxpay.a.i;
import com.tencent.mm.protocal.c.sj;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.ui.base.l;
import com.tencent.mm.ui.base.n.c;
import java.util.Iterator;
class WalletLqtDetailUI$4$1 implements c {
final /* synthetic */ 4 pbt;
WalletLqtDetailUI$4$1(4 4) {
this.pbt = 4;
}
public final void a(l lVar) {
if (WalletLqtDetailUI.c(this.pbt.pbs).sfG != null && WalletLqtDetailUI.c(this.pbt.pbs).sfG.size() > 0) {
Iterator it = WalletLqtDetailUI.c(this.pbt.pbs).sfG.iterator();
int i = 0;
while (it.hasNext()) {
sj sjVar = (sj) it.next();
if (!(bi.oW(sjVar.title) || bi.oW(sjVar.rvK))) {
lVar.add(0, i, 0, sjVar.title);
}
i++;
}
}
if (!WalletLqtDetailUI.c(this.pbt.pbs).sfN) {
lVar.add(0, -1, 0, i.wallet_lqt_close_account);
}
}
}
|
package com.njupt.ws_cxf_spring.ws.test;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import com.njupt.ws_cxf_spring.ws.bean.Device;
import com.njupt.ws_cxf_spring.ws.dao.Dao;
import com.njupt.ws_cxf_spring.ws.dao.Dao2;
import com.njupt.ws_cxf_spring.ws.dao.SendMessage;
public class WS_Test {
Dao dao;
Dao2 dao2;
public WS_Test() {
dao = new Dao();
dao2 = new Dao2();
}
public String queryProjectsTest() {
String res = dao.queryProjects("9de089c60f374fe5be7b9f0cf1206313");
return res;
}
public String queryDevicesTest() {
String res = dao.queryDevices(1000000);
return res;
}
public String queryDataTypeTest() {
String res = dao.queryDataType("93bfdc61ef56477d965cbe0a3a04f45d");
return res;
}
public String getRecentValuesTest() {
String res = dao.getRecentValues("temp", "b12c86db4a1f40db8595737fe3f47520");
return res;
}
public String changeShowTypeTest() {
String res = dao.changeShowType("humi", "eef8f40402e6437ca3d29282656763de", 2);
return res;
}
public String queryDevicesNumTest() {
String res = dao.queryDevicesNum(1000000);
return res;
}
public String queryDeviceInfoTest() {
String res = dao.queryDeviceInfo("eef8f40402e6437ca3d29282656763de");
return res;
}
public String queryOneDataTypeTest() {
String res = dao.queryOneDataType("eef8f40402e6437ca3d29282656763de", "humi");
return res;
}
public int queryProjectIdByDevkeyTest() {
int res = dao.queryProjectIdByDevkey("b12c86db4a1f40db8595737fe3f47520");
return res;
}
public String queryUserKeyByProjectIdTest() {
String res = dao.queryUserKeyByProjectId(1000000);
return res;
}
public String addOpenAppTest() {
String res = dao.addOpenApp("3d090918d4704a318054ca9157e8af75", "415a26bf5fb14a4bb8f6b2c02739eedd");
return res;
}
public String addOpenDeviceTest() {
String res = dao.addOpenDevice("415a26bf5fb14a4bb8f6b2c02739eeww", "415a26bf5fb14a4bb8f6b2c02739eeqq");
return res;
}
public int updateApplyStateByAppkeyTest() {
int res = dao.updateApplyStateByAppkey("415a26bf5fb14a4bb8f6b2c02739eegg", "审核通过");
return res;
}
public int updateApplyStateByDevicekeyTest() {
int res = dao.updateApplyStateByDevicekey("415a26bf5fb14a4bb8f6b2c02739eeqq", "审核通过");
return res;
}
public String queryOpenAppByUserKeyTest() {
String res = dao.queryOpenAppByUserKey("415a26bf5fb14a4bb8f6b2c02739eedd");
return res;
}
public String queryOpenDeviceByDevicekeyTest() {
String res = dao.queryOpenDeviceByDevicekey("415a26bf5fb14a4bb8f6b2c02739eeqq");
return res;
}
public String queryAllOpenAppTest() {
String res = dao.queryAllOpenApp();
return res;
}
public String queryDeviceByAppkeyTest() {
String res = dao.queryDeviceByAppkey("3d090918d4704a318054ca9157e8af75");
return res;
}
public String queryUserNameByUserkeyTest() {
String res = dao.queryUserNameByUserkey("c3682eaa73f54b96a3e3897682b56016");
return res;
}
public String queryOpenAppByApplystateTest() {
String res = dao.queryOpenAppByApplystate("申请中");
return res;
}
public int queryCountByApplykeyandUserkeyTest() {
int res = dao.queryCountByApplykeyandUserkey("6cca210be02b4804b65bd19ea2fda103",
"9de089c60f374fe5be7b9f0cf1206313");
return res;
}
public int queryCountByApplykeyandDevicekeyTest() {
int res = dao.queryCountByApplykeyandDevicekey("6cca210be02b4804b65bd19ea2fda103",
"a41e7aec6ac24d68b35ff621fa9c1689");
return res;
}
public String addThirdUserTest() {
String res = dao.addThirdUser("6cca210be02b4804b65bd19ea2fda103", "415a26bf5fb14a4bb8f6b2c02739eedd");
return res;
}
public String queryThirdApplyAppByUserkeyTest() {
String res = dao.queryThirdApplyAppByUserkey("1bcc391563034cd0adc929f0ecbd8b51");
return res;
}
public int updateApplyStateByAppkeyandUserkeyTest() {
int res = dao.updateApplyStateByAppkeyandUserkey("同意", "6cca210be02b4804b65bd19ea2fda103",
"415a26bf5fb14a4bb8f6b2c02739eedd");
return res;
}
public String queryThirdAppByUserkeyTest() {
String res = dao.queryThirdAppByUserkey("9de089c60f374fe5be7b9f0cf1206313");
return res;
}
public int queryCountByAppkeyandUserkeyTest() {
int res = dao.queryCountByAppkeyandUserkey("6cca210be02b4804b65bd19ea2fda103",
"415a26bf5fb14a4bb8f6b2c02739eedd");
return res;
}
public String getGatewayCurrentValueTest() {
String res = dao.getGatewayCurrentValue();
return res;
}
public Device getDeviceByDevkeyTest() {
Device res = dao.getDeviceByDevkey("3c65ba4a411b4d6197ee46fd3e8d045d");
return res;
}
public String findDevicesByIpTest() {
String res = dao.findDevicesByIp("192.168.1.108");
return res;
}
public String getDeviceDataCurrentValueTest() {
String res = dao.getDeviceDataCurrentValue("b7f3efdeea514d8a9454b510dd10a1fb");
return res;
}
public String getLocationTest() {
String res = dao.getLocation("25");
return res;
}
public String getIpByDevkeyTest() {
String res = dao.getIpByDevkey("3c65ba4a411b4d6197ee46fd3e8d045d");
return res;
}
public String getRelationidByDevkeyTest() {
String res = dao.getRelationidByDevkey("3c65ba4a411b4d6197ee46fd3e8d045d");
return res;
}
public String addConfigTest() {
String res = dao.addConfig("3c65ba4a411b4d6197ee46fd3e8d045d", "S:N=801002#NCTR@Period=10sE");
return res;
}
public String getRecentConfigValuesByDevkeyTest() {
String res = dao.getRecentConfigValuesByDevkey("3c65ba4a411b4d6197ee46fd3e8d045d");
return res;
}
public String configLocalTest() {
String res = dao.configLocal("10.10.25.89", "20000", "S:N=801002@Find=0E;");
return res;
}
public String getDeviceByIpTest() {
String res = dao.getDeviceByIp("10.10.25.89");
return res;
}
public String getOldDataByRangeTest() {
String res = dao.getOldDataByRange(326, 391);
return res;
}
public String configTest() {
String res = dao.controlHeartBeat("7e4e5ff11f014041a8975399ad08c02b", "S:N=801003#NCTR@Find=1E");
return res;
}
public String getLastFreAndPowerBydevkeyTest() {
String res = dao.getLastFreAndPowerBydevkey("835c80380a1d45668c41e20248f761d5");
return res;
}
public String getFreAndPowerBydevkeyAndTimeTest() {
String res = dao.getFreAndPowerBydevkeyAndTime("2017-4-9 20:45:00", "835c80380a1d45668c41e20248f761d5", "3",
"33");
return res;
}
public String getPowerAndTimeBydevkeyAndFreTest() {
String res = dao.getPowerAndTimeBydevkeyAndFre("601001", "26.5");
return res;
}
public String addDeviceTest() {
String res = dao.addDevice("1", "1", "1", "1", "1", "1", "1", "1", "1", "1");
return res;
}
public String selectTimeFromFreTest() {
String res = dao2.selectTimeFromFre("bbfe374c29d245a48920d99dfb27e8c1");
return res;
}
public String getTenTimePowerAndTimeBydevkeyAndFreTest() {
String res = dao2.getTenTimePowerAndTimeBydevkeyAndFre("bbfe374c29d245a48920d99dfb27e8c1");
return res;
}
public String controlFrequencyPeriodTest() {
String res = dao.controlFrequencyPeriod("S:N=835c80380a1d45668c41e20248f761d5@NCONF@Period=100sE;");
return res;
}
public String getFrequencyDevice() {
String res = dao2.getFrequencyDevice();
return res;
}
public String selectLastTenData() {
String res = dao2.selectLastTenData("835c80380a1d45668c41e20248f761d5");
return res;
}
public String SelectAdapterRealstate() {
String res = dao.SelectAdapterRealstate();
return res;
}
public String getAdapterHistoryByReltionid() {
String res = dao.getAdapterHistoryByReltionid("74");
return res;
}
public String parkingInfo() {
String res = dao.parkingInfo();
return res;
}
public String SensorValueGet() {
String res = dao.SensorValueGet("3c65ba4a411b4d6197ee46fd3e8d045d", "Temp");
System.out.println(res);
return res;
}
public String SensorControl() {
String res = dao.SensorControl("21", "23", "Temp", "3c65ba4a411b4d6197ee46fd3e8d045d",
"9c0b27c9e54b4db5aea08d889e38c346");
System.out.println(res);
return res;
}
public String Sendmessage() {
String apikey = "5055392273789589e01dc3fb2c23217c";
String text = "【云片网】您的验证码是12345678";
// 修改为您要发送的手机号
String mobile = "15005186909";
String res = SendMessage.singleSend(apikey, text, mobile);
System.out.println(res);
return res;
}
public static void main(String[] args) {
// new WS_Test().queryProjectsTest();
// new WS_Test().queryDevicesTest();
// new WS_Test().queryDataTypeTest();
// new WS_Test().getRecentValuesTest();
// new WS_Test().changeShowTypeTest();
// new WS_Test().queryDevicesNumTest();
// new WS_Test().queryDeviceInfoTest();
// new WS_Test().queryOneDataTypeTest();
// new WS_Test().queryProjectIdByDevkeyTest();
// new WS_Test().queryUserKeyByProjectIdTest();
// new WS_Test().addOpenAppTest();
// new WS_Test().addOpenDeviceTest();
// new WS_Test().updateApplyStateByAppkeyTest();
// new WS_Test().updateApplyStateByDevicekeyTest();
// new WS_Test().queryOpenAppByUserKeyTest();
// new WS_Test().queryOpenDeviceByDevicekeyTest();
// new WS_Test().queryAllOpenAppTest();
// new WS_Test().queryDeviceByAppkeyTest();
// new WS_Test().queryUserNameByUserkeyTest();
// new WS_Test().queryOpenAppByApplystateTest();
// new WS_Test().queryCountByApplykeyandUserkeyTest();
// new WS_Test().queryCountByApplykeyandDevicekeyTest();
// new WS_Test().addThirdUserTest();
// new WS_Test().queryThirdApplyAppByUserkeyTest();
// new WS_Test().updateApplyStateByAppkeyandUserkeyTest();
// new WS_Test().queryThirdAppByUserkeyTest();
// new WS_Test().queryCountByAppkeyandUserkeyTest();
// new WS_Test().getGatewayCurrentValueTest();
// new WS_Test().getDeviceByDevkeyTest();
new WS_Test().findDevicesByIpTest();
// new WS_Test().getDeviceDataCurrentValueTest();
// new WS_Test().getLocationTest();
// new WS_Test().getIpByDevkeyTest();
// new WS_Test().getRelationidByDevkeyTest();
// new WS_Test().addConfigTest();
// new WS_Test().getRecentConfigValuesByDevkeyTest();
// new WS_Test().configLocalTest();
// new WS_Test().getDeviceByIpTest();
// new WS_Test().getOldDataByRangeTest();
// new WS_Test().configTest();
// new WS_Test().getLastFreAndPowerBydevkeyTest();
// new WS_Test().getFreAndPowerBydevkeyAndTimeTest();
// new WS_Test().getPowerAndTimeBydevkeyAndFreTest();
// new WS_Test().addDeviceTest();
// new WS_Test().selectTimeFromFreTest();
// new WS_Test().getTenTimePowerAndTimeBydevkeyAndFreTest();
// new WS_Test().controlFrequencyPeriodTest();
// new WS_Test().getFrequencyDevice();
// new WS_Test().selectLastTenData();
// new WS_Test().SelectAdapterRealstate();
// new WS_Test().getAdapterHistoryByReltionid();
// new WS_Test().parkingInfo();
// new WS_Test().SensorValueGet();
// new WS_Test().SensorControl();
// new WS_Test().Sendmessage();
}
}
|
package ch22.ex22_11;
public class Mul extends SimpleTreeNode<String> {
Mul(SimpleTreeNode<String> parent) {
super(parent, "*");
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
/**
* MmaLagdaysZongjian generated by hbm2java
*/
public class MmaLagdaysZongjian implements java.io.Serializable {
private MmaLagdaysZongjianId id;
public MmaLagdaysZongjian() {
}
public MmaLagdaysZongjian(MmaLagdaysZongjianId id) {
this.id = id;
}
public MmaLagdaysZongjianId getId() {
return this.id;
}
public void setId(MmaLagdaysZongjianId id) {
this.id = id;
}
}
|
package utility;
import com.sun.xml.internal.ws.api.ha.StickyFeature;
import utility.Complex;
import java.io.*;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
public class Utility {
public static void writeToFile (String filename, int[]x) throws IOException{
// code from: https://stackoverflow.com/questions/13707223/how-to-write-an-array-to-a-file-java
BufferedWriter outputWriter = null;
outputWriter = new BufferedWriter(new FileWriter(filename));
for (int i = 0; i < x.length; i++) {
// Maybe:
outputWriter.write(x[i]+"");
// Or:
// outputWriter.write(Integer.toString(x[i]));
outputWriter.newLine();
}
outputWriter.flush();
outputWriter.close();
}
public static int getHighestAmplitude(byte[] audio) throws IOException{
int[] amplitudes = new int[audio.length];
int maxSoFar = 0;
for (int i = 0; i < audio.length; i++) {
amplitudes[i] = audio[i];
if (Math.abs(audio[i]) > maxSoFar)
maxSoFar = audio[i];
}
writeToFile("amplitudes.txt", amplitudes);
return maxSoFar;
}
public static Complex[][] performFFT(byte[] audio) {
final int audioTotalSize = audio.length;
final int chunkSize = 4096; // the chunk size in bytes
int numOfChunks = audioTotalSize / chunkSize;
Complex[][] fftResult = new Complex[numOfChunks][]; // The results of performing the FFT
// For all the chunks of the data
for (int chunkNumber = 0; chunkNumber < numOfChunks; chunkNumber++) {
Complex[] chunkToComplexArray = new Complex[chunkSize];
// Each byte in that chunk is converted to a complex number, and then the FFT is performed on that chunk
for (int i = 0; i < chunkSize; i++) {
chunkToComplexArray[i] = new Complex(audio[(chunkSize * chunkNumber) + i], 0);
}
fftResult[chunkNumber] = FFT.fft(chunkToComplexArray); // Performing the FFT and adding the results
}
System.out.println("In [performFFT]: FFT analysis done");
return fftResult;
}
public static ArrayList<int[]> extractAllMainFrequencies(Complex[][] allChunks) {
ArrayList<int[]> allMajorFreqs = new ArrayList<>();
for (Complex[] chunkFreqs: allChunks) {
int[] chunkMajorFreqs = extractChunkMajorFrequencies(chunkFreqs);
allMajorFreqs.add(chunkMajorFreqs);
}
System.out.println("In [extractAllMainFrequencies]: all major frequencies extracted");
return allMajorFreqs;
}
private static int[] extractChunkMajorFrequencies(Complex[] chunkAllFrequencies) {
/* This extracts the frequencies with the highest amplitude in the given chunk. To keep the implementation simple,
we have chosen to simply consider frequencies in specified intervals as they are the most common in the case of
music. For each range, we keep the frequency with the highest amplitude as the representative of that interval,
which will be later used as unique features for that song.
*/
final int HIGHEST_FREQ = 300;
final int[] FREQ_RANGE = new int[] {40, 80, 120, 180, HIGHEST_FREQ + 1};
double[] highestMagnitudes = new double[FREQ_RANGE.length]; // Containing the highest magnitude values
int[] highestMagnitudeFreqs = new int[FREQ_RANGE.length]; // Containing the corresponding frequencies
for (int freq = 1; freq < HIGHEST_FREQ - 1; freq++) {
double freqMagnitude = Math.log(chunkAllFrequencies[freq].abs() + 1);
// Take the logarithm to make it easier to work with. Note: that 1 added is to prevent facing log(0)
int index = getFreqRange(freq, FREQ_RANGE);
if (freqMagnitude > highestMagnitudes[index]) { // If the magnitude is the highest than what is seen so far
highestMagnitudes[index] = freqMagnitude;
highestMagnitudeFreqs[index] = freq;
}
}
return highestMagnitudeFreqs;
}
private static int getFreqRange(int freq, int[] freqRange) { // Returns the index of the interval to which the frequency belongs
int idx = 0;
while (freqRange[idx] < freq) idx++;
return idx;
}
public static String getChunkFingerprint(int[] chunk) {
// Returns the fingerprint of a given chunk by concatinating the major frequencies in that chunk
StringBuilder stringBuilder = new StringBuilder();
for (int freq : chunk)
// fingerprint += freq;
stringBuilder.append(freq);
return stringBuilder.toString();
}
public static void printHashMap(HashMap<String, ArrayList<MusicSegment>> map) {
System.out.println("\n============================ HashMap ============================");
for (String fingerprint: map.keySet()) {
ArrayList<MusicSegment> musicSegments = map.get(fingerprint);
StringBuilder stringBuilder = new StringBuilder("[fingerprint=");
stringBuilder.append(fingerprint);
stringBuilder.append(": ");
for (MusicSegment musicSegment : musicSegments) {
String tempStr = "(chunkNumber=" + musicSegment.getChunkNumber()
+ ", musicID='" + musicSegment.getMusicID() + "') ";
stringBuilder.append(tempStr);
}
System.out.println(stringBuilder.toString());
}
System.out.println("=================================================================\n");
}
public static void saveHashMap(HashMap<String, ArrayList<MusicSegment>> map) { // Serializing a hash map into a file
try {
FileOutputStream fileOutputStream = new FileOutputStream("map.ser");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(map);
objectOutputStream.close();
fileOutputStream.close();
System.out.println("In [saveHashMap]: Serialized HashMap data saved to map.ser");
} catch (IOException e) {
e.printStackTrace();
}
}
public static HashMap<String, ArrayList<MusicSegment>> loadHashMap() {
HashMap<String, ArrayList<MusicSegment>> map = null;
try {
FileInputStream fileInputStream = new FileInputStream("map.ser");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
map = (HashMap) objectInputStream.readObject();
objectInputStream.close();
fileInputStream.close();
System.out.println("In [loadHashMap]: Serialized HashMap data loaded from map.ser");
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return map;
}
public static void addNewSongToDB(ArrayList<int[]> allChunks, String musicID) { // allChunks: all the chunks of the given song
HashMap<String, ArrayList<MusicSegment>> map = loadHashMap(); // Load the DB
for (int chunkNumber = 0; chunkNumber < allChunks.size(); chunkNumber++) { // For each chunk in the music
String fingerprint = getChunkFingerprint(allChunks.get(chunkNumber)); // Get the fingerprint of that chunk
MusicSegment musicSegment = new MusicSegment(chunkNumber, musicID); // Create the corresponding data point
if (!map.containsKey(fingerprint)) { // If the fingerprint does not already exist
ArrayList<MusicSegment> musicSegments = new ArrayList<>();
musicSegments.add(musicSegment);
map.put(fingerprint, musicSegments); // Add it along with the music to which it corresponds
}
else { // If the fingerprint already exists
ArrayList<MusicSegment> musicSegments = map.get(fingerprint); // Get the current list
musicSegments.add(musicSegment); // Update the list
map.put(fingerprint, musicSegments);
}
}
saveHashMap(map); // Save the DB
System.out.println("In [addNewSongToDB]: new song added");
}
}
|
package main.java.sample;
import com.basho.riak.client.api.annotations.RiakBucketName;
import com.basho.riak.client.api.annotations.RiakKey;
import com.basho.riak.client.core.query.Namespace;
public class Person
{
// The @RiakKey annotation marks the field you want to use as the Key in Riak
@RiakKey
private String name;
@RiakBucketName
private String riakBucketName = "people";
private String address;
private String phone;
public Person() {}
public Person(String name, String address, String phone)
{
this.name = name;
this.address = address;
this.phone = phone;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getAddress()
{
return address;
}
public void setAddress(String address)
{
this.address = address;
}
public String getPhone()
{
return phone;
}
public void setPhone(String phone)
{
this.phone = phone;
}
Namespace getPersonNamespace()
{
return new Namespace(riakBucketName);
}
}
|
package com.bingo.code.example.design.abstractfactory.design;
public interface AbstractProductB {
}
|
package net.drs.myapp.model;
public class ResetPasswordDTO {
}
|
package com.github.mfriedenhagen.spocktest;
import groovy.xml.StaxBuilder;
import groovy.xml.StreamingDOMBuilder;
import org.junit.runner.notification.RunListener;
import java.io.File;
public class XmlRunListener extends RunListener {
private final File targetDir;
public XmlRunListener(File targetDir) {
this.targetDir = targetDir;
targetDir.mkdirs();
//new StaxBuilder()
}
}
|
public class Block {
private int tag;
private boolean isValid;
private int recentUse; // higher values are more recently used
private String[] bytedata;
public Block(int blocksize){
isValid = false;
recentUse = 0; //
bytedata = new String[blocksize];
}
public String read(int offset, int useCounter) {
recentUse = useCounter;
if(bytedata[offset] == null){
return "00";
}
else
return bytedata[offset];
}
public void write(int offset, String data, int useCounter) {
recentUse = useCounter;
bytedata[offset] = data;
isValid = true;
}
public void writeBlock(int tag, String[] data,int usecounter) {
this.tag = tag;
this.bytedata = data;
isValid = true;
recentUse = usecounter;
}
public String[] readAllData() {
return bytedata;
}
protected int getTag() {
return tag;
}
protected int getRecentUse() {
return recentUse;
}
protected boolean isValid() {
return isValid;
}
}
|
package ru.alxant.converter;
/**
* Created by Alxant on 10.03.2018.
*/
public class Address {
private String street;
private String home;
//private String housing; // корпус
private String apartment;
public Address(String street, String home, String apartment) {
this.street = street;
this.home = home;
this.apartment = apartment;
}
public String getStreet() {
return street;
}
public String getHome() {
return home;
}
public String getApartment() {
return apartment;
}
@Override
public String toString() {
return "Address{" +
"street='" + street + '\'' +
", home='" + home + '\'' +
", apartment='" + apartment + '\'' +
'}';
}
}
|
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
// write your code here
int n;
Scanner obj = new Scanner(System.in);
n = obj.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)
{
arr[i]=obj.nextInt();
}
//int ans = climbSt(0,n,arr);
int dp[]=new int[n+1];
Arrays.fill(dp,0);
int ans= climbstMem(0,n,arr,dp);//through memoization
System.out.println(ans);
}
static int climbSt(int src,int dest , int []arr)
{
if(src>dest)
return 0;
if(src==dest)
return 1;
int totalpaths=0;
for(int jumps=1;jumps<=arr[src];jumps++)
{
int path = climbSt(src+jumps,dest,arr);
totalpaths = totalpaths+path;
}
return totalpaths;
}
static int climbstMem(int src , int dest,int []arr,int []dp)
{
if(src>dest)
return 0;
if(src==dest)
return 1;
if(dp[src]!=0)
return dp[src];
int totalpaths=0;
for(int jumps=1;jumps<=arr[src];jumps++)
{
int path =climbstMem(src+jumps,dest,arr,dp);
totalpaths=totalpaths+path;
}
dp[src]=totalpaths;
return totalpaths;
}
}
|
import ij.*;
import ij.process.*;
import ij.gui.*;
import java.awt.*;
import ij.plugin.filter.*;
// Increase contrast 50%.
public class SO_IncreaseContrast50 implements PlugInFilter {
final float CONTRAST_INCREASE = 1.5f;
ImagePlus imp;
public int setup(String arg, ImagePlus imp) {
this.imp = imp;
return DOES_8G;
}
public void run(ImageProcessor ip) {
int w = ip.getWidth();
int h = ip.getHeight();
for (int v = 0; v < h; v++)
{
for (int u = 0; u < w; u++)
{
int p = (int) ((float) ip.get(u, v) * CONTRAST_INCREASE + 0.5f);
if (p > 255)
p = 255;
ip.set(u, v, p);
}
}
}
}
|
package com.example.locationapp;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.example.locationapp.Tasks.UpdateLocationTask;
public class MainActivity extends AppCompatActivity implements LocationListener{
private String username;
private FragmentRefreshListener fragmentRefreshListener;
private boolean wantLocationUpdates;
private static final String UPDATES_BUNDLE_KEY = "WantsLocationUpdates";
private TextView gpsLocation;
public static final int PERMISSION_REQUEST_CODE = 1;
private Location lastKnownLocation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = getIntent().getStringExtra("username");
TextView loggedinUsers = (TextView) this.findViewById(R.id.textView);
loggedinUsers.append(" ");
loggedinUsers.append(username);
Button updateButton = (Button) this.findViewById(R.id.updateLocation_button);
Button getLocationButton = (Button) this.findViewById(R.id.getLocation_button);
updateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
attemptUpdate();
}
});
getLocationButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
attemptGetLocation();
}
});
gpsLocation = (TextView) findViewById(R.id.gpsLocation);
if (savedInstanceState != null
&& savedInstanceState.containsKey(UPDATES_BUNDLE_KEY))
wantLocationUpdates
= savedInstanceState.getBoolean(UPDATES_BUNDLE_KEY);
else // activity is not being reinitialized from prior start
wantLocationUpdates = false;
if (!hasLocationPermission())
{
gpsLocation.setText(R.string.permissions_denied);
Log.w(MainActivity.class.getName(),
"Location permissions denied");
}
}
public void attemptUpdate() {
if (wantLocationUpdates)
{
wantLocationUpdates = false;
stopGPS();
}
else
{
wantLocationUpdates = true;
startGPS();
if (!Double.toString(lastKnownLocation.getLongitude()).equals(null)) {
UpdateLocationTask updateLocationTask = new UpdateLocationTask(this);
updateLocationTask.execute(Double.toString(lastKnownLocation.getLongitude()), Double.toString(lastKnownLocation.getLatitude()), username);
}
}
}
public void attemptGetLocation() {
if(getFragmentRefreshListener()!= null){
getFragmentRefreshListener().onRefresh();
}
}
//For refreshing lists of Location Fragments
public FragmentRefreshListener getFragmentRefreshListener() {
return fragmentRefreshListener;
}
public void setFragmentRefreshListener(FragmentRefreshListener fragmentRefreshListener) {
this.fragmentRefreshListener = fragmentRefreshListener;
}
public interface FragmentRefreshListener{
void onRefresh();
}
//Location-based methods
private boolean hasLocationPermission()
{
int permissionCheck = ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionCheck == PackageManager.PERMISSION_GRANTED)
{
return true;
}
else
{
if (ActivityCompat.shouldShowRequestPermissionRationale
(this, Manifest.permission.ACCESS_FINE_LOCATION))
{
new AlertDialog.Builder(this)
.setTitle(R.string.request_permission_title)
.setMessage(R.string.request_permission_text)
.setPositiveButton(
R.string.request_permission_positive,
new DialogInterface.OnClickListener()
{
@Override
public void onClick
(DialogInterface dialogInterface, int i)
{
ActivityCompat.requestPermissions
(MainActivity.this,new String[]
{Manifest.permission.
ACCESS_FINE_LOCATION},
PERMISSION_REQUEST_CODE);
}
})
.create()
.show();
}
else
{
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSION_REQUEST_CODE);
}
return false;
}
}
public static String convertDoubleToString(double doubleValue)
{
return String.valueOf(doubleValue);
}
private void startGPS()
{
LocationManager locationManager = (LocationManager)
this.getSystemService(Context.LOCATION_SERVICE);
try
{
String provider = LocationManager.GPS_PROVIDER;
locationManager.requestLocationUpdates(provider,0,0, (LocationListener) this);
lastKnownLocation
= locationManager.getLastKnownLocation(provider);
if (lastKnownLocation != null) {
String longitude = convertDoubleToString(lastKnownLocation.getLongitude());
String latitude = convertDoubleToString(lastKnownLocation.getLatitude());
String userLocation = "Longitude: " +longitude+ ", Latitude: " + latitude;
gpsLocation.setText(userLocation);
}
}
catch (SecurityException e)
{
gpsLocation.setText(R.string.permissions_denied);
Log.w(MainActivity.class.getName(),
"Security Exception: " + e);
}
}
private void stopGPS()
{
LocationManager locationManager = (LocationManager)
this.getSystemService(Context.LOCATION_SERVICE);
locationManager.removeUpdates((LocationListener) this);
}
@Override
public void onResume()
{
super.onResume();
int permissionCheck = ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (wantLocationUpdates
&& permissionCheck == PackageManager.PERMISSION_GRANTED)
startGPS();
}
@Override
public void onPause()
{
super.onPause();
// stop location updates while the activity is paused
int permissionCheck = ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionCheck == PackageManager.PERMISSION_GRANTED)
stopGPS();
}
// called when activity is about to be killed to save app state
@Override
public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putBoolean(UPDATES_BUNDLE_KEY, wantLocationUpdates);
}
// implementation of onLocationChanged method
public void onLocationChanged(Location location)
{
String longitude = convertDoubleToString(lastKnownLocation.getLongitude());
String latitude = convertDoubleToString(lastKnownLocation.getLatitude());
String userLocation = " Longitude: " +longitude+ " \n Latitude: " + latitude;
Log.d("userlocation", userLocation);
gpsLocation.setText(userLocation);
// gpsLocation.setText(location.toString());
// Log.i(MainActivity.class.getName(), "Location: "+location);
}
// implementation of onProviderDisabled method
public void onProviderDisabled(String provider)
{
gpsLocation.setText(R.string.provider_disabled);
}
// implementation of onProviderEnabled method
public void onProviderEnabled(String provider)
{
gpsLocation.setText(R.string.provider_enabled);
}
// implementation of onStatusChanged method
public void onStatusChanged(String provider, int status,
Bundle extras)
{
gpsLocation.setText(R.string.provider_status_changed);
}
} |
package com.akikun.leetcode.algorithm;
/**
* the two solutions of Fibonacci
*/
public class Fibonacci {
public static void main(String[] args) {
Fibonacci test = new Fibonacci();
int ans1, ans2;
long start, end;
int n = 45;
start = System.currentTimeMillis();
ans2 = test.iteration(n);
end = System.currentTimeMillis();
System.err.println("iteration answer: " + ans2 +", time: " + (end - start));
start = System.currentTimeMillis();
ans1 = test.recursion(n);
end = System.currentTimeMillis();
System.err.println("recursion answer: " + ans1 +", time: " + (end - start));
}
int recursion(int n) {
if (n == 1 || n == 2) {
return 1;
}
return recursion(n - 1) + recursion(n - 2);
}
int iteration(int n) {
if (n == 1 || n == 2) {
return 1;
}
n -= 2;
int a = 1, b = 1;
int temp;
for (int i = 0; i < n; ++i) {
temp = a + b;
a = b;
b = temp;
}
return b;
}
}
|
package arrays;
public class arrays {
public static void main(String[] args) {
String[] color = new String[3];
color[0] = "Red";
color[1] = "Green";
color[2] = "Blue";
String lastColor = color[color.length - 2];
System.out.println("Third color " + lastColor);
color[1] = ("White");
for (int index = 0; index < color.length; index++) {
System.out.println("Color: " + color[index]);
}
}
}
|
package ga.islandcrawl.controller;
import java.util.ArrayList;
import ga.islandcrawl.building.LookupCost;
import ga.islandcrawl.draw.Oval;
import ga.islandcrawl.draw.Renderer;
import ga.islandcrawl.form.Animation.Rain;
import ga.islandcrawl.form.Animation.Scatter;
import ga.islandcrawl.formation.StockFormation;
import ga.islandcrawl.map.Dimension;
import ga.islandcrawl.map.Map;
import ga.islandcrawl.map.O;
import ga.islandcrawl.map.Observer;
import ga.islandcrawl.map.Time;
import ga.islandcrawl.object.AdvObject;
import ga.islandcrawl.object.Item;
import ga.islandcrawl.object.Projectile;
import ga.islandcrawl.object.StockObject;
import ga.islandcrawl.object.unit.Man;
import ga.islandcrawl.object.unit.Unit;
import ga.islandcrawl.state.Animation;
import ga.islandcrawl.state.Fire;
/**
* Created by Ga on 1/30/2016.
*/
public enum Commands {
menu(new String[] { //Player only interface
"Craft",
"Status",
"Cheat",
"Options"
}){
@Override
public void show(O h){
String[] result = commands;
host = h;
if (h.occupant instanceof Man){
Item t = ((Man) h.occupant).getItem();
if (t != null){
ArrayList<String> addCommands = t.tag.getCommands();
result = new String[commands.length + addCommands.size()];
for (int i=0;i<commands.length + addCommands.size();i++){
if (i < addCommands.size()){
result[i] = "Use "+t.name+" - "+addCommands.get(i);
}
else result[i] = commands[i - addCommands.size()];
}
}
}
Menu.build(1, result, "Menu");
}
},
interact(new String[] { //Player only interface
}){
@Override
public void show(O h){
host = h;
ArrayList<O> p = getPlayerHost().interactee;
String[] t = new String[p.size()];
String[] t2 = new String[p.size()];
for (int i=0;i<p.size();i++) {
t[i] = p.get(i).occupant.name;
t2[i] = ""+i;
}
Menu.build(1, t, t2, "Interact");
}
},
menuBuild(new String[] {
"Palisade",
"Campfire",
"Cauldron",
"Bed",
"Farm",
"Workshop",
"Forge"
}),
menuCraft(new String[] {
"Knife",
"Backpack",
"Ration",
"Lasso"
}),
menuCut(new String[] {
"Hammer",
"Spear",
"Axe",
"Pickaxe",
"Cloth",
"Arrow",
"Shield"
}),
menuOptions(new String[]{
"Save",
"Fastmode",
"FPS Cap On"
}),
menuCheat(new String[] {
"Time",
"State",
"Spawn",
"Morph",
"Spell",
"Teleport",
"Test",
"Test2"
}),
menuSpell(new String[] {
"Fireball",
"Immolate",
"Rain"
}),
menuState(new String[] {
"Renew",
"Speed",
"Glow"
}),
menuSpawn(new String[] {
"Ash",
"Stone",
"Log",
"Branch",
"Cauldron",
"Spear",
"Axe",
"Hammer",
"Knife",
"Vine",
"Kiwi",
"Native",
"Jaguar",
"Drillboar",
"Cave",
"Workshop",
"WallTile"
}),
menuTime(new String[] {
"Day",
"Night",
"Nextday"
}),
menuMorph(new String[] {
"Man",
"Native",
"Kiwi",
"Bird",
"Jaguar",
"Drillboar"
});
private static O host;
public String[] commands;
private static String commandGameThread;
Commands(String[] p){
commands = p;
}
public void show(O h){
host = h;
Menu.build(1, commands, "Menu");
}
public void replaceCommand(String p, String n){
String[] newMenu = new String[commands.length];
for (int i=0;i<commands.length;i++){
if (!commands[i].equals(p)) newMenu[i] = commands[i];
else newMenu[i] = n;
}
commands = newMenu;
}
private static Player getPlayerHost(){
return (Player)((Unit) host.occupant).brain;
}
private static AdvObject getHost(){
return (AdvObject) host.occupant;
}
public static void update(){ //Game Thread command
if (commandGameThread == null) return;
String[] cmd = commandGameThread.split(" ");
if (cmd[0].equals("Use")) {
itemCommand(commandGameThread.split(" - ")[1]);
}else if (cmd[0].equals("State")){
if (cmd[1].equals("Glow")) getHost().state.addEffect("Fire", new Fire(1, -1));
else if (cmd[1].equals("Renew")) getHost().state.renewStat();
else if (cmd[1].equals("Speed")) getHost().state.getRawStat("speed").doMult(3);
}else if (cmd[0].equals("Confirm")){
if (cmd[1].equals("Build")) StockObject.getWith("Building", cmd[2]).place(getHost().pos);
else if (cmd[1].equals("Craft")) StockObject.getWith("Building", cmd[2]).place(getHost().pos);
}else if (cmd[0].equals("Time")){
if (cmd[1].equals("Nextday")) Observer.timeEvent(Time.Midnight);
else if (cmd[1].equals("Day")){
Observer.overlay.setTime(Time.Day);
}
else if (cmd[1].equals("Night")) Observer.overlay.setTime(Time.Night);
}else if (cmd[0].equals("Spawn")){
StockObject.getWith(cmd[1], "*").place(getHost().pos, .1f);
}else if (cmd[0].equals("Morph")){
Unit t = (Unit) StockObject.getWith(cmd[1],"0").place(new O(host));
t.state.addEffect(getHost().state);
getHost().die();
t.getStatus().addEffect("Morph",new Animation(new Scatter(),10));
new Player(t);
}else if (cmd[0].equals("Option")){
if (cmd[1].equals("Fastmode")){
Observer.disableShader();
menuOptions.replaceCommand("Fastmode", "Fastmode Can't be Disabled");
}else if (cmd[1].equals("FPS Cap On")){
Renderer.gameSpeed = 35;
menuOptions.replaceCommand("FPS Cap On", "FPS Cap Off");
}else if (cmd[1].equals("FPS Cap Off")){
Renderer.gameSpeed = 0;
menuOptions.replaceCommand("FPS Cap Off","FPS Cap On");
}
}else if (cmd[0].equals("Cast")){
if (cmd[1].equals("Fireball")) new Projectile(new Oval(.1f,.1f,new float[]{1,.4f,0,1f}),getHost().pos.x,getHost().pos.y,getHost().getForm().getRotation(),100, getHost()).shoot(.01f);
else if (cmd[1].equals("Rain")) ((Unit)host.occupant).getStatus().addEffect("Rain",new Animation(new Rain()));
else if (cmd[1].equals("Immolate")){
ArrayList<O> t = Dimension.gatherSync(host, 2);
for (int i=0;i<t.size();i++){
if (t.get(i).occupant instanceof AdvObject) {
((AdvObject) t.get(i).occupant).state.addEffect("Fire", new Fire(1, -1));
}
}
}
}else if (cmd[0].equals("Cheat")){
if (cmd[1].equals("Teleport")) {
if (Map.mapName.equals("Island")) Map.changeMap("Cave");
else if (Map.mapName.equals("Cave")) Map.changeMap("Island");
}
else if (cmd[1].equals("Test")) StockFormation.getWith("building1", host);
else if (cmd[1].equals("Test2")){
command("Spawn Native", host);
return;
}
}
commandGameThread = null;
}
public static void command(String p){ //UI Thread command
String[] cmd = p.split(" ");
if (cmd[0].equals("Interact")){
getPlayerHost().interact(getPlayerHost().interactee.get(Integer.parseInt(cmd[1])));
} else if (cmd[0].equals("Menu")) {
if (cmd[1].equals("Cheat")) {
Menu.build(1, menuCheat.commands, "Cheat");
} else if (cmd[1].equals("Craft")) {
Menu.build(1, menuCraft.commands, "Craft");
} else if (cmd[1].equals("Options")){
Menu.build(1, menuOptions.commands, "Option");
} else if (cmd[1].equals("Build")) {
Menu.build(1, menuBuild.commands, "Build");
}
} else if (cmd[0].equals("Build") || cmd[0].equals("Craft")){
Menu.build(2, new String[]{"Confirm " + p, "Confirm"}, "Material Qualities Required:\n" + new LookupCost(cmd[1]));
} else if (cmd[0].equals("Cheat")){ //Not thread safe
if (cmd[1].equals("State")) Menu.build(1, menuState.commands, "State");
else if (cmd[1].equals("Time")) Menu.build(1, menuTime.commands, "Time");
else if (cmd[1].equals("Spawn")) Menu.build(1, menuSpawn.commands, "Spawn");
else if (cmd[1].equals("Morph")) Menu.build(1, menuMorph.commands, "Morph");
else if (cmd[1].equals("Spell")) Menu.build(1, menuSpell.commands, "Cast");
else commandGameThread = p;
} else commandGameThread = p;
}
public static void command(String p, O h){
host = h;
commandGameThread = p;
}
private static void itemCommand(String p){
Man h = ((Man)host.occupant);
if (p.equals("Consume")){
h.brain.setAction("Consume");
} else if (p.equals("Ignite")){
h.getItem().state.addEffect("Fire", new Fire(1, -1));;
} else if (p.equals("Cut")){
Menu.build(1, menuCut.commands, "Craft");
} else if (p.equals("Build")){
Menu.build(1, menuBuild.commands, "Build");
}
}
}
|
package com.digitalhouse.api_edmilson.product;
import javax.persistence.*;
@Entity
@Table
public class Product {
@Id
@SequenceGenerator(name = "student_sequence", sequenceName = "student_sequence", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "product_sequence")
private Integer ID;
@Column(nullable = false, length = 255)
private String description;
@Column(nullable = false, length = 255)
private String providerDescription;
@Column(nullable = false)
private double price;
public Product(){}
public Product(Integer ID, String description, String providerDescription, double price) {
this.ID = ID;
this.description = description;
this.providerDescription = providerDescription;
this.price = price;
}
public Product(String description, String providerDescription, double price) {
this.description = description;
this.providerDescription = providerDescription;
this.price = price;
}
@Override
public String toString() {
return "Product{" +
"ID=" + ID +
", description='" + description + '\'' +
", providerDescription='" + providerDescription + '\'' +
", price='" + price + '\'' +
'}';
}
public Integer getID() {
return ID;
}
public void setID(Integer ID) {
this.ID = ID;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getProviderDescription() {
return providerDescription;
}
public void setProviderDescription(String providerDescription) {
this.providerDescription = providerDescription;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
|
package com.mathpar.students.savchenko.exception;
public class WrongDimensionsException extends Exception {
public WrongDimensionsException() {
super("Matrix has wrong dimensions!");
}
}
|
package zm.gov.moh.common.submodule.form.model.widgetModel;
import java.io.Serializable;
import java.util.List;
public class WidgetSectionModel extends AbstractWidgetGroupModel implements Serializable {
public WidgetSectionModel(){
super();
}
public WidgetSectionModel(List<WidgetModel> components){
super(components);
}
}
|
package com.deltastuido.shared;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class JsonConverter {
public static Gson gson = new GsonBuilder().create();
public String obj2Json(Object src) {
return gson.toJson(src);
}
public <T> T json2Obj(String jsonStr, Class<T> clazz) {
return gson.fromJson(jsonStr, clazz);
}
}
|
package br.uff.ic.provmonitor.business;
import java.io.IOException;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Set;
import org.eclipse.jgit.util.StringUtils;
import br.uff.ic.provmonitor.dao.ArtifactInstanceDAO;
import br.uff.ic.provmonitor.dao.ExecutionStatusDAO;
import br.uff.ic.provmonitor.dao.factory.ProvMonitorDAOFactory;
import br.uff.ic.provmonitor.exceptions.ConnectionException;
import br.uff.ic.provmonitor.exceptions.DatabaseException;
import br.uff.ic.provmonitor.exceptions.ProvMonitorException;
import br.uff.ic.provmonitor.exceptions.ServerDBException;
import br.uff.ic.provmonitor.exceptions.VCSCheckOutConflictException;
import br.uff.ic.provmonitor.exceptions.vcsexceptions.VCSException;
import br.uff.ic.provmonitor.log.ProvMonitorLogger;
import br.uff.ic.provmonitor.model.ArtifactInstance;
import br.uff.ic.provmonitor.model.ExecutionCommit;
import br.uff.ic.provmonitor.model.ExecutionFilesStatus;
import br.uff.ic.provmonitor.model.ExecutionStatus;
import br.uff.ic.provmonitor.output.ProvMonitorOutputManager;
import br.uff.ic.provmonitor.properties.ProvMonitorProperties;
import br.uff.ic.provmonitor.vcsmanager.VCSManager;
import br.uff.ic.provmonitor.vcsmanager.VCSManagerFactory;
import br.uff.ic.provmonitor.vcsmanager.VCSWorkspaceMetaData;
import br.uff.ic.provmonitor.workspaceWatcher.PathAccessType;
import br.uff.ic.provmonitor.workspaceWatcher.WorkspaceAccessReader;
import br.uff.ic.provmonitor.workspaceWatcher.WorkspacePathStatus;
/**
* ProvMonitor retrospective business services.
*
* Class responsible to manage the retrospective provenance information gathering and register.
*
* @author Vitor C. Neves - vcneves@ic.uff.br
*
*/
public class RetrospectiveProvenanceBusinessServices {
/**
* Experiment execution initialization.
* @param experimentId Experiment identifier.
* @throws ProvMonitorException ProvMonitor base exception if problems occurs.
* <br /><br />
* <b>Update - Instead Use:</b> public static String initializeExperimentExecution(String experimentId, String experimentInstanceId, String sourceRepository, String workspacePath) throws ProvMonitorException.
*
*/
@Deprecated
public static void initializeExperimentExecution(String experimentId) throws ProvMonitorException{
//Record Timestamp
Date timeStampInitExecute = Calendar.getInstance().getTime();
SimpleDateFormat sf = new SimpleDateFormat("YYYYMMddHHmmssS");
String nonce = sf.format(timeStampInitExecute);
String experimentInstanceId = experimentId + nonce;
//Printing Generated Values
ProvMonitorOutputManager.appendMessageLine("ExperimentInstanceId: " + experimentInstanceId);
ProvMonitorOutputManager.appendMessageLine("BranchName: " + experimentInstanceId);
//Initialize DB
ProvMonitorDAOFactory daoFactory = new ProvMonitorDAOFactory();
daoFactory.getDatabaseControlDAO().dbInitialize();
//Repository clone
//Repository Branch
//System.out.println("initializeExperimentExecution end execution.");
}
/**
* Experiment execution initialization.
* <br /><br /><strong>Description:</strong>
* Responsible to clone central repository, prepare the workspace, prepare the needed infrastructure (database tables, embedded database services initialization, etc.) and when applied generate experiment instance id.
*
* @param experimentId Experiment identifier.
* @param experimentInstanceId Experiment execution/trial identifier. Optional parameter. If Null or Empty is informed, this will be auto generated and returned at the end of the method execution.
* @param sourceRepository Central repository URI path. Repository from workspace will be cloned.
* @param workspacePath Experiment workspace URI path.
*
* @return ExperimentInstanceId Auto generated when the parameter is null or empty, otherwise the same inputed value.
*
* @throws ProvMonitorException ProvMonitor base exception if some irrecoverable or runtime exception occurs.
* @throws DatabaseException Database related problems.
* @throws ConnectionException Database connection problems.
* @throws ServerDBException Database server related problems.
*/
public synchronized static String initializeExperimentExecution(String experimentId, String experimentInstanceId, String sourceRepository, String workspacePath) throws ProvMonitorException{
//If experimentInstanceId is not informed, generate it.
if (StringUtils.isEmptyOrNull(experimentInstanceId)){
experimentInstanceId = ProvMonitorBusinessHelper.generateExperimentInstanceId(experimentId);
}
//Printing Generated/received/considered values
ProvMonitorOutputManager.appendMessageLine("ExperimentInstanceId: " + experimentInstanceId);
ProvMonitorOutputManager.appendMessageLine("BranchName: " + experimentInstanceId);
ProvMonitorOutputManager.appendMessageLine("Workspace: " + workspacePath);
ProvMonitorOutputManager.appendMessageLine("CentralRepository: " + sourceRepository);
//Initialize DB
ProvMonitorDAOFactory daoFactory = new ProvMonitorDAOFactory();
daoFactory.getDatabaseControlDAO().dbInitialize();
//Workspace preparation
VCSManager vcsManager = VCSManagerFactory.getInstance();
//System.out.println("Cloning to: " + workspacePath);
Boolean workspaceAlreadyCreated = false;
//Verify if Workspace already exists. If not, clone it.
if (vcsManager.isWorkspaceCreated(workspacePath)){
workspaceAlreadyCreated = true;
}
if (workspaceAlreadyCreated){
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "initializeExperimentExecution", "Workspace already created.");
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "initializeExperimentExecution", "checking out canonical branch...");
vcsManager.checkout(workspacePath, ProvMonitorProperties.getInstance().getCanonicalBranchName());
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "initializeExperimentExecution", "Canonical branch checkout.");
}else{
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "initializeExperimentExecution", "Creating new workspace...");
//Checking out/Creating canonical workspace
try {
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "initializeExperimentExecution", "checking out canonical branch...");
vcsManager.checkout(sourceRepository, ProvMonitorProperties.getInstance().getCanonicalBranchName());
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "initializeExperimentExecution", "Canonical branch checkout.");
} catch(VCSCheckOutConflictException e){
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "initializeExperimentExecution", "Resolving checking out canonical branch's conflict...");
vcsManager.commit(sourceRepository, "Resolving checkout conflicts.");
vcsManager.checkout(sourceRepository, ProvMonitorProperties.getInstance().getCanonicalBranchName());
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "initializeExperimentExecution", "Checking out canonical branch's conflict resolver.");
} catch(VCSException e){
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "initializeExperimentExecution", "creating canonical branch...");
vcsManager.createBranch(sourceRepository, ProvMonitorProperties.getInstance().getCanonicalBranchName());
vcsManager.checkout(sourceRepository, ProvMonitorProperties.getInstance().getCanonicalBranchName());
vcsManager.commit(sourceRepository, "Creating canonical branch for trial: " + ProvMonitorProperties.getInstance().getCanonicalBranchName());
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "initializeExperimentExecution", "Canonical branch created.");
}
//Repository branch
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "initializeExperimentExecution", "Creating branch for trial:" + experimentInstanceId + ".");
vcsManager.createBranch(sourceRepository, experimentInstanceId);
//Repository checkOut
vcsManager.checkout(sourceRepository, experimentInstanceId);
//Repository commit new branch
vcsManager.commit(sourceRepository, "Creating branch for trial: " + experimentInstanceId);
//Repository clone
//cvsManager.cloneRepository(sourceRepository, workspacePath);
List<String> branches2Clone = new ArrayList<String>();
branches2Clone.add(ProvMonitorProperties.getInstance().getCanonicalBranchName());
branches2Clone.add(experimentInstanceId);
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "initializeExperimentExecution", "Workspace checkout. Cloning from:" + sourceRepository + " to: " + workspacePath +".");
vcsManager.cloneRepository(sourceRepository, workspacePath, branches2Clone);
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "initializeExperimentExecution", "New workspace created.");
}
//Repository branch
//cvsManager.createBranch(workspacePath, experimentInstanceId);
//Repository checkOut
//cvsManager.checkout(workspacePath, experimentInstanceId);
//System.out.println("initializeExperimentExecution end execution.");
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "initializeExperimentExecution", "Returning experiment instance id:" + experimentInstanceId + ".");
return experimentInstanceId;
}
/**
* Experiment execution finalization.
* <br /><br /><strong>Description:</strong>
* Responsible to register the end of the experiment execution, push back workspace to the central repository, and shut down the used infrastructure.
*
* @param experimentInstanceId Experiment execution/trial identifier.
* @param sourceRepository Central repository URI path. Repository from workspace will be cloned.
* @param workspacePath Experiment workspace URI path.
* @param endDateTime Experiment end date time execution.
*
* @return ExperimentInstanceId - Auto generated when the parameter is null or empty, otherwise the same inputed value.
*
* @throws ProvMonitorException ProvMonitor base exception if some irrecoverable or runtime exception occurs.
* @throws VCSException Version control system related problems.
* @throws DatabaseException Database related problems.
* @throws ConnectionException Database connection problems.
* @throws ServerDBException Database server related problems.
*/
public synchronized static void FinalizeExperimentExecution(String experimentInstanceId, String sourceRepository, String workspacePath, Date endDateTime) throws ProvMonitorException{
//Stop DB infra
ProvMonitorDAOFactory daoFactory = new ProvMonitorDAOFactory();
daoFactory.getDatabaseControlDAO().dbFinalize();
//Pushback Repository
VCSManager vcsManager = VCSManagerFactory.getInstance();
vcsManager.pushBack(workspacePath, sourceRepository);
}
/**
* Notify startup of a simple activity instance execution.
* <br /><br />
* <b>Update - Instead Use:</b> <br />
* public static void notifyActivityExecutionStartup(String activityInstanceId, String[] context, Date activityStartDateTime, String workspacePath) throws ProvMonitorException.
*/
@Deprecated
public static boolean notifyActivityExecutionStartup(String activityInstanceId, String[] context){
//Record Timestamp
return false;
}
public static void notifyActivityExecutionStartup(String activityInstanceId, String[] context, Date activityStartDateTime, String workspaceInput, String activationWorkspace) throws ProvMonitorException{
notifyActivityExecutionStartup(activityInstanceId, context, activityStartDateTime, workspaceInput, activationWorkspace, false);
}
public synchronized static void notifyActivityExecutionStartup(String activityInstanceId, String[] context, Date activityStartDateTime, String workspaceInput, String activationWorkspace, Boolean firstActivity) throws ProvMonitorException{
switch (ProvMonitorProperties.getInstance().getBranchStrategy()){
case TRIAL:
notifyActivityExecutionStartupBranchByTrial(activityInstanceId, context, activityStartDateTime, workspaceInput, activationWorkspace, firstActivity);
break;
case ACTIVITY:
notifyActivityExecutionStartupBranchByActivity(activityInstanceId, context, activityStartDateTime, workspaceInput, activationWorkspace, firstActivity);
break;
}
}
public synchronized static void notifyActivityExecutionStartupBranchByTrial(String activityInstanceId, String[] context, Date activityStartDateTime, String workspaceInput, String activationWorkspace, Boolean firstActivity) throws ProvMonitorException{
//Prepare ActivityObject to be persisted
ExecutionStatus elementExecStatus = getNewExecStatus(activityInstanceId, context, activityStartDateTime, null);
//Activity start clone
VCSManager vcsManager = VCSManagerFactory.getInstance();
//First activity Branching
if (firstActivity){ //CREATE OR CHECK OUT CANONICAL BRANCH
try{
//Try to checkOut - First activity of first trial may have the branch already created by ExperimentInit
vcsManager.checkout(workspaceInput, context[0]);
}catch(VCSException e1){
//Checking out/Creating canonical workspace
try {
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "notifyActivityExecutionStartupBranchByTrial", "checking out canonical branch...");
vcsManager.checkout(workspaceInput, ProvMonitorProperties.getInstance().getCanonicalBranchName());
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "notifyActivityExecutionStartupBranchByTrial", "Canonical checked out.");
} catch(VCSCheckOutConflictException e){
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "notifyActivityExecutionStartupBranchByTrial", "Resolving checking out canonical branch's conflict...");
vcsManager.commit(workspaceInput, "Resolving checkout conflicts.");
vcsManager.checkout(workspaceInput, ProvMonitorProperties.getInstance().getCanonicalBranchName());
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "notifyActivityExecutionStartupBranchByTrial", "Canonical branch checked out...");
} catch(VCSException e){
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "notifyActivityExecutionStartupBranchByTrial", "creating canonical branch...");
vcsManager.createBranch(workspaceInput, ProvMonitorProperties.getInstance().getCanonicalBranchName());
vcsManager.checkout(workspaceInput, ProvMonitorProperties.getInstance().getCanonicalBranchName());
vcsManager.commit(workspaceInput, "Creating canonical branch for trial: " + ProvMonitorProperties.getInstance().getCanonicalBranchName());
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "notifyActivityExecutionStartupBranchByTrial", "Canonical branch created.");
}
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "notifyActivityExecutionStartupBranchByTrial", "Creating branch for trial...");
//Repository branch
vcsManager.createBranch(workspaceInput, context[0]);
//Repository checkOut
vcsManager.checkout(workspaceInput, context[0]);
//Repository commit new branch
vcsManager.commit(workspaceInput, "Creating branch for trial: " + context[0]);
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "notifyActivityExecutionStartupBranchByTrial", "Branch for trial created.");
}
}//else{ //DO NORMAL EXECUTION.
//vcsManager.checkout(workspaceInput, context[0]);
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "notifyActivityExecutionStartupBranchByTrial", "Creating activation workspace. Cloning from: " + workspaceInput + " to: " + activationWorkspace + "...");
vcsManager.cloneRepository(workspaceInput, activationWorkspace);
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "notifyActivityExecutionStartupBranchByTrial", "Activation workspace created.");
//}
//TODO: Implement transaction control and atomicity for multivalued attributes.
//Persisting
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "notifyActivityExecutionStartupBranchByTrial", "Updating database...");
ProvMonitorDAOFactory factory = new ProvMonitorDAOFactory();
//factory.getActivityInstanceDAO().persist(activityInstance);
factory.getExecutionStatusDAO().persist(elementExecStatus);
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "notifyActivityExecutionStartupBranchByTrial", "Database updated.");
}
public synchronized static void notifyActivityExecutionStartupBranchByActivity(String activityInstanceId, String[] context, Date activityStartDateTime, String workspaceInput, String activationWorkspace, Boolean firstActivity) throws ProvMonitorException{
//Prepare ActivityObject to be persisted
ExecutionStatus elementExecStatus = getNewExecStatus(activityInstanceId, context, activityStartDateTime, null);
//Activity start clone
VCSManager vcsManager = VCSManagerFactory.getInstance();
//First activity Branching
if (firstActivity){ //CREATE OR CHECK OUT CANONICAL BRANCH
//Checking out/Creating canonical workspace
try {
vcsManager.checkout(workspaceInput, ProvMonitorProperties.getInstance().getCanonicalBranchName());
} catch(VCSCheckOutConflictException e){
vcsManager.commit(workspaceInput, "Resolving checkout conflicts.");
vcsManager.checkout(workspaceInput, ProvMonitorProperties.getInstance().getCanonicalBranchName());
} catch(VCSException e){
vcsManager.createBranch(workspaceInput, ProvMonitorProperties.getInstance().getCanonicalBranchName());
vcsManager.checkout(workspaceInput, ProvMonitorProperties.getInstance().getCanonicalBranchName());
vcsManager.commit(workspaceInput, "Creating canonical branch for trial: " + ProvMonitorProperties.getInstance().getCanonicalBranchName());
}
//Repository branch
vcsManager.createBranch(workspaceInput, context[0]);
//Repository checkOut
vcsManager.checkout(workspaceInput, context[0]);
//Repository commit new branch
vcsManager.commit(workspaceInput, "Creating branch for trial: " + context[0]);
}else{ //DO NORMAL EXECUTION.
//BranchName
String branchName = ContextHelper.getBranchNameFromContext(context);
//Repository branch
vcsManager.createBranch(workspaceInput, branchName);
//Repository checkOut
vcsManager.checkout(workspaceInput, branchName);
//Repository commit new branch
vcsManager.commit(workspaceInput, "Creating branch for activity: " + activityInstanceId + ". branch name: " + branchName);
//vcsManager.checkout(workspaceInput, context[0]);
vcsManager.cloneRepository(workspaceInput, activationWorkspace);
}
//TODO: Implement transaction control and atomicity for multivalued attributes.
//Persisting
ProvMonitorDAOFactory factory = new ProvMonitorDAOFactory();
//factory.getActivityInstanceDAO().persist(activityInstance);
factory.getExecutionStatusDAO().persist(elementExecStatus);
}
public synchronized static void notifyActivityExecutionEnding(String activityInstanceId, String[] context, Date activityStartDateTime, Date endActiviyDateTime, String workspaceRoot, String activationWorkspace) throws ProvMonitorException{
//Recover executionStatus element
ProvMonitorOutputManager.appendMessageLine("Starting ActivityExecutionEnding Method...");
//Mounting context
//Prepare ActivityObject to be persisted
ExecutionStatus elementExecStatus = getNewExecStatus(activityInstanceId, context, activityStartDateTime, endActiviyDateTime);
ProvMonitorDAOFactory factory = new ProvMonitorDAOFactory();
ExecutionStatusDAO execStatusDAO = factory.getExecutionStatusDAO();
ProvMonitorOutputManager.appendMessageLine("Getting activity by id: " + activityInstanceId);
ExecutionStatus elemExecutionStatus = execStatusDAO.getById(activityInstanceId, elementExecStatus.getElementPath());
if (elemExecutionStatus == null){
throw new ProvMonitorException("Element: " + activityInstanceId + " not found exception. Activity could not be finished if it was not started." );
}
if (activityStartDateTime == null){
activityStartDateTime = elemExecutionStatus.getStartTime();
elementExecStatus.setStartTime(activityStartDateTime);
}
//Record Timestamp
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "notifyActivityExecutionEnding", "Identifying accessed files...");
//Verify accessed files
Collection<ExecutionFilesStatus> execFiles = getAccessedFiles(elementExecStatus, activationWorkspace);
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "notifyActivityExecutionEnding", "Accessed files identified.");
//Commit changed files
StringBuilder message = new StringBuilder();
message.append("ActivityInstanceId:")
.append(activityInstanceId)
.append("; context:")
.append(elementExecStatus.getElementPath())
.append("; EndActivityCommit");
VCSManager vcsManager = VCSManagerFactory.getInstance();
//((GitManager)cvsManager).getStatus(workspacePath);
//VCSWorkspaceMetaData wkMetaDataStatus = vcsManager.getStatus(activationWorkspace);
//Set<String> test = wkMetaDataStatus.getCreated();
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "notifyActivityExecutionEnding", "Adding new files...");
VCSWorkspaceMetaData wkMetaDataAddAll = vcsManager.addAllFromPath(activationWorkspace);
Set<String> created = wkMetaDataAddAll.getCreated();
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "notifyActivityExecutionEnding", "Files added.");
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "notifyActivityExecutionEnding", "Removing files...");
Set<String> removed = vcsManager.removeAllFromPath(activationWorkspace);
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "notifyActivityExecutionEnding", "Files removed.");
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "notifyActivityExecutionEnding", "Cheking in changes...");
//String commitId = vcsManager.commit(activationWorkspace, message.toString());
VCSWorkspaceMetaData wkMetaData = vcsManager.commit(activationWorkspace, message.toString());
String commitId = wkMetaData.getCommidId();
Set<String> modified = wkMetaData.getChanged();
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "notifyActivityExecutionEnding", "Changes checked in.");
//update execution element
ProvMonitorOutputManager.appendMessageLine("Updating Activity properties: End DateTime....");
elemExecutionStatus.setEndTime(endActiviyDateTime);
ProvMonitorOutputManager.appendMessageLine("Updating Activity properties: Status....");
elemExecutionStatus.setStatus("ended");
//Recording Commit ID
//elemExecutionStatus.setCommitId(commitId);
ExecutionCommit execCommit = new ExecutionCommit();
execCommit.setCommitId(commitId);
execCommit.setCommitTime(endActiviyDateTime);
execCommit.setStatus("ActivityEnd");
execCommit.setElementId(elemExecutionStatus.getElementId());
execCommit.setElementPath(elemExecutionStatus.getElementPath());
//Joining all files changes to be persisted.
Collection<ExecutionFilesStatus> removedFiles = getRemovedFiles(removed, elementExecStatus, activationWorkspace);
Collection<ExecutionFilesStatus> createdFiles = getCreatedFiles(created, elementExecStatus, activationWorkspace);
Collection<ExecutionFilesStatus> modifiedFiles = getModifiedFiles(modified, elementExecStatus, activationWorkspace);
execFiles.addAll(removedFiles);
execFiles.addAll(createdFiles);
execFiles.addAll(modifiedFiles);
//persist updated element
ProvMonitorOutputManager.appendMessageLine("Persisting Activity...");
execStatusDAO.update(elemExecutionStatus);
factory.getExecutionCommitDAO().persist(execCommit);
ProvMonitorOutputManager.appendMessageLine("Activity Persisted.");
//Persist accessed files
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "notifyActivityExecutionEnding", "Persisting accessed files...");
for (ExecutionFilesStatus executionFileStatus: execFiles){
factory.getExecutionFileStatusDAO().persist(executionFileStatus);
}
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "notifyActivityExecutionEnding", "Files persisted.");
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "notifyActivityExecutionEnding", "Pushing back changes to: " + workspaceRoot + "...");
//Pushing back to the experiment root workspace
vcsManager.pushBack(activationWorkspace, workspaceRoot);
ProvMonitorLogger.debug(RetrospectiveProvenanceBusinessServices.class.getName(), "notifyActivityExecutionEnding", "Changes pushed back.");
}
private static ExecutionStatus getNewExecStatus(String activityInstanceId, String[] context,Date activityStartDateTime, Date activityEndDateTime){
ExecutionStatus elementExecStatus = new ExecutionStatus();
elementExecStatus.setElementId(activityInstanceId);
elementExecStatus.setElementType("activity");
elementExecStatus.setStatus("starting");
//Mounting context
StringBuilder elementPath = new StringBuilder();
for (String path: context){
if (elementPath.length()>0){
elementPath.append("/");
}
elementPath.append(path);
}
elementExecStatus.setElementPath(elementPath.toString());
//Record Timestamp
elementExecStatus.setStartTime(activityStartDateTime);
if (activityEndDateTime != null){
elementExecStatus.setEndTime(activityEndDateTime);
}
return elementExecStatus;
}
private static Collection<ExecutionFilesStatus> getAccessedFiles(ExecutionStatus elementExecStatus, String workspacePath){
//Reading accessedFiles
ArrayList<ExecutionFilesStatus> execFiles = new ArrayList<ExecutionFilesStatus>();
try{
//Collection<AccessedPath> accessedFiles = WorkspaceAccessReader.readAccessedPathsAndAccessTime(Paths.get(workspacePath), startActivityDateTime, true);
//Collection<WorkspacePathStatus>accessedFiles = WorkspaceAccessReader.readWorkspacePathStatusAndStatusTime(Paths.get(workspacePath), elementExecStatus.getStartTime(), true);
Collection<WorkspacePathStatus>accessedFiles = WorkspaceAccessReader.readAccessedPathStatusAndStatusTime(Paths.get(workspacePath), elementExecStatus.getStartTime(), true);
if (accessedFiles != null && !accessedFiles.isEmpty()){
for (WorkspacePathStatus acFile: accessedFiles){
ExecutionFilesStatus execFileStatus = new ExecutionFilesStatus();
execFileStatus.setFileAccessDateTime(acFile.getStatusDateTime());
execFileStatus.setFilePath(acFile.getPathName().replaceFirst("/", ""));
execFileStatus.setElementId(elementExecStatus.getElementId());
execFileStatus.setElementPath(elementExecStatus.getElementPath());
execFileStatus.setFiletAccessType(acFile.getPathStatusType().name());
//execFileStatus.setFiletAccessType(ExecutionFilesStatus.TYPE_READ);
execFiles.add(execFileStatus);
}
}
}catch(Exception e){
ProvMonitorLogger.warning("RetrospectiveProvenanceBusinessServices", "notifyActivityExecutionStartup", e.getMessage());
ProvMonitorOutputManager.appendMenssage("WARNING: RetrospectiveProvenanceBusinessServices: notifyActivityExecutionStartup" + e.getMessage());
}
return execFiles;
}
private static Collection<ExecutionFilesStatus> getRemovedFiles(Set<String> removed, ExecutionStatus elementExecStatus, String workspacePath){
//Registering removed files
ArrayList<ExecutionFilesStatus> execFiles = new ArrayList<ExecutionFilesStatus>();
if (removed != null && !removed.isEmpty()){
for (String removedPath: removed){
ExecutionFilesStatus execFileStatus = new ExecutionFilesStatus();
execFileStatus.setFileAccessDateTime(elementExecStatus.getStartTime());
execFileStatus.setFilePath(workspacePath.concat("/".concat(removedPath)));
execFileStatus.setElementId(elementExecStatus.getElementId());
execFileStatus.setElementPath(elementExecStatus.getElementPath());
execFileStatus.setFiletAccessType(PathAccessType.REMOVE.name());
execFiles.add(execFileStatus);
}
}
return execFiles;
}
private static Collection<ExecutionFilesStatus> getModifiedFiles(Set<String> removed, ExecutionStatus elementExecStatus, String workspacePath){
//Registering removed files
ArrayList<ExecutionFilesStatus> execFiles = new ArrayList<ExecutionFilesStatus>();
if (removed != null && !removed.isEmpty()){
for (String removedPath: removed){
ExecutionFilesStatus execFileStatus = new ExecutionFilesStatus();
execFileStatus.setFileAccessDateTime(elementExecStatus.getStartTime());
execFileStatus.setFilePath(workspacePath.concat("/".concat(removedPath)));
execFileStatus.setElementId(elementExecStatus.getElementId());
execFileStatus.setElementPath(elementExecStatus.getElementPath());
execFileStatus.setFiletAccessType(PathAccessType.CHANGE.name());
execFiles.add(execFileStatus);
}
}
return execFiles;
}
private static Collection<ExecutionFilesStatus> getCreatedFiles(Set<String> removed, ExecutionStatus elementExecStatus, String workspacePath){
//Registering removed files
ArrayList<ExecutionFilesStatus> execFiles = new ArrayList<ExecutionFilesStatus>();
if (removed != null && !removed.isEmpty()){
for (String removedPath: removed){
ExecutionFilesStatus execFileStatus = new ExecutionFilesStatus();
execFileStatus.setFileAccessDateTime(elementExecStatus.getStartTime());
execFileStatus.setFilePath(workspacePath.concat("/".concat(removedPath)));
execFileStatus.setElementId(elementExecStatus.getElementId());
execFileStatus.setElementPath(elementExecStatus.getElementPath());
execFileStatus.setFiletAccessType(PathAccessType.CREATE.name());
execFiles.add(execFileStatus);
}
}
return execFiles;
}
/**
* Notify startup of a simple activity instance execution.
*
* @param activityInstanceId Activity instance identifier.
* @param context Sequence of identifiers that defines a simple activity instance location in the experiment. (path, i.e.: Sub workflows that wraps the simple activity instance)
* @param activityStartDateTime Activity instance date time of startup execution.
* @param workspacePath Experiment workspace path.
*
* @throws ProvMonitorException ProvMonitor base exception if some irrecoverable or runtime exception occurs.
* @throws VCSException Version control system related problems.
* @throws DatabaseException Database related problems.
* @throws ConnectionException Database connection problems.
*/
public synchronized static void notifyActivityExecutionStartup(String activityInstanceId, String[] context, Date activityStartDateTime, String workspacePath) throws ProvMonitorException{
newNotifyActivityExecutionStartup(activityInstanceId, context, activityStartDateTime, workspacePath);
}
/**
* Notify startup of a composite activity instance execution.
* <br /><br />
* <b>Update - Instead Use:</b> <br />
* public static void notifyProcessExecutionStartup(String processInstanceId, String[] context, Date processStartDateTime, String workspacePath) throws ProvMonitorException.
*/
@Deprecated
public static boolean notifyProcessExecutionStartup(String processInstanceId, String[] context){
return false;
}
/**
* Notify startup of a composite activity instance execution.
*
* @param processInstanceId Process (composite activity) instance identifier.
* @param context Sequence of identifiers that defines a process instance location in the experiment. (path, i.e.: Sub workflows that wraps the simple activity instance)
* @param processStartDateTime Process instance date time of startup execution.
* @param workspacePath Experiment workspace path.
*
* @throws ProvMonitorException ProvMonitor base exception if some irrecoverable or runtime exception occurs.
* @throws VCSException Version control system related problems.
* @throws DatabaseException Database related problems.
* @throws ConnectionException Database connection problems.
*/
public static void notifyProcessExecutionStartup(String processInstanceId, String[] context, Date processStartDateTime, String workspacePath) throws ProvMonitorException{
notifyActivityExecutionStartup(processInstanceId, context, processStartDateTime, workspacePath);
}
/**
* Notify ending of a simple activity instance execution.
* <br /><br />
* <b>Update - Instead Use:</b> <br />
* public static void notifyActivityExecutionEnding(String activityInstanceId, String[] context, Date startActivityDateTime, Date endActiviyDateTime, String workspacePath) throws ProvMonitorException.
*/
@Deprecated
public static boolean notifyActivityExecutionEnding(String activityInstanceId, String[] context){
return false;
}
/**
* Notify ending of a simple activity instance execution.
*
* @param activityInstanceId Activity instance identifier.
* @param context Sequence of identifiers that defines a simple activity instance location in the experiment. (path, i.e.: Sub workflows that wraps the simple activity instance)
* @param activityStartDateTime Activity instance date time of startup execution.
* @param endActiviyDateTime Activity instance date time of ending execution.
* @param workspacePath Experiment workspace path.
*
* @throws ProvMonitorException ProvMonitor base exception if some irrecoverable or runtime exception occurs.
* @throws VCSException Version control system related problems.
* @throws DatabaseException Database related problems.
* @throws ConnectionException Database connection problems.
*/
public synchronized static void notifyActivityExecutionEnding(String activityInstanceId, String[] context, Date startActivityDateTime, Date endActiviyDateTime, String workspacePath) throws ProvMonitorException{
//Mounting context
StringBuilder elementPath = new StringBuilder();
for (String path: context){
if (elementPath.length()>0){
elementPath.append("/");
}
elementPath.append(path);
}
//Record Timestamp
//Verify accessed files
ArrayList<ExecutionFilesStatus> execFiles = new ArrayList<ExecutionFilesStatus>();
try{
//Collection<AccessedPath> accessedFiles = WorkspaceAccessReader.readAccessedPathsAndAccessTime(Paths.get(workspacePath), startActivityDateTime, true);
Collection<WorkspacePathStatus>accessedFiles = WorkspaceAccessReader.readWorkspacePathStatusAndStatusTime(Paths.get(workspacePath), startActivityDateTime, true);
if (accessedFiles != null && !accessedFiles.isEmpty()){
for (WorkspacePathStatus acFile: accessedFiles){
ExecutionFilesStatus execFileStatus = new ExecutionFilesStatus();
execFileStatus.setFileAccessDateTime(acFile.getStatusDateTime());
execFileStatus.setFilePath(acFile.getPathName().replaceFirst("/", ""));
execFileStatus.setElementId(activityInstanceId);
execFileStatus.setElementPath(elementPath.toString());
execFileStatus.setFiletAccessType(acFile.getPathStatusType().name());
//execFileStatus.setFiletAccessType(ExecutionFilesStatus.TYPE_READ);
execFiles.add(execFileStatus);
}
}
}catch(IOException e){
throw new ProvMonitorException(e.getMessage(), e.getCause());
}
//Commit changed files
StringBuilder message = new StringBuilder();
message.append("ActivityInstanceId:")
.append(activityInstanceId)
.append("; context:")
.append(elementPath.toString())
.append("; EndActivityCommit");
VCSManager cvsManager = VCSManagerFactory.getInstance();
//((GitManager)cvsManager).getStatus(workspacePath);
cvsManager.addAllFromPath(workspacePath);
Set<String> removed = cvsManager.removeAllFromPath(workspacePath);
//String commitId = cvsManager.commit(workspacePath, message.toString());
VCSWorkspaceMetaData wkMetaData = cvsManager.commit(workspacePath, message.toString());
String commitId = wkMetaData.getCommidId();
//Recover executionStatus element
ProvMonitorOutputManager.appendMessageLine("Starting ActivityExecutionEnding Method...");
ProvMonitorDAOFactory factory = new ProvMonitorDAOFactory();
ExecutionStatusDAO execStatusDAO = factory.getExecutionStatusDAO();
ProvMonitorOutputManager.appendMessageLine("Getting activity by id: " + activityInstanceId);
ExecutionStatus elemExecutionStatus = execStatusDAO.getById(activityInstanceId, elementPath.toString());
if (elemExecutionStatus == null){
throw new ProvMonitorException("Element: " + activityInstanceId + " not found exception. Activity could not be finished if it was not started." );
}
//update execution element
ProvMonitorOutputManager.appendMessageLine("Updating Activity properties: End DateTime....");
elemExecutionStatus.setEndTime(endActiviyDateTime);
ProvMonitorOutputManager.appendMessageLine("Updating Activity properties: Status....");
elemExecutionStatus.setStatus("ended");
//Recording Commit ID
//elemExecutionStatus.setCommitId(commitId);
ExecutionCommit execCommit = new ExecutionCommit();
execCommit.setCommitId(commitId);
execCommit.setCommitTime(endActiviyDateTime);
execCommit.setStatus("ActivityEnd");
execCommit.setElementId(elemExecutionStatus.getElementId());
execCommit.setElementPath(elemExecutionStatus.getElementPath());
//Registering removed files
if (removed != null && !removed.isEmpty()){
for (String removedPath: removed){
ExecutionFilesStatus execFileStatus = new ExecutionFilesStatus();
execFileStatus.setFileAccessDateTime(endActiviyDateTime);
execFileStatus.setFilePath(workspacePath.concat("/".concat(removedPath)));
execFileStatus.setElementId(activityInstanceId);
execFileStatus.setElementPath(elementPath.toString());
execFileStatus.setFiletAccessType(PathAccessType.REMOVE.name());
execFiles.add(execFileStatus);
}
}
//persist updated element
ProvMonitorOutputManager.appendMessageLine("Persisting Activity....");
execStatusDAO.update(elemExecutionStatus);
factory.getExecutionCommitDAO().persist(execCommit);
ProvMonitorOutputManager.appendMessageLine("Activity Persisted.");
//Persist accessed files
for (ExecutionFilesStatus executionFileStatus: execFiles){
factory.getExecutionFileStatusDAO().persist(executionFileStatus);
}
}
/**
* Notify ending of a Process (composite activity) instance execution.
*
* @param processInstanceId Process (composite activity) instance identifier.
* @param context Sequence of identifiers that defines a composite activity instance location in the experiment. (path, i.e.: Sub workflows that wraps the composite activity instance)
* @param startProcessDateTime Process instance date time of startup execution.
* @param endProcessDateTime Process instance date time of ending execution.
* @param workspacePath Experiment workspace path.
*
* @throws ProvMonitorException ProvMonitor base exception if some irrecoverable or runtime exception occurs.
* @throws VCSException Version control system related problems.
* @throws DatabaseException Database related problems.
* @throws ConnectionException Database connection problems.
*/
public static void notifyProcessExecutionEnding(String processInstanceId, String[] context, Date startProcessDateTime, Date endProcessDateTime, String workspacePath) throws ProvMonitorException{
//Record Timestamp
//Verify accessed files
//Commit changed files
notifyActivityExecutionEnding(processInstanceId, context, startProcessDateTime, endProcessDateTime, workspacePath);
}
/**
* Notify ending of a Process (composite activity) instance execution.
* <br /><br />
* <b>Update - Instead Use:</b> <br />
* public static void notifyProcessExecutionEnding(String processInstanceId, String[] context, Date startProcessDateTime, Date endProcessDateTime, String workspacePath) throws ProvMonitorException.
*/
@Deprecated
public static boolean notifyProcessExecutionEnding(String processInstanceId, String[] context){
//Record Timestamp
//Verify accessed files
//Commit changed files
return false;
}
/**
* <strong>NOT YET IMPLEMENTED</strong><br /><br />
* Notify a decision point execution.
* @param decisionPointId Decision point identifier.
* @param optionValue Option value used on the decision.
* @param context Sequence of identifiers that defines a decision point location in the experiment. (path, i.e.: Sub workflows that wraps the decision point)
* @return if the operation was successful.
*
*/
public static boolean notifyDecisionPointEnding(String decisionPointId, String optionValue, String[] context){
return false;
}
/**
* Publish artifact values.
* @param artifactId Artifact identifier.
* @param context context Sequence of identifiers that defines an artifact location in the experiment.
* @param value Artifact value.
* @throws ProvMonitorException ProvMonitor base exception if some irrecoverable or runtime exception occurs.
* @throws DatabaseException Database related problems.
* @throws ConnectionException Database connection problems.
*/
//public boolean setArtifactValue(String artifactId, String[] context, String value) throws CharonException{
//return repository.getCharon().getCharonAPI().setArtifactValue(artifactId, context, value);
//}
public static void setArtifactValue(String artifactId, String[] context, String value) throws ProvMonitorException{
StringBuilder elementPath = new StringBuilder();
for (String path: context){
if (elementPath.length()>0){
elementPath.append("/");
}
elementPath.append(path);
}
//Preparing artifact Objetct to be persisted
ArtifactInstance artifactInstance = new ArtifactInstance();
artifactInstance.setArtifactId(artifactId);
artifactInstance.setArtifactValue(value);
artifactInstance.setArtifactPath(elementPath.toString());
ArtifactInstanceDAO artifactValueDAO = new ProvMonitorDAOFactory().getArtifactInstanceDAO();
artifactValueDAO.persist(artifactInstance);
}
/**
* Publish an artifact value location.
*
* @param artifactId Artifact identifier.
* @param context context Sequence of identifiers that defines an artifact location in the experiment.
* @param value Artifact value.
* @param hostURL URL of artifact location host.
* @param hostLocalPath Path of the artifact location inside the host.
*
* @throws ProvMonitorException ProvMonitor base exception if some irrecoverable or runtime exception occurs.
* @throws DatabaseException Database related problems.
* @throws ConnectionException Database connection problems.
*/
//public boolean publishArtifactValueLocation(String artifactId, String[] context, String hostURL, String hostLocalPath) throws CharonException{
//return repository.getCharon().getCharonAPI().publishArtifactValueLocation(artifactId, context, hostURL, hostLocalPath);
//}
public static void publishArtifactValueLocation(String artifactId, String[] context, String hostURL, String hostLocalPath){
}
@SuppressWarnings("unused")
private synchronized static void oldNotifyActivityExecutionStartup(String activityInstanceId, String[] context, Date activityStartDateTime, String workspacePath) throws ProvMonitorException{
try{
//Prepare ActivityObject to be persisted
ExecutionStatus elementExecStatus = new ExecutionStatus();
elementExecStatus.setElementId(activityInstanceId);
elementExecStatus.setElementType("activity");
elementExecStatus.setStatus("starting");
//Mounting context
StringBuilder elementPath = new StringBuilder();
for (String path: context){
if (elementPath.length()>0){
elementPath.append("/");
}
elementPath.append(path);
}
elementExecStatus.setElementPath(elementPath.toString());
//Record Timestamp
elementExecStatus.setStartTime(activityStartDateTime);
//ActivityInstance activity = new ActivityInstance();
//activity.setActivityInstanceId(activityInstanceId);
//activity.set
//Reading accessedFiles
ArrayList<ExecutionFilesStatus> execFiles = new ArrayList<ExecutionFilesStatus>();
try{
//Collection<AccessedPath> accessedFiles = WorkspaceAccessReader.readAccessedPathsAndAccessTime(Paths.get(workspacePath), startActivityDateTime, true);
Collection<WorkspacePathStatus>accessedFiles = WorkspaceAccessReader.readWorkspacePathStatusAndStatusTime(Paths.get(workspacePath), activityStartDateTime, true);
if (accessedFiles != null && !accessedFiles.isEmpty()){
for (WorkspacePathStatus acFile: accessedFiles){
ExecutionFilesStatus execFileStatus = new ExecutionFilesStatus();
execFileStatus.setFileAccessDateTime(acFile.getStatusDateTime());
execFileStatus.setFilePath(acFile.getPathName().replaceFirst("/", ""));
execFileStatus.setElementId(activityInstanceId);
execFileStatus.setElementPath(elementPath.toString());
execFileStatus.setFiletAccessType(acFile.getPathStatusType().name());
//execFileStatus.setFiletAccessType(ExecutionFilesStatus.TYPE_READ);
execFiles.add(execFileStatus);
}
}
}catch(Exception e){
ProvMonitorLogger.warning("RetrospectiveProvenanceBusinessServices", "notifyActivityExecutionStartup", e.getMessage());
ProvMonitorOutputManager.appendMenssage("WARNING: RetrospectiveProvenanceBusinessServices: notifyActivityExecutionStartup" + e.getMessage());
}
//Activity start commit
StringBuilder message = new StringBuilder();
message.append("ActivityInstanceId:")
.append(activityInstanceId)
.append("; context:")
.append(elementPath.toString())
.append("; StartActivityCommit");
VCSManager cvsManager = VCSManagerFactory.getInstance();
//((GitManager)cvsManager).getStatus(workspacePath);
//Set<String> removed = cvsManager.getRemovedFiles(workspacePath);
cvsManager.addAllFromPath(workspacePath);
Set<String> removed = cvsManager.removeAllFromPath(workspacePath);
VCSWorkspaceMetaData wkMetaData = cvsManager.commit(workspacePath, message.toString());
String commitId = wkMetaData.getCommidId();
//Registering removed files
if (removed != null && !removed.isEmpty()){
for (String removedPath: removed){
ExecutionFilesStatus execFileStatus = new ExecutionFilesStatus();
execFileStatus.setFileAccessDateTime(activityStartDateTime);
execFileStatus.setFilePath(workspacePath.concat("/".concat(removedPath)));
execFileStatus.setElementId(activityInstanceId);
execFileStatus.setElementPath(elementPath.toString());
execFileStatus.setFiletAccessType(PathAccessType.REMOVE.name());
execFiles.add(execFileStatus);
}
}
//Recording Commit ID
//elementExecStatus.setCommitId(commitId);
ExecutionCommit execCommit = new ExecutionCommit();
execCommit.setCommitId(commitId);
execCommit.setCommitTime(activityStartDateTime);
execCommit.setStatus("ActivityStart");
execCommit.setElementId(elementExecStatus.getElementId());
execCommit.setElementPath(elementExecStatus.getElementPath());
//TODO: Implementar controle de transação e atomicidade para os casos de atributos multivalorados
ProvMonitorDAOFactory factory = new ProvMonitorDAOFactory();
//factory.getActivityInstanceDAO().persist(activityInstance);
factory.getExecutionStatusDAO().persist(elementExecStatus);
factory.getExecutionCommitDAO().persist(execCommit);
//Persist acessed files
for (ExecutionFilesStatus executionFileStatus: execFiles){
factory.getExecutionFileStatusDAO().persist(executionFileStatus);
}
}catch(Exception e){
throw new ProvMonitorException(e.getMessage(), e.getCause());
}
}
public synchronized static void newNotifyActivityExecutionStartup(String activityInstanceId, String[] context, Date activityStartDateTime, String workspacePath) throws ProvMonitorException{
//Prepare ActivityObject to be persisted
ExecutionStatus elementExecStatus = getNewExecStatus(activityInstanceId, context, activityStartDateTime, null);
//Reading accessedFiles
Collection<ExecutionFilesStatus> execFiles = getAccessedFiles(elementExecStatus, workspacePath);
//Activity start commit
StringBuilder message = new StringBuilder();
message.append("ActivityInstanceId:")
.append(activityInstanceId)
.append("; context:")
.append(elementExecStatus.getElementPath())
.append("; StartActivityCommit");
VCSManager cvsManager = VCSManagerFactory.getInstance();
cvsManager.addAllFromPath(workspacePath);
//Identifying removed files
Set<String> removed = cvsManager.removeAllFromPath(workspacePath);
//Committing changes
VCSWorkspaceMetaData wkMetaData = cvsManager.commit(workspacePath, message.toString());
String commitId = wkMetaData.getCommidId();
//Joining all files changes to be persisted.
Collection<ExecutionFilesStatus> removedFiles = getRemovedFiles(removed, elementExecStatus, workspacePath);
execFiles.addAll(removedFiles);
//Recording Commit ID
//elementExecStatus.setCommitId(commitId);
ExecutionCommit execCommit = new ExecutionCommit();
execCommit.setCommitId(commitId);
execCommit.setCommitTime(activityStartDateTime);
execCommit.setStatus("ActivityStart");
execCommit.setElementId(elementExecStatus.getElementId());
execCommit.setElementPath(elementExecStatus.getElementPath());
//TODO: Implement transaction control and atomicity for multivalued attributes.
//Persisting
ProvMonitorDAOFactory factory = new ProvMonitorDAOFactory();
//factory.getActivityInstanceDAO().persist(activityInstance);
factory.getExecutionStatusDAO().persist(elementExecStatus);
factory.getExecutionCommitDAO().persist(execCommit);
//Persisting accessed files
for (ExecutionFilesStatus executionFileStatus: execFiles){
factory.getExecutionFileStatusDAO().persist(executionFileStatus);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.