text stringlengths 10 2.72M |
|---|
package com.example.fragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.dialogdemo2.R;
public class DetailsFragment extends Fragment {
private View v;
public static DetailsFragment newInstance(int index) {
DetailsFragment f = new DetailsFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
public int getShownIndex() {
return getArguments().getInt("index", 0);
}
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
v = inflater.inflate(R.layout.fragment_tmp, container, false);
TextView text = (TextView)v.findViewById(R.id.text_view);
text.setText("Page" + getShownIndex());
return v;
}
}
|
package specification;
import designer.ui.editor.element.Element;
import designer.ui.editor.element.StepElement;
import specification.core.DefaultValuesBundle;
import javax.xml.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Tomas Hanus on 2/21/2015.
*/
@XmlAccessorType(XmlAccessType.NONE)
public class Step extends StepElement {
private static final String CHUNK_ELEMENT = "Chunk";
private static final String BATCHLET_ELEMENT = "Batchlet";
@XmlElement
private Properties properties;
@XmlElement
private Listeners listeners;
// **** STEP TYPE ***
@XmlElement
private Chunk chunk;
@XmlElement
private Batchlet batchlet;
// **** ATTRIBUTES ***
@XmlAttribute(name = "start-limit")
private Integer startLimit;
@XmlAttribute(name = "allow-start-if-complete")
private Boolean allowStartIfComplete;
@XmlAttribute(name = "next")
private String nextElementId;
@XmlAttribute(name = "abstract")
private Boolean isAbstract;
@XmlAttribute(name = "parent")
private String parentElement;
// **** ELEMENTS ***
@XmlElement
private Partition partition;
@XmlElements({@XmlElement(name = "stop", type = Stop.class)})
private List<Stop> stops;
@XmlElements({@XmlElement(name = "end", type = End.class)})
private List<End> ends;
@XmlElements({@XmlElement(name = "fail", type = Fail.class)})
private List<Fail> fails;
@XmlElements({@XmlElement(name = "next", type = Next.class)})
private List<Next> nexts;
private boolean partitionEnabled = false;
private PartitionPlan partitionPlanBackup;
private PartitionMapper partitionMapperBackup;
public Step() {
super();
}
public Step(String id, String type) {
super(type);
this.setId(id);
if (type.equals(this.CHUNK_ELEMENT)) {
this.chunk = new Chunk(id);
this.batchlet = null;
} else {
this.batchlet = new Batchlet(id);
this.chunk = null;
}
}
/**
* Returns true if step is chunkOriented (contains chunk) or false if it is taskOriented (conains batchlet)
*
* @return
*/
public Boolean isChunkOriented() {
if (this.chunk != null) {
return true;
} else {
return false;
}
}
public Chunk getChunk() {
return chunk;
}
public void setChunk(Chunk chunk) {
this.chunk = chunk;
}
public Batchlet getBatchlet() {
return batchlet;
}
public void setBatchlet(Batchlet batchlet) {
this.batchlet = batchlet;
}
/**
* Returns start limit. If there is no start limit defined (null) returns it's default value.
*/
public Integer getStartLimit() {
if (this.startLimit == null) return Integer.valueOf(DefaultValuesBundle.value("step.startLimit"));
return startLimit;
}
public void setStartLimit(Integer startLimit) {
if (startLimit == Integer.valueOf(DefaultValuesBundle.value("step.startLimit")))
this.startLimit = null;
else
this.startLimit = startLimit;
}
public Boolean isAllowStartIfComplete() {
if (this.allowStartIfComplete == null)
return Boolean.valueOf(DefaultValuesBundle.value("step.allowStartIfComplete"));
return allowStartIfComplete;
}
public void setAllowStartIfComplete(Boolean allowStartIfComplete) {
if (allowStartIfComplete == Boolean.valueOf(DefaultValuesBundle.value("step.allowStartIfComplete")))
this.allowStartIfComplete = null;
else
this.allowStartIfComplete = allowStartIfComplete;
}
public Boolean isAbstract() {
if (this.isAbstract == null) return Boolean.valueOf(DefaultValuesBundle.value("step.abstract"));
return isAbstract;
}
public void setIsAbstract(Boolean isAbstract) {
if (isAbstract == Boolean.valueOf(DefaultValuesBundle.value("step.abstract")))
this.isAbstract = null;
else
this.isAbstract = isAbstract;
}
public String getParentElement() {
return parentElement;
}
public void setParentElement(String parentElement) {
if (parentElement.equals("")) this.parentElement = null;
else this.parentElement = parentElement;
}
public Properties getProperties() {
return properties;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
public Listeners getListeners() {
return this.listeners;
}
public void setListeners(Listeners listeners) {
this.listeners = listeners;
}
public Partition getPartition() {
//if (this.partition == null) this.partition = new Partition();
return partition;
}
public void setPartition(Partition partition) {
this.partition = partition;
}
public boolean isPartitionEnabled() {
return partitionEnabled;
}
public void setPartitionEnabled(boolean partitionEnabled) {
this.partitionEnabled = partitionEnabled;
}
public void removePartitionPlan() {
if (this.partition.getPartitionPlan() == null) {
this.partitionPlanBackup = null;
} else {
this.partitionPlanBackup = new PartitionPlan(this.partition.getPartitionPlan().getPartitionsNumber(),
this.partition.getPartitionPlan().getThreadsNumber(), this.partition.getPartitionPlan().getProperties());
}
this.partition.setPartitionPlan(null);
}
public void removePartitionMapper() {
if (this.partition.getPartitionMapper() == null) {
this.partitionMapperBackup = null;
} else {
// this.partitionMapperBackup = this.partition.getPartitionMapper().deepClone();
this.partitionMapperBackup = new PartitionMapper(this.partition.getPartitionMapper());
}
this.partition.setPartitionMapper(null);
}
public void getPartitionPlanFromBackup() {
this.partition.setPartitionPlan(partitionPlanBackup);
}
public void getPartitionMapperFromBackup() {
this.partition.setPartitionMapper(partitionMapperBackup);
}
public void setPartitionPlanBackup(PartitionPlan partitionPlanBackup) {
this.partitionPlanBackup = partitionPlanBackup;
}
public void setPartitionMapperBackup(PartitionMapper partitionMapperBackup) {
this.partitionMapperBackup = partitionMapperBackup;
}
public void addStop(Stop stop) {
if (this.stops == null) this.stops = new ArrayList<Stop>();
if (!this.stops.contains(stop))
this.stops.add(stop);
}
// ---------------- STOP ------------------
public Stop getStop(String stopId) {
if (this.stops == null) return null;
Stop stopToReturn = null;
for (Stop stop : this.stops) {
if (stop.getId().equals(stopId))
stopToReturn = stop;
}
return stopToReturn;
}
public void removeStop(Stop stop) {
if (this.stops == null) return;
this.stops.remove(stop);
if (this.stops.size() == 0) this.stops = null;
}
public void removeStop(String stopId) {
if (this.stops == null) return;
Stop stopToRemove = null;
for (Stop stop : this.stops) {
if (stop.getId().equals(stopId))
stopToRemove = stop;
}
if (stopToRemove == null) return;
this.stops.remove(stopToRemove);
if (this.stops.size() == 0) this.stops = null;
}
@Override
public List<Stop> getStops() {
return stops;
}
// ---------------- END ------------------
public void addEnd(End end) {
if (this.ends == null) this.ends = new ArrayList<End>();
if (!this.ends.contains(end))
this.ends.add(end);
}
public End getEnd(String endId) {
if (this.ends == null) return null;
End endToReturn = null;
for (End end : this.ends) {
if (end.getId().equals(endId))
endToReturn = end;
}
return endToReturn;
}
public void removeEnd(End end) {
if (this.ends == null) return;
this.ends.remove(end);
if (this.ends.size() == 0) this.ends = null;
}
public void removeEnd(String endId) {
if (this.ends == null) return;
End endToRemove = null;
for (End end : this.ends) {
if (end.getId().equals(endId))
endToRemove = end;
}
if (endToRemove == null) return;
this.ends.remove(endToRemove);
if (this.ends.size() == 0) this.ends = null;
}
@Override
public List<End> getEnds() {
return ends;
}
// ---------------- FAIL ------------------
public void addFail(Fail fail) {
if (this.fails == null) this.fails = new ArrayList<Fail>();
if (!this.fails.contains(fail))
this.fails.add(fail);
}
public void removeFail(Fail fail) {
if (this.fails == null) return;
this.fails.remove(fail);
if (this.fails.size() == 0) this.fails = null;
}
public void removeFail(String failId) {
if (this.fails == null) return;
Fail failToRemove = null;
for (Fail fail : this.fails) {
if (fail.getId().equals(failId))
failToRemove = fail;
}
if (failToRemove == null) return;
this.fails.remove(failToRemove);
if (this.fails.size() == 0) this.fails = null;
}
@Override
public List<Fail> getFails() {
return fails;
}
public Fail getFail(String failId) {
if (this.fails == null) return null;
Fail failToReturn = null;
for (Fail fail : this.fails) {
if (fail.getId().equals(failId))
failToReturn = fail;
}
return failToReturn;
}
public boolean canAddStop(String id) {
if (this.stops == null) return true;
// if (this.stops.size() >= 1) return false;
for (Stop stop : this.stops) {
if (stop.getId().equals(id)) return false;
}
return true;
}
public boolean canAddFail(String id) {
if (this.fails == null) return true;
// if (this.fails.size() >= 1) return false;
for (Fail fail : this.fails) {
if (fail.getId().equals(id)) return false;
}
return true;
}
public boolean canAddEnd(String id) {
if (this.ends == null) return true;
//if (this.ends.size() >= 1) return false;
for (End end : this.ends) {
if (end.getId().equals(id)) return false;
}
return true;
}
@Override
public boolean canAddTransitionElement(Element transitionElement) {
// if (transitionElement instanceof EndTransition){
// if (this.ends == null) return true;
// if (this.ends.size() >= 1 ) return false;
// for (End end : this.ends){
// if (end.getId().equals(transitionElement.getId())) return false;
// }
// return true;
// }else if (transitionElement instanceof StopTransition){
// if (this.stops == null) return true;
// if (this.stops.size() >= 1 ) return false;
// for (Stop stop : this.stops){
// if (stop.getId().equals(transitionElement.getId())) return false;
// }
// return true;
// }
// else if (transitionElement instanceof FailTransition){
// if (this.fails == null) return true;
// if (this.fails.size() >= 1 ) return false;
// for (Fail fail : this.fails){
// if (fail.getId().equals(transitionElement.getId())) return false;
// }
// return true;
// }
return true;
}
public void addNextElementId(String newNextElementId) {
if (getNextTransition(newNextElementId) != null) return;
if (this.nextElementId == null && this.nexts == null) {
this.nextElementId = newNextElementId;
return;
}
if (this.nextElementId != null && !this.nextElementId.equals("")) {
this.nexts = new ArrayList<Next>();
this.nexts.add(new Next("", nextElementId)); // makes next element from next attribute
this.nextElementId = null;
}
this.nexts.add(new Next("", newNextElementId));
}
public Next getNextTransition(String id) {
if (nextElementId != null && nextElementId.equals(id)) return new Next(null, nextElementId);
if (nexts != null) {
for (Next next : this.nexts) {
if (next.getTo().equals(id)) return next;
}
}
return null;
}
public void removeNextElementId(String nextElementIdToRemove) {
if (this.nextElementId != null && this.nexts == null) {
if (this.nextElementId.equals(nextElementIdToRemove)) {
this.nextElementId = null;
return;
}
}
if (this.nextElementId == null && this.nexts != null) {
for (Next next : this.nexts) {
if (next.getTo().equals(nextElementIdToRemove)) {
this.nexts.remove(next);
break;
}
}
if (this.nexts.size() == 0) {
this.nexts = null;
return;
}
if (this.nexts.size() == 1 && (this.nexts.get(0).getOn() == null || this.nexts.get(0).getOn().equals(""))) {
this.nextElementId = this.nexts.get(0).getTo();
this.nexts = null;
}
}
}
public List<Next> getAllNextTransitions() {
List<Next> nextsToReturn = new ArrayList<Next>();
if (this.nextElementId != null && this.nexts == null) {
nextsToReturn.add(new Next(null, nextElementId));
} else if (this.nextElementId == null && this.nexts != null) {
for (Next next : this.nexts) {
nextsToReturn.add(next);
}
}
if (nextsToReturn.size() == 0) return null;
return nextsToReturn;
}
public void editNextTransitionTo(String nextTransitionTo, String newOnValue) {
if (this.nextElementId != null && this.nexts == null) {
if (newOnValue == null || newOnValue.equals("")) return;
else {
this.nexts = new ArrayList<Next>();
this.nexts.add(new Next(newOnValue, nextTransitionTo));
this.nextElementId = null;
}
} else if (this.nextElementId == null && this.nexts != null) {
if (this.nexts.size() == 1) {
if (newOnValue == null || newOnValue.equals("")) {
this.nextElementId = nextTransitionTo;
this.nexts = null;
} else {
this.nexts.get(0).setOn(newOnValue);
}
} else getNextTransition(nextTransitionTo).setOn(newOnValue);
}
}
public void renameDestinationOfNextTransition(String nextTransitionTo, String newNextTransitionDestination) {
if (this.nextElementId != null && this.nexts == null) {
this.nextElementId = newNextTransitionDestination;
} else if (this.nextElementId == null && this.nexts != null) {
getNextTransition(nextTransitionTo).setTo(newNextTransitionDestination);
}
}
} |
/**
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2015 Paco Avila & Josep Llort
*
* No bytes were intentionally harmed during the development of this application.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.openkm.cmis;
import java.math.BigInteger;
import java.util.Map;
import org.apache.chemistry.opencmis.commons.impl.server.AbstractServiceFactory;
import org.apache.chemistry.opencmis.commons.server.CallContext;
import org.apache.chemistry.opencmis.commons.server.CmisService;
import org.apache.chemistry.opencmis.server.support.CmisServiceWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* CMIS Service Factory.
*/
public class CmisServiceFactory extends AbstractServiceFactory {
private static Logger log = LoggerFactory.getLogger(CmisServiceFactory.class);
private CmisTypeManager typeManager;
private CmisRepository repository;
/** Default maxItems value for getTypeChildren()}. */
private static final BigInteger DEFAULT_MAX_ITEMS_TYPES = BigInteger.valueOf(50);
/** Default depth value for getTypeDescendants(). */
private static final BigInteger DEFAULT_DEPTH_TYPES = BigInteger.valueOf(-1);
/** Default maxItems value for getChildren() and other methods returning lists of objects. */
private static final BigInteger DEFAULT_MAX_ITEMS_OBJECTS = BigInteger.valueOf(200);
/** Default depth value for getDescendants(). */
private static final BigInteger DEFAULT_DEPTH_OBJECTS = BigInteger.valueOf(10);
@Override
public void init(Map<String, String> parameters) {
typeManager = new CmisTypeManager();
repository = new CmisRepository("test", typeManager);
}
@Override
public void destroy() {
}
@Override
public CmisService getService(CallContext context) {
// authentication can go here
String user = context.getUsername();
String password = context.getPassword();
log.debug("User: {}", user);
log.debug("Password: {}", password);
// if the authentication fails, throw a CmisPermissionDeniedException
// create a new service object (can also be pooled or stored in a ThreadLocal)
CmisServiceImpl service = new CmisServiceImpl(repository);
// add the CMIS service wrapper
// (The wrapper catches invalid CMIS requests and sets default values
// for parameters that have not been provided by the client.)
CmisServiceWrapper<CmisService> wrapperService = new CmisServiceWrapper<CmisService>(service, DEFAULT_MAX_ITEMS_TYPES,
DEFAULT_DEPTH_TYPES, DEFAULT_MAX_ITEMS_OBJECTS, DEFAULT_DEPTH_OBJECTS);
// hand over the call context to the service object
service.setCallContext(context);
return wrapperService;
}
}
|
package io.reark.rxgithubapp.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import javax.inject.Inject;
import io.reark.rxgithubapp.R;
import io.reark.rxgithubapp.RxGitHubApp;
import io.reark.rxgithubapp.activities.ChooseRepositoryActivity;
import io.reark.rxgithubapp.utils.ApplicationInstrumentation;
import io.reark.rxgithubapp.view.RepositoriesView;
import io.reark.rxgithubapp.viewmodels.RepositoriesViewModel;
/**
* Created by ttuo on 19/03/14.
*/
public class RepositoriesFragment extends Fragment {
private RepositoriesView.ViewBinder repositoriesViewBinder;
@Inject
RepositoriesViewModel repositoriesViewModel;
@Inject
ApplicationInstrumentation mInstrumentation;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RxGitHubApp.getInstance().getGraph().inject(this);
repositoriesViewModel.getSelectRepository()
.subscribe(repository ->
((ChooseRepositoryActivity) getActivity())
.chooseRepository(repository.getId()));
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.repositories_fragment, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
repositoriesViewBinder = new RepositoriesView.ViewBinder(
(RepositoriesView) view.findViewById(R.id.repositories_view),
repositoriesViewModel);
repositoriesViewModel.subscribeToDataStore();
}
@Override
public void onResume() {
super.onResume();
repositoriesViewBinder.bind();
}
@Override
public void onPause() {
super.onPause();
repositoriesViewBinder.unbind();
}
@Override
public void onDestroyView() {
super.onDestroyView();
repositoriesViewModel.unsubscribeFromDataStore();
}
@Override
public void onDestroy() {
super.onDestroy();
repositoriesViewModel.dispose();
repositoriesViewModel = null;
mInstrumentation.getLeakTracing().traceLeakage(this);
}
}
|
package com.diozero.sampleapps;
/*
* #%L
* Organisation: diozero
* Project: diozero - Sample applications
* Filename: EepromTest.java
*
* This file is part of the diozero project. More information about this project
* can be found at https://www.diozero.com/.
* %%
* Copyright (C) 2016 - 2023 diozero
* %%
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* #L%
*/
import java.util.Arrays;
import org.tinylog.Logger;
import com.diozero.api.RuntimeIOException;
import com.diozero.devices.McpEeprom;
public class EepromTest {
private static final String LOREM_IPSUM = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, "
+ "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, "
+ "quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis "
+ "aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla "
+ "pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia "
+ "deserunt mollit anim id est laborum.";
public static void main(String[] args) {
if (args.length < 1) {
Logger.error("Usage: {} <i2c-controller> [device-address]", EepromTest.class.getName());
System.exit(1);
}
int controller = Integer.parseInt(args[0]);
int device_address = McpEeprom.DEFAULT_ADDRESS;
if (args.length > 1) {
device_address = Integer.parseInt(args[1]);
}
// test(controller, 0x04);
// test(controller, 0x05);
test(controller, device_address);
}
private static void test(int controller, int deviceAddress) {
try (McpEeprom eeprom = new McpEeprom(controller, deviceAddress, McpEeprom.Type.MCP_24xx512)) {
byte d = eeprom.readByte(0);
Logger.info("Read " + (d & 0xff) + " from address 0");
// Validate write byte and random read
for (int address = 0; address < 2; address++) {
Logger.info("Testing write and read for memory address: 0x{}", Integer.valueOf(address));
for (int data = 0; data < 256; data++) {
eeprom.writeByte(address, data);
int data_read = eeprom.readByte(address) & 0xff;
if (data_read != data) {
Logger.error("For address 0x{} expected 0x{}, read 0x{}", Integer.toHexString(address),
Integer.toHexString(data), Integer.toHexString(data_read));
}
}
}
// Validate write byte and current address read
String text_to_write = "Hello World";
int address = 0x10;
for (byte b : text_to_write.getBytes()) {
Logger.debug("Writing '" + ((char) b) + "'");
eeprom.writeByte(address++, b);
}
address = 0x10;
byte b = eeprom.readByte(address);
Logger.debug("Read '" + ((char) b) + "'");
for (int i = 1; i < text_to_write.length(); i++) {
b = eeprom.readCurrentAddress();
Logger.debug("Read '" + ((char) b) + "'");
if (((char) b) != text_to_write.charAt(i)) {
Logger.error("Error expected '{}', read '{}'", Character.valueOf(text_to_write.charAt(i)),
Character.valueOf((char) b));
}
}
// Test writing more that a page size
address = 0x1000;
Logger.debug("Writing '" + LOREM_IPSUM + "'");
eeprom.writeBytes(address, LOREM_IPSUM.getBytes());
byte[] data = eeprom.readBytes(address, LOREM_IPSUM.length());
Logger.debug("read " + data.length + " bytes");
String text = new String(data);
Logger.debug("Read '" + text + "'");
if (!Arrays.equals(LOREM_IPSUM.getBytes(), data)) {
Logger.error("Expected to read Lorem Ipsum text");
}
} catch (RuntimeIOException e) {
Logger.error(e);
}
}
}
|
package alarmclock;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Calendar;
import java.util.Scanner;
import java.util.Set;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
public class alarm {
static Calendar calendar = Calendar.getInstance();
static int amPm = calendar.get(Calendar.AM_PM);// AM = 0, PM = 1
// static JButton snooze = new JButton("Snooze");
public static void main(String[] args) throws Exception{
//Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);//January = 0, December = 11
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
// int amPm = calendar.get(Calendar.AM_PM);// AM = 0, PM = 1
AlarmClock alarm = new AlarmClock(10, 30, 0);
System.out.println(month + "-" + dayOfMonth + "-" + year);
//System.out.println(hour + ":" + minute + " " + amPm);
System.out.println(hour + ":" + minute + " " + getStringAMPM());
System.out.println(alarm.getalarmHour() + ":" + alarm.getAlarmMinute() + alarm.getAlarmAmPm());
System.out.println(alarm.isAlarmRinging());
//Static Class to convert 0/1 to AM/PM
//Frame Build
JFrame frame = new JFrame("Alarm Clock");
//frame.setSize(550, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setResizable(true);
JPanel main = new JPanel();
JPanel bottom = new JPanel();
JPanel datePanel = new JPanel();
JPanel timePanel = new JPanel();
JPanel alarmPanel = new JPanel();
JPanel ipanel = new JPanel();
//JTextField input = new JTextField();
JTextField iHour = new JTextField("Hour");
JTextField iMinute = new JTextField("Minute");
JTextField iAMPM = new JTextField("0(am)/1(pm)");
bottom.setLayout(new GridLayout(1,4));
main.setLayout(new BoxLayout(main, BoxLayout.Y_AXIS));
//input.setPreferredSize(new Dimension( 100, 24 ));
iHour.setPreferredSize(new Dimension( 100, 24 ));
iMinute.setPreferredSize(new Dimension( 100, 24 ));
iAMPM.setPreferredSize(new Dimension( 100, 24 ));
String date = month + "-" + dayOfMonth + "-" + year;
String Time = hour + ":" + minute + " " + getStringAMPM();
String alarmTime = alarm.getalarmHour() + ":" + alarm.getAlarmMinute() + " " + alarm.getAlarmAmPm() +" ";
Boolean isAlarm = alarm.isAlarmRinging();
//Change background colors
bottom.setBackground(Color.RED);
timePanel.setBackground(Color.BLUE);
datePanel.setBackground(Color.PINK);
alarmPanel.setBackground(Color.ORANGE);
//JLabels
JLabel cTime1 = new JLabel("Time");
JLabel cTime = new JLabel("Current Date");
JLabel timeAlarm = new JLabel("Alarm Time");
JLabel onoff = new JLabel("on/off");
//String Date
cTime.setText(date);
cTime1.setText(Time);
timeAlarm.setText(alarmTime);
onoff.setText(isAlarm.toString());
//Font
cTime1.setFont(new Font("DejaVu Sans", Font.BOLD, 72));
cTime.setFont(new Font("DejaVu Sans", Font.BOLD, 56));
timeAlarm.setFont(new Font("DejaVu Sans", Font.BOLD, 36));
onoff.setFont(new Font("DejaVu Sans", Font.BOLD, 36));
//Change Text Color
cTime1.setForeground(Color.WHITE);
cTime.setForeground(Color.WHITE);
timeAlarm.setForeground(Color.WHITE);
onoff.setForeground(Color.WHITE);
//JButtons
// JButton snooze = new JButton("Snooze");
JButton set = new JButton("Set Alarm");
JButton off = new JButton("Off");
// snooze.setVisible(true);
//Add Labels to panel
main.add(datePanel);
main.add(timePanel);
main.add(alarmPanel);
main.add(ipanel);
bottom.add(set);
//bottom.add(snooze);
bottom.add(off);
main.add(bottom);
timePanel.add(cTime1);
datePanel.add(cTime);
//ipanel.add(input);
ipanel.add(iHour);
ipanel.add(iMinute);
ipanel.add(iAMPM);
alarmPanel.add(timeAlarm);
alarmPanel.add(onoff);
frame.add(main);
frame.setPreferredSize(new Dimension(580, 350));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(true);
//handle buttons
set.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent a)
{
String text = iHour.getText();
int hourInt = Integer.parseInt(text);
alarm.setAlarmHour(hourInt);
System.out.println(alarm.getalarmHour());
String text1 = iMinute.getText();
int minuteInt = Integer.parseInt(text1);
alarm.setAlarmMinute(minuteInt);
System.out.println(alarm.getAlarmMinute());
String text2 = iAMPM.getText();
int ampmInt = Integer.parseInt(text2);
alarm.setAlarmAmPm(ampmInt);
System.out.println(alarm.getAlarmAmPm());
timeAlarm.setText(text + ":" + text1 + " " + text2 + " ");
}
});
off.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
if(off.getModel().isPressed()){
}
System.exit(0);
System.out.println("off");
}
});
System.out.println(alarm.getalarmHour());
double lastTime = System.currentTimeMillis();
double currentTime = lastTime;
double seconds = 45;
double milliSeconds = 0;
while(true){
currentTime = System.currentTimeMillis();
double deltaTime = currentTime - lastTime;
lastTime = currentTime;
//seconds += deltaTime / 1000.0;
milliSeconds += deltaTime;
if(milliSeconds >= 1000){
seconds +=1 ;
milliSeconds -= 1000;
}
if(seconds >= 60){
minute += 1;
seconds -= 60;
}
String Time1 = hour + ":" + minute + " " + (int)seconds + " " + getStringAMPM();
cTime1.setText(Time1);
//Play Alarm At Time
if((hour == alarm.getalarmHour()) && (minute == alarm.getAlarmMinute()) && (amPm == alarm.getAlarmAmPm())){
//int number;
URL url = new URL("http://www.wavsource.com/snds_2016-11-20_5768273412148964/sfx/ocean.wav");
File soundAlarm = new File("/Users/nosaedogun/Desktop/horn2.wav");
playRadioStream("http://radio.flex.ru:8000/radionami" );
}
timePanel.repaint();
}
}
private static void playRadioStream(String spec) throws IOException, JavaLayerException {
// TODO Auto-generated method stub
URLConnection urlConnection = new URL ( spec ).openConnection ();
urlConnection.connect ();
// Playing
Player player = new Player ( urlConnection.getInputStream () );
player.play ();
}
public static String getStringAMPM(){
if(amPm == 0)
return "AM";
else
return "PM";
}
}
|
package org.ddth.dinoage.eclipse.ui.handlers;
import java.io.File;
import org.ddth.dinoage.DinoAge;
import org.ddth.dinoage.ResourceManager;
import org.ddth.dinoage.core.BrowsingSession;
import org.ddth.dinoage.core.ConsoleLogger;
import org.ddth.dinoage.core.Profile;
import org.ddth.dinoage.eclipse.Activator;
import org.ddth.dinoage.eclipse.ui.UniversalUtil;
import org.ddth.dinoage.eclipse.ui.model.ProfileNode;
import org.ddth.dinoage.eclipse.ui.views.WorkspaceView;
import org.ddth.http.core.SessionChangeListener;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.console.ConsolePlugin;
import org.eclipse.ui.console.IConsole;
import org.eclipse.ui.console.MessageConsole;
import org.eclipse.ui.console.MessageConsoleStream;
import org.eclipse.ui.handlers.HandlerUtil;
public class ExecuteProfileHandler extends AbstractHandler {
public Object execute(ExecutionEvent event) throws ExecutionException {
IWorkbenchWindow workbenchWindow = HandlerUtil
.getActiveWorkbenchWindow(event);
IWorkbenchPage activePage = workbenchWindow.getActivePage();
IViewPart view = activePage.findView(WorkspaceView.ID);
if (view == null) {
return null;
}
IStructuredSelection selection = (IStructuredSelection) view
.getSite().getSelectionProvider().getSelection();
ProfileNode node = (ProfileNode) selection.getFirstElement();
DinoAge dinoage = Activator.getDefault().getDinoAge();
Profile profile = node.getData();
BrowsingSession session = dinoage.getSession(profile);
session.addSessionChangeListener((SessionChangeListener) view);
if (session.isRunning()) {
if (MessageDialog.openQuestion(workbenchWindow.getShell(),
workbenchWindow.getShell().getText(),
ResourceManager.getMessage(ResourceManager.KEY_CONFIRM_STOP_ACTIVE_PROFILE,
new Object[] {profile.getProfileName()}))) {
session.shutdown();
session.removeSessionChangeListener((SessionChangeListener) view);
dinoage.getWorkspace().saveProfile(profile);
}
}
else {
int answer = SWT.NO;
if (session.isRestorable()) {
File profileFolder = dinoage.getWorkspace().getProfileFolder(
profile);
String message = ResourceManager.getMessage(
ResourceManager.KEY_RESUME_RETRIEVING_CONFIRM,
new String[] {
profile.getProfileName(),
profileFolder.getAbsolutePath() });
answer = UniversalUtil.showConfirmDlg(
workbenchWindow.getShell(),
workbenchWindow.getShell().getText(),
message);
}
IConsole console = getConsole(profile, session);
final MessageConsoleStream consoleStream = ((MessageConsole)console).newMessageStream();
ConsoleLogger logger = new ConsoleLogger() {
@Override
public void println(String message) {
// Make sure premature close of display
// won't break the whole system.
if (!ConsolePlugin.getStandardDisplay().isDisposed()) {
consoleStream.println(message);
}
}
};
session.attach(logger);
if (answer == SWT.YES) {
session.restore();
}
else if (answer == SWT.NO) {
session.start();
}
if (answer != SWT.CANCEL) {
ConsolePlugin.getDefault().getConsoleManager().showConsoleView(console);
}
}
return null;
}
/**
* Try to get the existing console. If it's not found, a new message console
* will be created and attaches to the given session.
*
* @param profile
* @param session
* @return
*/
private IConsole getConsole(Profile profile, BrowsingSession session) {
IConsole console = null;
IConsole[] consoles = ConsolePlugin.getDefault().getConsoleManager().getConsoles();
for (IConsole con : consoles) {
if (con.getName() == profile.getProfileName()) {
console = con;
break;
}
}
if (console == null) {
console = new MessageConsole(profile.getProfileName(), null);
ConsolePlugin.getDefault().getConsoleManager().addConsoles(new IConsole[] { console });
}
return console;
}
}
|
package com.example.dllo.notestudio.SP;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.example.dllo.notestudio.R;
/**
* Created by dllo on 16/11/12.
*/
public class SPTwoDemo extends AppCompatActivity {
private TextView tv1 ;
private Button btn1 ;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo_sp2);
tv1 = (TextView) findViewById(R.id.SP_tv1);
btn1 = (Button) findViewById(R.id.SP_btn3);
SharedPreferences sp = getSharedPreferences("menu" , MODE_PRIVATE);
String tete = sp.getString("son" , "没获取到" );
tv1.setText(tete);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
}
}
|
package com.ybh.front.mapper;
import com.ybh.front.model.Product_VPS_ACLTemplate;
import com.ybh.front.model.Product_VPS_ACLTemplateExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface Product_VPS_ACLTemplateMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table FreeHost_Product_VPS_ACLTemplate
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
long countByExample(Product_VPS_ACLTemplateExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table FreeHost_Product_VPS_ACLTemplate
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
int deleteByExample(Product_VPS_ACLTemplateExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table FreeHost_Product_VPS_ACLTemplate
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
int insert(Product_VPS_ACLTemplate record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table FreeHost_Product_VPS_ACLTemplate
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
int insertSelective(Product_VPS_ACLTemplate record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table FreeHost_Product_VPS_ACLTemplate
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
List<Product_VPS_ACLTemplate> selectByExample(Product_VPS_ACLTemplateExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table FreeHost_Product_VPS_ACLTemplate
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
int updateByExampleSelective(@Param("record") Product_VPS_ACLTemplate record, @Param("example") Product_VPS_ACLTemplateExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table FreeHost_Product_VPS_ACLTemplate
*
* @mbg.generated Fri May 11 11:16:07 CST 2018
*/
int updateByExample(@Param("record") Product_VPS_ACLTemplate record, @Param("example") Product_VPS_ACLTemplateExample example);
} |
package controlador;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import implementacion.UsuarioImpl;
import modelo.Cliente;
/**
* Servlet implementation class EditarClienteServlet
*/
@WebServlet("/EditarClienteServlet")
public class EditarClienteServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public EditarClienteServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
int runusuario = Integer.parseInt(request.getParameter("run"));
UsuarioImpl usimpl = new UsuarioImpl();
Cliente usraux = usimpl.obtenerClientePorRun(runusuario);
request.setAttribute("us", usraux);
request.getRequestDispatcher("editarCliente.jsp").forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
|
package com.mycompany.restaum;
import java.util.ArrayList;
/**
*
* @author kassuelo.okaszeski
*/
public class Logica {
private static StringBuilder indices = new StringBuilder();
private static ArrayList<String> posicoesVazias = new ArrayList();
private static ArrayList<Movimento> movimentos = new ArrayList();
private static Movimento movimento = new Movimento();
private static byte matriz[][] = new byte[7][7];
private static final String[] posicoesOcupadas = {"02", "03", "04", "12", "13", "14", "20", "21", "22", "23", "24", "25", "26", "30", "31", "32", "34", "33", "35", "36", "40", "41", "42", "43", "44", "45", "46", "52", "53", "54", "62", "63", "64"};
private static final String[] posicoesInvalidas = {"00", "01", "05", "06", "10", "11", "15", "16", "50", "51", "55", "56", "60", "61", "65", "66"};
public static void criaMatriz(byte inicioX, byte inicioY) {
for (byte i = 0; i < posicoesOcupadas.length; i++) {
int x = Integer.valueOf(String.valueOf(posicoesOcupadas[i].charAt(0)));
int y = Integer.valueOf(String.valueOf(posicoesOcupadas[i].charAt(1)));
matriz[x][y] = 1;
}
matriz[inicioX][inicioY] = 0;
for (byte i = 0; i < posicoesInvalidas.length; i++) {
int x = Integer.valueOf(String.valueOf(posicoesInvalidas[i].charAt(0)));
int y = Integer.valueOf(String.valueOf(posicoesInvalidas[i].charAt(1)));
matriz[x][y] = -1;
}
}
public static void exibeMatriz() {
System.out.println("");
for (int i = 0; i <= 6; i++) {
for (int j = 0; j <= 6; j++) {
if (Logica.matriz[i][j] < 0) {
System.out.print(" " + Logica.matriz[i][j]);
} else {
System.out.print(" " + Logica.matriz[i][j]);
}
}
System.out.println("");
}
}
public static String concatenarIndice(byte x, byte y) {
if (indices.length() > 0) {
indices.delete(0, (indices.length()));
}
indices.append(x);
indices.append(y);
return indices.toString();
}
public static byte buscaMovimentos() {
posicoesVazias.clear();
for (int i = 0; i <= 6; i++) {
for (int j = 0; j <= 6; j++) {
if (Logica.matriz[i][j] == 0) {
posicoesVazias.add(concatenarIndice((byte) i, (byte) j));
}
}
}
//for(String b: posicoesVazias)
System.out.println("Posiçõs vazias: " + posicoesVazias.toString());
return (byte) posicoesVazias.size();
}
public static boolean movePeca() {
buscaMovimentos();
if (posicoesVazias.size() > 0) {
for (String s : posicoesVazias) {
byte x = Byte.valueOf(String.valueOf(s).substring(0, 1));
byte y = Byte.valueOf(String.valueOf(s).substring(1, 2));
if (((x - 2) >= 0) && (matriz[(x - 1)][y] == 1) && (matriz[(x - 2)][y] == 1)) { //testa a posição acima da vazia x-1
matriz[(x - 1)][y] = 0; //remove a peça atribuindo zero
matriz[(x - 2)][y] = 0;
matriz[x][y] = 1; //posiciona a peça removida no novo local recebido por argumento
String posicaoOrigem = concatenarIndice((byte) (x - 2), y);
String posicaoDestino = concatenarIndice(x, y);
movimento.setPosicaoOrigem(posicaoOrigem);
movimento.setPosicaoDestino(posicaoDestino);
movimento.setLadoMov(Movimento.ladoMovimentado.CIMA);
movimentos.add(movimento);
exibeMatriz();
movePeca();
return true;
} else if (((y + 2) <= 6) && (matriz[x][(y + 1)] == 1) && (matriz[x][(y + 2)] == 1)) { //testa a posição à direita da vazia y+1
matriz[x][(y + 1)] = 0; //remove a peça atribuindo zero
matriz[x][(y + 2)] = 0;
matriz[x][y] = 1; //posiciona a peça removida no novo local recebido por argumento
String posicaoOrigem = concatenarIndice(x, (byte) (y + 2));
String posicaoDestino = concatenarIndice(x, y);
movimento.setPosicaoOrigem(posicaoOrigem);
movimento.setPosicaoDestino(posicaoDestino);
movimento.setLadoMov(Movimento.ladoMovimentado.DIREITA);
movimentos.add(movimento);
exibeMatriz();
movePeca();
return true;
} else if (((x + 2) <= 6) && (matriz[(x + 1)][y] == 1) && (matriz[(x + 2)][y] == 1)) { //testa a posição abaixo da vazia x+1
matriz[(x + 1)][y] = 0; //remove a peça atribuindo zero
matriz[(x + 2)][y] = 0;
matriz[x][y] = 1; //posiciona a peça removida no novo local recebido por argumento
String posicaoOrigem = concatenarIndice((byte) (x + 2), y);
String posicaoDestino = concatenarIndice(x, y);
movimento.setPosicaoOrigem(posicaoOrigem);
movimento.setPosicaoDestino(posicaoDestino);
movimento.setLadoMov(Movimento.ladoMovimentado.BAIXO);
movimentos.add(movimento);
exibeMatriz();
movePeca();
return true;
} else if (((y - 2) >= 0) && (matriz[x][(y - 1)] == 1) && (matriz[x][(y - 2)] == 1)) { //testa a posição à esquerda da vazia y-1
matriz[x][(y - 1)] = 0; //remove a peça atribuindo zero
matriz[x][(y - 2)] = 0;
matriz[x][y] = 1; //posiciona a peça removida no novo local recebido por argumento
String posicaoOrigem = concatenarIndice(x, (byte) (y - 2));
String posicaoDestino = concatenarIndice(x, y);
movimento.setPosicaoOrigem(posicaoOrigem);
movimento.setPosicaoDestino(posicaoDestino);
movimento.setLadoMov(Movimento.ladoMovimentado.ESQUERDA);
movimentos.add(movimento);
exibeMatriz();
movePeca();
return true;
}
}
}
exibeMatriz();
System.out.println("Não há mais movimentos");
Start.terminou = true;
pecasRestantes();
return false;
}
public static void pecasRestantes() {
byte pecasRestantes = 0;
for (int i = 0; i <= 6; i++) {
for (int j = 0; j <= 6; j++) {
if (Logica.matriz[i][j] == 1) {
pecasRestantes++;
}
}
}
System.out.println("Peças restantes = " + pecasRestantes);
}
public static StringBuilder getIndices() {
return indices;
}
public static void setIndices(StringBuilder indices) {
Logica.indices = indices;
}
public static ArrayList<Movimento> getMovimentos() {
return movimentos;
}
public static void setMovimentos(ArrayList<Movimento> movimentos) {
Logica.movimentos = movimentos;
}
public static Movimento getMovimento() {
return movimento;
}
public static void setMovimento(Movimento movimento) {
Logica.movimento = movimento;
}
public static byte[][] getMatriz() {
return matriz;
}
public static void setMatriz(byte[][] matriz) {
Logica.matriz = matriz;
}
}
|
package com.yunhe.cargomanagement.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
/**
* <p>
* 库存查询
* </p>
*
* @author 耿旺
* @since 2019-01-02
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("warehouse")
public class Warehouse implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id",type = IdType.AUTO)
private Integer id;
/**
* 商品编号
*/
@TableField("wa_number")
private String waNumber;
/**
* 商品名称
*/
@TableField("wa_sp_name")
private String waSpName;
/**
* 规格
*/
@TableField("wa_sp_specifications")
private String waSpSpecifications;
/**
* 单位
*/
@TableField("wa_sp_company")
private String waSpCompany;
/**
* 可用库存量
*/
@TableField("wa_sp_lnventory")
private Integer waSpLnventory;
/**
* 当前存货
*/
@TableField("wa_sp_current_inventory")
private Integer waSpCurrentInventory;
/**
* 待出库量
*/
@TableField("wa_sp_forout")
private Integer waSpForout;
/**
* 待入库量
*/
@TableField("wa_sp_forenter")
private Integer waSpForenter;
/**
* 成本价
*/
@TableField("wa_cost")
private Double waCost;
/**
* 总金额
*/
@TableField("wa_total_sum")
private Double waTotalSum;
}
|
package co.raisense.bluetoothdemo.adapter;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import co.raisense.bluetoothdemo.R;
import static co.raisense.bluetoothdemo.Contants.ACCEL_PEDAL;
import static co.raisense.bluetoothdemo.Contants.DRIVER_TORQUE;
import static co.raisense.bluetoothdemo.Contants.GPS;
import static co.raisense.bluetoothdemo.Contants.PCT_LOAD;
import static co.raisense.bluetoothdemo.Contants.PCT_TORQUE;
import static co.raisense.bluetoothdemo.Contants.RPM;
import static co.raisense.bluetoothdemo.Contants.SPEED;
import static co.raisense.bluetoothdemo.Contants.TIME;
import static co.raisense.bluetoothdemo.Contants.TORQUE_MODE;
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.DataViewHolder>{
private ArrayList<HashMap<String, String>> data;
public DataAdapter(ArrayList<HashMap<String, String>> data) {
this.data = data;
}
@NonNull
@Override
public DataViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_list, viewGroup, false);
return new DataViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull DataViewHolder dataViewHolder, int i) {
dataViewHolder.setData(data.get(i));
}
@Override
public int getItemCount() {
return data.size();
}
class DataViewHolder extends RecyclerView.ViewHolder{
private TextView time;
private TextView dataView1;
private TextView dataView2;
private TextView dataView3;
private TextView dataView4;
private TextView dataView5;
private TextView dataView6;
private TextView dataView7;
private TextView dataView8;
private TextView dataView9;
private TextView textView1;
private TextView textView2;
private TextView textView3;
private TextView textView4;
private TextView textView5;
private TextView textView6;
private TextView textView7;
private TextView textView8;
private TextView textView9;
DataViewHolder(@NonNull View itemView) {
super(itemView);
init(itemView);
}
private void init(View itemView) {
time = itemView.findViewById(R.id.txt_time);
dataView3 = itemView.findViewById(R.id.txt_dataLabel1);
dataView1 = itemView.findViewById(R.id.txt_dataLabel2);
dataView2 = itemView.findViewById(R.id.txt_dataLabel3);
dataView4 = itemView.findViewById(R.id.txt_dataLabel4);
dataView5 = itemView.findViewById(R.id.txt_dataLabel5);
dataView6 = itemView.findViewById(R.id.txt_dataLabel6);
dataView7 = itemView.findViewById(R.id.txt_dataLabel7);
dataView8 = itemView.findViewById(R.id.txt_dataLabel8);
dataView9 = itemView.findViewById(R.id.txt_dataLabel9);
textView1 = itemView.findViewById(R.id.txt_dataText1);
textView2 = itemView.findViewById(R.id.txt_dataText2);
textView3 = itemView.findViewById(R.id.txt_dataText3);
textView4 = itemView.findViewById(R.id.txt_dataText4);
textView5 = itemView.findViewById(R.id.txt_dataText5);
textView6 = itemView.findViewById(R.id.txt_dataText6);
textView7 = itemView.findViewById(R.id.txt_dataText7);
textView8 = itemView.findViewById(R.id.txt_dataText8);
textView9 = itemView.findViewById(R.id.txt_dataText9);
}
void setData(HashMap<String, String> data){
time.setText(data.get(TIME));
dataView1.setText("RPM");
dataView2.setText("Speed");
dataView3.setText("Accel Pedal");
dataView4.setText("Pct Load");
dataView5.setText("Pct Torque");
dataView6.setText("Driver Torque");
dataView7.setText("Torque Mode");
dataView8.setText("Longitude");
dataView9.setText("Latitude");
textView1.setText(data.get(RPM));
textView2.setText(data.get(SPEED));
textView3.setText(data.get(ACCEL_PEDAL));
textView4.setText(data.get(PCT_LOAD));
textView5.setText(data.get(PCT_TORQUE));
textView6.setText(data.get(DRIVER_TORQUE));
textView7.setText(data.get(TORQUE_MODE));
String[] gps_data = data.get(GPS).split(" ");
if (gps_data.length == 2) {
textView8.setText(gps_data[0]);
textView9.setText(gps_data[1]);
}
}
}
}
|
package com.grasset.bernard.morseviceversa;
import java.text.Normalizer;
public class ControleTraduction implements TraducteurMorse{
//=====
public DictionnaireMorse [] tableauDictionnaireMorse = DictionnaireMorse.values();
//=====
@Override
public String toAlpha(String morse) {
//---
String retTraduction = "";
String [] arrayMotsTraduit = morse.split(" ");
int tailleArray = arrayMotsTraduit.length;
for (int x = 0; x < tailleArray; x++) {
if (arrayMotsTraduit[x].equalsIgnoreCase("...---...")) {
retTraduction += "SOS";
} else if (arrayMotsTraduit[x].equalsIgnoreCase(".-.-.-")) {
retTraduction += ".";
} else if (arrayMotsTraduit[x].equalsIgnoreCase("/")) {
retTraduction += " ";
} else {
for(int i = 0; i < tableauDictionnaireMorse.length; i++) {
if (tableauDictionnaireMorse[i].getMorse().toString().equalsIgnoreCase(arrayMotsTraduit[x])) {
switch (tableauDictionnaireMorse[i].toString()) {
case "ZERO":
retTraduction += "0";
break;
case "UN":
retTraduction += "1";
break;
case "DEUX":
retTraduction += "2";
break;
case "TROIS":
retTraduction += "3";
break;
case "QUATRE":
retTraduction += "4";
break;
case "CINQ":
retTraduction += "5";
break;
case "SEX":
retTraduction += "6";
break;
case "SEPT":
retTraduction += "7";
break;
case "HUIT":
retTraduction += "8";
break;
case "NEUF":
retTraduction += "9";
break;
default:
retTraduction += tableauDictionnaireMorse[i].toString();
break;
}
}
}
}
}
return retTraduction;
}
//=====
@Override
public String toMorse(String alpha) {
String retTraduiction = "";
String [] arrayMotsTraduit = alpha.split(" ");
int tailleArray = arrayMotsTraduit.length;
for (int x = 0; x < tailleArray; x++) {
if (arrayMotsTraduit[x].equalsIgnoreCase("SOS")) {
retTraduiction += "...---... ";
} else if (arrayMotsTraduit[x].equalsIgnoreCase(".")) {
retTraduiction += ".-.-.- ";
} else {
for (int y = 0; y < arrayMotsTraduit[x].length(); y++) {
if (!String.valueOf(arrayMotsTraduit[x].charAt(y)).equalsIgnoreCase(".")) {
retTraduiction += DictionnaireMorse.valueOf(transformNumMot(String.valueOf(arrayMotsTraduit[x].charAt(y)))).getMorse()+" ";
} else {
retTraduiction += ".-.-.- ";
}
}
}
if (x+1 < tailleArray) {
retTraduiction += "/ ";
}
}
return retTraduiction;
}
//=====
@Override
public String nettoyerAlpha(String alpha) {
alpha = alpha.toUpperCase();
alpha = Normalizer.normalize(alpha, Normalizer.Form.NFD).replaceAll("[[^\\p{ASCII}][\\p{Punct}&&[^.]]]", "");
alpha = Normalizer.normalize(alpha, Normalizer.Form.NFD).replaceAll("[$+<>=^`|~]", "");
return alpha;
}
//=====
@Override
public String getNomProgrammeurs() {
return " Claude-Bernard Millen/ Claude-Bernard Millen";
}
//=====
public String transformNumMot(String lettre) {
switch (lettre) {
case "0":
lettre = "ZERO";
break;
case "1":
lettre = "UN";
break;
case "2":
lettre = "DEUX";
break;
case "3":
lettre = "TROIS";
break;
case "4":
lettre = "QUATRE";
break;
case "5":
lettre = "CINQ";
break;
case "6":
lettre = "SIX";
break;
case "7":
lettre = "SEPT";
break;
case "8":
lettre = "HUIT";
break;
case "9":
lettre = "NEUF";
break;
default:
break;
}
return lettre;
}
}
|
package com.scmaster.milanmall.board.vo;
public class Board {
private int revw_boardnum;
private String revw_id;
private String revw_title;
private String revw_content;
private String revw_inputdate;
private int revw_hits;
private int revw_like;
private String revw_originalfile;
private String revw_savedfile;
public Board() {
super();
}
public Board(int revw_boardnum, String revw_id, String revw_title, String revw_content, String revw_inputdate,
int revw_hits, int revw_like, String revw_originalfile, String revw_savedfile) {
super();
this.revw_boardnum = revw_boardnum;
this.revw_id = revw_id;
this.revw_title = revw_title;
this.revw_content = revw_content;
this.revw_inputdate = revw_inputdate;
this.revw_hits = revw_hits;
this.revw_like = revw_like;
this.revw_originalfile = revw_originalfile;
this.revw_savedfile = revw_savedfile;
}
public int getRevw_boardnum() {
return revw_boardnum;
}
public void setRevw_boardnum(int revw_boardnum) {
this.revw_boardnum = revw_boardnum;
}
public String getRevw_id() {
return revw_id;
}
public void setRevw_id(String revw_id) {
this.revw_id = revw_id;
}
public String getRevw_title() {
return revw_title;
}
public void setRevw_title(String revw_title) {
this.revw_title = revw_title;
}
public String getRevw_content() {
return revw_content;
}
public void setRevw_content(String revw_content) {
this.revw_content = revw_content;
}
public String getRevw_inputdate() {
return revw_inputdate;
}
public void setRevw_inputdate(String revw_inputdate) {
this.revw_inputdate = revw_inputdate;
}
public int getRevw_hits() {
return revw_hits;
}
public void setRevw_hits(int revw_hits) {
this.revw_hits = revw_hits;
}
public int getRevw_like() {
return revw_like;
}
public void setRevw_like(int revw_like) {
this.revw_like = revw_like;
}
public String getRevw_originalfile() {
return revw_originalfile;
}
public void setRevw_originalfile(String revw_originalfile) {
this.revw_originalfile = revw_originalfile;
}
public String getRevw_savedfile() {
return revw_savedfile;
}
public void setRevw_savedfile(String revw_savedfile) {
this.revw_savedfile = revw_savedfile;
}
@Override
public String toString() {
return "Board [revw_boardnum=" + revw_boardnum + ", revw_id=" + revw_id + ", revw_title=" + revw_title
+ ", revw_content=" + revw_content + ", revw_inputdate=" + revw_inputdate + ", revw_hits=" + revw_hits
+ ", revw_like=" + revw_like + ", revw_originalfile=" + revw_originalfile + ", revw_savedfile="
+ revw_savedfile + "]";
}
}
|
package cn.yami.wechat.demo.service;
import cn.yami.wechat.demo.dao.ShopDao;
import cn.yami.wechat.demo.dto.Shops;
import cn.yami.wechat.demo.dto.SpikeShops;
import cn.yami.wechat.demo.entity.ShopVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ShopService {
@Autowired
ShopDao shopDao;
public List<ShopVo> listShopVo(){
return shopDao.listShopVo();
}
public ShopVo getShopVoByShopId(long shopId) {
return shopDao.getShopVoByShopId(shopId);
}
public void reduceStock(ShopVo shopVo) {
SpikeShops spikeShops = new SpikeShops();
spikeShops.setShopId(shopVo.getId());
shopDao.reduceStock(spikeShops);
}
}
|
/*
* 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 fr.univlyon1.m1if.m1if03.servlets;
import fr.univlyon1.m1if.m1if03.classes.Groupe;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author vasli
*/
@WebFilter("/AutorisationFilter")
public class AutorisationFilter implements Filter{
private ServletContext context;//utilisé pour de la log;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.context = filterConfig.getServletContext();
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String chemin = request.getRequestURI();
HttpSession session = request.getSession(false);
// Accés à un billet, on vérifie si le billet indiqué existe
if (request.getMethod().equals("GET") && chemin.equals("/billet")) {
if (request.getParameter("id") != null) {
String nameGroupe = (String) session.getAttribute("groupe");
Map<String,Groupe> modele = (HashMap<String, Groupe>) request.getServletContext().getAttribute("groupes");
if (modele != null
&& modele.get(nameGroupe) != null
&& modele.get(nameGroupe).getgBillets() != null
&& modele.get(nameGroupe).getgBillets().getBillet(new Integer(request.getParameter("id"))) != null
){
this.context.log("Le billet existe avec le groupe de l'utilisateur");
chain.doFilter(request, response);
}else{
this.context.log("Le billet n'est pas accessible à l'utilisateur");
request.getRequestDispatcher("/billets").forward(request, response);
}
}
} else {
chain.doFilter(request, response);
}
}
@Override
public void destroy() {}
}
|
package com.tencent.mm.modelcdntran;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import com.tencent.mm.a.g;
import com.tencent.mm.model.q;
import com.tencent.mm.sdk.platformtools.ao;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import java.net.HttpURLConnection;
import java.util.List;
public final class d {
public static int dPg = 1;
public static int dPh = 2;
public static int dPi = 3;
public static int dPj = -1;
public static int dPk = 3;
public static int dPl = 4;
public static int dPm = 5;
public static int dPn = 1;
public static int dPo = 2;
public static int dPp = -10001;
public static int dPq = -10002;
public static int dPr = -10003;
public static int dPs = -10004;
public static void b(byte[] bArr, String str, int i) {
if (bi.bC(bArr)) {
bArr = new byte[0];
}
String str2 = new String(bArr);
if (i == 4) {
x.e(str, str2);
} else if (i == 3) {
x.w(str, str2);
} else if (i == 2) {
x.i(str, str2);
} else if (i == 1) {
x.d(str, str2);
} else if (i == 0) {
x.v(str, str2);
}
}
private static String ly(String str) {
if (bi.oW(str)) {
return str;
}
for (int i = 0; i < str.length(); i++) {
char charAt = str.charAt(i);
if (!bi.o(charAt) && !bi.p(charAt)) {
return null;
}
}
return str;
}
public static String a(String str, long j, String str2, String str3) {
x.d("MicroMsg.CdnUtil", "cdntra genClientId prefix[%s] createtime:%d talker[%s] suffix:[%s] stack[%s]", new Object[]{str, Long.valueOf(j), str2, str3, bi.cjd()});
if (bi.oW(ly(str)) || bi.oW(str2) || j <= 0) {
return null;
}
String oV = bi.oV(ly(str3));
String str4 = "a" + str + "_" + g.u((q.GF() + "-" + str2).getBytes()).substring(0, 16) + "_" + j;
if (bi.oW(oV)) {
return str4;
}
return str4 + "_" + oV;
}
public static int bK(Context context) {
try {
NetworkInfo activeNetworkInfo = ((ConnectivityManager) context.getSystemService("connectivity")).getActiveNetworkInfo();
if (activeNetworkInfo == null) {
return dPg;
}
if (activeNetworkInfo.getType() == 1) {
return dPi;
}
if (activeNetworkInfo.getSubtype() == 1) {
return dPg;
}
if (activeNetworkInfo.getSubtype() == 2) {
return dPg;
}
if (activeNetworkInfo.getSubtype() >= 3) {
return dPh;
}
return dPg;
} catch (Throwable e) {
x.e("MicroMsg.CdnUtil", "exception:%s", new Object[]{bi.i(e)});
return dPg;
}
}
public static int bL(Context context) {
int netType = ao.getNetType(context);
NetworkInfo activeNetworkInfo = ((ConnectivityManager) context.getSystemService("connectivity")).getActiveNetworkInfo();
if (activeNetworkInfo == null) {
return dPj;
}
if (activeNetworkInfo.getType() == 1) {
return dPn;
}
if (activeNetworkInfo.getSubtype() == 1 || activeNetworkInfo.getSubtype() == 2) {
return dPk;
}
if (activeNetworkInfo.getSubtype() >= 13) {
return dPm;
}
if (activeNetworkInfo.getSubtype() >= 3) {
return dPl;
}
if (ao.isWap(netType)) {
return dPo;
}
return dPk;
}
public static int c(HttpURLConnection httpURLConnection) {
try {
List list = (List) httpURLConnection.getHeaderFields().get("cache-control");
if (list == null || list.size() == 0) {
return 0;
}
if (bi.oW(list.toString()) || !list.toString().contains("no-cache")) {
return 0;
}
return -1;
} catch (Throwable e) {
x.e("MicroMsg.CdnUtil", "exception:%s", new Object[]{bi.i(e)});
return -2;
}
}
}
|
public class BadInstructionException extends RuntimeException {
public BadInstructionException() {
super();
}
public BadInstructionException(String message) {
super(message);
}
}
|
package org.akrogen.dynaresume.raphelloworld;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.DecoratingLabelProvider;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ILabelDecorator;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.views.properties.IPropertyDescriptor;
import org.eclipse.ui.views.properties.IPropertySource;
import org.eclipse.ui.views.properties.TextPropertyDescriptor;
public class TreeViewPart extends ViewPart {
public static final String ID = "org.akrogen.dynaresume.raphelloworld.treeviewpart";
public static final String ID_II = "org.akrogen.dynaresume.raphelloworld.treeviewpartII";
private TreeViewer treeViewer;
@Override
public void createPartControl(Composite parent) {
treeViewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
treeViewer.setContentProvider(new ViewContentProvider());
ILabelDecorator labelDecorator = PlatformUI.getWorkbench()
.getDecoratorManager().getLabelDecorator();
ILabelProvider labelProvider = new DecoratingLabelProvider(
new ViewLabelProvider(), labelDecorator);
treeViewer.setLabelProvider(labelProvider);
treeViewer.setInput(this);
treeViewer.addDoubleClickListener(new IDoubleClickListener() {
@Override
public void doubleClick(DoubleClickEvent event) {
String msg = "You double clicked on: "
+ event.getSelection().toString();
Shell shell = treeViewer.getTree().getShell();
MessageDialog.openInformation(shell, "Treeviewer", msg);
}
});
getSite().setSelectionProvider(treeViewer);
}
@Override
public void setFocus() {
treeViewer.getControl().setFocus();
}
class ViewContentProvider implements ITreeContentProvider, IStructuredContentProvider {
private TreeParent treeParent;
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
@Override
public boolean hasChildren(Object element) {
if (element instanceof TreeParent) {
return ((TreeParent) element).hasChildren();
}
return false;
}
@Override
public Object getParent(Object element) {
if (element instanceof TreeObject) {
return ((TreeObject) element).getParent();
}
return null;
}
@Override
public Object[] getElements(Object inputElement) {
if (inputElement instanceof IViewPart) {
if (treeParent == null) {
initTreeView();
}
return getChildren(treeParent);
}
return getChildren(inputElement);
}
private void initTreeView() {
TreeObject treeObject_1 = new TreeObject(
"EclipseCon location",
"http://google.com");
TreeObject treeObject_2 = new TreeObject("Eclipse Foundation",
"http://maps.google.com/maps?q=Ottawa");
TreeObject treeObject_3 = new TreeObject("Innoopract Inc",
"http://maps.google.com/maps?q=Portland");
TreeParent treeParent_1 = new TreeParent("Locate in browser view");
treeParent_1.addChild(treeObject_1);
treeParent_1.addChild(treeObject_2);
treeParent_1.addChild(treeObject_3);
BrokenTreeObject treeObject_4 = new BrokenTreeObject("Leaf 4");
TreeParent treeParent_2 = new TreeParent("Parent 2");
treeParent_2.addChild(treeObject_4);
TreeParent treeParent_3 = new TreeParent("Child X - Filter me!");
TreeParent root = new TreeParent("Root");
root.addChild(treeParent_1);
root.addChild(treeParent_2);
root.addChild(treeParent_3);
treeParent = new TreeParent("");
treeParent.addChild(root);
}
@Override
public Object[] getChildren(Object parentElement) {
if (parentElement instanceof TreeParent) {
return ((TreeParent) parentElement).getChildren();
}
return new Object[0];
}
@Override
public void dispose() {
}
}
class ViewLabelProvider extends LabelProvider {
@Override
public Image getImage(Object element) {
IWorkbench workbench = PlatformUI.getWorkbench();
ISharedImages sharedImages = workbench.getSharedImages();
return sharedImages.getImage(ISharedImages.IMG_OBJ_ELEMENT);
}
}
class TreeObject implements IPropertySource {
private static final String PROP_ID_LOCATION = "location";
private static final String PROP_ID_NAME = "name";
private String name;
private String location;
private TreeParent parent;
public TreeObject(String name) {
this(name, "");
}
public TreeObject(String name, String location) {
this.name = name;
this.location = location;
}
public String getName() {
return name;
}
public String getLocation() {
return location;
}
public void setParent(TreeParent parent) {
this.parent = parent;
}
public TreeParent getParent() {
return parent;
}
@Override
public String toString() {
return getName();
}
@Override
public Object getEditableValue() {
return this;
}
@Override
public IPropertyDescriptor[] getPropertyDescriptors() {
return new IPropertyDescriptor[] {
new TextPropertyDescriptor(PROP_ID_NAME, "Name"),
new TextPropertyDescriptor(PROP_ID_LOCATION, "Location"), };
}
@Override
public Object getPropertyValue(Object id) {
Object result = null;
if (PROP_ID_NAME.equals(id)) {
result = name;
} else if (PROP_ID_LOCATION.equals(id)) {
result = location;
}
return result;
}
@Override
public void resetPropertyValue(Object id) {
if (PROP_ID_NAME.equals(id)) {
name = "";
} else if (PROP_ID_LOCATION.equals(id)) {
location = "";
}
}
@Override
public void setPropertyValue(Object id, Object value) {
if (PROP_ID_NAME.equals(id)) {
name = (String) value;
} else if (PROP_ID_LOCATION.equals(id)) {
location = (String) value;
}
treeViewer.update(this, null);
}
@Override
public boolean isPropertySet(Object id) {
boolean result = false;
if (PROP_ID_NAME.equals(id)) {
result = name != null && !"".equals(name);
} else if (PROP_ID_LOCATION.equals(id)) {
result = location != null && !"".equals(location);
}
return result;
}
}
private class TreeParent extends TreeObject {
private final List<TreeObject> children;
public TreeParent(String name) {
super(name);
children = new ArrayList<TreeObject>();
}
public void addChild(TreeObject child) {
children.add(child);
child.setParent(this);
}
public TreeObject[] getChildren() {
TreeObject[] result = new TreeObject[children.size()];
children.toArray(result);
return result;
}
public boolean hasChildren() {
return children.size() > 0;
}
}
private class BrokenTreeObject extends TreeObject {
public BrokenTreeObject(String name) {
super(name);
}
}
}
|
package com.cheng.targetmanager.service;
import com.cheng.targetmanager.entity.Task;
public interface TaskService {
void add(Task task);
int getCount();
}
|
package no.uib.info331.activities;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;
import com.google.gson.Gson;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import no.uib.info331.R;
import no.uib.info331.adapters.BeaconListViewAdapter;
import no.uib.info331.models.Beacon;
import no.uib.info331.models.messages.BeaconListEvent;
import no.uib.info331.queries.BeaconQueries;
import no.uib.info331.util.DataManager;
public class AddBeaconToGroupActivity extends AppCompatActivity {
BeaconQueries beaconQueries = new BeaconQueries();
DataManager dataManager = new DataManager();
@BindView(R.id.edittext_create_search_for_beacons) EditText editTextSearchForBeacons;
@BindView(R.id.imagebutton_search_for_beacons) ImageButton imageBtnSearchForBeacons;
@BindView(R.id.listview_beacon_search_result) ListView listViewBeaconSearchResult;
@BindView(R.id.listview_added_beacons) ListView listViewBeaconsAdded;
@BindView(R.id.btn_accept_searched_beacons) Button btnAcceptRegisteredBeacons;
Context context;
BeaconListViewAdapter listViewAdapterBeaconsSearchResult;
BeaconListViewAdapter listViewAdapterBeaconsAdded;
List<Beacon> arrayListBeaconsAdded = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_beacon_to_group);
context = getApplicationContext();
ButterKnife.bind(this);
initListeners();
initListViewBeaconsAdded(arrayListBeaconsAdded);
}
private void initListeners() {
imageBtnSearchForBeacons.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String query = String.valueOf(editTextSearchForBeacons.getText());
beaconQueries.getBeaconsByStringFromDb(context, query);
}
});
btnAcceptRegisteredBeacons.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
listViewBeaconSearchResult.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Beacon beacon = listViewAdapterBeaconsSearchResult.getItem(position);
listViewAdapterBeaconsAdded.add(beacon);
listViewAdapterBeaconsAdded.notifyDataSetChanged();
}
});
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onBeaconListEvent(BeaconListEvent beaconListEvent) {
initListViewBeaconSearchList(beaconListEvent.getBeaconList());
}
private void initListViewBeaconSearchList(List<Beacon> beaconSearch) {
listViewAdapterBeaconsSearchResult = new BeaconListViewAdapter(context, R.layout.list_element_beacon, beaconSearch);
listViewBeaconSearchResult.setAdapter(listViewAdapterBeaconsSearchResult);
}
private void initListViewBeaconsAdded(List<Beacon> beaconsAdded) {
listViewAdapterBeaconsAdded = new BeaconListViewAdapter(context, R.layout.list_element_beacon, beaconsAdded);
listViewBeaconsAdded.setAdapter(listViewAdapterBeaconsAdded);
}
/**
* Method from activity to display the "Back arrow"
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
super.onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
Gson gson = new Gson();
String addedBeaconsString = gson.toJson(arrayListBeaconsAdded);
Intent intent = new Intent();
intent.putExtra("addedBeacons", addedBeaconsString);
setResult(RESULT_OK, intent);
super.onBackPressed();
}
@Override
protected void onResume() {
super.onResume();
EventBus.getDefault().register(this);
}
@Override
protected void onPause() {
EventBus.getDefault().unregister(this);
super.onPause();
}
}
|
package com.rastiehaiev.notebook.constants;
/**
* @author Roman Rastiehaiev
* Created on 04.10.15.
*/
public interface CommonConstants {
String LOGIN_PATTERN = "[a-z0-9]{3,15}";
String NAME_AND_SURNAME_PATTERN = "[A-Za-z]{2,15}";
}
|
package com.example.gourav_chawla.taskready;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class noteDetail extends AppCompatActivity {
EditText note;
Button notebutton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_detail);
note = (EditText)findViewById(R.id.mynote);
notebutton = (Button)findViewById(R.id.submitButton);
notebutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String text = note.getText().toString();
sqlnotehelper sqlnotehelper = new sqlnotehelper(noteDetail.this);
SQLiteDatabase db = sqlnotehelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("content" , text);
db.insert("note",null,values);
Intent i = new Intent(noteDetail.this,MainActivity.class);
Toast.makeText(noteDetail.this,"Note created" ,Toast.LENGTH_SHORT).show();
startActivity(i);
}
});
}
}
|
package cd.com.a.model;
import java.io.Serializable;
/*
CREATE TABLE product
(
`product_num` INT(5) NOT NULL AUTO_INCREMENT COMMENT '�젣�뭹SEQ',
`product_name` VARCHAR(45) NOT NULL COMMENT '�젣�뭹紐�',
`product_readcount` INT(7) NULL COMMENT '議고쉶�닔',
`product_img` TEXT NOT NULL COMMENT '�씠誘몄�',
`product_price` INT(6) NOT NULL COMMENT '媛�寃�',
`product_group` INT(2) NOT NULL COMMENT '洹몃9',
`product_sub_group` INT(2) NULL COMMENT '�꽌釉뚭렇猷�',
`product_code` VARCHAR(45) NOT NULL COMMENT '�젣�뭹肄붾뱶',
PRIMARY KEY (product_num)
);
*/
public class productDto implements Serializable {
private int product_num; // 제품SEQ
private String product_name; // 제품명
private String product_code; // 제품코드
private int product_readcount; // 조회수
private String product_img; // 이미지
private int product_price; // 가격
private String product_group; // 그룹
private String product_sub_group; // 서브그룹
private String product_content; // 내용
private String product_regi_date; // 제품등록날짜
private String product_brand; // 브랜드회사명
private int product_sale; // 판매여부
private int product_hidden; // 노출여부
private int product_stock; // 현재재고량
private int product_delivery_auth; // 배송비
private int product_del; // 제품 삭제
public productDto() {
super();
}
public productDto(int product_num, String product_name, String product_code, int product_readcount,
String product_img, int product_price, String product_group, String product_sub_group,
String product_content, String product_regi_date, String product_brand, int product_sale,
int product_hidden, int product_stock, int product_delivery_auth, int product_del) {
super();
this.product_num = product_num;
this.product_name = product_name;
this.product_code = product_code;
this.product_readcount = product_readcount;
this.product_img = product_img;
this.product_price = product_price;
this.product_group = product_group;
this.product_sub_group = product_sub_group;
this.product_content = product_content;
this.product_regi_date = product_regi_date;
this.product_brand = product_brand;
this.product_sale = product_sale;
this.product_hidden = product_hidden;
this.product_stock = product_stock;
this.product_delivery_auth = product_delivery_auth;
this.product_del = product_del;
}
public int getProduct_num() {
return product_num;
}
public void setProduct_num(int product_num) {
this.product_num = product_num;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public String getProduct_code() {
return product_code;
}
public void setProduct_code(String product_code) {
this.product_code = product_code;
}
public int getProduct_readcount() {
return product_readcount;
}
public void setProduct_readcount(int product_readcount) {
this.product_readcount = product_readcount;
}
public String getProduct_img() {
return product_img;
}
public void setProduct_img(String product_img) {
this.product_img = product_img;
}
public int getProduct_price() {
return product_price;
}
public void setProduct_price(int product_price) {
this.product_price = product_price;
}
public String getProduct_group() {
return product_group;
}
public void setProduct_group(String product_group) {
this.product_group = product_group;
}
public String getProduct_sub_group() {
return product_sub_group;
}
public void setProduct_sub_group(String product_sub_group) {
this.product_sub_group = product_sub_group;
}
public String getProduct_content() {
return product_content;
}
public void setProduct_content(String product_content) {
this.product_content = product_content;
}
public String getProduct_regi_date() {
return product_regi_date;
}
public void setProduct_regi_date(String product_regi_date) {
this.product_regi_date = product_regi_date;
}
public String getProduct_brand() {
return product_brand;
}
public void setProduct_brand(String product_brand) {
this.product_brand = product_brand;
}
public int getProduct_sale() {
return product_sale;
}
public void setProduct_sale(int product_sale) {
this.product_sale = product_sale;
}
public int getProduct_hidden() {
return product_hidden;
}
public void setProduct_hidden(int product_hidden) {
this.product_hidden = product_hidden;
}
public int getProduct_stock() {
return product_stock;
}
public void setProduct_stock(int product_stock) {
this.product_stock = product_stock;
}
public int getProduct_delivery_auth() {
return product_delivery_auth;
}
public void setProduct_delivery_auth(int product_delivery_auth) {
this.product_delivery_auth = product_delivery_auth;
}
public int getProduct_del() {
return product_del;
}
public void setProduct_del(int product_del) {
this.product_del = product_del;
}
@Override
public String toString() {
return "productDto [product_num=" + product_num + ", product_name=" + product_name + ", product_code="
+ product_code + ", product_readcount=" + product_readcount + ", product_img=" + product_img
+ ", product_price=" + product_price + ", product_group=" + product_group + ", product_sub_group="
+ product_sub_group + ", product_content=" + product_content + ", product_regi_date="
+ product_regi_date + ", product_brand=" + product_brand + ", product_sale=" + product_sale
+ ", product_hidden=" + product_hidden + ", product_stock=" + product_stock + ", product_delivery_auth="
+ product_delivery_auth + ", product_del=" + product_del + "]";
}
}
|
package com.example.mapping;
import android.app.AlertDialog;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.osmdroid.config.Configuration;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.ItemizedIconOverlay;
import org.osmdroid.views.overlay.OverlayItem;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
MapView mv;
ItemizedIconOverlay<OverlayItem> items;
ItemizedIconOverlay.OnItemGestureListener<OverlayItem> markerGestureListener;
double lat;
double lon;
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// This line sets the user agent, a requirement to download OSM maps
Configuration.getInstance().load(this, PreferenceManager.getDefaultSharedPreferences(this));
setContentView(R.layout.activity_main);
mv = (MapView) findViewById(R.id.map1);
mv.setBuiltInZoomControls(true);
mv.getController().setZoom(17);
mv.getController().setCenter(new GeoPoint(50.9349, -1.4219));
markerGestureListener = new ItemizedIconOverlay.OnItemGestureListener<OverlayItem>() {
public boolean onItemLongPress(int i, OverlayItem item) {
Toast.makeText(MainActivity.this, item.getSnippet(), Toast.LENGTH_SHORT).show();
return true;
}
public boolean onItemSingleTapUp(int i, OverlayItem item) {
Toast.makeText(MainActivity.this, item.getSnippet(), Toast.LENGTH_SHORT).show();
return true;
}
};
items = new ItemizedIconOverlay<OverlayItem>(this, new ArrayList<OverlayItem>(), markerGestureListener);
try {
FileReader fr = new FileReader(Environment.getExternalStorageDirectory().getAbsolutePath() + "/restaurants.txt");
BufferedReader reader = new BufferedReader(fr);
String line = "";
while ((line = reader.readLine()) != null) {
String[] components = line.split(",");
if (components.length == 5) {
OverlayItem currentPoi = new OverlayItem(components[0], components[1], components[2], new GeoPoint(Double.parseDouble(components[4]), Double.parseDouble(components[3])));
switch (components[1]) {
case "Chinese":
currentPoi.setMarker(this.getDrawable(R.drawable.pub));
break;
case "Indian":
currentPoi.setMarker(this.getDrawable(R.drawable.teashop));
break;
case "Thai":
currentPoi.setMarker(this.getDrawable(R.drawable.restaurant));
break;
default:
currentPoi.setMarker(this.getDrawable(R.drawable.marker));
}
items.addItem(currentPoi);
}
}
reader.close();
} catch (IOException e) {
new AlertDialog.Builder(this).setPositiveButton("OK", null).
setMessage("ERROR: " + e).show();
}
items.addItem(new OverlayItem("Matt's House", "The home of the man the legend that is Matthew Dear", new GeoPoint(50.9349, -1.4219)));
mv.getOverlays().add(items);
Button b = (Button) findViewById(R.id.btn1);
b.setOnClickListener(this);
}
@Override
public void onClick(View v) {
EditText et1 = (EditText) findViewById(R.id.et1);
EditText et2 = (EditText) findViewById(R.id.et2);
if (et1.getText().toString().isEmpty()) {
new AlertDialog.Builder(this).setPositiveButton("OK", null).setMessage("Latitude should not be empty").show();
return;
} else {
lat = Double.parseDouble(et1.getText().toString());
}
if (et2.getText().toString().isEmpty()) {
new AlertDialog.Builder(this).setPositiveButton("OK", null).setMessage("Longitude should not be empty").show();
return;
} else {
lon = Double.parseDouble(et2.getText().toString());
}
mv.getController().setZoom(17);
mv.getController().setCenter(new GeoPoint(lat, lon));
}
} |
package com.jasoftsolutions.mikhuna.routing;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import com.jasoftsolutions.mikhuna.util.ExceptionUtil;
import com.usepropeller.routable.Router;
/**
* Created by pc07 on 17/10/2014.
*/
public class RoutingHandler {
/**
* True si hay rutas que manejar, sino retorna false
* @param intent
* @return
*/
public static boolean handleRouter(Context context, Intent intent) {
Routes.setContext(context);
Uri uri = intent.getData();
if (uri != null) {
try {
Router.sharedRouter().open(uri.getPath());
return true;
} catch (Exception e) {
ExceptionUtil.handleException(e);
}
}
return false;
}
}
|
package Questao03;
/**
* 17/03/2020
* @author thais
*/
public class Main {
public static void main(String[] args) {
Q1 q1 = new Q1();
Q2 q2 = new Q2();
q1.start();
q2.start();
q1.interrupt();
System.out.println("Thread q1: " + q1.isInterrupted());
q2.interrupt();
System.out.println("Thread q2: " + q2.isInterrupted());
}
}
|
/*
* created 28.10.2005
*
* Copyright 2009, ByteRefinery
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* $Id: SchemaNode.java 669 2007-10-27 08:23:31Z cse $
*/
package com.byterefinery.rmbench.export.diff.db;
import java.util.List;
import com.byterefinery.rmbench.RMBenchPlugin;
import com.byterefinery.rmbench.export.diff.IComparisonNode;
import com.byterefinery.rmbench.external.IDDLGenerator;
import com.byterefinery.rmbench.external.IDDLScript;
import com.byterefinery.rmbench.model.Model;
import com.byterefinery.rmbench.model.dbimport.DBSchema;
import com.byterefinery.rmbench.model.dbimport.DBTable;
import com.byterefinery.rmbench.operations.AddSchemaOperation;
import com.byterefinery.rmbench.operations.RMBenchOperation;
import com.byterefinery.rmbench.util.ImageConstants;
/**
* @author cse
*/
class SchemaNode extends DBStructureNode {
private final DBSchema schema;
SchemaNode(DBSchema schema) {
super(schema.getName(), RMBenchPlugin.getImage(ImageConstants.SCHEMA2));
this.schema = schema;
List<DBTable> schemaTables = schema.getTables();
TableNode[] tableNodes = new TableNode[schemaTables.size()];
for (int i = 0; i < tableNodes.length; i++) {
tableNodes[i] = new TableNode(schemaTables.get(i));
}
setChildNodes(tableNodes);
}
public Object getElement() {
return schema;
}
public void generateDropDDL(IDDLGenerator generator, IDDLScript script) {
script.beginStatementContext();
generator.dropSchema(schema.getISchema(), script);
setStatementContext(script.endStatementContext());
}
public String getNodeType() {
return IComparisonNode.SCHEMA;
}
public RMBenchOperation newAddToModelOperation(Model model) {
return new AddSchemaOperation(model, schema.getName());
}
}
|
package org.maven.ide.eclipse.ui.common.validation;
import junit.framework.TestCase;
import org.netbeans.validation.api.Problems;
public class SonatypeValidatorsTest
extends TestCase
{
public void testValidHttpUrl()
{
Problems p = new Problems();
SonatypeValidators.createRemoteHttpUrlValidators().validate( p, "testfield", "http://devclone-55.1515.mtvi.com:8081/nexus" );
assertFalse( p.toString(), p.hasFatal() );
}
public void testInvalidHttpUrl()
{
String url = "http://localhost:8081/nexus/foo%";
Problems p = new Problems();
SonatypeValidators.createRemoteHttpUrlValidators().validate( p, "testfield", url );
assertTrue( p.toString(), p.hasFatal() );
assertTrue( p.getLeadProblem().getMessage(),
p.getLeadProblem().getMessage().startsWith( "'" + url + "' is not a valid URL" ) );
}
public void testValidScmUrl()
{
Problems p = new Problems();
SonatypeValidators.URL_MUST_BE_VALID.validate( p, "testfield", "scm:git:github.com:sonatype/sonatype-tycho.git" );
assertFalse( p.toString(), p.hasFatal() );
}
public void testInvalidScmUrl()
{
Problems p = new Problems();
SonatypeValidators.URL_MUST_BE_VALID.validate( p, "testfield", "scm:x" );
assertTrue( p.toString(), p.hasFatal() );
assertEquals( "'scm:x' is not a valid URL: SCM URI 'scm:x' does not specify SCM type",
p.getLeadProblem().getMessage() );
}
}
|
package mobi.wrt.oreader.app.view;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import java.util.List;
import mobi.wrt.oreader.app.R;
import mobi.wrt.oreader.app.image.Displayers;
import mobi.wrt.oreader.app.image.IContentImage;
/**
* Created by Uladzimir_Klyshevich on 5/6/2014.
*/
public class ImagesViewGroup extends RelativeLayout implements ImageLoadingListener {
@Override
public void onLoadingStarted(String imageUri, View view) {
}
@Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
view.setLayoutParams(DEFAULT_LAYOUT_PARAMS);
}
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
}
@Override
public void onLoadingCancelled(String imageUri, View view) {
}
public static enum DisplayMode {
FULL, CROP;
}
private List<IContentImage> mImages;
private int mLastWidth = -1;
private DisplayMode mDisplayMode = DisplayMode.FULL;
public ImagesViewGroup(Context context) {
super(context);
}
public ImagesViewGroup(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ImagesViewGroup(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void setDisplayMode(DisplayMode displayMode) {
if (mDisplayMode != displayMode) {
mDisplayMode = displayMode;
}
if (mLastWidth == -1) {
return;
}
refresh(mLastWidth);
}
public void setSrc(List<IContentImage> images) {
if (mImages == images) {
return;
}
mImages = images;
if (mLastWidth == -1) {
return;
}
refresh(mLastWidth);
}
private void checkWidthAndRefresh(int width) {
if (mLastWidth == width) {
return;
}
mLastWidth = width;
refresh(width);
}
private static LayoutParams DEFAULT_LAYOUT_PARAMS = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
private void refresh(int w) {
removeAllViews();
if (mImages == null) {
ViewGroup.LayoutParams layoutParams = getLayoutParams();
if (layoutParams != DEFAULT_LAYOUT_PARAMS) {
setLayoutParams(DEFAULT_LAYOUT_PARAMS);
}
return;
}
int containerWidth = w;
if (containerWidth == 0) {
return;
}
for (int i = 0; i < mImages.size(); i++) {
IContentImage contentImage = mImages.get(i);
ImageView imageView = new ImageView(getContext());
LayoutParams params = null;
String url = contentImage.getUrl();
ViewGroup thumbnailContainer = null;
if (i == 0) {
params = initBigImage(containerWidth, contentImage, imageView);
addView(imageView, params);
} else {
//TODO remove when will multi image support
if (true) {
return;
}
if (thumbnailContainer == null) {
LinearLayout linearLayout = new LinearLayout(getContext());
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getContext().getResources().getDimensionPixelSize(R.dimen.image_thumbs_height));
layoutParams.addRule(ALIGN_PARENT_BOTTOM);
thumbnailContainer = linearLayout;
addView(thumbnailContainer);
}
params = new LayoutParams(containerWidth/(mImages.size()-2), ViewGroup.LayoutParams.MATCH_PARENT);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(params);
thumbnailContainer.addView(imageView);
}
ImageLoader.getInstance().displayImage(url, imageView, Displayers.BITMAP_DISPLAYER_OPTIONS, this);
}
}
private LayoutParams initBigImage(int containerWidth, IContentImage contentImage, ImageView imageView) {
LayoutParams params;
if (mDisplayMode == DisplayMode.FULL) {
params = initFirstImageForFullDisplayMode(containerWidth, contentImage, imageView);
} else {
params = initFirstImageForCropDisplayMode(containerWidth, contentImage, imageView);
}
ViewGroup.LayoutParams layoutParams = getLayoutParams();
layoutParams.width = params.width;
layoutParams.height = params.height;
setLayoutParams(layoutParams);
return params;
}
private LayoutParams initFirstImageForFullDisplayMode(int containerWidth, IContentImage contentImage, ImageView imageView) {
LayoutParams params;
Integer width = contentImage.getWidth();
Integer height = contentImage.getHeight();
if (width == null || height == null) {
//make square image
params = new LayoutParams(containerWidth, containerWidth);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
} else {
int imageHeight = (int) (((double) containerWidth * (double) height) / (double) width);
params = new LayoutParams(containerWidth, imageHeight);
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
}
return params;
}
private LayoutParams initFirstImageForCropDisplayMode(int containerWidth, IContentImage contentImage, ImageView imageView) {
LayoutParams params = new LayoutParams(containerWidth, containerWidth/2);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
return params;
}
@Override
protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
final int width = getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec);
checkWidthAndRefresh(width);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
checkWidthAndRefresh(w);
}
}
|
package day05_primitives_concatanation;
public class WatchInfo {
public static void main (String [] args){
String brand = "Rolex";
String color = "Black";
Double price = 15000.0;
char gender = 'F';
boolean waterresistant = true;
boolean isSmart = false;
System.out.println("Brand is " + brand);
System.out.println("Color is " + color);
System.out.println("Price is" + price);
System.out.println("It is for " + gender);
System.out.print("It has waterresistance " +waterresistant);
}
}
|
package com.demo.test.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 全局订单ID——Synchronized
*/
public class OrderNumberGeneratorSynchronized implements OrderNumberGeneratorInterface {
public static int count = 0;
public static Object lock = new Object();
@Override
public String getNumber() {
synchronized (lock) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String s = simpleDateFormat.format(new Date()) + "-" + FileId.nextId();
}
return null;
}
}
|
package org.iptc.extra.core.utils;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.iptc.extra.core.types.document.Sentence;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import edu.stanford.nlp.ling.CoreAnnotations.SentencesAnnotation;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.pipeline.StanfordCoreNLP;
import edu.stanford.nlp.util.CoreMap;
/*
* Static methods for text pre-processing
*/
public class TextUtils {
/*
* Remove HTML tags and redundant white-spaces for a text
*/
public static String clean(String txt) {
//txt = txt.replaceAll("<!--.*?-->", " ").replaceAll("<[^>]+>", " ");
txt = Jsoup.parse(txt).text();
txt = StringEscapeUtils.unescapeHtml4(txt);
txt = StringUtils.normalizeSpace(txt);
txt = StringUtils.trim(txt);
return txt;
}
/*
* Extract a list of sentences from a given text, using Stanford NLP
*/
public static List<Sentence> getSentences(String text) {
Properties props = new Properties();
props.put("annotators", "tokenize, ssplit");
StanfordCoreNLP pipeline = new StanfordCoreNLP(props);
List<Sentence> sentences = new ArrayList<Sentence>();
Annotation document = new Annotation(text);
pipeline.annotate(document);
List<CoreMap> nlpSentences = document.get(SentencesAnnotation.class);
for(CoreMap sentence: nlpSentences) {
Sentence s = new Sentence(sentence.toString());
sentences.add(s);
}
return sentences;
}
/*
* Extract a list of paragraphs from a given text. Paragraphs are enclosed into <p>...</p> tags
*/
public static List<String> getParagraphs(String text) {
List<String> paragraphs = new ArrayList<String>();
org.jsoup.nodes.Document doc = Jsoup.parse(text);
Elements pElements = doc.select("p");
for (Element pElement : pElements) {
String paragraph = pElement.text();
paragraphs.add(paragraph);
}
return paragraphs;
}
}
|
/**
* Provides the implementation of {@link network.codex.codexjava.interfaces.IRPCProvider} by using Retrofit library to communicate with CODEX blockchain.
*/
package network.codex.codexjavarpcprovider.implementations; |
package model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "Coupons")
public class CouponBean {
@Id
@Column(name = "coupon")
private String coupon;
@Column(name = "discount")
private int discount;
@Column(name = "deadline")
private java.util.Date deadline;
@Column(name = "times")
private Integer times;
@Column(name = "notes")
private String notes;
public String getCoupon() {
return coupon;
}
public void setCoupon(String coupon) {
this.coupon = coupon;
}
public int getDiscount() {
return discount;
}
public void setDiscount(int discount) {
this.discount = discount;
}
public Integer getTimes() {
return times;
}
public void setTimes(Integer times) {
this.times = times;
}
public java.util.Date getDeadline() {
return deadline;
}
public void setDeadline(java.util.Date deadline) {
this.deadline = deadline;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
}
|
package it.sevenbits.spring.web.controllers;
import it.sevenbits.spring.web.models.CreateStatusRequest;
import it.sevenbits.spring.web.models.CreateTaskRequest;
import it.sevenbits.spring.core.models.Task;
import it.sevenbits.spring.core.repository.ITaskRepository;
import it.sevenbits.spring.web.models.CreateTaskTextRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PathVariable;
import javax.validation.Valid;
import java.util.List;
/**
* Manages requests
*/
@Controller
public class TasksController {
private ITaskRepository repository;
/**
* transmit Bean in constructor
* @param taskRepository task repository interface
*/
public TasksController(final ITaskRepository taskRepository) {
this.repository = taskRepository;
}
/**
* @return list task
*/
@RequestMapping(value = "/tasks", method = RequestMethod.GET)
@ResponseBody
private ResponseEntity<List<Task>> getTask(final @RequestParam(value = "status", required = false,
defaultValue = "inbox") String status) {
if (status != null) {
if (CreateStatusRequest.getStatus(status) != null) {
return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON_UTF8).body(repository.getTaskByStatus(status));
} else {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
}
} else {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
}
}
/**
* @param taskText task
* @return created task
*/
@RequestMapping(value = "/tasks", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<String> addTask(final @RequestBody @Valid CreateTaskTextRequest taskText) {
try {
Task newTask = repository.addTask(taskText);
HttpHeaders headers = new HttpHeaders();
headers.set("Location", "/task/" + newTask.getId());
return ResponseEntity.status(HttpStatus.CREATED).contentType(MediaType.APPLICATION_JSON_UTF8)
.headers(headers).build();
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
}
}
@RequestMapping(value = "/tasks/{taskId}", method = RequestMethod.GET)
@ResponseBody
private ResponseEntity<Task> getTaskById(final @PathVariable("taskId") String id) {
Task task = repository.getTaskById(id);
if (task != null) {
return ResponseEntity.status(HttpStatus.OK).contentType(MediaType.APPLICATION_JSON).body(task);
} else {
return ResponseEntity.notFound().build();
}
}
@RequestMapping(value = "/tasks/{taskId}", method = RequestMethod.PATCH)
@ResponseBody
private ResponseEntity<String> updateTask(final @PathVariable("taskId") String id,
final @RequestBody CreateTaskRequest jsonArgument) {
if (repository.getTaskById(id) != null) {
if (jsonArgument.getText() != null) {
if (jsonArgument.validText() != null) {
repository.updateText(id, jsonArgument.getText());
} else {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
}
}
if (jsonArgument.getStatus() != null) {
if (jsonArgument.validStatus() != null) {
repository.updateStatus(id, jsonArgument.getStatus());
} else {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
}
}
return ResponseEntity.status(HttpStatus.OK).build();
} else {
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}
}
@RequestMapping(value = "/tasks/{taskId}", method = RequestMethod.DELETE)
@ResponseBody
private ResponseEntity updateTask(final @PathVariable("taskId") String id) {
try {
if (repository.deleteTask(id)) {
return ResponseEntity.status(HttpStatus.OK).build();
} else {
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
}
}
}
|
package com.greenapex.quizapp.controllertest;
import static org.mockito.Mockito.when;
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.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
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.ContextConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.greenapex.quizapp.controller.UserController;
import com.greenapex.quizapp.entity.UserModule;
import com.greenapex.quizapp.service.UserService;
@AutoConfigureMockMvc
@ContextConfiguration
@SpringBootTest(classes= {UserControllerTest.class})
public class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@Mock
private UserService userService;
@InjectMocks
private UserController userController;
@BeforeEach
public void setUp() {
mockMvc=MockMvcBuilders.standaloneSetup(userController).build();
}
@Test
@Order(1)
public void insertUserTest() throws Exception {
UserModule user = new UserModule();
user.setUser_id(1);
user.setUsername("Deepak");
user.setEmail("dkb@green.com");
user.setPassword("Dk23");
when(userService.insertUser(user)).thenReturn(user);
ObjectMapper mapper=new ObjectMapper();
String jsonbody=mapper.writeValueAsString(user);
this.mockMvc.perform(post("/insertuser")
.accept(MediaType.APPLICATION_JSON)
.content(jsonbody)
.contentType(MediaType.APPLICATION_JSON)
)
.andExpect(status().isOk())
.andDo(print());
System.out.println("User added Successfully");
}
@Test
@Order(2)
public void updateUserTest() throws Exception {
UserModule user = new UserModule();
user.setUser_id(1);
user.setUsername("Deepak Kumar");
user.setEmail("dkb@green.com");
user.setPassword("Dk23");
when(userService.updateUser(user)).thenReturn(user);
ObjectMapper mapper=new ObjectMapper();
String jsonbody=mapper.writeValueAsString(user);
this.mockMvc.perform(put("/updateuser")
.accept(MediaType.APPLICATION_JSON)
.content(jsonbody)
.contentType(MediaType.APPLICATION_JSON)
)
.andExpect(status().isOk())
.andDo(print());
System.out.println("User Updated Successfully");
}
@Test
@Order(3)
public void getUserByIdTest() throws Exception{
UserModule user = new UserModule(1,"Sachi","sac@gmail.com","sc123");
when(userService.getUserById(1)).thenReturn(user);
this.mockMvc.perform(get("/getuserbyid/{user_id}",1))
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath(".user_id").value(1))
.andExpect(MockMvcResultMatchers.jsonPath(".username").value("Sachi"))
.andExpect(MockMvcResultMatchers.jsonPath(".email").value("sac@gmail.com"))
.andExpect(MockMvcResultMatchers.jsonPath(".password").value("sc123"))
.andDo(print());
}
@Test
@Order(4)
public void getAllUserTest() throws Exception {
UserModule user = new UserModule();
user.setUser_id(1);
user.setUsername("Deepak Kumar");
user.setEmail("dkb@green.com");
user.setPassword("Dk23");
UserModule user1 = new UserModule();
user1.setUser_id(2);
user1.setUsername("Soumya");
user1.setEmail("sm@green.com");
user1.setPassword("Sou23");
List<UserModule> users=new ArrayList<>();
users.add(user);
users.add(user1);
when(userService.getAllUser()).thenReturn(users);
this.mockMvc.perform(get("/getalluser"))
.andExpect(status().isOk())
.andDo(print());
}
} |
package com.example.android.customerapp.adapters;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.android.customerapp.R;
public class IngredientViewHolder extends RecyclerView.ViewHolder {
public TextView ingredient;
public IngredientViewHolder(@NonNull View itemView) {
super(itemView);
ingredient = itemView.findViewById(R.id.ingredient);
}
}
|
package jogador;
import propriedades.*;
import java.util.ArrayList;
import propriedades.Titulo;
public class Jogador {
private String nome;
private java.awt.Color cor;
private int saldo = 3458;
private int posicao = 0; //posicao no tabuleiro
private ArrayList<Titulo> titulos = new ArrayList<Titulo>();
private int isPreso = 0;
private int tentativas = 0;
/*
* 1 = imune;
* 0 = n�o imune
*/
private int imune = 0;
public Jogador(String nome, java.awt.Color cor){
this.setCor(cor);
this.setNome(nome);
}
public void comprarTitulo(Titulo t){
this.transacao(-t.getPreco()); //subtrai o preco do titulo ao saldo atual
titulos.add(t);
}
public int transacao(int valor){
if( valor < 0){
if( this.getSaldo() >= (-valor)){
this.setSaldo(this.getSaldo() + valor);
return 1;
}else{
return 0;
}
}else{
this.setSaldo(this.getSaldo() + valor);
return 1;
}
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public java.awt.Color getCor() {
return cor;
}
public void setCor(java.awt.Color cor) {
this.cor = cor;
}
public int getImune() {
return imune;
}
public void setImune(int imune) {
this.imune = imune;
}
public int getSaldo() {
return saldo;
}
public void setSaldo(int saldo) {
this.saldo = saldo;
}
public ArrayList<Titulo> getTitulos() {
return titulos;
}
public void setTitulos(ArrayList<Titulo> titulos) {
this.titulos = titulos;
}
public int andar(int somaDados){
int soma = this.posicao + somaDados;
if(soma < 40){
this.posicao = soma;
return 0;
}else{
this.posicao = soma - 40;
return 1;
}
}
public int getPosicao() {
return posicao;
}
public void setPosicao(int posicao) {
this.posicao = posicao;
}
public int getIsPreso() {
return isPreso;
}
public void setIsPreso(int isPreso) {
this.isPreso = isPreso;
}
public int getTentativas() {
return tentativas;
}
public void setTentativas(int tentativas) {
this.tentativas = tentativas;
}
public int getPatrimonio(){
Titulo t;
Terreno lote;
int total = saldo;
for(int i = 0; i < titulos.size(); i++){
t = titulos.get(i);
total += t.getPreco();
if (t.getTipo().equals("terreno")){
lote = (Terreno) t;
if(lote.getEstado() < 5){
total += (lote.getEstado() * lote.getPrecoCasa())/2;
}
else{
total += (lote.getEstado() * lote.getPrecoCasa())/2;
total += (lote.getPrecoHotel())/2;
}
}
}
return total;
}
public void venderParaBanco(Titulo t){
int valor = t.getPreco();
if(t.getTipo().equals("terreno")){
Terreno terreno = (Terreno) t;
valor = terreno.getPrecoVendaBanco();
}
this.transacao(valor);
this.getTitulos().remove(t);
t.setDono(null);
}
public void removerTitulos(){
for (Titulo t : this.titulos) {
t.setDono(null);
}
}
}
|
package com.nibado.fastcollections.lookup;
import com.nibado.fastcollections.lookup.fastutil.FastUtilHashSetIntLookup;
import com.nibado.fastcollections.lookup.hppc.HppcHashSetIntLookup;
import com.nibado.fastcollections.lookup.hppc.HppcScatterSetIntLookup;
import com.nibado.fastcollections.lookup.java.*;
import com.nibado.fastcollections.lookup.trove.TroveHashSetIntLookup;
import java.util.List;
public interface IntLookup {
boolean contains(int value);
static IntLookup get(String implementation, List<Integer> list, float loadFactor) {
switch (implementation) {
case "javaStringHashSet":
return new StringHashSetIntLookup(list, loadFactor);
case "javaHashSet":
return new HashSetIntLookup(list, loadFactor);
case "arrayList":
return new ArrayListIntLookup(list);
case "array":
return new ArrayIntLookup(list);
case "arrayBS":
return new ArrayIntBSLookup(list);
case "equals":
return new EqualsIntLookup(list);
case "hppcHashSet" :
return new HppcHashSetIntLookup(list, loadFactor);
case "hppcScatterSet" :
return new HppcScatterSetIntLookup(list, loadFactor);
case "troveHashSet" :
return new TroveHashSetIntLookup(list, loadFactor);
case "fuHashSet" :
return new FastUtilHashSetIntLookup(list, loadFactor);
default:
throw new IllegalArgumentException("Unknown implementation: " + implementation);
}
}
}
|
package com.tencent.mm.plugin.voiceprint.ui;
import com.tencent.mm.R;
import com.tencent.mm.plugin.voiceprint.ui.a.a;
class VoiceCreateUI$7 implements a {
final /* synthetic */ VoiceCreateUI oGi;
VoiceCreateUI$7(VoiceCreateUI voiceCreateUI) {
this.oGi = voiceCreateUI;
}
public final void bJd() {
this.oGi.oFI.reset();
this.oGi.oFI.bJn();
this.oGi.oFI.bJo();
this.oGi.oFF.setVisibility(4);
this.oGi.oFI.setTitleText(R.l.voice_print_reg_step_tip);
VoiceCreateUI.c(this.oGi).setVisibility(0);
this.oGi.oFI.bJm();
}
public final void bJe() {
}
}
|
/*
* Copyright (c) 2011. Peter Lawrey
*
* "THE BEER-WARE LICENSE" (Revision 128)
* As long as you retain this notice you can do whatever you want with this stuff.
* If we meet some day, and you think this stuff is worth it, you can buy me a beer in return
* There is no warranty.
*/
package com.google.code.java.core.parser;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
public class ByteBufferTextDoubleReader implements DoubleReader {
public static final long MAX_VALUE_DIVIDE_10 = Long.MAX_VALUE / 10;
private final ByteBuffer buffer;
public ByteBufferTextDoubleReader(ByteBuffer buffer) {
this.buffer = buffer;
}
static double asDouble(long value, int exp, boolean negative, int decimalPlaces) {
if (decimalPlaces > 0 && value < Long.MAX_VALUE / 2) {
if (value < Long.MAX_VALUE / (1L << 32)) {
exp -= 32;
value <<= 32;
}
if (value < Long.MAX_VALUE / (1L << 16)) {
exp -= 16;
value <<= 16;
}
if (value < Long.MAX_VALUE / (1L << 8)) {
exp -= 8;
value <<= 8;
}
if (value < Long.MAX_VALUE / (1L << 4)) {
exp -= 4;
value <<= 4;
}
if (value < Long.MAX_VALUE / (1L << 2)) {
exp -= 2;
value <<= 2;
}
if (value < Long.MAX_VALUE / (1L << 1)) {
exp -= 1;
value <<= 1;
}
}
for (; decimalPlaces > 0; decimalPlaces--) {
exp--;
long mod = value % 5;
value /= 5;
int modDiv = 1;
if (value < Long.MAX_VALUE / (1L << 4)) {
exp -= 4;
value <<= 4;
modDiv <<= 4;
}
if (value < Long.MAX_VALUE / (1L << 2)) {
exp -= 2;
value <<= 2;
modDiv <<= 2;
}
if (value < Long.MAX_VALUE / (1L << 1)) {
exp -= 1;
value <<= 1;
modDiv <<= 1;
}
value += modDiv * mod / 5;
}
final double d = Math.scalb((double) value, exp);
return negative ? -d : d;
}
@Override
public double read() throws BufferUnderflowException {
long value = 0;
int exp = 0;
boolean negative = false;
int decimalPlaces = Integer.MIN_VALUE;
while (true) {
byte ch = buffer.get();
if (ch >= '0' && ch <= '9') {
while (value >= MAX_VALUE_DIVIDE_10) {
value >>>= 1;
exp++;
}
value = value * 10 + (ch - '0');
decimalPlaces++;
} else if (ch == '-') {
negative = true;
} else if (ch == '.') {
decimalPlaces = 0;
} else {
break;
}
}
return asDouble(value, exp, negative, decimalPlaces);
}
@Override
public void close() {
}
}
|
/**
* DNet eBusiness Suite
* Copyright: 2010-2013 Nan21 Electronics SRL. All rights reserved.
* Use is subject to license terms.
*/
package net.nan21.dnet.module.bd.domain.impl.comment;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.PrePersist;
import javax.persistence.QueryHint;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import net.nan21.dnet.core.domain.impl.AbstractType;
import org.eclipse.persistence.config.HintValues;
import org.eclipse.persistence.config.QueryHints;
import org.hibernate.validator.constraints.NotBlank;
@NamedQueries({@NamedQuery(name = CommentType.NQ_FIND_BY_NAME, query = "SELECT e FROM CommentType e WHERE e.clientId = :clientId and e.name = :name", hints = @QueryHint(name = QueryHints.BIND_PARAMETERS, value = HintValues.TRUE))})
@Entity
@Table(name = CommentType.TABLE_NAME, uniqueConstraints = {@UniqueConstraint(name = CommentType.TABLE_NAME
+ "_UK1", columnNames = {"CLIENTID", "NAME"})})
public class CommentType extends AbstractType {
public static final String TABLE_NAME = "BD_NOTE_TYPE";
private static final long serialVersionUID = -8865917134914502125L;
/**
* Named query find by unique key: Name.
*/
public static final String NQ_FIND_BY_NAME = "CommentType.findByName";
@NotBlank
@Column(name = "TARGETFQN", nullable = false, length = 255)
private String targetFqn;
@Column(name = "TARGETTYPE", length = 32)
private String targetType;
public String getTargetFqn() {
return this.targetFqn;
}
public void setTargetFqn(String targetFqn) {
this.targetFqn = targetFqn;
}
public String getTargetType() {
return this.targetType;
}
public void setTargetType(String targetType) {
this.targetType = targetType;
}
@PrePersist
public void prePersist() {
super.prePersist();
}
}
|
package com.tongji.android.recorder_app.Model;
import java.util.Comparator;
/**
* Created by e on 16/6/7.
*/
public class FriendSort implements Comparator<Friend>{
@Override
public int compare(Friend lhs, Friend rhs) {
if(lhs.score>=rhs.score) return -1;
else if(lhs.score<rhs.score) return 1;
else return 0;
}
}
|
package com.onlythinking.commons.config.annotation;
import org.springframework.core.annotation.AliasFor;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import java.lang.annotation.*;
/**
* <p> The validated service . </p>
*
* @author Li Xingping
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Validated
@Service
public @interface ValidatedService {
@AliasFor(annotation = Validated.class, attribute = "value")
Class<?>[] validatedValue() default {};
@AliasFor(annotation = Service.class)
String value() default "";
}
|
package templates_and_tests;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import scala.Tuple2;
import java.util.*;
/**
* This class is a remake of the templates_and_tests.SecondTemplate file provided from the homework 2.
* The class implement a word count algorithm as in the templates_and_tests.SecondTemplate but uses methods instead of lambda functions.
* Also makes a time measurement of the time needed for the algorithm to complete.
* @author Giovanni Candeo
*/
public class WordCountTest {
public static void main(String[] args){
if(args.length == 0){
throw new IllegalArgumentException("expeting the file name");
}
SparkConf conf=new SparkConf(true)
.setAppName("templates_and_tests.WordCountTest")
.setMaster("local[*]");
JavaSparkContext sc = new JavaSparkContext(conf);
//the test-sample file contains documents composed by a single line of words.
// #docs 10122
// #words 3503570
//RDD contains 10122 docs composed by a single line of numerous strings
JavaRDD<String> document = sc.textFile(args[0]).cache();
System.out.println("Test count: "+document.count());
//lets start measuring time from here
long start = System.currentTimeMillis();
//Iterator<Tuple2<String, Long>> countForSingleWord = document.flatMapToPair(templates_and_tests.WordCountTest::countSingleWords);
JavaPairRDD<String,Long> dWordCountPairs = document
.flatMapToPair(WordCountTest::countSingleWords)
.groupByKey()
.mapValues(WordCountTest::countOccurrences);
//end of time measuring
long end = System.currentTimeMillis();
System.out.println("Elapsed time: " + (end - start) + " ms");
}
private static Iterator<Tuple2<String,Long>> countSingleWords(String s) {
String[] words = s.split(" ");
ArrayList<Tuple2<String, Long>> counts = new ArrayList<>();
for(String w : words){
counts.add(new Tuple2<>(w,1L));
}
return counts.iterator();
}
private static Long countOccurrences(Iterable<Long> iterable) {
Long sum = Long.valueOf(0);
for(Long c: iterable){
sum += c;
}
return sum;
}
}
|
package pe.gob.trabajo.repository;
import pe.gob.trabajo.domain.Perjuridica;
import org.springframework.stereotype.Repository;
import org.springframework.data.jpa.repository.*;
import java.util.List;
/**
* Spring Data JPA repository for the Perjuridica entity.
*/
@SuppressWarnings("unused")
@Repository
public interface PerjuridicaRepository extends JpaRepository<Perjuridica, Long> {
@Query("select perjuridica from Perjuridica perjuridica where perjuridica.nFlgactivo = true")
List<Perjuridica> findAll_Activos();
@Query("select perjuridica from Perjuridica perjuridica where perjuridica.tipdocident.id=?1 and perjuridica.vNumdoc=?2 and perjuridica.nFlgactivo = true")
Perjuridica findPersonajuridByIdentDoc(Long id_tdoc,String ndoc);
}
|
/*
* Welcome to the world of Java! Just print "Hello World."
* and "Hello Java." in two separate lines to complete this challenge.
*
*/
package introduction;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World.");
System.out.println("Hello Java.");
}
}
|
package com.data.collector.template;
import com.data.advertiser.system.stub.storage.SalesResponseStorage;
import com.data.collector.dto.SaleDto;
import com.data.model.Advertiser;
import com.data.model.ResponseDetail;
import com.data.repository.AdvertiserRepository;
import com.data.util.DateTimeUtil;
import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;
import net.minidev.json.parser.JSONParser;
import net.minidev.json.parser.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
/**
* Ildar Makhmutov
* 08.08.2019.
* <p>
* RestTemplate используемый Коллектором для получения статистики Offer'ов
* Имитирует вызов REST API Advertiser'а и получение Response'а
* Парсит Response и создает список SaleDto
* Поддерживает работу как со стандраным REST API, так и с кастомным
*/
@Component
public class CollectorRestTemplateImpl implements CollectorRestTemplate {
private static final Logger logger = LoggerFactory.getLogger(CollectorRestTemplateImpl.class);
@Autowired
private AdvertiserRepository advertiserRepository;
/**
* Получение статистики Sale'ов для Publisher'а
*
* @param statisticUrl урл Advertiser'а для получения статистики Sale'ов
* @param publisherName имя Publisher'а для которого нужно получить статистику
* @return список Sale'ов для Publisher'а
*/
public List<SaleDto> getSaleStatistic(String statisticUrl, String publisherName) {
List<SaleDto> saleDtos = new ArrayList<>();
String jsonSales = SalesResponseStorage.getJsonSalesResponse(statisticUrl, publisherName);
if (jsonSales != null) {
Advertiser advertiser = advertiserRepository.findByStatisticUrl(statisticUrl);
ResponseDetail responseDetail = advertiser.getResponseDetail();
JSONParser jsonParser = new JSONParser(JSONParser.DEFAULT_PERMISSIVE_MODE);
JSONArray parse = new JSONArray();
try {
parse = jsonParser.parse(jsonSales, JSONArray.class);
} catch (ParseException e) {
logger.info(e.getMessage(), DateTimeUtil.DATE_TIME_FORMATTER.format(LocalDateTime.now()));
}
for (int i = 0; i < parse.size(); i++) {
JSONObject cap = (JSONObject) parse.get(i);
String transactionNumber = (String) cap.get(responseDetail.getTransactionNumberName());
String dateTime = (String) cap.get(responseDetail.getDateTimeName());
String offerName = (String) cap.get(responseDetail.getOfferName());
String offerNumber = (String) cap.get(responseDetail.getOfferNumberName());
String publisher = (String) cap.get(responseDetail.getPublisherName());
SaleDto saleDto = new SaleDto(transactionNumber, dateTime, offerName, offerNumber, publisher);
saleDtos.add(saleDto);
}
}
return saleDtos;
}
}
|
package ru.lember.neointegrationadapter.message;
public enum DestinationType {
NONE,
//
}
|
package com.example.vitor.a05_controle_abastecimento;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
public class telaCriarPosto extends AppCompatActivity {
Spinner spinner_1;
List<String> list = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tela_criar_posto);
this.spinner_1 = findViewById(R.id.spinner);
this.list.add("Ipiranga");
this.list.add("Shell");
this.list.add("Texaco");
this.list.add("Petrobas");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getApplicationContext(), android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
this.spinner_1.setAdapter(adapter);
}
public void salvar(View view) { //Faz as conversões necessarias e salva no arquivo DAO
try {
abastecimentoDAO salvar = new abastecimentoDAO();
EditText kmAtual, Litros, data;
kmAtual = findViewById(R.id.kmAtualPosto);
Litros = findViewById(R.id.litrosAtualPosto);
data = findViewById(R.id.dataAtualPosto);
String dataString = data.getText().toString();
double litrosDouble = Double.parseDouble(Litros.getText().toString());
double kmDouble = Double.parseDouble(kmAtual.getText().toString());
Posto novo = new Posto();
novo.setLitrosAbastecidos(litrosDouble);
novo.setKmAtual(kmDouble);
novo.setData(dataString);
novo.setPosto(this.list.get(this.spinner_1.getSelectedItemPosition()));
if(ContextCompat.checkSelfPermission(this.getApplicationContext(), ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION}, 1);//Pede permissão pra usar o local
}
GPSProvider g = new GPSProvider(getApplicationContext());
Location l = g.getLocation();
double longitude = l.getLongitude();
double latitude = l.getLatitude();
novo.setLongitude(longitude);
novo.setLatitude(latitude);
double kmAntigo = this.getIntent().getDoubleExtra("kmAtual",0); //So salva se o kmAntigo for menor que o km atual
if (kmAntigo < kmDouble || kmAntigo == 0) {
if (abastecimentoDAO.salvar(this.getApplicationContext(), novo) == true) {
setResult(1);
finish();
}
}else {
kmAtual.setError("Precisa ser maior que o KM anterior.");
}
} catch (Exception e) {
}
}
}
|
package com.vilio.bps.quartz.service;
import org.quartz.SchedulerException;
import org.quartz.ee.servlet.QuartzInitializerListener;
import org.quartz.impl.StdSchedulerFactory;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
/**
* Created by xiezhilei on 2017/3/8.
*/
public class HHQuartZInitializerListener extends QuartzInitializerListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
// TODO Auto-generated method stub
super.contextInitialized(sce);
ServletContext sc=sce.getServletContext();
StdSchedulerFactory fac=(StdSchedulerFactory) sc.getAttribute(QUARTZ_FACTORY_KEY);
try {
fac.getScheduler().getContext().put("servletContext", sc);
} catch (SchedulerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package com.zhouyi.business.core.dao;
import com.zhouyi.business.core.model.LedenBbsAttachment;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
import java.util.Map;
@Mapper
public interface LedenBbsAttachmentMapper {
int deleteByPrimaryKey(String pkId);
int insert(LedenBbsAttachment record);
int insertSelective(LedenBbsAttachment record);
LedenBbsAttachment selectByPrimaryKey(String pkId);
int updateByPrimaryKeySelective(LedenBbsAttachment record);
int updateByPrimaryKey(LedenBbsAttachment record);
List<LedenBbsAttachment> listBbsAttachmentByConditions(Map<String,Object> conditions);
int getBbsAttachmentCountByConditions(Map<String,Object> conditions);
/**
* 上传多个附件
* @param records
* @return
*/
int insertMulti(List<LedenBbsAttachment> records);
} |
package com.rishi.baldawa.iq;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class AddBinaryTest {
@Test
public void simpleSolution() throws Exception {
assertEquals(new AddBinary().simpleSolution("11", "1"), "100");
assertEquals(new AddBinary().simpleSolution(
"10100000100100110110010000010101111011011001101110111111111101000000101111001110001111100001101",
"110101001011101110001111100110001010100001101011101010000011011011001011101111001100000011011110011"),
"110111101100010011000101110110100000011101000101011001000011011000001100011110011010010011000000000");
}
@Test
public void solution() throws Exception {
assertEquals(new AddBinary().solution("11", "1"), "100");
assertEquals(new AddBinary().solution(
"10100000100100110110010000010101111011011001101110111111111101000000101111001110001111100001101",
"110101001011101110001111100110001010100001101011101010000011011011001011101111001100000011011110011"),
"110111101100010011000101110110100000011101000101011001000011011000001100011110011010010011000000000");
}
} |
package com.github.abryb.bsm;
public class InsufficientPasswordException extends AppException {
public InsufficientPasswordException(String message) {
super(message, null);
}
}
|
package org.sagebionetworks.repo.manager.schema;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.sagebionetworks.repo.manager.EntityManager;
import org.sagebionetworks.repo.model.dbo.schema.SchemaValidationResultDao;
import org.sagebionetworks.repo.model.schema.JsonSchema;
import org.sagebionetworks.repo.model.schema.JsonSchemaObjectBinding;
import org.sagebionetworks.repo.model.schema.JsonSchemaVersionInfo;
import org.sagebionetworks.repo.model.schema.ObjectType;
import org.sagebionetworks.repo.model.schema.ValidationResults;
import org.sagebionetworks.repo.web.NotFoundException;
@ExtendWith(MockitoExtension.class)
public class EntitySchemaValidatorImplTest {
@Mock
private EntityManager mockEntityManger;
@Mock
private JsonSchemaManager mockJsonSchemaManager;
@Mock
private JsonSchemaValidationManager mockJsonSchemaValidationManager;
@Mock
private SchemaValidationResultDao mockSchemaValidationResultDao;
@InjectMocks
private EntitySchemaValidator manager;
String entityId;
String schema$id;
JsonSchemaObjectBinding binding;
@Mock
JsonSubject mockEntitySubject;
@Mock
JsonSchema mockJsonSchema;
@Mock
ValidationResults mockValidationResults;
@BeforeEach
public void before() {
entityId = "syn123";
schema$id = "my.org-foo.bar-1.0.0";
binding = new JsonSchemaObjectBinding();
JsonSchemaVersionInfo versionInfo = new JsonSchemaVersionInfo();
versionInfo.set$id(schema$id);
binding.setJsonSchemaVersionInfo(versionInfo);
}
@Test
public void testValidateObject() {
when(mockEntityManger.getBoundSchema(entityId)).thenReturn(binding);
when(mockEntityManger.getEntityJsonSubject(entityId)).thenReturn(mockEntitySubject);
when(mockJsonSchemaManager.getValidationSchema(schema$id)).thenReturn(mockJsonSchema);
when(mockJsonSchemaValidationManager.validate(mockJsonSchema, mockEntitySubject))
.thenReturn(mockValidationResults);
// call under test
manager.validateObject(entityId);
verify(mockSchemaValidationResultDao).createOrUpdateResults(mockValidationResults);
verify(mockSchemaValidationResultDao, never()).clearResults(any(), any());
verify(mockEntityManger).getBoundSchema(entityId);
verify(mockEntityManger).getEntityJsonSubject(entityId);
verify(mockJsonSchemaManager).getValidationSchema(schema$id);
verify(mockJsonSchemaValidationManager).validate(mockJsonSchema, mockEntitySubject);
}
@Test
public void testValidateObjectWithNotFound() {
NotFoundException exception = new NotFoundException("");
when(mockEntityManger.getBoundSchema(entityId)).thenThrow(exception);
// call under test
manager.validateObject(entityId);
verify(mockSchemaValidationResultDao, never()).createOrUpdateResults(any());
verify(mockSchemaValidationResultDao).clearResults(entityId, ObjectType.entity);
}
@Test
public void testValidateObjectWithNullEntityId() {
entityId = null;
assertThrows(IllegalArgumentException.class, ()->{
// call under test
manager.validateObject(entityId);
});
}
}
|
package ThreadOrderAccess;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Order {
private int flag = 1;// 标志位:1:下订单 2、库存查询 3、确认订单
private Lock lock = new ReentrantLock();
private Condition condition1 = lock.newCondition();
private Condition condition2 = lock.newCondition();
private Condition condition3 = lock.newCondition();
public void pushOrder() {
lock.lock();
try {
while (flag != 1) {
condition1.await();
}
System.out.println("顾客下订单了!");
flag = 2;
condition2.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void checkLab() {
lock.lock();
try {
while(flag!=2){
condition2.await();
}
System.out.println("查询仓库余量");
flag = 3;
condition3.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void confirmOrder(){
lock.lock();
try {
while (flag!=3){
condition3.await();
}
System.out.println("订单已确认!");
flag = 1;
condition1.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
|
package com.ryit.entity;
import java.util.Date;
//广告管理
public class Advertising extends AdstractEntity{
private Integer id;//广告编号
private String pic_num;//图片数量
private String pic_url;//图片路径
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getPic_num() {
return pic_num;
}
public void setPic_num(String pic_num) {
this.pic_num = pic_num;
}
public String getPic_url() {
return pic_url;
}
public void setPic_url(String pic_url) {
this.pic_url = pic_url;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((pic_num == null) ? 0 : pic_num.hashCode());
result = prime * result + ((pic_url == null) ? 0 : pic_url.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
Advertising other = (Advertising) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (pic_num == null) {
if (other.pic_num != null)
return false;
} else if (!pic_num.equals(other.pic_num))
return false;
if (pic_url == null) {
if (other.pic_url != null)
return false;
} else if (!pic_url.equals(other.pic_url))
return false;
return true;
}
@Override
public String toString() {
return "Advertising [id=" + id + ", pic_num=" + pic_num + ", pic_url=" + pic_url + "]";
}
public Advertising(String created_user, Date created_datetime, String updated_user, Date updated_datetime,
Integer id, String pic_num, String pic_url) {
super(created_user, created_datetime, updated_user, updated_datetime);
this.id = id;
this.pic_num = pic_num;
this.pic_url = pic_url;
}
public Advertising() {
super();
// TODO Auto-generated constructor stub
}
}
|
/**
* Prompts the user to choose from menu options and executes the chosen class.
*
* @author C. Thurston
* @version 5/6/2014
*/
import java.util.Scanner;
public class Main {
public static void main(String[]args){
Scanner in = new Scanner(System.in);
CaesarShiftEncryption.encryptionInstantiator();
CaesarShiftEncryption convToCC = new CaesarShiftEncryption();
CaesarShiftDecryption convFromCC = new CaesarShiftDecryption();
System.out.println("Menu:");
System.out.println("\n 1. Encode English to Caesers Cipher\n 2. Decode Caesers Cipher to English\n 3. Quit\n--\n");
int input = in.nextInt();
in.nextLine();
System.out.println("--");
if(input == 1)
{
System.out.println("Enter a string of English without punctuation to encode:");
String toEncode = in.nextLine();
convToCC.CaeserConverter(toEncode);
}
else if(input == 2)
{
System.out.println("Enter a string of Caesars Cipher without punctuation to decode:");
String toDecode = in.nextLine();
convFromCC.CaeserConverter(toDecode);
}
else if(input == 3)
{
System.exit(0);
}
}
} |
package states;
import java.util.Stack;
import shape.Shape;
public interface StackState {
public Stack insert(Shape shape);
}
|
package dmillerw.ping.client;
import com.mojang.blaze3d.platform.GlStateManager;
import net.minecraft.client.renderer.RenderState;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.util.ResourceLocation;
public class PingRenderType extends RenderState {
protected static final RenderState.LayerState DISABLE_DEPTH = new RenderState.LayerState("disable_depth", GlStateManager::disableDepthTest, GlStateManager::enableDepthTest);
public PingRenderType(String string, Runnable r, Runnable r1) {
super(string, r, r1);
}
public static RenderType getPingOverlay() {
RenderType.State renderTypeState = RenderType.State.getBuilder().transparency(TRANSLUCENT_TRANSPARENCY).texture(BLOCK_SHEET).layer(DISABLE_DEPTH).build(true);
return RenderType.makeType("ping_overlay", DefaultVertexFormats.POSITION_TEX_COLOR, 7, 262144, true, true, renderTypeState);
}
public static RenderType getPingIcon(ResourceLocation location) {
RenderType.State renderTypeState = RenderType.State.getBuilder().texture(new RenderState.TextureState(location, false, true)).transparency(TRANSLUCENT_TRANSPARENCY).layer(DISABLE_DEPTH).build(true);
return RenderType.makeType("ping_icon", DefaultVertexFormats.POSITION_TEX_COLOR, 7, 262144, true, true, renderTypeState);
}
} |
package vehicle;
import enums.Condition;
import enums.Origin;
import java.util.Objects;
public class Vehicle {
// variaveis de instancia de vehicle
private int id;
private int vin; // numero de chassis
private String brand;
private String model;
private String manufacturingDate;
private Origin origin;
private int kms;
private Condition condition;
private int price;
// construtor default de vehicle
public Vehicle() {
}
// construtor de vehicle
public Vehicle(int id, int vin, String brand, String model, String manufacturingDate, Origin origin, int kms, Condition condition, int price) {
this.id = id;
this.vin = vin;
this.brand = brand;
this.model = model;
this.manufacturingDate = manufacturingDate;
this.origin = origin;
this.kms = kms;
this.condition = condition;
this.price = price;
}
// TODOS GETTERS E SETTERS
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getVin() {
return vin;
}
public void setVin(int vin) {
this.vin = vin;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getManufacturingDate() {
return manufacturingDate;
}
public void setManufacturingDate(String manufacturingDate) {
this.manufacturingDate = manufacturingDate;
}
public Origin getOrigin() {
return origin;
}
public void setOrigin(Origin origin) {
this.origin = origin;
}
public int getKms() {
return kms;
}
public void setKms(int kms) {
this.kms = kms;
}
public Condition getCondition() {
return condition;
}
public void setCondition(Condition condition) {
this.condition = condition;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
// metodo toString para imprimir
public String toString() {
String text = "ID : " + id + "\n"
+ "Numero de chassis : " + vin + "\n"
+ "Marca : " + brand + "\n"
+ "Modelo : " + model + "\n"
+ "Data veiculo : " + manufacturingDate + "\n"
+ "Origem : " + origin + "\n"
+ "Quilometros : " + kms + "\n"
+ "Condiçao : " + condition + "\n"
+ "Preço : " + getPrice() + "\n";
return text;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Vehicle vehicle = (Vehicle) o;
if (this.vin != vehicle.vin) {
return false;
}
return true;
}
}
|
package com.pcer.puzzlegame.tool;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import java.util.ArrayList;
/**
* Created by pcer on 2016.9.4.0004.
* 拼图块的切割类,可实现九宫格的规律切割 和 自由拼图的无序切割
*/
public class ImageSpliter {
/**
* 对传进来的图片进行 n x n 的规律切割,通过数组返回
* @param source 源文件
* @param k 块数量参数
* @param screenWidth 屏幕大小
* @return 切割后的有序碎片
*/
public static ArrayList<Bitmap> regularSplit(Bitmap source, int k, int screenWidth) {
source = Bitmap.createScaledBitmap(source, (int) (screenWidth * 0.8f), (int) (screenWidth * 0.8f), true);
ArrayList<Bitmap> al = new ArrayList<Bitmap>();
int len = source.getWidth() / k;
for (int i = 0; i < k; i++) {
for (int j = 0; j < k; j++) {
Bitmap bmp = Bitmap.createBitmap(source, j * len, i * len, len, len);
al.add(bmp);
}
}
return al;
}
/**
* 月芽片切割
* @param source 原图片
* @param k 块数量参数
* @param screenWidth 屏幕较短的长度
* @return 有序的封装好的月芽碎片
*/
public static ArrayList<Node> irregularSplit(Bitmap source, int k, int screenWidth) {
source = Bitmap.createScaledBitmap(source, (int) (screenWidth * 0.9f), (int) (screenWidth * 0.9f), true);
// 定义一些微常量
int len = source.getWidth() / k;
int offset = len / 2;
float len1d2 = len * 0.5f;
float len1d16 = len * 1.0f / 16;
float len3d8 = len * 3.0f / 8;
float len5d16 = len * 5.0f / 16;
float len5d8 = len * 5.0f / 8;
float len7d8 = len * 7.0f / 8;
float len1d8 = len * 1.0f / 8;
// 定义每个碎片的不规则偏移量
int fx = offset;
int fy = offset;
int sx = fx + len;
int sy = fy;
int tx = sx;
int ty = sy + len;
int lx = tx - len;
int ly = ty;
ArrayList<Node> bitmaps = new ArrayList<Node>();
for (int i = 0; i < k; i++) {
for (int j = 0; j < k; j++) {
// 定义路径画笔
Paint paint = new Paint();
paint.setAntiAlias(true);
Path path = new Path();
path.moveTo(fx, fy); //画笔就位
int neg = dir(i, j); //凹凸
// 通过凹凸参数和边缘参数,用OpenGL画出四条路径边
if (isLineTo(i, j, i + 1, j, k)) {
path.lineTo(sx, sy);
} else {
path.quadTo(fx + len1d2, fy + neg * len1d8, fx + len3d8, fy - neg * len1d16);
path.cubicTo(fx + len1d8, fy - neg * len5d16, fx + len7d8, fy - neg * len5d16, fx + len5d8, fy - neg * len1d16);
path.quadTo(fx + len1d2, fy + neg * len1d8, sx, sy);
}
if (isLineTo(i + 1, j, i + 1, j + 1, k)) {
path.lineTo(tx, ty);
} else {
path.quadTo(sx + neg * len1d8, sy + len1d2, sx - neg * len1d16, sy + len3d8);
path.cubicTo(sx - neg * len5d16, sy + len1d8, sx - neg * len5d16, sy + len7d8, sx - neg * len1d16, sy + len5d8);
path.quadTo(sx + neg * len1d8, sy + len1d2, tx, ty);
}
if (isLineTo(i + 1, j + 1, i, j + 1, k)) {
path.lineTo(lx, ly);
} else {
path.quadTo(tx - len1d2, ty - neg * len1d8, tx - len3d8, ty + neg * len1d16);
path.cubicTo(tx - len1d8, ty + neg * len5d16, tx - len7d8, ty + neg * len5d16, tx - len5d8, ty + neg * len1d16);
path.quadTo(tx - len1d2, ty - neg * len1d8, lx, ly);
}
if (isLineTo(i, j + 1, i, j, k)) {
path.lineTo(fx, fy);
} else {
path.quadTo(lx - neg * len1d8, ly - len1d2, lx + neg * len1d16, ly - len3d8);
path.cubicTo(lx + neg * len5d16, ly - len1d8, lx + neg * len5d16, ly - len7d8, lx + neg * len1d16, ly - len5d8);
path.quadTo(lx - neg * len1d8, ly - len1d2, fx, fy);
}
// 至此月芽片四条路径边完成,月芽片成型,可以通过其截取原图片上的碎片了
Bitmap target = Bitmap.createBitmap(len * 2, len * 2, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(target);
canvas.drawPath(path, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); // 定义SRC_IN透图模式
canvas.drawBitmap(source, -i * len + offset, -j * len + offset, paint); // 截取月芽片图像
int w = i * len;
int h = j * len;
// 保存截图的位置信息,用于在游戏中判断碎片相对位置的磁贴效果
Node node = new Node(target, i * k + j);
bitmaps.add(node);
node.curX = node.x = w + (screenWidth - (k + 1) * len) / 2;
node.curY = node.y = h + 300 - len / 2;
}
}
// 定义碎片的四维相邻关系
for (int i = 0; i < k; i++) {
for (int j = 0; j < k; j++) {
Node cur = bitmaps.get(i * k + j);
cur.lt = (i == 0) ? null : bitmaps.get((i - 1) * k + j);
cur.up = (j == 0) ? null : bitmaps.get(i * k + j - 1);
cur.rt = (i == k - 1) ? null : bitmaps.get((i + 1) * k + j);
cur.dn = (j == k - 1) ? null : bitmaps.get(i * k + j + 1);
}
}
return bitmaps;
}
// 是否是边缘片
public static boolean isLineTo(int x1, int y1, int x2, int y2, int k) {
if (x1 == 0 && x2 == 0) return true;
if (y1 == 0 && y2 == 0) return true;
if (x1 == k && x2 == k) return true;
if (y1 == k && y2 == k) return true;
return false;
}
// 判断月芽片的形状
private static int dir(int x, int y) {
if (((x + y) & 1) == 0) {
return 1;
}
return -1;
}
}
|
package nl.rug.oop.flaps.simulation.model.map.coordinates;
import nl.rug.oop.flaps.simulation.model.map.WorldDimensions;
/**
* Simple interface that defines a method that maps from one 2D coordinate space
* to another.
*
* @author T.O.W.E.R.
*/
@FunctionalInterface
public interface ProjectionMapping {
PointProvider map(PointProvider source);
static ProjectionMapping mercatorToWorld(WorldDimensions worldDimensions) {
return new MercatorToWorldMapping(worldDimensions);
}
static ProjectionMapping worldToMercator(WorldDimensions worldDimensions) {
return new WorldToMercatorMapping(worldDimensions);
}
}
|
package openopoly.err;
public class HousesNotBuildableException extends GameException{
public HousesNotBuildableException(){
super("Not a buildable property.");
}
}
|
public class Fibonacci {
public static long F(int N) { //faster one
long current = 0;
long after = 1;
for (int i = 0; i < N; i++) {
long temp;
temp = after;
after = after + current;
current = temp;
}
return current;
}
public static long F1(int N) {
if (N == 0) return 0;
if (N == 1) return 1;
return F1(N-1) + F1(N-2);
}
public static void main(String[] args) {
for (int N = 0; N < 100; N++)
StdOut.println(N + " " + F(N));
}
|
package com.ericazevedo.bookstoremanager.dto;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
//Cria os GETTER e SETTERS
@Data
//Cria o objeto de forma diferente com menos linhas.
//LivroDTO.builder().id(1L).isbn("local").nome("Nome").build();
@Builder
//Cria um contrutor sem argumentos
@NoArgsConstructor
//Cria um contrutor com todos os argumentos
@AllArgsConstructor
public class LivroDTO {
private Long id;
//Trata os dados antes de irem pro banco de dados, para darem um retorno de erro melhor para o usuário.
@NotBlank(message = "Nome precisa ser preenchido.")
@Size(max = 50, message = "Máximo de 50 caracteres.")
private String nome;
@NotNull(message = "Páginas não pode ser nulo.")
private Integer paginas;
@NotNull(message = "Capítulos não pode ser nulo.")
private Integer capitulos;
@NotBlank(message = "ISBN precisa ser preenchido.")
@Size(max = 100, message = "Máximo de 200 caracteres.")
private String isbn;
@Valid
@NotNull(message = "EditoraDTO precisa ser preenchido.")
private EditoraDTO editora;
@Valid
@NotNull(message = "AutorDTO precisa ser preenchido.")
private AutorDTO autor;
}
|
package com.yjjyjy.yjj.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import com.yjjyjy.yjj.entity.Course;
import com.yjjyjy.yjj.repository.CourseRepository;
import com.yjjyjy.yjj.service.CourseService;
@Service
public class CourseServiceImpl implements CourseService{
@Resource
private CourseRepository courseRepository;
@Override
public Course findByCourseId(long id)
{
return courseRepository.findById(id);
}
@Override
public boolean create(Course course) {
// TODO Auto-generated method stub
Course newCourse = courseRepository.save(course);
if(newCourse == null)
{
return false;
}
return true;
}
@Override
public List<Course> findAll() {
// TODO Auto-generated method stub
return courseRepository.findAll();
}
@Override
public Course findOne(long id) {
// TODO Auto-generated method stub
return courseRepository.findById(id);
}
@Override
public int deleteCourse(long id) {
return courseRepository.deleteCourseById(id);
}
@Override
public Page<Course> getCourseList(Pageable request) {
// TODO Auto-generated method stub
return courseRepository.findAll(request);
}
}
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class TraadKlientHaandterer extends Thread {
private Socket forbindelse = null;
public TraadKlientHaandterer(Socket forbindelse) throws IOException {
this.forbindelse=forbindelse;
}
public void run(){
try{
//hele komunikasjonen med klient skal ligge i run()-metoden
/* Åpner strømmer for kommunikasjon med klientprogrammet */
InputStreamReader leseforbindelse = new InputStreamReader(forbindelse.getInputStream());
BufferedReader leseren = new BufferedReader(leseforbindelse);
PrintWriter skriveren = new PrintWriter(forbindelse.getOutputStream(), true);
System.out.println("Kontakt!!");
/* Mottar data fra klienten */
String enLinje = leseren.readLine(); // mottar en linje med tekst
while (enLinje != null && !enLinje.equals("close")) { // forbindelsen på klientsiden er lukket
System.out.println("Klient "+ this.getId() +" skrev: " + enLinje);
String oppgave[]=enLinje.split(" ");
switch (oppgave[1]){
case "+":
skriveren.println(Double.parseDouble(oppgave[0])+Double.parseDouble(oppgave[2]));
break;
case "-":
skriveren.println(Double.parseDouble(oppgave[0])-Double.parseDouble(oppgave[2]));
break;
case "*":
skriveren.println(Double.parseDouble(oppgave[0])*Double.parseDouble(oppgave[2]));
break;
case "/":
skriveren.println(Double.parseDouble(oppgave[0])/Double.parseDouble(oppgave[2]));
break;
}
enLinje = leseren.readLine();
}
/* Lukker forbindelsen */
System.out.println("Klienten "+this.getId()+" har lokket forbindelsen");
leseren.close();
skriveren.close();
forbindelse.close();
}catch (Exception e){
System.out.println(e.getCause());
System.out.println(e.getClass());
System.out.println(e.getLocalizedMessage());
System.out.println(e.getMessage());
System.out.println(e.getStackTrace()[0].getLineNumber());
}
}
} |
package com.smxknife.jmx.demo02.server.instrument;
import java.time.LocalDateTime;
public interface UserMBean {
public void setId(int id);
public int getId();
public void setName(String name);
public String getName();
public void setPassword(String password);
public String getPassword();
public void printUserInfo();
public LocalDateTime currentDate();
}
|
/* Copyright 2017 Andrew Dawson
*
* This file is a part of Roma.
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* Roma is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* You should have received a copy of the GNU General Public License along with Roma; if not,
* see <http://www.gnu.org/licenses>. */
package tech.bigfig.romachat.utils;
import android.content.ContentResolver;
import android.net.Uri;
import androidx.annotation.Nullable;
import java.io.*;
public class IOUtils {
private static final int DEFAULT_BLOCKSIZE = 16384;
public static void closeQuietly(@Nullable Closeable stream) {
try {
if (stream != null) {
stream.close();
}
} catch (IOException e) {
// intentionally unhandled
}
}
public static boolean copyToFile(ContentResolver contentResolver, Uri uri, File file) {
InputStream from;
FileOutputStream to;
try {
from = contentResolver.openInputStream(uri);
to = new FileOutputStream(file);
} catch (FileNotFoundException e) {
return false;
}
if (from == null) {
return false;
}
byte[] chunk = new byte[DEFAULT_BLOCKSIZE];
try {
while (true) {
int bytes = from.read(chunk, 0, chunk.length);
if (bytes < 0) {
break;
}
to.write(chunk, 0, bytes);
}
} catch (IOException e) {
return false;
}
closeQuietly(from);
closeQuietly(to);
return true;
}
}
|
/*
* [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.bulkedit.renderer;
import com.google.common.collect.Sets;
import com.hybris.backoffice.attributechooser.Attribute;
import com.hybris.backoffice.attributechooser.AttributeChooserForm;
import com.hybris.backoffice.bulkedit.BulkEditConstants;
import com.hybris.backoffice.bulkedit.BulkEditForm;
import com.hybris.backoffice.bulkedit.BulkEditValidationHelper;
import com.hybris.backoffice.widgets.notificationarea.NotificationService;
import com.hybris.backoffice.widgets.notificationarea.event.NotificationEvent;
import com.hybris.cockpitng.components.Editor;
import com.hybris.cockpitng.components.validation.EditorValidation;
import com.hybris.cockpitng.components.validation.EditorValidationFactory;
import com.hybris.cockpitng.components.validation.ValidatableContainer;
import com.hybris.cockpitng.config.jaxb.wizard.ViewType;
import com.hybris.cockpitng.dataaccess.facades.permissions.PermissionFacade;
import com.hybris.cockpitng.dataaccess.facades.type.DataAttribute;
import com.hybris.cockpitng.dataaccess.facades.type.DataType;
import com.hybris.cockpitng.editors.EditorRegistry;
import com.hybris.cockpitng.engine.WidgetInstanceManager;
import com.hybris.cockpitng.labels.LabelService;
import com.hybris.cockpitng.testing.util.BeanLookup;
import com.hybris.cockpitng.testing.util.BeanLookupFactory;
import com.hybris.cockpitng.testing.util.CockpitTestUtil;
import com.hybris.cockpitng.widgets.configurableflow.validation.ConfigurableFlowValidationRenderer;
import de.hybris.platform.core.model.ItemModel;
import de.hybris.platform.core.model.product.ProductModel;
import org.assertj.core.util.Lists;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.select.Selectors;
import org.zkoss.zul.Checkbox;
import org.zkoss.zul.Div;
import org.zkoss.zul.Label;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import static org.fest.assertions.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class BulkEditRendererTest
{
@Mock
private ConfigurableFlowValidationRenderer validationRenderer;
@InjectMocks
@Spy
private BulkEditRenderer renderer;
@Mock
private ValidatableContainer validatableContainer;
@Mock
private NotificationService notificationService;
@Mock
private BulkEditValidationHelper bulkEditValidationHelper;
private WidgetInstanceManager wim;
@Before
public void setUp()
{
wim = CockpitTestUtil.mockWidgetInstanceManager();
CockpitTestUtil.mockZkEnvironment();
final EditorValidationFactory editorValidationFactory = mock(EditorValidationFactory.class);
when(editorValidationFactory.createValidation(any())).thenReturn(mock(EditorValidation.class));
when(editorValidationFactory.createValidation(any(), any())).thenReturn(mock(EditorValidation.class));
final BeanLookup beanLookup = BeanLookupFactory.createBeanLookup()
.registerBean("editorRegistry", mock(EditorRegistry.class))
.registerBean("labelService", mock(LabelService.class))
.registerBean("permissionFacade", mock(PermissionFacade.class))
.registerBean("editorValidationFactory", editorValidationFactory).getLookup();
CockpitTestUtil.mockBeanLookup(beanLookup);
}
@Test
public void testLocalizedAttributeLocales()
{
//given
final DataAttribute name = mockDataAttribute(ProductModel.NAME, DataAttribute.AttributeType.SINGLE);
when(name.isLocalized()).thenReturn(true);
final Attribute attributeName = mockAttribute(name);
attributeName.setSubAttributes(Sets.newHashSet(new Attribute(attributeName, Locale.ENGLISH.toLanguageTag()),
new Attribute(attributeName, Locale.TRADITIONAL_CHINESE.toLanguageTag())));
final DataType dataType = mockDataTypeWithAttributes(ProductModel._TYPECODE, Lists.newArrayList(name));
final ItemModel product = mock(ProductModel.class);
final AttributeChooserForm attributesForm = new AttributeChooserForm();
attributesForm.setChosenAttributes(Sets.newHashSet(attributeName));
final BulkEditForm bulkEditForm = new BulkEditForm();
bulkEditForm.setItemsToEdit(Lists.newArrayList(product));
bulkEditForm.setAttributesForm(attributesForm);
final HashMap<String, String> params = new HashMap<>();
params.put(BulkEditAttributesSelectorRenderer.PARAM_BULK_EDIT_FORM_MODEL_KEY, "bulkEditForm");
wim.getModel().setValue("bulkEditForm", bulkEditForm);
//when
final Div parent = new Div();
renderer.render(parent, validatableContainer, new ViewType(), params, dataType, wim);
//then
final Optional<Component> approvalLine = getAttributesLineForQualifier(parent, attributeName.getQualifier());
assertThat(approvalLine.isPresent()).isTrue();
final Optional<Editor> attributeEditor = getAttributeEditor(approvalLine.get());
assertThat(attributeEditor.isPresent()).isTrue();
assertThat(attributeEditor.get().getWritableLocales()).containsOnly(Locale.ENGLISH, Locale.TRADITIONAL_CHINESE);
assertThat(attributeEditor.get().getReadableLocales()).containsOnly(Locale.ENGLISH, Locale.TRADITIONAL_CHINESE);
}
@Test
public void testCollectionTypeHasOverrideExisting()
{
//given
final DataAttribute categories = mockDataAttribute(ProductModel.SUPERCATEGORIES, DataAttribute.AttributeType.COLLECTION);
final Attribute attributeCategories = mockAttribute(categories);
final DataType dataType = mockDataTypeWithAttributes(ProductModel._TYPECODE, Lists.newArrayList(categories));
final ItemModel product = mock(ProductModel.class);
final AttributeChooserForm attributesForm = new AttributeChooserForm();
attributesForm.setChosenAttributes(Sets.newHashSet(attributeCategories));
final BulkEditForm bulkEditForm = new BulkEditForm();
bulkEditForm.setItemsToEdit(Lists.newArrayList(product));
bulkEditForm.setAttributesForm(attributesForm);
final HashMap<String, String> params = new HashMap<>();
params.put(BulkEditAttributesSelectorRenderer.PARAM_BULK_EDIT_FORM_MODEL_KEY, "bulkEditForm");
wim.getModel().setValue("bulkEditForm", bulkEditForm);
//when
final Div parent = new Div();
renderer.render(parent, validatableContainer, new ViewType(), params, dataType, wim);
//then
final Optional<Component> categoriesLine = getAttributesLineForQualifier(parent, attributeCategories.getQualifier());
assertThat(categoriesLine.isPresent()).isTrue();
assertThat(getAttributesOverrideExisting(categoriesLine.get()).isPresent()).isTrue();
}
@Test
public void testMandatoryAttributeWithoutClearSwitch()
{
//given
final DataAttribute approval = mockDataAttribute(ProductModel.APPROVALSTATUS, DataAttribute.AttributeType.SINGLE);
when(approval.isMandatory()).thenReturn(true);
final Attribute attributeApproval = mockAttribute(approval);
final DataType dataType = mockDataTypeWithAttributes(ProductModel._TYPECODE, Lists.newArrayList(approval));
final ItemModel product = mock(ProductModel.class);
final AttributeChooserForm attributesForm = new AttributeChooserForm();
attributesForm.setChosenAttributes(Sets.newHashSet(attributeApproval));
final BulkEditForm bulkEditForm = new BulkEditForm();
bulkEditForm.setItemsToEdit(Lists.newArrayList(product));
bulkEditForm.setAttributesForm(attributesForm);
final HashMap<String, String> params = new HashMap<>();
params.put(BulkEditAttributesSelectorRenderer.PARAM_BULK_EDIT_FORM_MODEL_KEY, "bulkEditForm");
wim.getModel().setValue("bulkEditForm", bulkEditForm);
//when
final Div parent = new Div();
renderer.render(parent, validatableContainer, new ViewType(), params, dataType, wim);
//then
final Optional<Component> approvalLine = getAttributesLineForQualifier(parent, attributeApproval.getQualifier());
assertThat(approvalLine.isPresent()).isTrue();
assertThat(getAttributesClearValueSwitch(approvalLine.get()).isPresent()).isFalse();
}
protected Optional<Component> getAttributesLineForQualifier(final Component parent, final String qualifier)
{
for (final Component attributesLine : getAttributesLines(parent))
{
final Optional<Label> label = getAttributesLabel(attributesLine);
if (label.isPresent() && qualifier.equals(label.get().getValue()))
{
return Optional.of(attributesLine);
}
}
return Optional.empty();
}
protected List<Component> getAttributesLines(final Component parent)
{
return Selectors.find(parent, "." + BulkEditRenderer.SCLASS_ATTR);
}
protected Optional<Editor> getAttributeEditor(final Component attributesLine)
{
return Selectors.find(attributesLine, "." + BulkEditRenderer.SCLASS_ATTR + "-value ").stream()
.flatMap(cmp -> cmp.getChildren().stream()).filter(Editor.class::isInstance).findFirst().map(Editor.class::cast);
}
protected Optional<Checkbox> getAttributesOverrideExisting(final Component attributesLine)
{
return Selectors.find(attributesLine, "." + BulkEditRenderer.SCLASS_ATTR + "-value ").stream()
.flatMap(cmp -> cmp.getChildren().stream()).filter(Checkbox.class::isInstance).findFirst().map(Checkbox.class::cast);
}
protected Optional<Checkbox> getAttributesClearValueSwitch(final Component attributesLine)
{
return Selectors.find(attributesLine, "." + BulkEditRenderer.SCLASS_ATTR + "-clear-switch ").stream()
.flatMap(cmp -> cmp.getChildren().stream()).filter(Checkbox.class::isInstance).findFirst().map(Checkbox.class::cast);
}
protected Optional<Label> getAttributesLabel(final Component attributesLine)
{
return Selectors.find(attributesLine, "." + BulkEditRenderer.SCLASS_ATTR + "-name ").stream()
.flatMap(cmp -> cmp.getChildren().stream()).filter(Label.class::isInstance).findFirst().map(Label.class::cast);
}
protected Attribute mockAttribute(final DataAttribute approval)
{
return new Attribute(approval.getQualifier(), approval.getQualifier(), approval.isMandatory());
}
@Test
public void renderLabelOnMissingForm()
{
final HashMap<String, String> params = new HashMap<>();
params.put(BulkEditAttributesSelectorRenderer.PARAM_BULK_EDIT_FORM_MODEL_KEY, "bulkEditForm");
wim.getModel().setValue("bulkEditForm", null);
final DataType dataType = Mockito.mock(DataType.class);
final Div parent = new Div();
renderer.render(parent, validatableContainer, new ViewType(), params, dataType, wim);
verify(notificationService).notifyUser(BulkEditConstants.NOTIFICATION_SOURCE_BULK_EDIT,
BulkEditConstants.NOTIFICATION_EVENT_TYPE_MISSING_FORM, NotificationEvent.Level.FAILURE);
}
@Test
public void renderLabelOnMissingSelectedAttributes()
{
final HashMap<String, String> params = new HashMap<>();
params.put(BulkEditAttributesSelectorRenderer.PARAM_BULK_EDIT_FORM_MODEL_KEY, "bulkEditForm");
final BulkEditForm bulkEditForm = new BulkEditForm();
wim.getModel().setValue("bulkEditForm", bulkEditForm);
final DataType dataType = Mockito.mock(DataType.class);
final Div parent = new Div();
renderer.render(parent, validatableContainer, new ViewType(), params, dataType, wim);
verify(notificationService).notifyUser(BulkEditConstants.NOTIFICATION_SOURCE_BULK_EDIT,
BulkEditConstants.NOTIFICATION_EVENT_TYPE_MISSING_ATTRIBUTES, NotificationEvent.Level.FAILURE);
}
private DataType mockDataTypeWithAttributes(final String typeCode, final Collection<DataAttribute> attributes)
{
final DataType dataType = mock(DataType.class);
when(dataType.getCode()).thenReturn(typeCode);
when(dataType.getAttributes()).thenReturn(attributes);
attributes.forEach(attr -> when(dataType.getAttribute(attr.getQualifier())).thenReturn(attr));
return dataType;
}
private DataAttribute mockDataAttribute(final String attribute, final DataAttribute.AttributeType attributeType)
{
final DataAttribute da = mock(DataAttribute.class);
when(da.getQualifier()).thenReturn(attribute);
when(da.getDefinedType()).thenReturn(DataType.STRING);
when(da.getValueType()).thenReturn(DataType.STRING);
when(da.getAttributeType()).thenReturn(attributeType);
return da;
}
}
|
package com.allen.lightstreamdemo;
import android.os.Handler;
import android.widget.ListView;
import com.lightstreamer.client.ItemUpdate;
import com.orhanobut.logger.Logger;
import java.util.ArrayList;
/**
* Created by: allen on 16/8/29.
*/
public class MainSubscription extends SimpleSubscriptionListener {
private static final String TAG = "MainSubscription";
private ArrayList<StockForList> mLists;
private Context mContext = new Context();
public MainSubscription(ArrayList<StockForList> list) {
super(TAG);
this.mLists = list;
}
public void changeContext(Handler handler, ListView listView) {
this.mContext.mHandler = handler;
this.mContext.mListView = listView;
}
@Override
public void onItemUpdate(ItemUpdate itemUpdate) {
super.onItemUpdate(itemUpdate);
final StockForList toUpdate = mLists.get(itemUpdate.getItemPos() - 1);
toUpdate.update(itemUpdate, this.mContext);
Logger.d("onItemUpdate: "+itemUpdate);
}
public class Context {
public Handler mHandler;
public ListView mListView;
}
}
|
package br.com.thiagoGomes.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import br.com.thiagoGomes.service.EmailService;
import br.com.thiagoGomes.service.SmtpEmailService;
//Configuração do banco de dados de prod, que esta setado no application-teste.properties
@Configuration
@Profile("prod")
public class ProdConfig {
//Desse modo, quando injetar o email Service, usando o profile prod, irá criar a instancia do SmtpEmailService
@Bean
public EmailService emailService() {
return new SmtpEmailService();
}
}
|
package org.openfact.rest;
import io.swagger.annotations.*;
import org.openfact.rest.idm.*;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@SwaggerDefinition(
securityDefinition = @SecurityDefinition(
apiKeyAuthDefinitions = {
@ApiKeyAuthDefinition(key = "keycloak", name = "Authorization", in = ApiKeyAuthDefinition.ApiKeyLocation.HEADER)
}
)
)
@Path("/admin/organizations")
@Api(
value = "/admin/organizations",
description = "Comprobantes de pago", tags = "comprobantes",
authorizations = {
@Authorization(value = "keycloak", scopes = {})
}
)
@Consumes(MediaType.APPLICATION_JSON)
public interface DocumentsService {
@GET
@Path("/{organization}/documents")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Buscar comprobantes",
notes = "Busca un comprobante de acuerdo a los parámetros especificados",
response = SearchResultsRepresentation.class
)
SearchResultsRepresentation<DocumentResponseRepresentation> getDocuments(
@ApiParam(value = "Nombre de la organización", required = true)
@PathParam("organization") final String organization,
@ApiParam(value = "Tipo de documento a buscar", allowableValues = "INVOICE, CREDIT_NOTE, DEBIT_NOTE, VOIDED_DOCUMENTS", example = "INVOICE")
@QueryParam("documentType") String documentType,
@ApiParam(value = "Serie y número de del comprobante a buscar", example = "F001-00000001")
@QueryParam("documentId") String documentId);
@GET
@Path("/{organization}/documents/{id}")
@ApiOperation(value = "Obtener comprobante",
notes = "Retorna un comprobante de pago",
response = DocumentResponseRepresentation.class
)
@Produces(MediaType.APPLICATION_JSON)
DocumentResponseRepresentation getDocumentById(
@PathParam("organization") String organization,
@PathParam("id") String id
);
// @GET
// @Path("/{organization}/documents/{id}/representation/xml")
// @Produces(MediaType.APPLICATION_JSON)
// Response getXml(
// @PathParam("organization") String organization,
// @PathParam("id") String id
// );
//
// @GET
// @Path("/{organization}/documents/{id}/report")
// @Produces(MediaType.APPLICATION_JSON)
// Response getPdf(
// @PathParam("organization") String organization,
// @PathParam("id") String id
// );
//
// @POST
// @Path("/{organization}/documents/{id}/send-to-third-party")
// @Produces(MediaType.APPLICATION_JSON)
// Response sendToThirdParty(
// @PathParam("organization") String organization,
// @PathParam("id") String id
// );
//
// @POST
// @Path("/{organization}/documents/{id}/send-to-third-party-by-email")
// @Produces(MediaType.APPLICATION_JSON)
// Response sendToCustomThirdParty(
// @PathParam("organization") String organization,
// @PathParam("id") String id,
// ThirdPartyEmail thirdParty
// );
//
// @POST
// @Path("/{organization}/documents/search")
// @Produces(MediaType.APPLICATION_JSON)
// Response search(
// @PathParam("organization") String organization,
// SearchCriteriaRepresentation criteria
// );
@GET
@Path("/{organization}/sunat/documents/{id}/cdr")
@Produces(MediaType.APPLICATION_JSON)
Response getCdr(
@PathParam("organization") String organization,
@PathParam("id") String id
);
// @GET
// @Path("/{organization}/sunat/documents/{id}/check-ticket")
// @Produces(MediaType.APPLICATION_JSON)
// Response checkTicket(
// @PathParam("organization") String organization,
// @PathParam("id") String id
// );
@POST
@Path("/{organization}/sunat/documents/invoices")
@ApiOperation(value = "Crear boleta/factura",
notes = "Crea una boleta/factura y retorna el comprobante creado",
response = DocumentResponseRepresentation.class
)
@Produces(MediaType.APPLICATION_JSON)
DocumentResponseRepresentation createInvoice(
@ApiParam(value = "Nombre de la organización", example = "miempresa")
@PathParam("organization") String organization,
@ApiParam(value = "Tipo de operación", defaultValue = "true")
@QueryParam("async") boolean async,
@ApiParam(value = "Cuerpo del comprobante", required = true) Invoice invoice
);
@POST
@Path("/{organization}/sunat/documents/credit-notes")
@ApiOperation(value = "Crear Nota de Crédito",
notes = "Crea una Nota de Crédito y retorna el comprobante creado",
response = DocumentResponseRepresentation.class
)
@Produces(MediaType.APPLICATION_JSON)
DocumentResponseRepresentation createCreditNote(
@ApiParam(value = "Nombre de la organización", example = "miempresa")
@PathParam("organization") String organization,
@ApiParam(value = "Tipo de operación", defaultValue = "true")
@QueryParam("async") boolean async,
@ApiParam(value = "Cuerpo del comprobante", required = true) CreditNote creditNote
);
@POST
@Path("/{organization}/sunat/documents/debit-notes")
@ApiOperation(value = "Crear Nota de Débito",
notes = "Crea una Nota de Débito y retorna el comprobante creado",
response = DocumentResponseRepresentation.class
)
@Produces(MediaType.APPLICATION_JSON)
DocumentResponseRepresentation createDebitNote(
@ApiParam(value = "Nombre de la organización", example = "miempresa")
@PathParam("organization") String organization,
@ApiParam(value = "Tipo de operación", defaultValue = "true")
@QueryParam("async") boolean async,
@ApiParam(value = "Cuerpo del comprobante", required = true) DebitNote debitNote
);
@POST
@Path("/{organization}/sunat/documents/perceptions")
@ApiOperation(value = "Crear Percepción",
notes = "Crea una Percepción y retorna el comprobante creado",
response = DocumentResponseRepresentation.class
)
@Produces(MediaType.APPLICATION_JSON)
DocumentResponseRepresentation createPerception(
@ApiParam(value = "Nombre de la organización", example = "miempresa")
@PathParam("organization") String organization,
@ApiParam(value = "Tipo de operación", defaultValue = "true")
@QueryParam("async") boolean async,
@ApiParam(value = "Cuerpo del comprobante", required = true) Perception perception
);
@POST
@Path("/{organization}/sunat/documents/retentions")
@ApiOperation(value = "Crear Retención",
notes = "Crea una Retención y retorna el comprobante creado",
response = DocumentResponseRepresentation.class
)
@Produces(MediaType.APPLICATION_JSON)
DocumentResponseRepresentation createRetention(
@ApiParam(value = "Nombre de la organización", example = "miempresa")
@PathParam("organization") String organization,
@ApiParam(value = "Tipo de operación", defaultValue = "true")
@QueryParam("async") boolean async,
@ApiParam(value = "Cuerpo del comprobante", required = true) Retention retention
);
@POST
@Path("/{organization}/sunat/documents/voided-documents")
@ApiOperation(value = "Crear VoidedDocument",
notes = "Crea una VoidedDocument y retorna el comprobante creado",
response = DocumentResponseRepresentation.class
)
@Produces(MediaType.APPLICATION_JSON)
DocumentResponseRepresentation createVoidedDocument(
@ApiParam(value = "Nombre de la organización", example = "miempresa")
@PathParam("organization") String organization,
@ApiParam(value = "Tipo de operación", defaultValue = "true")
@QueryParam("async") boolean async,
@ApiParam(value = "Cuerpo del comprobante", required = true) VoidedDocument voidedDocument
);
}
|
package practiceLogic;
public class ReverseString {
static String reverseString(String str) {
String rev="";
for(int i=(str.length() - 1); i >= 0; i--) {
rev = rev+str.charAt(i);
}
return rev;
}
static boolean isPlalindrome(String str) {
if(str.equals(reverseString(str))) {
return true;
}else {
return false;
}
}
static String capitalizeWord(String str) {
String[] words = str.split("\\s");
String capitalizedWord="";
for(String s : words) {
String first = s.substring(0,1);
String afterFirst = s.substring(1);
capitalizedWord = capitalizedWord + first.toUpperCase() + afterFirst + " ";
}
return capitalizedWord;
}
static String reverseEachWord(String str) {
String word[] = str.split("\\s");
String reverseEachWord = "";
for(String w : word) {
reverseEachWord = reverseEachWord + reverseString(w) + " ";
}
return reverseEachWord;
}
public static void main(String []args) {
System.out.println(reverseString("Jayanta"));
System.out.println(isPlalindrome("nitin"));
System.out.println(capitalizeWord("my name is jayanta"));
System.out.println(reverseEachWord("my name is jayanta"));
}
}
|
package com.tencent.mm.protocal.c;
import com.tencent.mm.bk.a;
import f.a.a.b;
import java.util.LinkedList;
public final class cfv extends a {
public String jQb;
public cfs sAq;
protected final int a(int i, Object... objArr) {
int h;
if (i == 0) {
f.a.a.c.a aVar = (f.a.a.c.a) objArr[0];
if (this.jQb == null) {
throw new b("Not all required fields were included: AppId");
} else if (this.sAq == null) {
throw new b("Not all required fields were included: PkgConfig");
} else {
if (this.jQb != null) {
aVar.g(1, this.jQb);
}
if (this.sAq == null) {
return 0;
}
aVar.fV(2, this.sAq.boi());
this.sAq.a(aVar);
return 0;
}
} else if (i == 1) {
if (this.jQb != null) {
h = f.a.a.b.b.a.h(1, this.jQb) + 0;
} else {
h = 0;
}
if (this.sAq != null) {
h += f.a.a.a.fS(2, this.sAq.boi());
}
return h;
} else if (i == 2) {
f.a.a.a.a aVar2 = new f.a.a.a.a((byte[]) objArr[0], unknownTagHandler);
for (h = a.a(aVar2); h > 0; h = a.a(aVar2)) {
if (!super.a(aVar2, this, h)) {
aVar2.cJS();
}
}
if (this.jQb == null) {
throw new b("Not all required fields were included: AppId");
} else if (this.sAq != null) {
return 0;
} else {
throw new b("Not all required fields were included: PkgConfig");
}
} else if (i != 3) {
return -1;
} else {
f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0];
cfv cfv = (cfv) objArr[1];
int intValue = ((Integer) objArr[2]).intValue();
switch (intValue) {
case 1:
cfv.jQb = aVar3.vHC.readString();
return 0;
case 2:
LinkedList IC = aVar3.IC(intValue);
int size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
byte[] bArr = (byte[]) IC.get(intValue);
cfs cfs = new cfs();
f.a.a.a.a aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (boolean z = true; z; z = cfs.a(aVar4, cfs, a.a(aVar4))) {
}
cfv.sAq = cfs;
}
return 0;
default:
return -1;
}
}
}
}
|
package com.levi9.taster.rest.api.controller;
import java.util.List;
import javax.inject.Inject;
import javax.validation.Valid;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;
import com.codiform.moo.curry.Translate;
import com.levi9.taster.commons.model.Page;
import com.levi9.taster.core.Category;
import com.levi9.taster.core.Question;
import com.levi9.taster.core.api.CategoryService;
import com.levi9.taster.core.api.QuestionService;
import com.levi9.taster.rest.api.exception.InvalidInputException;
import com.levi9.taster.rest.api.exception.InvalidInputExceptionExtractor;
import com.levi9.taster.rest.api.resource.CategoryResource;
import com.levi9.taster.rest.api.resource.QuestionResource;
/**
* REST Controller for categories.
*
* @author d.gajic
*/
@RestController
@RequestMapping("/api/categories")
public class CategoryController {
@Inject
private CategoryService categoryService;
@Inject
private QuestionService questionService;
/**
* Gets categories.
*
* @param number the number
* @param size the size
* @return the list
*/
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<List<CategoryResource>> list(@RequestParam Integer number, @RequestParam Integer size) {
Page<? extends Category> categories = categoryService.findAll(number, size);
final HttpHeaders headers = new HttpHeaders();
headers.add("X-total", String.valueOf(categories.getTotalElements()));
return new ResponseEntity<List<CategoryResource>>(Translate.to(CategoryResource.class).fromEach(categories.getContent()), headers, HttpStatus.OK);
}
/**
* Gets the single category based on ID.
*
* @param id the id
* @return the category resource
*/
@RequestMapping(method = RequestMethod.GET, value = "/{id}")
public CategoryResource get(@PathVariable Long id) {
return Translate.to(CategoryResource.class).from(categoryService.findOne(id));
}
/**
* Posts/creates new category.
*
* @param categoryResource the category resource
* @param builder the builder
* @return the new saved category
*/
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<CategoryResource> post(@Valid @RequestBody CategoryResource categoryResource, BindingResult bindingResult,
UriComponentsBuilder builder) throws InvalidInputException {
InvalidInputExceptionExtractor.extractAndThrow(bindingResult);
Category savedCategory = categoryService.save(categoryService.builder(categoryResource.getName()).build());
final HttpHeaders headers = new HttpHeaders();
headers.setLocation(builder.path("/categories/{id}").buildAndExpand(savedCategory.getId()).toUri());
return new ResponseEntity<CategoryResource>(Translate.to(CategoryResource.class).from(savedCategory), headers, HttpStatus.CREATED);
}
/**
* Updates single category and all its properties.
*
* @param categoryResource the category resource
* @param id the id
* @param builder the builder
* @return the response entity
*/
@RequestMapping(method = RequestMethod.PUT, value = "/{id}")
public ResponseEntity<CategoryResource> put(@Valid @RequestBody CategoryResource categoryResource, BindingResult bindingResult, @PathVariable Long id,
UriComponentsBuilder builder) throws InvalidInputException {
InvalidInputExceptionExtractor.extractAndThrow(bindingResult);
Category savedCategory = categoryService.updateName(id, categoryResource.getName());
final HttpHeaders headers = new HttpHeaders();
headers.setLocation(builder.path("/categories/{id}").buildAndExpand(savedCategory.getId()).toUri());
return new ResponseEntity<CategoryResource>(Translate.to(CategoryResource.class).from(savedCategory), headers, HttpStatus.OK);
}
/**
* Patches/updates only the name of category.
*
* @param categoryResource the category resource
* @param id the id
* @param builder the builder
* @return the response entity
*/
@RequestMapping(method = RequestMethod.PATCH, value = "/{id}")
public ResponseEntity<CategoryResource> patch(@Valid @RequestBody CategoryResource categoryResource, @PathVariable Long id,
UriComponentsBuilder builder) {
Category savedCategory = categoryService.updateName(id, categoryResource.getName());
final HttpHeaders headers = new HttpHeaders();
headers.setLocation(builder.path("/categories/{id}").buildAndExpand(savedCategory.getId()).toUri());
return new ResponseEntity<CategoryResource>(Translate.to(CategoryResource.class).from(savedCategory), headers, HttpStatus.OK);
}
/**
* Delete category based on ID.
*
* @param id the id
* @return the response entity
*/
@RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
public ResponseEntity<HttpStatus> delete(@PathVariable Long id) {
categoryService.delete(id);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
/**
* Gets list of questions based on category ID.
*
* @param categoryId id of category
* @return list of question resources
*/
@RequestMapping(method = RequestMethod.GET, value = "/{categoryId}/questions")
public ResponseEntity<List<QuestionResource>> listForCategory(@PathVariable Long categoryId) {
List<? extends Question> questions = questionService.findQuestionsByCategoryId(categoryId);
final HttpHeaders headers = new HttpHeaders();
headers.add("X-total", String.valueOf(questions.size()));
return new ResponseEntity<List<QuestionResource>>(Translate.to(QuestionResource.class).fromEach(questions), headers, HttpStatus.OK);
}
}
|
class Solution {
/*public int hammingDistance(int x, int y) {
String xBin = Integer.toBinaryString(x);
String yBin = Integer.toBinaryString(y);
StringBuilder xb = new StringBuilder(xBin);
StringBuilder yb = new StringBuilder(yBin);
int distance =0;
if(xBin.length() < yBin.length()){
while(xb.length() != yb.length()){
xb.insert(0,"0");
}
//xb = xb.reverse();
System.out.println(xb +" "+ yb);
}else if(xBin.length() > yBin.length()){
while(yb.length() != xb.length()){
yb.insert(0,"0");
}
//yb = yb.reverse();
System.out.println(xb +" "+ yb);
}
for(int i = 0; i < xb.length() ; i++){
if(xb.charAt(i) != yb.charAt(i)){
distance ++;
}
}
return distance;
}*/
/*
public int hammingDistance(int x, int y) {
return Integer.bitCount(x ^ y);
}
*/
public int hammingDistance(int x, int y) {
String str = Integer.toBinaryString(x^y);
return str.replace("0","").length();
}
}
|
package com.tt.miniapp.jsbridge;
import android.content.ContextWrapper;
import com.he.v8_inspect.Inspect;
import com.tt.frontendapiinterface.j;
import com.tt.miniapp.AppbrandApplicationImpl;
import com.tt.miniapp.AppbrandServiceManager;
import com.tt.miniapp.JsRuntime;
import com.tt.miniapp.debug.DebugManager;
import com.tt.miniapphost.AppBrandLogger;
import java.util.HashSet;
public class JsRuntimeManager extends AppbrandServiceManager.ServiceBase {
private volatile JsRuntime mCurrentRuntime;
private PreloadedJsContext preloadedJsContext;
private final HashSet<JsRuntimeReadyListener> sReadyListeners = new HashSet<JsRuntimeReadyListener>();
private JsRuntimeManager(AppbrandApplicationImpl paramAppbrandApplicationImpl) {
super(paramAppbrandApplicationImpl);
}
private void checkCurrent(boolean paramBoolean) {
if (this.mCurrentRuntime == null)
return;
if (this.mCurrentRuntime instanceof JsTMARuntime == paramBoolean && this.mCurrentRuntime.getJsSdkLoadState() != 1)
return;
StringBuilder stringBuilder = new StringBuilder("release ");
stringBuilder.append(this.mCurrentRuntime);
AppBrandLogger.i("tma_JsRuntimeManager", new Object[] { stringBuilder.toString() });
if ((DebugManager.getInst()).mTmaDebugOpen) {
Inspect.onDispose("0");
(DebugManager.getInst()).mTmaDebugOpen = false;
}
this.mCurrentRuntime.release();
this.mCurrentRuntime = null;
}
public void addJsRuntimeReadyListener(JsRuntimeReadyListener paramJsRuntimeReadyListener) {
// Byte code:
// 0: aload_0
// 1: monitorenter
// 2: aload_1
// 3: ifnull -> 23
// 6: aload_0
// 7: getfield sReadyListeners : Ljava/util/HashSet;
// 10: aload_1
// 11: invokevirtual add : (Ljava/lang/Object;)Z
// 14: pop
// 15: goto -> 23
// 18: astore_1
// 19: aload_0
// 20: monitorexit
// 21: aload_1
// 22: athrow
// 23: aload_0
// 24: monitorexit
// 25: return
// Exception table:
// from to target type
// 6 15 18 finally
}
public JsRuntime getCurrentRuntime() {
// Byte code:
// 0: aload_0
// 1: monitorenter
// 2: aload_0
// 3: getfield mCurrentRuntime : Lcom/tt/miniapp/JsRuntime;
// 6: astore_1
// 7: aload_0
// 8: monitorexit
// 9: aload_1
// 10: areturn
// 11: astore_1
// 12: aload_0
// 13: monitorexit
// 14: aload_1
// 15: athrow
// Exception table:
// from to target type
// 2 7 11 finally
}
public j getJsBridge() {
// Byte code:
// 0: aload_0
// 1: monitorenter
// 2: aload_0
// 3: getfield mCurrentRuntime : Lcom/tt/miniapp/JsRuntime;
// 6: ifnull -> 21
// 9: aload_0
// 10: getfield mCurrentRuntime : Lcom/tt/miniapp/JsRuntime;
// 13: invokevirtual getJsBridge : ()Lcom/tt/frontendapiinterface/j;
// 16: astore_1
// 17: aload_0
// 18: monitorexit
// 19: aload_1
// 20: areturn
// 21: aload_0
// 22: monitorexit
// 23: aconst_null
// 24: areturn
// 25: astore_1
// 26: aload_0
// 27: monitorexit
// 28: aload_1
// 29: athrow
// Exception table:
// from to target type
// 2 17 25 finally
}
public void initTMARuntime(ContextWrapper paramContextWrapper) {
// Byte code:
// 0: aload_0
// 1: monitorenter
// 2: aload_0
// 3: iconst_1
// 4: invokespecial checkCurrent : (Z)V
// 7: invokestatic getInst : ()Lcom/tt/miniapp/AppbrandApplicationImpl;
// 10: ldc com/tt/miniapp/util/timeline/MpTimeLineReporter
// 12: invokevirtual getService : (Ljava/lang/Class;)Lcom/tt/miniapp/AppbrandServiceManager$ServiceBase;
// 15: checkcast com/tt/miniapp/util/timeline/MpTimeLineReporter
// 18: astore_2
// 19: aload_2
// 20: ldc 'create_jsEngine_begin'
// 22: invokevirtual addPoint : (Ljava/lang/String;)Z
// 25: pop
// 26: aload_0
// 27: getfield mCurrentRuntime : Lcom/tt/miniapp/JsRuntime;
// 30: ifnonnull -> 49
// 33: aload_0
// 34: new com/tt/miniapp/jsbridge/JsTMARuntime
// 37: dup
// 38: aload_1
// 39: aload_0
// 40: getfield preloadedJsContext : Lcom/tt/miniapp/jsbridge/PreloadedJsContext;
// 43: invokespecial <init> : (Landroid/content/ContextWrapper;Lcom/tt/miniapp/jsbridge/PreloadedJsContext;)V
// 46: putfield mCurrentRuntime : Lcom/tt/miniapp/JsRuntime;
// 49: aload_2
// 50: ldc 'create_jsEngine_end'
// 52: invokevirtual addPoint : (Ljava/lang/String;)Z
// 55: pop
// 56: aload_0
// 57: getfield sReadyListeners : Ljava/util/HashSet;
// 60: invokevirtual iterator : ()Ljava/util/Iterator;
// 63: astore_1
// 64: aload_1
// 65: invokeinterface hasNext : ()Z
// 70: ifeq -> 96
// 73: aload_1
// 74: invokeinterface next : ()Ljava/lang/Object;
// 79: checkcast com/tt/miniapp/jsbridge/JsRuntimeManager$JsRuntimeReadyListener
// 82: astore_2
// 83: aload_2
// 84: ifnull -> 64
// 87: aload_2
// 88: invokeinterface onJsRuntimeReady : ()V
// 93: goto -> 64
// 96: aload_0
// 97: getfield sReadyListeners : Ljava/util/HashSet;
// 100: invokevirtual clear : ()V
// 103: aload_0
// 104: monitorexit
// 105: return
// 106: astore_1
// 107: aload_0
// 108: monitorexit
// 109: goto -> 114
// 112: aload_1
// 113: athrow
// 114: goto -> 112
// Exception table:
// from to target type
// 2 49 106 finally
// 49 64 106 finally
// 64 83 106 finally
// 87 93 106 finally
// 96 103 106 finally
}
public void initTMGRuntime(JSRuntimeFactory paramJSRuntimeFactory) {
// Byte code:
// 0: aload_0
// 1: monitorenter
// 2: aload_0
// 3: iconst_0
// 4: invokespecial checkCurrent : (Z)V
// 7: invokestatic getInst : ()Lcom/tt/miniapp/AppbrandApplicationImpl;
// 10: ldc com/tt/miniapp/util/timeline/MpTimeLineReporter
// 12: invokevirtual getService : (Ljava/lang/Class;)Lcom/tt/miniapp/AppbrandServiceManager$ServiceBase;
// 15: checkcast com/tt/miniapp/util/timeline/MpTimeLineReporter
// 18: astore_2
// 19: aload_2
// 20: ldc 'create_jsEngine_begin'
// 22: invokevirtual addPoint : (Ljava/lang/String;)Z
// 25: pop
// 26: aload_0
// 27: getfield mCurrentRuntime : Lcom/tt/miniapp/JsRuntime;
// 30: ifnonnull -> 47
// 33: aload_0
// 34: aload_1
// 35: aload_0
// 36: getfield preloadedJsContext : Lcom/tt/miniapp/jsbridge/PreloadedJsContext;
// 39: invokeinterface create : (Lcom/tt/miniapp/jsbridge/PreloadedJsContext;)Lcom/tt/miniapp/JsRuntime;
// 44: putfield mCurrentRuntime : Lcom/tt/miniapp/JsRuntime;
// 47: aload_2
// 48: ldc 'create_jsEngine_end'
// 50: invokevirtual addPoint : (Ljava/lang/String;)Z
// 53: pop
// 54: aload_0
// 55: monitorexit
// 56: return
// 57: astore_1
// 58: aload_0
// 59: monitorexit
// 60: aload_1
// 61: athrow
// Exception table:
// from to target type
// 2 47 57 finally
// 47 54 57 finally
}
public void preloadTMARuntime(ContextWrapper paramContextWrapper) {
// Byte code:
// 0: aload_0
// 1: monitorenter
// 2: aload_0
// 3: getfield mCurrentRuntime : Lcom/tt/miniapp/JsRuntime;
// 6: astore_2
// 7: aload_2
// 8: ifnull -> 14
// 11: aload_0
// 12: monitorexit
// 13: return
// 14: aload_1
// 15: iconst_0
// 16: iconst_2
// 17: anewarray java/lang/Enum
// 20: dup
// 21: iconst_0
// 22: getstatic com/tt/miniapp/settings/keys/Settings.TT_TMA_SWITCH : Lcom/tt/miniapp/settings/keys/Settings;
// 25: aastore
// 26: dup
// 27: iconst_1
// 28: getstatic com/tt/miniapp/settings/keys/Settings$TmaSwitch.PRELOAD_TMG : Lcom/tt/miniapp/settings/keys/Settings$TmaSwitch;
// 31: aastore
// 32: invokestatic getBoolean : (Landroid/content/Context;Z[Ljava/lang/Enum;)Z
// 35: ifeq -> 62
// 38: invokestatic getInst : ()Lcom/tt/miniapp/debug/DebugManager;
// 41: getfield mIsDebugOpen : Z
// 44: ifne -> 62
// 47: aload_0
// 48: new com/tt/miniapp/jsbridge/PreloadedJsContext
// 51: dup
// 52: aload_1
// 53: invokespecial <init> : (Landroid/content/ContextWrapper;)V
// 56: putfield preloadedJsContext : Lcom/tt/miniapp/jsbridge/PreloadedJsContext;
// 59: aload_0
// 60: monitorexit
// 61: return
// 62: aload_0
// 63: new com/tt/miniapp/jsbridge/JsTMARuntime
// 66: dup
// 67: aload_1
// 68: aconst_null
// 69: invokespecial <init> : (Landroid/content/ContextWrapper;Lcom/tt/miniapp/jsbridge/PreloadedJsContext;)V
// 72: putfield mCurrentRuntime : Lcom/tt/miniapp/JsRuntime;
// 75: aload_0
// 76: monitorexit
// 77: return
// 78: astore_1
// 79: aload_0
// 80: monitorexit
// 81: aload_1
// 82: athrow
// Exception table:
// from to target type
// 2 7 78 finally
// 14 59 78 finally
// 62 75 78 finally
}
public static interface JSRuntimeFactory {
JsRuntime create(PreloadedJsContext param1PreloadedJsContext);
}
public static interface JsRuntimeReadyListener {
void onJsRuntimeReady();
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\jsbridge\JsRuntimeManager.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ |
package oop.snakegame;
import oop.snakegame.cells.*;
public interface IVisitor {
void visit(Wall wall);
void visit(SizeBonus bonus);
void visit(SnakeBlock block);
void visit(Teleport teleport);
void visit(MovingBonus movingBonus);
void visit(TemporaryBonus temporaryBonus);
void visit(LifeCell lifeCell);
}
|
package com.facebook.react;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class CompositeReactPackage extends ReactInstancePackage implements ViewManagerOnDemandReactPackage {
private final List<ReactPackage> mChildReactPackages = new ArrayList<ReactPackage>();
public CompositeReactPackage(ReactPackage paramReactPackage1, ReactPackage paramReactPackage2, ReactPackage... paramVarArgs) {
this.mChildReactPackages.add(paramReactPackage1);
this.mChildReactPackages.add(paramReactPackage2);
Collections.addAll(this.mChildReactPackages, paramVarArgs);
}
public List<NativeModule> createNativeModules(ReactApplicationContext paramReactApplicationContext) {
HashMap<Object, Object> hashMap = new HashMap<Object, Object>();
Iterator<ReactPackage> iterator = this.mChildReactPackages.iterator();
while (iterator.hasNext()) {
for (NativeModule nativeModule : ((ReactPackage)iterator.next()).createNativeModules(paramReactApplicationContext))
hashMap.put(nativeModule.getName(), nativeModule);
}
return new ArrayList<NativeModule>(hashMap.values());
}
public List<NativeModule> createNativeModules(ReactApplicationContext paramReactApplicationContext, ReactInstanceManager paramReactInstanceManager) {
HashMap<Object, Object> hashMap = new HashMap<Object, Object>();
for (ReactPackage reactPackage : this.mChildReactPackages) {
List<NativeModule> list;
if (reactPackage instanceof ReactInstancePackage) {
list = ((ReactInstancePackage)reactPackage).createNativeModules(paramReactApplicationContext, paramReactInstanceManager);
} else {
list = list.createNativeModules(paramReactApplicationContext);
}
for (NativeModule nativeModule : list)
hashMap.put(nativeModule.getName(), nativeModule);
}
return new ArrayList<NativeModule>(hashMap.values());
}
public ViewManager createViewManager(ReactApplicationContext paramReactApplicationContext, String paramString, boolean paramBoolean) {
List<ReactPackage> list = this.mChildReactPackages;
ListIterator<ReactPackage> listIterator = list.listIterator(list.size());
while (listIterator.hasPrevious()) {
ReactPackage reactPackage = listIterator.previous();
if (reactPackage instanceof ViewManagerOnDemandReactPackage) {
ViewManager viewManager = ((ViewManagerOnDemandReactPackage)reactPackage).createViewManager(paramReactApplicationContext, paramString, paramBoolean);
if (viewManager != null)
return viewManager;
}
}
return null;
}
public List<ViewManager> createViewManagers(ReactApplicationContext paramReactApplicationContext) {
HashMap<Object, Object> hashMap = new HashMap<Object, Object>();
Iterator<ReactPackage> iterator = this.mChildReactPackages.iterator();
while (iterator.hasNext()) {
for (ViewManager viewManager : ((ReactPackage)iterator.next()).createViewManagers(paramReactApplicationContext))
hashMap.put(viewManager.getName(), viewManager);
}
return new ArrayList<ViewManager>(hashMap.values());
}
public List<String> getViewManagerNames(ReactApplicationContext paramReactApplicationContext, boolean paramBoolean) {
HashSet<String> hashSet = new HashSet();
for (ReactPackage reactPackage : this.mChildReactPackages) {
if (reactPackage instanceof ViewManagerOnDemandReactPackage) {
List<String> list = ((ViewManagerOnDemandReactPackage)reactPackage).getViewManagerNames(paramReactApplicationContext, paramBoolean);
if (list != null)
hashSet.addAll(list);
}
}
return new ArrayList<String>(hashSet);
}
}
/* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\react\CompositeReactPackage.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ |
package com.lecture.spring.model;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ModelVideo {
private int componentTBNO ;
private String video_url ;
private char video_autoplay ;
public ModelVideo(int componentTBNO, String video_url, char video_autoplay) {
super();
this.componentTBNO = componentTBNO;
this.video_url = video_url;
this.video_autoplay = video_autoplay;
}
public ModelVideo() {
super();
}
public int getComponentTBNO() {
return componentTBNO;
}
public void setComponentTBNO(int componentTBNO) {
this.componentTBNO = componentTBNO;
}
public String getVideo_url() {
return video_url;
}
public void setVideo_url(String video_url) {
this.video_url = video_url;
}
public char getVideo_autoplay() {
return video_autoplay;
}
public void setVideo_autoplay(char video_autoplay) {
this.video_autoplay = video_autoplay;
}
@Override
public String toString() {
return "ModelVideo [componentTBNO=" + componentTBNO + ", video_url="
+ video_url + ", video_autoplay=" + video_autoplay + "]";
}
}
|
package edu.eci.arsw.webstore.controllers;
import java.util.Date;
import java.util.Map;
import com.google.gson.Gson;
import org.bson.types.ObjectId;
import org.omg.IOP.TransactionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.util.HtmlUtils;
import edu.eci.arsw.webstore.model.Notification;
import edu.eci.arsw.webstore.services.notification.NotificationServices;
import edu.eci.arsw.webstore.services.transaction.TransactionServices;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.google.gson.reflect.TypeToken;
import java.io.Console;
import java.lang.reflect.Type;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime; // Import the LocalDateTime class
import java.time.format.DateTimeFormatter; // Import the DateTimeFormatter class
@Controller
@RestController
@RequestMapping(value = "/api/v1")
public class SynchronizeController {
@Autowired
NotificationServices nService;
@Autowired
TransactionServices tService;
@MessageMapping("/upgrade")
@SendTo("/topic/syncup")
public Notification synchronize(Notification notification) throws Exception {
try {
System.out.println(">>> 3) suscripto...");
Thread.sleep(1000); // simulated delay
// recibe: envio, destino, funcion, fecha, url, visto:falso, mensaje
Notification noti = notification;
// Notification notiWeb = HtmlUtils.htmlEscape(notification);
// System.out.println(noti.getNotificationDestination());
//System.out.println(noti.getNotificationMessage());
System.out.println(noti.getNotificationDate());
// System.out.println(noti.getNotificationSend());
// System.out.println(noti.getNotificationUrl());
// System.out.println(noti.getNotificationFunction());
// System.out.println(noti.isNotificationViewed());
// guardar fecha
String dateColombia = tService.getDateColombia();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
LocalDateTime myDateObj = LocalDateTime.parse(dateColombia.substring(0, 19), formatter);
DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
String formattedDate = myDateObj.format(myFormatObj);
// System.out.println("After formatting: " + formattedDate);
noti.setNotificationDate(formattedDate);
notification.setNotificationDate(formattedDate);
// Guardar notificacion en base de datos
if (noti.getNotificationFunction().equals("newMessage")
|| noti.getNotificationFunction().equals("newTransaction")
|| noti.getNotificationFunction().equals("editTransaction")) {
System.out.println(">> es notificacion a guardar");
ObjectId newObjectIdNotification = new ObjectId(new Date());
noti.setNotificationId(newObjectIdNotification.toHexString());
nService.createNewNotification(notification);
}
return new Notification(HtmlUtils.htmlEscape(notification.getNotificationMessage()),
HtmlUtils.htmlEscape(notification.getNotificationDate()),
HtmlUtils.htmlEscape(notification.getNotificationDestination()),
HtmlUtils.htmlEscape(notification.getNotificationSend()),
HtmlUtils.htmlEscape(notification.getNotificationUrl()),
HtmlUtils.htmlEscape(notification.getNotificationFunction()), false);
} catch (Exception ex) {
Logger.getLogger(SynchronizeController.class.getName()).log(Level.SEVERE, null, ex);
return new Notification();
}
}
@RequestMapping(method = RequestMethod.GET, path = { "notifications/{nickname}" })
public ResponseEntity<?> getNotificationsByNickname(@PathVariable("nickname") String nickname) {
try {
System.out.println("Consultando Notificaciones del usuario " + nickname + "...");
String data = new Gson().toJson(nService.getNotificationsByNickname(nickname));
return new ResponseEntity<>(data, HttpStatus.ACCEPTED);
} catch (Exception ex) {
Logger.getLogger(SynchronizeController.class.getName()).log(Level.SEVERE, null, ex);
return new ResponseEntity<>("No se ha podido retornar las notificaciones", HttpStatus.NOT_FOUND);
}
}
@RequestMapping(method = RequestMethod.GET, path = { "notifications/user/{notificationId}" })
public ResponseEntity<?> getNotificationById(@PathVariable("notificationId") String notificationId) {
try {
System.out.println("Consultando la Notificacion con Id: " + notificationId + "...");
String data = new Gson().toJson(nService.getNotificationsById(notificationId));
return new ResponseEntity<>(data, HttpStatus.ACCEPTED);
} catch (Exception ex) {
Logger.getLogger(SynchronizeController.class.getName()).log(Level.SEVERE, null, ex);
return new ResponseEntity<>("No se ha podido retornar las notificaciones", HttpStatus.NOT_FOUND);
}
}
@RequestMapping(method = RequestMethod.POST, path = "notifications")
public ResponseEntity<?> createNewNotification(@RequestBody String notification) {
// Formato de json
// {"1":{"notificationMessage":"sent you a
// message","notificationDate":"2020/05/20
// 17:25pm","notificationDestination":"david","notificationSend":"juan","notificationUrl":"/transaction.html?txnId=5eb8bf403d212a77e4de9bb3","notificationFunction":"newMessage","notificationViewed":false}}
try {
System.out.println("Creando una nueva notificacion...");
// Pasar el String JSON a un Map
Type listType = new TypeToken<Map<Integer, Notification>>() {
}.getType();
Map<String, Notification> result = new Gson().fromJson(notification, listType);
// Obtener las llaves del Map
Object[] nameKeys = result.keySet().toArray();
Notification noti = result.get(nameKeys[0]);
ObjectId newObjectIdUser = new ObjectId(new Date());
noti.setNotificationId(newObjectIdUser.toHexString());
// Usuario nuevo Inactivo
noti.setNotificationViewed(false);
nService.createNewNotification(noti);
return new ResponseEntity<>(HttpStatus.CREATED);
} catch (Exception ex) {
Logger.getLogger(SynchronizeController.class.getName()).log(Level.SEVERE, null, ex);
return new ResponseEntity<>("No se ha podido guardar la notificacion", HttpStatus.NOT_FOUND);
}
}
@RequestMapping(method = RequestMethod.PUT, path = { "notifications/{notificationId}" })
public ResponseEntity<?> changeNotificationStatus(@PathVariable("notificationId") String notificationId) {
try {
System.out.println("Actualizando estado de notificacion: " + notificationId);
Notification noti = nService.getNotificationsById(notificationId);
nService.changeNotificationStatus(true, noti.getNotificationId());
return new ResponseEntity<>(HttpStatus.ACCEPTED);
} catch (Exception ex) {
Logger.getLogger(SynchronizeController.class.getName()).log(Level.SEVERE, null, ex);
return new ResponseEntity<>("No se puede actualizar el estado de la notificacion", HttpStatus.NOT_FOUND);
}
}
@RequestMapping(method = RequestMethod.DELETE, path = { "notifications/{notificationId}" })
public ResponseEntity<?> deleteNotificationById(@PathVariable("notificationId") String notificationId) {
try {
System.out.println("Eliminando Notificacion: " + notificationId);
nService.deleteNotificationById(notificationId);
return new ResponseEntity<>(HttpStatus.ACCEPTED);
} catch (Exception ex) {
Logger.getLogger(SynchronizeController.class.getName()).log(Level.SEVERE, null, ex);
return new ResponseEntity<>("No se ha podido eliminar la notificacion: " + notificationId,
HttpStatus.FORBIDDEN);
}
}
}
|
package com.team_linne.digimov.repository;
import com.team_linne.digimov.model.Order;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface OrderRepository extends MongoRepository<Order, String> {
List<Order> findAllByEmailAndCreditCardNumber(String email, String creditCardNumber);
List<Order> findAllByMovieSessionId(String movieSessionId);
}
|
package com.cy.pj.sys.controller;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.cy.pj.common.vo.JsonResult;
import com.cy.pj.common.vo.PageObject;
import com.cy.pj.common.vo.SysUserDeptVo;
import com.cy.pj.sys.entity.SysUser;
import com.cy.pj.sys.service.SysUserService;
//@Controller
//@ResponseBody
@RestController //@Controller+@ResponseBody
@RequestMapping("/user/")
public class SysUserController {
@Autowired
private SysUserService sysUserService;
@RequestMapping("doUpdatePassword")
public JsonResult doUpdatePassword(String pwd,String newPwd,String cfgPwd) {
sysUserService.updatePassword(pwd, newPwd, cfgPwd);
return new JsonResult("update ok!");
}
@RequestMapping("doLogin")
public JsonResult doLogin(boolean isRememberMe,String username, String password) {
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
if(isRememberMe) {
token.setRememberMe(true);
}
Subject currentUser = SecurityUtils.getSubject();
currentUser.login(token);//将用户信息提交给securitymanager进行认证
return new JsonResult("login ok!");
}
@RequestMapping("doFindPageObjects")
public JsonResult doFindPageObjects(String username, Integer pageCurrent) {
PageObject<SysUserDeptVo> pageObject = sysUserService.findObjects(username, pageCurrent);
return new JsonResult(pageObject);
}
@RequestMapping("doValidById")
public JsonResult doValidById(Integer id, Integer valid ) {
sysUserService.validById(id, valid );
return new JsonResult("成功修改!");
}
@RequestMapping("doSaveObject")
public JsonResult doSaveObject(SysUser entity, Integer[] roleIds) {
//System.out.println(entity+"==="+ Arrays.toString(roleIds));
sysUserService.saveObject(entity, roleIds);
//System.out.println(rows);
return new JsonResult("添加保存成功!");
}
@RequestMapping("doFindObjectById")
public JsonResult doFindObjectById(Integer id) {
//System.out.println(id);
return new JsonResult(sysUserService.findObjectBId(id));
}
@RequestMapping("doUpdateObject")
public JsonResult doUpdateObject(SysUser entity, Integer[] roleIds) {
//System.out.println(entity+"==="+roleIds);
sysUserService.updateObjectById(entity, roleIds);
return new JsonResult("更新修改成功!");
}
}
|
package com.pay.payo.model;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import lombok.Getter;
import lombok.Setter;
public class InputElementsItem implements Parcelable {
@SerializedName("name")
@Expose
@Getter
@Setter
public String name;
@SerializedName("type")
@Expose
private String type;
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.name);
dest.writeString(this.type);
}
public void readFromParcel(Parcel source) {
this.name = source.readString();
this.type = source.readString();
}
public InputElementsItem() {
}
protected InputElementsItem(Parcel in) {
this.name = in.readString();
this.type = in.readString();
}
public static final Parcelable.Creator<InputElementsItem> CREATOR = new Parcelable.Creator<InputElementsItem>() {
@Override
public InputElementsItem createFromParcel(Parcel source) {
return new InputElementsItem(source);
}
@Override
public InputElementsItem[] newArray(int size) {
return new InputElementsItem[size];
}
};
} |
package com.geekhelp.util;
/**
* Created by Вова on 26.01.2015.
*/
public enum LoadDir {
PROFILE,QUESTION
}
|
package razerdp.util.animation;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.util.Property;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import razerdp.util.PopupUtils;
import razerdp.util.log.PopupLog;
public class TranslationConfig extends BaseAnimationConfig<TranslationConfig> {
private static final String TAG = "TranslationConfig";
float fromX, toX, fromY, toY;
boolean isPercentageFromX, isPercentageToX, isPercentageFromY, isPercentageToY;
@Override
void resetInternal() {
fromX = toX = fromY = toY = 0;
isPercentageFromX = isPercentageToX = isPercentageFromY = isPercentageToY = false;
}
public TranslationConfig() {
super(false, false);
resetInternal();
}
TranslationConfig(boolean resetParent, boolean resetInternal) {
super(resetParent, resetInternal);
resetInternal();
}
public TranslationConfig from(Direction... directions) {
if (directions != null) {
fromX = fromY = 0;
int flag = 0;
for (Direction direction : directions) {
flag |= direction.flag;
}
PopupLog.i(TAG, "from", PopupUtils.gravityToString(flag));
if (Direction.isDirectionFlag(Direction.LEFT, flag)) {
fromX(fromX - 1, true);
}
if (Direction.isDirectionFlag(Direction.RIGHT, flag)) {
fromX(fromX + 1, true);
}
if (Direction.isDirectionFlag(Direction.CENTER_HORIZONTAL, flag)) {
fromX(fromX + 0.5f, true);
}
if (Direction.isDirectionFlag(Direction.TOP, flag)) {
fromY(fromY - 1, true);
}
if (Direction.isDirectionFlag(Direction.BOTTOM, flag)) {
fromY(fromY + 1, true);
}
if (Direction.isDirectionFlag(Direction.CENTER_VERTICAL, flag)) {
fromY(fromY + 0.5f, true);
}
isPercentageFromX = isPercentageFromY = isPercentageToX = isPercentageToY = true;
}
return this;
}
public TranslationConfig to(Direction... directions) {
if (directions != null) {
toX = toY = 0;
int flag = 0;
for (Direction direction : directions) {
flag |= direction.flag;
}
PopupLog.i(TAG, "to", PopupUtils.gravityToString(flag));
if (Direction.isDirectionFlag(Direction.LEFT, flag)) {
toX += -1;
}
if (Direction.isDirectionFlag(Direction.RIGHT, flag)) {
toX += 1;
}
if (Direction.isDirectionFlag(Direction.CENTER_HORIZONTAL, flag)) {
toX += .5f;
}
if (Direction.isDirectionFlag(Direction.TOP, flag)) {
toY += -1;
}
if (Direction.isDirectionFlag(Direction.BOTTOM, flag)) {
toY += 1;
}
if (Direction.isDirectionFlag(Direction.CENTER_VERTICAL, flag)) {
toY += .5f;
}
isPercentageFromX = isPercentageFromY = isPercentageToX = isPercentageToY = true;
}
return this;
}
public TranslationConfig fromX(float fromX) {
fromX(fromX, true);
return this;
}
public TranslationConfig toX(float toX) {
toX(toX, true);
return this;
}
public TranslationConfig fromY(float fromY) {
fromY(fromY, true);
return this;
}
public TranslationConfig toY(float toY) {
toY(toY, true);
return this;
}
public TranslationConfig fromX(int fromX) {
fromX(fromX, false);
return this;
}
public TranslationConfig toX(int toX) {
toX(toX, false);
return this;
}
public TranslationConfig fromY(int fromY) {
fromY(fromY, false);
return this;
}
public TranslationConfig toY(int toY) {
toY(toY, false);
return this;
}
TranslationConfig fromX(float fromX, boolean percentage) {
this.isPercentageFromX = percentage;
this.fromX = fromX;
return this;
}
TranslationConfig toX(float toX, boolean percentage) {
isPercentageToX = percentage;
this.toX = toX;
return this;
}
TranslationConfig fromY(float fromY, boolean percentage) {
isPercentageFromY = percentage;
this.fromY = fromY;
return this;
}
TranslationConfig toY(float toY, boolean percentage) {
isPercentageToY = percentage;
this.toY = toY;
return this;
}
@Override
public String toString() {
return "TranslationConfig{" +
"fromX=" + fromX +
", toX=" + toX +
", fromY=" + fromY +
", toY=" + toY +
", isPercentageFromX=" + isPercentageFromX +
", isPercentageToX=" + isPercentageToX +
", isPercentageFromY=" + isPercentageFromY +
", isPercentageToY=" + isPercentageToY +
'}';
}
@Override
protected Animation buildAnimation(boolean isRevert) {
Animation animation = new TranslateAnimation(isPercentageFromX ? Animation.RELATIVE_TO_SELF : Animation.ABSOLUTE,
fromX,
isPercentageToX ? Animation.RELATIVE_TO_SELF : Animation.ABSOLUTE,
toX,
isPercentageFromY ? Animation.RELATIVE_TO_SELF : Animation.ABSOLUTE,
fromY,
isPercentageToY ? Animation.RELATIVE_TO_SELF : Animation.ABSOLUTE,
toY);
deploy(animation);
return animation;
}
@Override
protected Animator buildAnimator(boolean isRevert) {
AnimatorSet animatorSet = new AnimatorSet();
Property<View, Float> TRANSLATION_X = (isPercentageFromX && isPercentageToY) ? new FloatPropertyCompat<View>(
View.TRANSLATION_X.getName()) {
@Override
public void setValue(View object, float value) {
object.setTranslationX(object.getWidth() * value);
}
@Override
public Float get(View object) {
return object.getTranslationX();
}
} : View.TRANSLATION_X;
Property<View, Float> TRANSLATION_Y = (isPercentageFromY && isPercentageToY) ? new FloatPropertyCompat<View>(
View.TRANSLATION_Y.getName()) {
@Override
public void setValue(View object, float value) {
object.setTranslationY(object.getHeight() * value);
}
@Override
public Float get(View object) {
return object.getTranslationY();
}
} : View.TRANSLATION_Y;
ObjectAnimator translationX = ObjectAnimator.ofFloat(null, TRANSLATION_X, fromX, toX);
ObjectAnimator translationY = ObjectAnimator.ofFloat(null, TRANSLATION_Y, fromY, toY);
animatorSet.playTogether(translationX, translationY);
deploy(animatorSet);
return animatorSet;
}
//------------------default
public static final TranslationConfig FROM_LEFT = new TranslationConfig(true, true) {
@Override
void resetInternal() {
super.resetInternal();
from(Direction.LEFT);
}
};
public static final TranslationConfig FROM_TOP = new TranslationConfig(true, true) {
@Override
void resetInternal() {
super.resetInternal();
from(Direction.TOP);
}
};
public static final TranslationConfig FROM_RIGHT = new TranslationConfig(true, true) {
@Override
void resetInternal() {
super.resetInternal();
from(Direction.RIGHT);
}
};
public static final TranslationConfig FROM_BOTTOM = new TranslationConfig(true, true) {
@Override
void resetInternal() {
super.resetInternal();
from(Direction.BOTTOM);
}
};
public static final TranslationConfig TO_LEFT = new TranslationConfig(true, true) {
@Override
void resetInternal() {
super.resetInternal();
to(Direction.LEFT);
}
};
public static final TranslationConfig TO_TOP = new TranslationConfig(true, true) {
@Override
void resetInternal() {
super.resetInternal();
to(Direction.TOP);
}
};
public static final TranslationConfig TO_RIGHT = new TranslationConfig(true, true) {
@Override
void resetInternal() {
super.resetInternal();
to(Direction.RIGHT);
}
};
public static final TranslationConfig TO_BOTTOM = new TranslationConfig(true, true) {
@Override
void resetInternal() {
super.resetInternal();
to(Direction.BOTTOM);
}
};
}
|
package com.microsilver.mrcard.basicservice.common;
import com.microsilver.mrcard.basicservice.utils.SystemConfig;
public class Consts {
//token开关
public static final Boolean CHECK_TOKEN = SystemConfig.getBooleanValue("CHECK_TOKEN");
//图片存储位置
public static final String PICTURES_ADDRESS = SystemConfig.getValue("PICTURES_ADDRESS");
//电话正则表达式
public static final String MOBILE_REGEX = SystemConfig.getValue("MOBILE_REGEX");
//支付微信应用ID
public static final String APP_ID = SystemConfig.getValue("APP_ID");
//支付微信商户ID
public static final String MCH_ID = SystemConfig.getValue("MCH_ID");
//支付微信公钥
public static final String PARENT_KEY = SystemConfig.getValue("PARENT_KEY");
//支付宝APPID
public static final String AliPAYAPP_ID = SystemConfig.getValue("AliPAYAPP_ID");
//支付宝秘钥(验证回调是否支付成功的秘钥)
public static final String AliPAYAPP_KEY = SystemConfig.getValue("AliPAYAPP_KEY");
//支付宝交易订单私钥
public static final String AliPAYAPP_PRIVATE_KEY = SystemConfig.getValue("AliPAYAPP_PRIVATE_KEY");
//骑手分润比例
public static final Double DELIVERY_PROPORTION = SystemConfig.getDoubleValue("DELIVERY_PROPORTION");
//代理商分润比例
public static final Double AGENT_PROPORTION = SystemConfig.getDoubleValue("AGENT_PROPORTION");
//平台分润比例
public static final Double PLATFORM_PROPORTION = SystemConfig.getDoubleValue("PLATFORM_PROPORTION");
//平台电话
public static final Integer PLATfORMPHONE = SystemConfig.getIntValue("PLATfORMPHONE");
}
|
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;
public class AddCmd extends LibraryCommand{
/** Generate a path to remember the path for book's data. */
private Path bookDataPath;
/**
* Create an add command and initialise it with
* the given command argument.
*
* @param argumentInput argument input as expected to be a existing path ended with .csv.
* @throws IllegalArgumentException if given arguments are invalid
* @throws NullPointerException if any of the given parameters are null.
*/
public AddCmd(String argumentInput) {
super(CommandType.ADD, argumentInput);
}
/**
* Execute the add command. This will add the data from the
* input path to library data.
* @param data book data to be considered for input data.
* @throws NullPointerException if given LibraryData is null.
*/
@Override
public void execute(LibraryData data) {
Objects.requireNonNull(data,"Given data shouldn't be null.");
data.loadData(bookDataPath);
}
/**
* Check the validity of the argument input and parse the path in.
* @param argumentInput argument input which expected to be a valid path.
* @return true if the argument input is valid.
* @throws NullPointerException if given argument are null.
*/
@Override
protected boolean parseArguments(String argumentInput) {
Objects.requireNonNull(argumentInput, "Given input argument must not be null.");
bookDataPath = Paths.get(argumentInput);
return isValidPathInput(argumentInput);
}
private boolean isValidPathInput(String argumentInput) {
try {
String fileExtension = argumentInput.substring(argumentInput.lastIndexOf('.'));
return (fileExtension.equals(".csv"));
}
catch (StringIndexOutOfBoundsException e){
return false;
}
}
}
|
package fr.eseo.poo.projet.artiste.controleur.actions;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import fr.eseo.poo.projet.artiste.controleur.outils.OutilSelectionner;
import fr.eseo.poo.projet.artiste.vue.ihm.PanneauDessin;
@SuppressWarnings("serial")
public class ActionSelectionner extends AbstractAction {
public static final String NOM_ACTION = "Selectionner";
public PanneauDessin panneauDessin = null;
public ActionSelectionner(PanneauDessin panneauDessin) {
super(NOM_ACTION);
this.panneauDessin = panneauDessin;
}
@Override
public void actionPerformed(ActionEvent event) {
this.panneauDessin.associerOutil(new OutilSelectionner());
}
} |
//Additional Tutorial 2 - Q3.16
import java.util.Scanner;
import java.util.Arrays;
public class Q_3_16{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.print("Enter three strings: ");
String input = sc.nextLine();
String[] aryOfStrings = input.split("\\s");
Arrays.sort(aryOfStrings);
for(int i=0;i<aryOfStrings.length;i++){
System.out.println(aryOfStrings[i]);
}
}
} |
package com.avalara.avatax.services.avacert2;
/**
* CertificateImageGetRequest.java
* The class contains Input for certificateImageGet
* <br><b>Example:</b>
* <pre>
* [Java]
* <b> CertificateImageGetRequest certificateImageGetRequest = new CertificateImageGetRequest();</b>
*
* certificateImageGetRequest.setAvaCertId ("CBT3");
* certificateImageGetRequest.setCompanyCode ("Default");
* certificateImageGetRequest.setFormat(FormatType.PNG);
* certificateImageGetRequest.setPageNumber(1);
* CertificateImageGetResult certificateImageGetResult = null;
* try {
* certificateImageGetResult = port.certificateImageGet(certificateImageGetRequest);
* } catch (RemoteException e) {
* e.printStackTrace();
* }
* </pre>
* @author Nitin Shirsat
* Copyright (c) 2011, Avalara. All rights reserved.
*/
public class CertificateImageGetRequest implements java.io.Serializable {
/**
* Field Contains Company Code value
*/
private java.lang.String companyCode;
/**
* Fields Contains AvaCertId
*/
private java.lang.String avaCertId;
/**
* Format
*/
private FormatType format;
/**
* Field comntains page number
*/
private int pageNumber;
/**
* Initializes the onject of CertificateImageGetRequest class with default values
*/
public CertificateImageGetRequest() {
this.format=FormatType.NULL;
}
/**
* * Initializes the onject of CertificateImageGetRequest class with parameterised values
* @param companyCode
* @param avaCertId
* @param format
* @param pageNumber
*/
public CertificateImageGetRequest(
java.lang.String companyCode,
java.lang.String avaCertId,
FormatType format,
int pageNumber) {
this.companyCode = companyCode;
this.avaCertId = avaCertId;
this.format = format;
this.pageNumber = pageNumber;
}
/**
* Gets the companyCode value for this CertificateImageGetRequest.
*
* @return companyCode
*/
public java.lang.String getCompanyCode() {
return companyCode;
}
/**
* Sets the companyCode value for this CertificateImageGetRequest.
*
* @param companyCode
*/
public void setCompanyCode(java.lang.String companyCode) {
this.companyCode = companyCode;
}
/**
* Gets the avaCertId value for this CertificateImageGetRequest.
*
* @return avaCertId
*/
public java.lang.String getAvaCertId() {
return avaCertId;
}
/**
* Sets the avaCertId value for this CertificateImageGetRequest.
*
* @param avaCertId
*/
public void setAvaCertId(java.lang.String avaCertId) {
this.avaCertId = avaCertId;
}
/**
* Gets the format value for this CertificateImageGetRequest.
*
* @return format
*/
public FormatType getFormat() {
return format;
}
/**
* Sets the format value for this CertificateImageGetRequest.
*
* @param format
*/
public void setFormat(FormatType format) {
this.format = format;
}
/**
* Gets the pageNumber value for this CertificateImageGetRequest.
*
* @return pageNumber
*/
public int getPageNumber() {
return pageNumber;
}
/**
* Sets the pageNumber value for this CertificateImageGetRequest.
*
* @param pageNumber
*/
public void setPageNumber(int pageNumber) {
this.pageNumber = pageNumber;
}
private java.lang.Object __equalsCalc = null;
/**
* Determines whether the specified Object is equal to the current Object.
* Note: In current implementation all Java Strings members of the two
* objects must be exactly alike, including in case, for equal to return true.
* @param obj
* @return true or false, indicating if the two objects are equal.
*/
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof CertificateImageGetRequest)) return false;
CertificateImageGetRequest other = (CertificateImageGetRequest) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.companyCode==null && other.getCompanyCode()==null) ||
(this.companyCode!=null &&
this.companyCode.equals(other.getCompanyCode()))) &&
((this.avaCertId==null && other.getAvaCertId()==null) ||
(this.avaCertId!=null &&
this.avaCertId.equals(other.getAvaCertId()))) &&
((this.format==null && other.getFormat()==null) ||
(this.format!=null &&
this.format.equals(other.getFormat()))) &&
this.pageNumber == other.getPageNumber();
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
/**
* Serves as a hash function for a particular type,
* suitable for use in hashing algorithms and data
* structures like a hash table.
* @return hash code for this CertificateImageGetRequest object
* @see java.lang.Object#hashCode
*/
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getCompanyCode() != null) {
_hashCode += getCompanyCode().hashCode();
}
if (getAvaCertId() != null) {
_hashCode += getAvaCertId().hashCode();
}
if (getFormat() != null) {
_hashCode += getFormat().hashCode();
}
_hashCode += getPageNumber();
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(CertificateImageGetRequest.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "CertificateImageGetRequest"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("companyCode");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "CompanyCode"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("avaCertId");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "AvaCertId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("format");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "Format"));
elemField.setXmlType(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "FormatType"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("pageNumber");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "PageNumber"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
|
package com.sunli.decembermultiple.loginorenroll;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.sunli.decembermultiple.R;
import com.sunli.decembermultiple.loginorenroll.bean.EnRollBean;
import com.sunli.decembermultiple.shell_frame.mvp.presenter.IPresenterImpl;
import com.sunli.decembermultiple.shell_frame.mvp.view.IView;
import com.sunli.decembermultiple.shell_frame.network.ApiUtils;
import com.sunli.decembermultiple.shell_frame.network.Constants;
import java.util.HashMap;
import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
public class RegisterActivity extends AppCompatActivity implements IView {
@BindView(R.id.activity_register_edit_phone_number)
EditText edit_number;
@BindView(R.id.activity_register_edit_pwd)
EditText edit_pwd;
@BindView(R.id.activity_register_edit_validatecode)
EditText edit_validatecode;
@BindView(R.id.activity_register_text_send_validatecode)
TextView text_send_validate_code;
private Unbinder bind;
private IPresenterImpl iPresenter;
private int i = 60;
private Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
if(msg.what == 0){
if(i == 0){
text_send_validate_code.setText("发送验证码");
text_send_validate_code.setTextColor(Color.WHITE);
}else{
i--;
text_send_validate_code.setText(i+"s秒后重试");
handler.sendEmptyMessageDelayed(0, 1000);
}
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
iPresenter = new IPresenterImpl(this);
bind = ButterKnife.bind(this);
}
@OnClick(R.id.activity_register_text_login)
public void textLoginClick(){
startActivity(new Intent(RegisterActivity.this, MainActivity.class));
}
@OnClick(R.id.activity_register_btn_enroll)
public void btnEnrollClick(){
Map<String, String> params = new HashMap<>();
params.put(Constants.POST_BODY_KEY_REGISTER_PHONE, edit_number.getText().toString());
params.put(Constants.POST_BODY_KEY_REGISTER_PASSWORD, edit_pwd.getText().toString());
iPresenter.startRequestPost(ApiUtils.POST_URL_USER_REGISTER, params, EnRollBean.class);
}
@OnClick(R.id.activity_register_text_send_validatecode)
public void textSendValidateCode(){
handler.sendEmptyMessageDelayed(0, 1000);
if (i == 0) {
handler.sendEmptyMessageDelayed(0, 1000);
}
}
@Override
public void showResponseData(Object data) {
EnRollBean bean = (EnRollBean) data;
Toast.makeText(RegisterActivity.this, bean.getMessage(), Toast.LENGTH_SHORT).show();
startActivity(new Intent(RegisterActivity.this, MainActivity.class));
}
@Override
public void showResponseFail(String e) {
}
@Override
protected void onPause() {
super.onPause();
handler.removeCallbacksAndMessages(null);
}
@Override
protected void onDestroy() {
super.onDestroy();
bind.unbind();
}
}
|
package com.tencent.mm.plugin.fav.ui.detail;
import android.app.Dialog;
class FavoriteSightDetailUI$7 implements Runnable {
final /* synthetic */ Dialog iYD;
final /* synthetic */ FavoriteSightDetailUI jdp;
FavoriteSightDetailUI$7(FavoriteSightDetailUI favoriteSightDetailUI, Dialog dialog) {
this.jdp = favoriteSightDetailUI;
this.iYD = dialog;
}
public final void run() {
this.iYD.dismiss();
}
}
|
package seveida.firetvforreddit.domain.objects;
import java.util.List;
import androidx.annotation.NonNull;
public class ThreadDetails {
@NonNull public final ThreadMetadata threadMetadata;
@NonNull public final String content;
@NonNull public final List<Comment> topLevelComments;
public ThreadDetails(@NonNull ThreadMetadata threadMetadata,
@NonNull String content, @NonNull List<Comment> topLevelComments) {
this.threadMetadata = threadMetadata;
this.content = content;
this.topLevelComments = topLevelComments;
}
}
|
package com.rc.utils;
import java.util.HashMap;
import java.util.Map;
/**
* Created by song on 05/04/2017.
*/
public class MimeTypeUtil
{
public static Map<String, String> MimeMap;
static
{
MimeMap = new HashMap<>();
MimeMap.put(".3gp", "video/3gpp");
MimeMap.put(".apk", "application/vnd.android.package-archive");
MimeMap.put(".asf", "video/x-ms-asf");
MimeMap.put(".avi", "video/x-msvideo");
MimeMap.put(".bin", "application/octet-stream");
MimeMap.put(".bmp", "image/bmp");
MimeMap.put(".c", "text/plain");
MimeMap.put(".class", "application/octet-stream");
MimeMap.put(".conf", "text/plain");
MimeMap.put(".cpp", "text/plain");
MimeMap.put(".doc", "application/msword");
MimeMap.put(".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
MimeMap.put(".xls", "application/vnd.ms-excel");
MimeMap.put(".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
MimeMap.put(".exe", "application/octet-stream");
MimeMap.put(".gif", "image/gif");
MimeMap.put(".gtar", "application/x-gtar");
MimeMap.put(".gz", "application/x-gzip");
MimeMap.put(".h", "text/plain");
MimeMap.put(".htm", "text/html");
MimeMap.put(".html", "text/html");
MimeMap.put(".jar", "application/java-archive");
MimeMap.put(".java", "text/plain");
MimeMap.put(".jpeg", "image/jpeg");
MimeMap.put(".jpg", "image/jpeg");
MimeMap.put(".js", "application/x-javascript");
MimeMap.put(".log", "text/plain");
MimeMap.put(".m3u", "audio/x-mpegurl");
MimeMap.put(".m4a", "audio/mp4a-latm");
MimeMap.put(".m4b", "audio/mp4a-latm");
MimeMap.put(".m4p", "audio/mp4a-latm");
MimeMap.put(".m4u", "video/vnd.mpegurl");
MimeMap.put(".m4v", "video/x-m4v");
MimeMap.put(".mov", "video/quicktime");
MimeMap.put(".mp2", "audio/x-mpeg");
MimeMap.put(".mp3", "audio/x-mpeg");
MimeMap.put(".mp4", "video/mp4");
MimeMap.put(".mpc", "application/vnd.mpohun.certificate");
MimeMap.put(".mpe", "video/mpeg");
MimeMap.put(".mpeg", "video/mpeg");
MimeMap.put(".mpg", "video/mpeg");
MimeMap.put(".mpg4", "video/mp4");
MimeMap.put(".mpga", "audio/mpeg");
MimeMap.put(".msg", "application/vnd.ms-outlook");
MimeMap.put(".ogg", "audio/ogg");
MimeMap.put(".pdf", "application/pdf");
MimeMap.put(".png", "image/png");
MimeMap.put(".pps", "application/vnd.ms-powerpoint");
MimeMap.put(".ppt", "application/vnd.ms-powerpoint");
MimeMap.put(".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation");
MimeMap.put(".prop", "text/plain");
MimeMap.put(".rc", "text/plain");
MimeMap.put(".rmvb", "audio/x-pn-realaudio");
MimeMap.put(".rtf", "application/rtf");
MimeMap.put(".sh", "text/plain");
MimeMap.put(".tar", "application/x-tar");
MimeMap.put(".tgz", "application/x-compressed");
MimeMap.put(".txt", "text/plain");
MimeMap.put(".wav", "audio/x-wav");
MimeMap.put(".wma", "audio/x-ms-wma");
MimeMap.put(".wmv", "audio/x-ms-wmv");
MimeMap.put(".wps", "application/vnd.ms-works");
MimeMap.put(".xml", "text/plain");
MimeMap.put(".z", "application/x-compress");
MimeMap.put(".rar", "application/x-compress");
MimeMap.put(".7z", "application/x-compress");
MimeMap.put(".zip", "application/x-zip-compressed");
// MimeMap.put("", "*/*");
}
public static String getMime(String suffix)
{
if (!suffix.startsWith("."))
{
suffix = "." + suffix;
}
return MimeMap.get(suffix);
}
}
|
class Solution {
Set<Integer> set = new HashSet<>();
Map<Integer , Integer> map = new HashMap<>();
int helper(int prev , int count) {
if (count == 0)
return 1;
int res = 0;
for (int i : map.keySet()) {
if (map.get(i) > 0 && set.contains(prev + i)) {
map.put(i , map.get(i) - 1);
res += helper(i , count - 1);
map.put(i , map.get(i) + 1);
}
}
return res;
}
public int numSquarefulPerms(int[] A) {
for (int i = 0 ; i * i <= 2000000000 ; i++)
set.add(i * i);
for (int i = 0 ; i < A.length ; i++) {
if (map.containsKey(A[i]))
map.put(A[i] , map.get(A[i]) + 1);
else
map.put(A[i] , 1);
}
int res = 0;
for (int i : map.keySet()) {
map.put(i , map.get(i) - 1);
res += helper(i , A.length - 1);
map.put(i , map.get(i) + 1);
}
return res;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.