text
stringlengths 10
2.72M
|
|---|
package com.citisense.vidklopcic.e_smart;
/**
* Created by vidklopcic on 05/08/16.
*/
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.github.lzyzsd.circleprogress.ArcProgress;
/**
* A placeholder fragment containing a simple view.
*/
public class DashboardFragment extends Fragment {
private DataProvider mDataProvider;
private ArcProgress mCurentProgress;
private ArcProgress mBMSTempProgress;
private ArcProgress mCellTempProgress;
private ArcProgress mSOCProgress;
private TextView mWhText;
private TextView mCellMaxText;
private TextView mCellMinText;
private TextView mVoltageText;
private RelativeLayout mWhLayout;
public DashboardFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static DashboardFragment newInstance(DataProvider dp) {
DashboardFragment fragment = new DashboardFragment();
fragment.setDataProvider(dp);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_dashboard, container, false);
mCurentProgress = (ArcProgress) rootView.findViewById(R.id.current_arc);
mBMSTempProgress = (ArcProgress) rootView.findViewById(R.id.temp_bms_arc);
mCellTempProgress = (ArcProgress) rootView.findViewById(R.id.temp_cell_arc);
mSOCProgress = (ArcProgress) rootView.findViewById(R.id.soc_arc);
mWhText = (TextView) rootView.findViewById(R.id.wh_val_text);
mCellMaxText = (TextView) rootView.findViewById(R.id.cell_max_value);
mCellMinText = (TextView) rootView.findViewById(R.id.cell_min_value);
mVoltageText = (TextView) rootView.findViewById(R.id.voltage_value);
mWhLayout = (RelativeLayout) rootView.findViewById(R.id.wh_layout);
initOnClickListeners();
return rootView;
}
private void initOnClickListeners() {
mWhLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
mDataProvider.setWh(0d);
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Are you sure?").setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
}
});
}
@Override
public void onPause() {
super.onPause();
}
@Override
public void onResume() {
super.onResume();
}
public void setDataProvider(DataProvider dp) {
mDataProvider = dp;
}
public void dataUpdated() {
mCurentProgress.setProgress(mDataProvider.getCurent());
if (mDataProvider.getCurent() < 0) {
mCurentProgress.setFinishedStrokeColor(ContextCompat.getColor(getActivity(), R.color.material_green));
} else {
mCurentProgress.setFinishedStrokeColor(ContextCompat.getColor(getActivity(), R.color.accent_blue));
}
mSOCProgress.setProgress(mDataProvider.getSOC());
mBMSTempProgress.setProgress(mDataProvider.getBMSTemp());
mCellTempProgress.setProgress(mDataProvider.getCellTemp());
mWhText.setText(String.format("%.1f", mDataProvider.getWh()/1000.0));
mCellMaxText.setText(mDataProvider.getCellMax().toString());
mCellMinText.setText(mDataProvider.getCellMin().toString());
mVoltageText.setText(mDataProvider.getVoltage().toString());
}
}
|
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.Color;
/**
* Write a description of class DeathScreen here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class DeathScreen extends ScreenWorld
{
/**
* Constructor for objects of class DeathScreen.
*
*/
public DeathScreen(World next)
{
super("images/pause.png", next);
addObject(new LevelText("press any key to continue", 14, Color.BLACK, Color.WHITE, null), getWidth()/2, getHeight() - 20);
}
}
|
//Author: Timothy van der Graaff
package controllers;
import java.sql.Connection;
import java.sql.SQLException;
import utilities.Form_Validation;
import views.Show_For_Sale_Item_Details;
public class Control_Search_For_Sale_Item_Details extends models.Search_For_Sale_Item_Details {
//global variables
public static Connection use_connection;
public static String item_id;
public static String results_per_page;
public static String page_number;
public static String sort_by;
public static String control_search_for_sale_item_details() {
String output;
connection = use_connection;
set_item_id(item_id);
Show_For_Sale_Item_Details.for_sale_item_details = search_sale_item_details();
output = Show_For_Sale_Item_Details.show_for_sale_item_details();
return output;
}
public static String control_search_for_sale_item_additional_pictures() {
String output;
connection = use_connection;
set_item_id(item_id);
Show_For_Sale_Item_Details.for_sale_item_additional_pictures = search_sale_item_additional_pictures();
output = Show_For_Sale_Item_Details.show_for_sale_item_additional_pictures();
return output;
}
public static String control_search_for_sale_item_reviews() {
String output;
connection = use_connection;
if (Form_Validation.is_string_null_or_white_space(results_per_page) || results_per_page.equals("null")) {
results_per_page = "10";
}
if (!(results_per_page.equals("10")) && !(results_per_page.equals("20"))
&& !(results_per_page.equals("30")) && !(results_per_page.equals("40"))
&& !(results_per_page.equals("50"))) {
results_per_page = "10";
}
if (Form_Validation.is_string_null_or_white_space(page_number) || page_number.equals("null")) {
page_number = "1";
}
set_item_id(item_id);
set_results_per_page(results_per_page);
set_page_number(page_number);
switch (sort_by) {
case "Oldest":
Show_For_Sale_Item_Details.for_sale_item_reviews = search_sale_item_reviews_oldest_first();
break;
case "Highest rating":
Show_For_Sale_Item_Details.for_sale_item_reviews = search_sale_item_reviews_highest_rating_first();
break;
case "Lowest rating":
Show_For_Sale_Item_Details.for_sale_item_reviews = search_sale_item_reviews_lowest_rating_first();
break;
default:
Show_For_Sale_Item_Details.for_sale_item_reviews = search_sale_item_reviews_newest_first();
break;
}
output = Show_For_Sale_Item_Details.show_for_sale_item_reviews();
return output;
}
public static String control_calculate_page_number_count() {
String output;
connection = use_connection;
if ((Form_Validation.is_string_null_or_white_space(results_per_page) || results_per_page.equals("null"))) {
results_per_page = "10";
}
if (!(results_per_page.equals("10")) && !(results_per_page.equals("20"))
&& !(results_per_page.equals("30")) && !(results_per_page.equals("40"))
&& !(results_per_page.equals("50"))) {
results_per_page = "10";
}
set_item_id(item_id);
set_results_per_page(results_per_page);
Show_For_Sale_Item_Details.page_number_count = calculate_page_number_count(search_for_sale_item_reviews_count());
output = Show_For_Sale_Item_Details.show_page_numbers();
try {
use_connection.close();
} catch (SQLException e) {
}
return output;
}
}
|
package com.designPattern.behavioral.chainOfResponsibility;
public class Dollar20Dispenser implements DispenseChain {
private DispenseChain chain;
@Override
public void next(DispenseChain chain) {
this.chain = chain;
}
@Override
public void dispense(Currency currency) {
if(currency.getAmount() >= 20) {
int number = currency.getAmount() / 20;
int reminder = currency.getAmount() % 20;
System.out.println("Dispensing "+number+" of 20 Note.");
if(reminder != 0)
chain.dispense(new Currency(reminder));
} else {
chain.dispense(currency);
}
}
}
|
package pe.gob.trabajo.web.rest;
import com.codahale.metrics.annotation.Timed;
import pe.gob.trabajo.domain.Tipcalperi;
import pe.gob.trabajo.repository.TipcalperiRepository;
import pe.gob.trabajo.repository.search.TipcalperiSearchRepository;
import pe.gob.trabajo.web.rest.util.HeaderUtil;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import static org.elasticsearch.index.query.QueryBuilders.*;
/**
* REST controller for managing Tipcalperi.
*/
@RestController
@RequestMapping("/api")
public class TipcalperiResource {
private final Logger log = LoggerFactory.getLogger(TipcalperiResource.class);
private static final String ENTITY_NAME = "tipcalperi";
private final TipcalperiRepository tipcalperiRepository;
private final TipcalperiSearchRepository tipcalperiSearchRepository;
public TipcalperiResource(TipcalperiRepository tipcalperiRepository, TipcalperiSearchRepository tipcalperiSearchRepository) {
this.tipcalperiRepository = tipcalperiRepository;
this.tipcalperiSearchRepository = tipcalperiSearchRepository;
}
/**
* POST /tipcalperis : Create a new tipcalperi.
*
* @param tipcalperi the tipcalperi to create
* @return the ResponseEntity with status 201 (Created) and with body the new tipcalperi, or with status 400 (Bad Request) if the tipcalperi has already an ID
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@PostMapping("/tipcalperis")
@Timed
public ResponseEntity<Tipcalperi> createTipcalperi(@Valid @RequestBody Tipcalperi tipcalperi) throws URISyntaxException {
log.debug("REST request to save Tipcalperi : {}", tipcalperi);
if (tipcalperi.getId() != null) {
return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new tipcalperi cannot already have an ID")).body(null);
}
Tipcalperi result = tipcalperiRepository.save(tipcalperi);
tipcalperiSearchRepository.save(result);
return ResponseEntity.created(new URI("/api/tipcalperis/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
.body(result);
}
/**
* PUT /tipcalperis : Updates an existing tipcalperi.
*
* @param tipcalperi the tipcalperi to update
* @return the ResponseEntity with status 200 (OK) and with body the updated tipcalperi,
* or with status 400 (Bad Request) if the tipcalperi is not valid,
* or with status 500 (Internal Server Error) if the tipcalperi couldn't be updated
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@PutMapping("/tipcalperis")
@Timed
public ResponseEntity<Tipcalperi> updateTipcalperi(@Valid @RequestBody Tipcalperi tipcalperi) throws URISyntaxException {
log.debug("REST request to update Tipcalperi : {}", tipcalperi);
if (tipcalperi.getId() == null) {
return createTipcalperi(tipcalperi);
}
Tipcalperi result = tipcalperiRepository.save(tipcalperi);
tipcalperiSearchRepository.save(result);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, tipcalperi.getId().toString()))
.body(result);
}
/**
* GET /tipcalperis : get all the tipcalperis.
*
* @return the ResponseEntity with status 200 (OK) and the list of tipcalperis in body
*/
@GetMapping("/tipcalperis")
@Timed
public List<Tipcalperi> getAllTipcalperis() {
log.debug("REST request to get all Tipcalperis");
return tipcalperiRepository.findAll();
}
/**
* GET /tipcalperis/:id : get the "id" tipcalperi.
*
* @param id the id of the tipcalperi to retrieve
* @return the ResponseEntity with status 200 (OK) and with body the tipcalperi, or with status 404 (Not Found)
*/
@GetMapping("/tipcalperis/{id}")
@Timed
public ResponseEntity<Tipcalperi> getTipcalperi(@PathVariable Long id) {
log.debug("REST request to get Tipcalperi : {}", id);
Tipcalperi tipcalperi = tipcalperiRepository.findOne(id);
return ResponseUtil.wrapOrNotFound(Optional.ofNullable(tipcalperi));
}
/** JH
* GET /tipcalperis/activos : get all the tipcalperis.
*
* @return the ResponseEntity with status 200 (OK) and the list of tipcalperis in body
*/
@GetMapping("/tipcalperis/activos")
@Timed
public List<Tipcalperi> getAll_Activos() {
log.debug("REST request to get all tipcalperis");
return tipcalperiRepository.findAll_Activos();
}
/**
* DELETE /tipcalperis/:id : delete the "id" tipcalperi.
*
* @param id the id of the tipcalperi to delete
* @return the ResponseEntity with status 200 (OK)
*/
@DeleteMapping("/tipcalperis/{id}")
@Timed
public ResponseEntity<Void> deleteTipcalperi(@PathVariable Long id) {
log.debug("REST request to delete Tipcalperi : {}", id);
tipcalperiRepository.delete(id);
tipcalperiSearchRepository.delete(id);
return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
}
/**
* SEARCH /_search/tipcalperis?query=:query : search for the tipcalperi corresponding
* to the query.
*
* @param query the query of the tipcalperi search
* @return the result of the search
*/
@GetMapping("/_search/tipcalperis")
@Timed
public List<Tipcalperi> searchTipcalperis(@RequestParam String query) {
log.debug("REST request to search Tipcalperis for query {}", query);
return StreamSupport
.stream(tipcalperiSearchRepository.search(queryStringQuery(query)).spliterator(), false)
.collect(Collectors.toList());
}
}
|
package com.spbsu.flamestream.runtime;
import akka.actor.ActorPath;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.japi.pf.ReceiveBuilder;
import akka.pattern.PatternsCS;
import com.spbsu.flamestream.core.Graph;
import com.spbsu.flamestream.core.graph.FlameMap;
import com.spbsu.flamestream.core.graph.HashGroup;
import com.spbsu.flamestream.runtime.config.ClusterConfig;
import com.spbsu.flamestream.runtime.config.ComputationProps;
import com.spbsu.flamestream.runtime.config.SystemConfig;
import com.spbsu.flamestream.runtime.config.ZookeeperWorkersNode;
import com.spbsu.flamestream.runtime.edge.api.AttachFront;
import com.spbsu.flamestream.runtime.edge.api.AttachRear;
import com.spbsu.flamestream.runtime.master.acker.Acker;
import com.spbsu.flamestream.runtime.master.acker.Committer;
import com.spbsu.flamestream.runtime.master.acker.MinTimeUpdater;
import com.spbsu.flamestream.runtime.master.acker.RegistryHolder;
import com.spbsu.flamestream.runtime.master.acker.ZkRegistry;
import com.spbsu.flamestream.runtime.serialization.FlameSerializer;
import com.spbsu.flamestream.runtime.state.StateStorage;
import com.spbsu.flamestream.runtime.utils.FlameConfig;
import com.spbsu.flamestream.runtime.utils.akka.AwaitResolver;
import com.spbsu.flamestream.runtime.utils.akka.LoggingActor;
import org.apache.commons.lang.StringUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.api.CuratorWatcher;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.data.Stat;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ProcessingWatcher extends LoggingActor {
private final String id;
private final CuratorFramework curator;
private final ZookeeperWorkersNode zookeeperWorkersNode;
private final SystemConfig systemConfig;
private final StateStorage stateStorage;
private final FlameSerializer serializer;
private NodeCache graphCache = null;
private PathChildrenCache frontsCache = null;
private PathChildrenCache rearsCache = null;
private ActorRef flameNode = null;
private Graph graph = null;
public ProcessingWatcher(String id,
CuratorFramework curator,
ZookeeperWorkersNode zookeeperWorkersNode,
SystemConfig systemConfig,
StateStorage stateStorage,
FlameSerializer serializer
) {
this.id = id;
this.curator = curator;
this.zookeeperWorkersNode = zookeeperWorkersNode;
this.systemConfig = systemConfig;
this.stateStorage = stateStorage;
this.serializer = serializer;
}
public static Props props(String id,
CuratorFramework curator,
ZookeeperWorkersNode zookeeperWorkersNode,
SystemConfig systemConfig,
StateStorage stateStorage,
FlameSerializer serializer
) {
return Props.create(
ProcessingWatcher.class,
id,
curator,
zookeeperWorkersNode,
systemConfig,
stateStorage,
serializer
);
}
@Override
public void preStart() throws Exception {
super.preStart();
graphCache = new NodeCache(curator, "/graph");
graphCache.getListenable().addListener(() -> {
final Graph graph = serializer.deserialize(graphCache.getCurrentData().getData(), Graph.class);
self().tell(graph, self());
});
graphCache.start();
final Stat stat = curator.checkExists().usingWatcher((CuratorWatcher) watchedEvent -> {
if (watchedEvent.getType() == Watcher.Event.EventType.NodeCreated) {
startEdgeCaches();
}
}).forPath("/graph");
if (stat != null) {
startEdgeCaches();
}
}
@Override
public void postStop() {
//noinspection EmptyTryBlock,unused
try (
NodeCache gc = graphCache;
PathChildrenCache fc = frontsCache;
PathChildrenCache rc = rearsCache
) {
} catch (IOException e) {
e.printStackTrace();
}
super.postStop();
}
@Override
public Receive createReceive() {
return ReceiveBuilder.create()
.match(Graph.class, this::onGraph)
.matchAny(o -> stash())
.build();
}
private Receive running() {
return ReceiveBuilder.create()
.match(AttachFront.class, attachFront -> flameNode.tell(attachFront, self()))
.match(AttachRear.class, attachRear -> flameNode.tell(attachRear, self()))
.build();
}
private void onGraph(Graph graph) {
if (this.graph != null) {
throw new RuntimeException("Graph updating is not supported yet");
}
final ClusterConfig config = ClusterConfig.fromWorkers(zookeeperWorkersNode.workers());
final List<String> workerIds =
zookeeperWorkersNode.workers().stream().map(ZookeeperWorkersNode.Worker::id).collect(Collectors.toList());
final Map<String, HashGroup> ranges = systemConfig.workersResourcesDistributor.hashGroups(workerIds);
try {
PatternsCS.ask(context().actorOf(InitAgent.props(ranges.get(id))), graph, FlameConfig.config.bigTimeout())
.toCompletableFuture()
.get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
this.graph = graph;
final List<String> ackerIds = systemConfig.workersResourcesDistributor.ackers(workerIds);
if (ackerIds.contains(id)) {
context().actorOf(Acker.props(systemConfig.defaultMinimalTime(), ackerIds.size() < 2, graph), "acker");
}
final List<ActorRef> ackers = ackers(config);
final @Nullable ActorRef localAcker = ackers.isEmpty() ? null
: context().actorOf(systemConfig.localAckerProps(ackers, id));
final ActorRef committer, registryHolder;
if (zookeeperWorkersNode.isLeader(id)) {
registryHolder = context().actorOf(
RegistryHolder.props(new ZkRegistry(curator), ackers, systemConfig.defaultMinimalTime()),
"registry-holder"
);
committer = context().actorOf(Committer.props(
config.paths().size(),
systemConfig,
registryHolder,
new MinTimeUpdater(ackers, systemConfig.defaultMinimalTime()),
graph.sinkTrackingComponent().index
), "committer");
} else {
final ActorPath masterPath = config.paths().get(config.masterLocation()).child("processing-watcher");
registryHolder = AwaitResolver.syncResolve(masterPath.child("registry-holder"), context());
committer = AwaitResolver.syncResolve(masterPath.child("committer"), context());
}
this.flameNode = context().actorOf(
FlameNode.props(
id,
graph,
config.withChildPath("processing-watcher").withChildPath("graph"),
localAcker,
registryHolder,
committer,
new ComputationProps(
new HashMap<>(ranges),
systemConfig.maxElementsInGraph(),
systemConfig.barrierIsDisabled(),
systemConfig.defaultMinimalTime()
),
stateStorage
),
"graph"
);
unstashAll();
getContext().become(running());
}
private void startEdgeCaches() throws Exception {
rearsCache = new PathChildrenCache(curator, "/graph/rears", false);
rearsCache.getListenable().addListener((client, event) -> {
if (event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED) {
final FlameRuntime.RearInstance<?> rear = serializer.deserialize(
curator.getData().forPath(event.getData().getPath()),
FlameRuntime.RearInstance.class
);
self().tell(
new AttachRear<>(StringUtils.substringAfterLast(event.getData().getPath(), "/"), rear),
self()
);
}
});
rearsCache.start();
frontsCache = new PathChildrenCache(curator, "/graph/fronts", false);
frontsCache.getListenable().addListener((client, event) -> {
if (event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED) {
final FlameRuntime.FrontInstance<?> front = serializer.deserialize(
curator.getData().forPath(event.getData().getPath()),
FlameRuntime.FrontInstance.class
);
self().tell(
new AttachFront<>(StringUtils.substringAfterLast(event.getData().getPath(), "/"), front),
self()
);
}
});
frontsCache.start();
}
private static class InitAgent extends LoggingActor {
final HashGroup hashGroup;
private InitAgent(HashGroup hashGroup) {this.hashGroup = hashGroup;}
@Override
public Receive createReceive() {
return ReceiveBuilder.create()
.match(Graph.class, graph -> {
graph.init(hashGroup);
graph.components().forEach(vertexStream -> vertexStream.forEach(vertex -> {
if (vertex instanceof FlameMap) {
((FlameMap) vertex).init(hashGroup);
}
}));
sender().tell(InitDone.OBJECT, self());
context().stop(self());
})
.build();
}
public static Props props(HashGroup hashGroup) {
return Props.create(InitAgent.class, hashGroup);
}
}
private enum InitDone {
OBJECT
}
private List<ActorRef> ackers(ClusterConfig config) {
final Stream<ActorPath> paths =
systemConfig.workersResourcesDistributor.ackers(new ArrayList<>(config.paths().keySet()))
.stream().map(config.paths()::get);
final List<CompletableFuture<ActorRef>> ackerFutures = paths
.map(actorPath -> AwaitResolver.resolve(actorPath.child("processing-watcher").child("acker"), context())
.toCompletableFuture())
.collect(Collectors.toList());
ackerFutures.forEach(CompletableFuture::join);
return ackerFutures.stream().map(future -> {
try {
return future.get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}).collect(Collectors.toList());
}
}
|
package ru.otus.db.dao.jpa;
/*
* Created by VSkurikhin at winter 2018.
*/
import ru.otus.exeptions.ExceptionThrowable;
import ru.otus.models.DeptEntity;
import javax.persistence.EntityManager;
import java.util.List;
public class DeptController extends AbstractController <DeptEntity, Long>
{
public DeptController(EntityManager entityManager)
{
super(entityManager);
}
@Override
public List<DeptEntity> getAll() throws ExceptionThrowable
{
return getAll(DeptEntity.class);
}
@Override
public DeptEntity getEntityById(Long id) throws ExceptionThrowable
{
return getEntityViaClassById(id, DeptEntity.class);
}
public DeptEntity getEntityByTitle(String title) throws ExceptionThrowable
{
return getEntityViaClassByName("title", title, DeptEntity.class);
}
@Override
public DeptEntity update(DeptEntity entity) throws ExceptionThrowable
{
return mergeEntity(entity);
}
@Override
public boolean delete(Long id) throws ExceptionThrowable
{
return deleteEntityViaClassById(id, DeptEntity.class);
}
@Override
public boolean create(DeptEntity entity) throws ExceptionThrowable
{
return persistEntity(entity);
}
}
/* vim: syntax=java:fileencoding=utf-8:fileformat=unix:tw=78:ts=4:sw=4:sts=4:et
*/
//EOF
|
package com.onesignal.influence;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.onesignal.OSLogger;
import com.onesignal.OSSharedPreferences;
import com.onesignal.OneSignal;
import com.onesignal.OneSignalRemoteParams;
import com.onesignal.influence.model.OSInfluence;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
public class OSTrackerFactory {
private ConcurrentHashMap<String, OSChannelTracker> trackers = new ConcurrentHashMap<>();
private OSInfluenceDataRepository dataRepository;
public OSTrackerFactory(OSSharedPreferences preferences, OSLogger logger) {
dataRepository = new OSInfluenceDataRepository(preferences);
trackers.put(OSInAppMessageTracker.TAG, new OSInAppMessageTracker(dataRepository, logger));
trackers.put(OSNotificationTracker.TAG, new OSNotificationTracker(dataRepository, logger));
}
public void saveInfluenceParams(OneSignalRemoteParams.InfluenceParams influenceParams) {
dataRepository.saveInfluenceParams(influenceParams);
}
public void addSessionData(@NonNull JSONObject jsonObject, List<OSInfluence> influences) {
for (OSInfluence influence : influences) {
switch (influence.getInfluenceChannel()) {
case NOTIFICATION:
getNotificationChannelTracker().addSessionData(jsonObject, influence);
case IAM:
// We don't track IAM session data for on_focus call
}
}
}
public void initFromCache() {
for (OSChannelTracker tracker : trackers.values()) {
tracker.initInfluencedTypeFromCache();
}
}
public List<OSInfluence> getInfluences() {
List<OSInfluence> influences = new ArrayList<>();
for (OSChannelTracker tracker : trackers.values()) {
influences.add(tracker.getCurrentSessionInfluence());
}
return influences;
}
public OSChannelTracker getIAMChannelTracker() {
return trackers.get(OSInAppMessageTracker.TAG);
}
public OSChannelTracker getNotificationChannelTracker() {
return trackers.get(OSNotificationTracker.TAG);
}
@Nullable
public OSChannelTracker getChannelByEntryAction(OneSignal.AppEntryAction entryAction) {
if (entryAction.isNotificationClick())
return getNotificationChannelTracker();
return null;
}
public List<OSChannelTracker> getChannels() {
List<OSChannelTracker> channels = new ArrayList<>();
OSChannelTracker notificationChannel = getNotificationChannelTracker();
if (notificationChannel != null)
channels.add(notificationChannel);
OSChannelTracker iamChannel = getIAMChannelTracker();
if (iamChannel != null)
channels.add(iamChannel);
return channels;
}
public List<OSChannelTracker> getChannelsToResetByEntryAction(OneSignal.AppEntryAction entryAction) {
List<OSChannelTracker> channels = new ArrayList<>();
// Avoid reset session if application is closed
if (entryAction.isAppClose())
return channels;
// Avoid reset session if app was focused due to a notification click (direct session recently set)
if (entryAction.isAppOpen()) {
OSChannelTracker notificationChannel = getNotificationChannelTracker();
if (notificationChannel != null)
channels.add(notificationChannel);
}
OSChannelTracker iamChannel = getIAMChannelTracker();
if (iamChannel != null)
channels.add(iamChannel);
return channels;
}
}
|
package com.saaolheart.mumbai.store.stock;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.saaolheart.mumbai.customer.CustomerDetail;
@Repository
public interface StockRepo extends JpaRepository<StockDomain,Long> {
public List<StockDomain> findAllByOrderByAddedOnDesc();
Optional<List<StockDomain>> findByStockNameContaining(String name);
public Optional<List<StockDomain>> findByQtyOfStockAvailableGreaterThanEqual(Long limit);
public Optional<List<StockDomain>> findByStockNameIgnoreCaseLike(String searchParam);
public Optional<List<StockDomain>> findByQtyOfStockAvailableLessThanEqual(Long limit);
}
|
package com.cg.project.castleglobalproject.base.constants;
/**
* Created by sam on 7/9/17.
*/
public interface Constants {
String API_HOST = "https://developers.zomato.com/api/v2.1";
String ZOMATO_AUTH_KEY = "2b7957c4fdaa2b314b7a945f0bc7247e";
}
|
/**
* Given an array of integers.
* Return an array, where the first element is the count of positives numbers and
* the second element is sum of negative numbers.
*
* If the input array is empty or null, return an empty array.
*
* Example
* For input [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15], you should return [10, -65].
*/
package oriorihuela;
public class Kata {
public static int[] countPositivesSumNegatives(int[] input) {
if (input.length == 0 || input == null) {
return input;
}
else {
int countOfPositiveOnes = 0;
int sumatoryOfNegativeOnes = 0;
for (int index = 0; index < input.length; index++) {
if (input[index] > 0) {
countOfPositiveOnes++; }
else if (input[index] < 0) {
sumatoryOfNegativeOnes += input[index]; }
}
int[] arrayToReturn = {countOfPositiveOnes, sumatoryOfNegativeOnes};
return arrayToReturn;
}
}
}
|
class ArrayStack<T> implements MyStack<T> {
private T[] array;
private int total;
public ArrayStack() {
this.array = (T[]) new Object[2];
this.total = 0;
}
@Override
public void push(T item) {
if (array.length == total) {
resize(total * 2);
}
array[total++] = item;
}
@Override
public T pop() {
T item = array[--total];
if (total > 0 && total == array.length / 4) {
resize(array.length / 2);
}
return item;
}
@Override
public boolean isEmpty() {
return total == 0;
}
private void resize(int size) {
T[] temp = (T[]) new Object[size];
for (int i = 0; i < total; i++) {
temp[i] = array[i];
}
this.array = temp;
}
public static void main(String[] args) {
MyStack<String> stack = new ArrayStack<String>();
stack.push("hello");
stack.push("world");
stack.push("yes");
while (!stack.isEmpty()) {
System.out.println(stack.pop());
}
}
}
|
package com.verbovskiy.finalproject.controller.command.impl.jump;
import com.verbovskiy.finalproject.controller.AttributeKey;
import com.verbovskiy.finalproject.controller.command.ActionCommand;
import com.verbovskiy.finalproject.controller.command.Constant;
import com.verbovskiy.finalproject.controller.command.PageType;
import com.verbovskiy.finalproject.controller.command.RequestParameter;
import com.verbovskiy.finalproject.exception.ServiceException;
import com.verbovskiy.finalproject.model.entity.UserOrder;
import com.verbovskiy.finalproject.model.service.OrderService;
import com.verbovskiy.finalproject.model.service.impl.OrderServiceImpl;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
/**
* The type admin show orders page command.
*
* @author Verbovskiy Sergei
* @version 1.0
*/
public class AdminShowOrdersPageCommand implements ActionCommand {
private final Logger logger = LogManager.getLogger(AdminShowOrdersPageCommand.class);
@Override
public String execute(HttpServletRequest request) {
HttpSession session = request.getSession();
session.setAttribute(RequestParameter.HAS_PREVIOUS_PAGE, false);
session.setAttribute(AttributeKey.IS_FIRST_PAGE, true);
OrderService service = new OrderServiceImpl();
String page = PageType.ERROR.getPath();
session.setAttribute(RequestParameter.HAS_NEXT_PAGE, true);
try {
List<UserOrder> allOrders = service.findAllOrders();
if (allOrders == null || allOrders.isEmpty()) {
request.setAttribute(RequestParameter.IS_EMPTY, true);
session.setAttribute(RequestParameter.HAS_NEXT_PAGE, false);
} else {
int toIndex = Constant.NUMBER_OF_ORDER_PER_PAGE;
if (allOrders.size() <= Constant.NUMBER_OF_ORDER_PER_PAGE) {
toIndex = allOrders.size();
session.setAttribute(RequestParameter.HAS_NEXT_PAGE, false);
}
List<UserOrder> ordersPerPage;
ordersPerPage = (allOrders.size() == 1) ? allOrders : allOrders.subList(0, toIndex);
session.setAttribute(AttributeKey.ORDER_PER_PAGE, ordersPerPage);
session.setAttribute(AttributeKey.ORDER_LIST, allOrders);
session.setAttribute(AttributeKey.TO_INDEX, toIndex);
session.setAttribute(AttributeKey.FROM_INDEX, 0);
}
page = PageType.ADMIN_SHOW_ORDER.getPath();
} catch (ServiceException e) {
logger.log(Level.ERROR, e);
}
return page;
}
}
|
package demo.li.opal.uidemo.Utils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class GsonUtils {
private static final String TAG = GsonUtils.class.getName();
private static Gson gson;
static {
gson = new GsonBuilder().create();
}
/**
* json to object
*/
public static <T> T json2Obj(Gson gson, String json, Type cls) {
T obj = null;
try {
obj = gson.fromJson(json, cls);
} catch (Exception e) {
LogUtils.e(e);
}
return obj;
}
public static <T> T json2Obj(String json, Type cls) {
T obj = null;
try {
obj = gson.fromJson(json, cls);
} catch (Exception e) {
LogUtils.e(e);
}
return obj;
}
public static <T> T json2Obj(Gson gson, String json, Class<T> clazz) {
try {
return gson.fromJson(json, clazz);
} catch (JsonSyntaxException e) {
LogUtils.e(TAG, e);
}
return null;
}
public static <T> T json2Obj(String json, Class<T> clazz) {
return json2Obj(gson, json, clazz);
}
/**
* object to json
*/
public static <T> String obj2Json(Gson gson, T obj) {
String json = null;
try {
json = gson.toJson(obj);
} catch (Exception e) {
LogUtils.e(e);
}
return json;
}
public static <T> String obj2Json(T obj) {
return obj2Json(gson, obj);
}
public static <T> String obj2Json(Gson gson, T obj, Type tTYpe) {
String json = null;
try {
json = gson.toJson(obj, tTYpe);
} catch (Exception e) {
LogUtils.e(e);
}
return json;
}
public static <T> String obj2Json(T obj, Type tTYpe) {
return obj2Json(gson, obj, tTYpe);
}
/**
* json to object list
*/
public static <T> List<T> json2ObjList(Gson gson, String jsonString, Class<T> clazz) {
List<T> list = null;
try {
JsonParser jsonParser = new JsonParser();
JsonArray jsonArray = jsonParser.parse(jsonString).getAsJsonArray();
list = new ArrayList<>();
for (int i = 0, size = jsonArray.size(); i < size; i++) {
list.add(gson.<T>fromJson(jsonArray.get(i), clazz));
}
} catch (Exception e) {
LogUtils.e(e);
}
return list;
}
public static <T> List<T> json2ObjList(String jsonString, Class<T> clazz) {
return json2ObjList(gson, jsonString, clazz);
}
/**
* object list to json
*/
public static <T> String objList2Json(Gson gson, List<T> list) {
String json = null;
try {
json = gson.toJson(list);
} catch (Exception e) {
LogUtils.e(e);
}
return json;
}
public static <T> String objList2Json(List<T> list) {
return objList2Json(gson, list);
}
// XML.toJSONObject转出来的JSON,如果一个父节点只有一个孩子节点的话,转出来的是Object,但有时期望的是array
public static void confirmValueIsArray(JsonObject fatherNode, String key) {
if (fatherNode == null || key == null) {
return;
}
JsonElement element = fatherNode.get(key);
if (element == null) {
return;
}
if (element.isJsonArray()) {
return;
}
JsonArray array = new JsonArray();
array.add(element);
fatherNode.remove(key);
fatherNode.add(key, array);
}
}
|
package com.chessman;
import javax.swing.JFrame;
public class MainChessMan {
public static void main(String[] args) {
GameFram GFrame = new GameFram();
GFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GFrame.setVisible(true);
}
}
|
package com.magit.logic.system.tasks;
import com.magit.logic.exceptions.*;
import com.magit.logic.system.MagitEngine;
import javafx.application.Platform;
import javafx.concurrent.Task;
import java.io.IOException;
import java.text.ParseException;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
public class NewCommitTask extends Task<Void> {
MagitEngine engine;
Runnable onSuccess;
String input;
public NewCommitTask(Runnable onSuccess, MagitEngine engine, String input) {
this.engine = engine;
this.onSuccess = onSuccess;
this.input = input;
}
@Override
protected Void call() throws WorkingCopyStatusNotChangedComparedToLastCommitException, ParseException, PreviousCommitsLimitExceededException, IOException, RepositoryNotFoundException, WorkingCopyIsEmptyException, UnhandledConflictsException, FastForwardException {
engine.commit(input);
Platform.runLater(() -> onSuccess.run());
return null;
}
}
|
package com.tanmengen.en.tanmengenqi.adapters;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.tanmengen.en.tanmengenqi.R;
import com.tanmengen.en.tanmengenqi.beans.FuliBean;
import com.youth.banner.Banner;
import com.youth.banner.loader.ImageLoader;
import java.util.ArrayList;
/**
* Created by en on 2019/9/3.
*/
public class MyAdapter extends RecyclerView.Adapter {
private Context context;
private ArrayList<String> banners;
private ArrayList<FuliBean.DataBean.DatasBean> list;
public MyAdapter(Context context, ArrayList<String> banners, ArrayList<FuliBean.DataBean.DatasBean> list) {
this.context = context;
this.banners = banners;
this.list = list;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
if (viewType == 1) {
View view = LayoutInflater.from(context).inflate(R.layout.layout_my_banner, parent, false);
return new MyBanner(view);
} else {
View view = LayoutInflater.from(context).inflate(R.layout.layout_item, parent, false);
return new MyViewHolder(view);
}
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {
int i = getItemViewType(position);
if (i == 1) {
MyBanner holder1 = (MyBanner) holder;
holder1.banner_item.setImages(banners).setImageLoader(new MyImage()).start();
} else {
int index = 0;
if (banners.size()>0) {
index = position - 1;
}
MyViewHolder holder2 = (MyViewHolder) holder;
if (position-1 % 2 == 0) {
holder2.tv_item.setText(list.get(position-1).getTitle());
Glide.with(context).load(list.get(position-1).getEnvelopePic())
.apply(RequestOptions.bitmapTransform(new CircleCrop()))
.into(holder2.iv_item);
} else{
holder2.tv_item.setText(list.get(position-1).getAuthor());
Glide.with(context).load(list.get(position-1).getEnvelopePic())
.into(holder2.iv_item);
}
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (myOnClickLinstener!=null){
myOnClickLinstener.onClick(position);
}
}
});
}
public interface MyOnClickLinstener{
void onClick(int position);
}
private MyOnClickLinstener myOnClickLinstener;
public void setMyOnClickLinstener(MyOnClickLinstener myOnClickLinstener) {
this.myOnClickLinstener = myOnClickLinstener;
}
class MyImage extends ImageLoader {
@Override
public void displayImage(Context context, Object path, ImageView imageView) {
Glide.with(context).load(path).into(imageView);
}
}
@Override
public int getItemCount() {
if (banners.size() > 0) {
return list.size() + 1;
} else {
return list.size();
}
}
@Override
public int getItemViewType(int position) {
if (position == 0 && banners.size() > 0) {
return 1;
} else {
return 2;
}
}
class MyBanner extends RecyclerView.ViewHolder {
Banner banner_item;
public MyBanner(View itemView) {
super(itemView);
banner_item = itemView.findViewById(R.id.banner_item);
}
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView tv_item;
ImageView iv_item;
public MyViewHolder(View itemView) {
super(itemView);
tv_item = itemView.findViewById(R.id.tv_item);
iv_item = itemView.findViewById(R.id.iv_item);
}
}
}
|
/*
* GNUnetWebUI - A Web User Interface for P2P networks. <https://gitorious.org/gnunet-webui>
* Copyright 2013 Sébastien Moratinos <sebastien.moratinos@gmail.com>
*
*
* This file is part of GNUnetWebUI.
*
* GNUnetWebUI is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GNUnetWebUI 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with GNUnetWebUI. If not, see <http://www.gnu.org/licenses/>.
*/
package org.gnunet.integration.statistics;
import org.gnunet.statistics.StatisticsWatcher;
public class StatGeneratorFactory {
private static String defaultTypeName;
public enum TYPE {
JAVA_API("java-api"), FAKE_RANDOM("fake-random");
private final String name;
TYPE(final String name) {
this.name = name;
};
}
public static StatGenerator getReceiver(final StatisticsWatcher watcher) {
StatGenerator generator = null;
if (defaultTypeName.equals(TYPE.JAVA_API.name)) {
generator = new StatProgram(null, watcher);
} else {
generator = new FakeRandomReceiver(watcher);
}
return generator;
}
public static void setDefaultTypeName(final String typeName) {
defaultTypeName = typeName;
}
}
|
package be.usgprofessionals.POJOs;
import be.usgprofessionals.Utils.EID;
/**
* Created by Thomas Straetmans on 17/11/15.
* <p>
* Digigram for USG Professionals
*/
public class BasicUserProfile {
private EID userId;
private String firstName;
private String lastName;
private String profilePicURI;
private String uniqueProperty;
private Project project;
private Employer employer;
private boolean intern;
private CC dept;
private EID reportsTo;
private String nextDept;
public BasicUserProfile(EID userId, String firstName, String lastName) {
this.userId = userId;
this.firstName = firstName;
this.lastName = lastName;
}
public EID getUserId() {
return userId;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getProfilePicURI() {
return profilePicURI;
}
public String getUniqueProperty() {
return uniqueProperty;
}
public Project getProject() {
return project;
}
public Employer getEmployer() {
return employer;
}
public boolean isIntern() {
return intern;
}
public void setProfilePicURI(String profilePicURI) {
this.profilePicURI = profilePicURI;
}
public void setUniqueProperty(String uniqueProperty) {
this.uniqueProperty = uniqueProperty;
}
public void setProject(Project project) {
this.project = project;
}
public void setEmployer(Employer employer) {
this.employer = employer;
}
public void setIntern(boolean intern) {
this.intern = intern;
}
public CC getDept() {
return dept;
}
public void setDept(CC dept) {
this.dept = dept;
}
public EID getReportsTo() {
return reportsTo;
}
public void setReportsTo(EID reportsTo) {
this.reportsTo = reportsTo;
}
public String getNextDept() {
return nextDept;
}
public void setNextDept(String nextDept) {
this.nextDept = nextDept;
}
}
|
package com.espendwise.manta.service;
import com.espendwise.manta.dao.*;
import com.espendwise.manta.model.data.PropertyData;
import com.espendwise.manta.model.view.EmailTemplateIdentView;
import com.espendwise.manta.model.view.EmailTemplateListView;
import com.espendwise.manta.model.view.EntityHeaderView;
import com.espendwise.manta.util.PropertyUtil;
import com.espendwise.manta.util.RefCodeNames;
import com.espendwise.manta.util.Utility;
import com.espendwise.manta.util.criteria.StoreTemplateCriteria;
import com.espendwise.manta.util.validation.ServiceLayerValidation;
import com.espendwise.manta.util.validation.rules.EmailTemplateChangeNameConstraint;
import com.espendwise.manta.util.validation.rules.EmailTemplateUniqueConstraint;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@Service
@Transactional(readOnly = true, propagation = Propagation.REQUIRED)
public class TemplateServiceImpl extends DataAccessService implements TemplateService {
private static final Logger logger = Logger.getLogger(TemplateServiceImpl.class);
@Override
@Transactional(readOnly = true, propagation = Propagation.REQUIRED)
public List<EmailTemplateListView> findEmailTemplatesByCriteria(StoreTemplateCriteria criteria) {
TemplateDAOImpl templateDao = new TemplateDAOImpl(getEntityManager());
return templateDao.findEmailTemplates(criteria);
}
@Override
@Transactional(readOnly = true, propagation = Propagation.REQUIRED)
public EntityHeaderView findTemplateHeader(Long templateId) {
TemplateDAO templateDao = new TemplateDAOImpl(getEntityManager());
return templateDao.findTemplateHeader(templateId);
}
@Override
@Transactional(readOnly = true, propagation = Propagation.REQUIRED)
public EmailTemplateIdentView findEmailTemplateIdent(Long storeId, Long emailTemplateId) {
TemplateDAO templateDao = new TemplateDAOImpl(getEntityManager());
return templateDao.findEmailTemplateIdent(storeId, emailTemplateId);
}
@Override
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public EmailTemplateIdentView saveEmailTemplateIdent(Long storeId, EmailTemplateIdentView emailTemplateView) {
ServiceLayerValidation validation = new ServiceLayerValidation();
validation.addRule(new EmailTemplateUniqueConstraint(storeId, emailTemplateView));
validation.addRule(new EmailTemplateChangeNameConstraint(storeId, emailTemplateView));
validation.validate();
TemplateDAO templateDao = new TemplateDAOImpl(getEntityManager());
return templateDao.saveEmailTemplateIdent(storeId, emailTemplateView);
}
@Override
@Transactional(readOnly = true, propagation = Propagation.REQUIRED)
public boolean isTemplateUsedBySystem(Long storeId, Long templateId) {
if (Utility.longNN(templateId) <= 0 || Utility.longNN(storeId) <= 0 ) {
return false;
}
boolean returnValue;
EntityManager entityManager = getEntityManager();
//next, see if this template is the only one with the original name
List<EmailTemplateListView> existingTemplates = findEmailTemplatesByCriteria(new StoreTemplateCriteria(storeId));
String originalTemplateName = null;
boolean isOnlyInstance = false;
boolean isUsedByStore = false;
boolean isUsedByAccount = false;
if (existingTemplates != null) {
Map<String, Integer> nameToCountMap = new HashMap<String, Integer>();
for (EmailTemplateListView existingTemplate : existingTemplates) {
String templateName = existingTemplate.getName();
if (existingTemplate.getTemplateId() == templateId.longValue()) {
originalTemplateName = templateName;
}
Integer count = nameToCountMap.get(templateName);
if (count == null) {
nameToCountMap.put(templateName, 1);
} else {
nameToCountMap.put(templateName, count + 1);
}
}
if (Utility.isSet(originalTemplateName)) {
isOnlyInstance = nameToCountMap.get(originalTemplateName) == 1;
}
}
if (isOnlyInstance) {
PropertyDAO propertyDao = new PropertyDAOImpl(entityManager);
List<PropertyData> storeProperties = propertyDao.findEntityProperties(storeId, null);
String storeOrderConfirmationEmailTemplate = null;
String storeShippingNotificationEmailTemplate = null;
String storePendingApprovalEmailTemplate = null;
String storeRejectedOrderEmailTemplate = null;
String storeModifiedOrderEmailTemplate = null;
for (PropertyData pD : storeProperties) {
String propType = pD.getPropertyTypeCd();
if (RefCodeNames.PROPERTY_TYPE_CD.ORDER_CONFIRMATION_EMAIL_TEMPLATE.equals(propType)) {
storeOrderConfirmationEmailTemplate = pD.getValue();
} else if (RefCodeNames.PROPERTY_TYPE_CD.SHIPPING_NOTIFICATION_EMAIL_TEMPLATE.equals(propType)) {
storeShippingNotificationEmailTemplate = pD.getValue();
} else if (RefCodeNames.PROPERTY_TYPE_CD.PENDING_APPROVAL_EMAIL_TEMPLATE.equals(propType)) {
storePendingApprovalEmailTemplate = pD.getValue();
} else if (RefCodeNames.PROPERTY_TYPE_CD.REJECTED_ORDER_EMAIL_TEMPLATE.equals(propType)) {
storeRejectedOrderEmailTemplate = pD.getValue();
} else if (RefCodeNames.PROPERTY_TYPE_CD.MODIFIED_ORDER_EMAIL_TEMPLATE.equals(propType)) {
storeModifiedOrderEmailTemplate = pD.getValue();
}
}
isUsedByStore = (Utility.isSet(storeOrderConfirmationEmailTemplate) && storeOrderConfirmationEmailTemplate.equalsIgnoreCase(originalTemplateName))
|| (Utility.isSet(storeShippingNotificationEmailTemplate) && storeShippingNotificationEmailTemplate.equalsIgnoreCase(originalTemplateName))
|| (Utility.isSet(storePendingApprovalEmailTemplate) && storePendingApprovalEmailTemplate.equalsIgnoreCase(originalTemplateName))
|| (Utility.isSet(storeRejectedOrderEmailTemplate) && storeRejectedOrderEmailTemplate.equalsIgnoreCase(originalTemplateName))
|| (Utility.isSet(storeModifiedOrderEmailTemplate) && storeModifiedOrderEmailTemplate.equalsIgnoreCase(originalTemplateName));
if (!isUsedByStore) {
AccountDAO accountDao = new AccountDAOImpl(entityManager);
List<Long> accountIds = (accountDao.findAccountIdsByStore(storeId));
List<String> propertyTypes = Utility.toList(RefCodeNames.PROPERTY_TYPE_CD.EXTRA);
List<String> shortDescriptions = Utility.toList(
RefCodeNames.PROPERTY_TYPE_CD.ORDER_CONFIRMATION_EMAIL_TEMPLATE,
RefCodeNames.PROPERTY_TYPE_CD.SHIPPING_NOTIFICATION_EMAIL_TEMPLATE,
RefCodeNames.PROPERTY_TYPE_CD.PENDING_APPROVAL_EMAIL_TEMPLATE,
RefCodeNames.PROPERTY_TYPE_CD.REJECTED_ORDER_EMAIL_TEMPLATE,
RefCodeNames.PROPERTY_TYPE_CD.MODIFIED_ORDER_EMAIL_TEMPLATE
);
List<PropertyData> accountProperties = propertyDao.findEntityProperties(accountIds, shortDescriptions, propertyTypes, true);
Map<Long, List<PropertyData>> accountPropertiesMap = PropertyUtil.toBusEntityPropMap(accountProperties);
Iterator<Long> accountIterator = accountPropertiesMap.keySet().iterator();
while (accountIterator.hasNext() && !isUsedByAccount) {
Long accountId = accountIterator.next();
List<PropertyData> properties = accountPropertiesMap.get(accountId);
if (properties != null) {
Iterator<PropertyData> propertyIterator = properties.iterator();
while (propertyIterator.hasNext() && !isUsedByAccount) {
PropertyData property = propertyIterator.next();
isUsedByAccount = originalTemplateName.equalsIgnoreCase(property.getValue());
}
}
}
}
}
//this template can be removed if it isn't the only instance or it isn't used by either the store or an account
returnValue = !isOnlyInstance || (!isUsedByStore && !isUsedByAccount);
return !returnValue;
}
@Override
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public boolean deleteEmailTemplate(Long storeId, Long templateId) {
if (isTemplateUsedBySystem(storeId, templateId)) {
return false;
} else {
TemplateDAO templateDao = new TemplateDAOImpl(getEntityManager());
return templateDao.deleteTemplate(storeId, templateId);
}
}
}
|
package com.shopify.api.lotte.delivery;
import lombok.Data;
@Data
public class ResultPair {
private String data; // 성공인 경우 data 만 set 함
private String msg; // 에러인 경우 msg 만 set 함
}
|
package fr.cp.train.api;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
@Path("/reseau")
public interface TrainResource {
@GET
@Consumes("text/plain")
@Produces("application/json")
Train getTrain(@QueryParam(value = "id") long id);
}
|
package Pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Waits {
private WebDriver driver;
public Waits(WebDriver driver){
this.driver = driver;
}
public boolean isElementPresent(By by){
WebDriverWait wait = new WebDriverWait(driver,2);
try{
wait.until(ExpectedConditions.visibilityOfElementLocated(by));
return true;
}catch (Exception e){
return false;
}
}
public WebElement WaitForVisibility(By by){
WebDriverWait wait = new WebDriverWait(driver,5);
wait.until(ExpectedConditions.elementToBeClickable(by));
return driver.findElement(by);
}
}
|
package com.gumbley.jonathon.findmeaplace;
import android.Manifest;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.location.LocationServices;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,
ListFragment.OnFragmentInteractionListener,
DetailsFragment.OnFragmentInteractionListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
ActivityCompat.OnRequestPermissionsResultCallback {
private static final String LOCATION_BUNDLE = "location";
private static final String LOCATION_BUNDLE_LATITUDE = "location_latitude";
private static final String LOCATION_BUNDLE_LONGITUTDE = "location_longitude";
private static final String LOCATION_BUNDLE_NAME = "location_name";
private static final int MY_PERMISSION_REQUEST_FINE_LOCATION = 0;
private static final int MY_PERMISSION_REQUEST_INTERNET = 10;
private static final int DEFAULT_RADIUS = 5000;
private static final String CURRENT_ITEM_TYPE = "current item type";
private static final String LAST_LOCATION = "last location";
private static final String FROM_ROTATE = "from rotate";
boolean fromRotate = false;
GoogleApiClient mGoogleApiClient;
LatLng mLastLocation;
String mCurrentItemType = "";
List<PlaceItem> mCurrentItems;
RequestQueue mRequestQueue;
PlacesDbHelper mDbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Allow another application to send a location (from a bundle) which this application will display onto the map activity
if (Intent.ACTION_SEND.equals(getIntent().getAction()) && getIntent().getType() != null) {
if ("location".equals(getIntent().getType())) {
Bundle bundleFromApp = getIntent().getBundleExtra(LOCATION_BUNDLE);
LatLng location = new LatLng(
bundleFromApp.getDouble(LOCATION_BUNDLE_LATITUDE),
bundleFromApp.getDouble(LOCATION_BUNDLE_LONGITUTDE));
String locationName = bundleFromApp.getString(LOCATION_BUNDLE_NAME);
Intent i = new Intent(this, MapsActivity.class);
Bundle b = new Bundle();
b.putParcelable(getString(R.string.ITEM_LOCATION), location);
b.putString(getString(R.string.ITEM_NAME), locationName);
i.putExtra(getString(R.string.LOCATIONS_BUNDLE), b);
startActivity(i);
}
} else {
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (savedInstanceState != null) {
showProgressLoader(false);
fromRotate = savedInstanceState.getBoolean(FROM_ROTATE);
if (savedInstanceState.containsKey(LAST_LOCATION)) {
String[] location = savedInstanceState.getStringArray(LAST_LOCATION);
mLastLocation = new LatLng(Double.parseDouble(location[0]), Double.parseDouble(location[1]));
}
mCurrentItemType = savedInstanceState.getString(CURRENT_ITEM_TYPE);
if (mCurrentItemType.equals(getString(R.string.food_type))) {
getSupportActionBar().setTitle(getString(R.string.food));
}
else if (mCurrentItemType.equals(getString(R.string.lodging))) {
getSupportActionBar().setTitle(getString(R.string.lodging));
}
else if (mCurrentItemType.equals(getString(R.string.petrol_type))) {
getSupportActionBar().setTitle(getString(R.string.petrol));
}
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
mRequestQueue = Volley.newRequestQueue(this);
mDbHelper = new PlacesDbHelper(this);
if(mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
mGoogleApiClient.connect();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
}
@Override
public void onSaveInstanceState(Bundle bundle) {
super.onSaveInstanceState(bundle);
bundle.putBoolean(FROM_ROTATE, true);
if (mLastLocation != null) {
bundle.putStringArray(LAST_LOCATION, new String[] { Double.toString(mLastLocation.latitude), Double.toString(mLastLocation.longitude) });
}
bundle.putString(CURRENT_ITEM_TYPE, mCurrentItemType);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_reload) {
showProgressLoader(true);
getAllPlaces();
return true;
}
else if (id == R.id.action_change_radius) {
Intent i = new Intent(this, ChangeRadiusActivity.class);
startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
String title = getSupportActionBar().getTitle().toString();
if (id == R.id.nav_food) {
setUpList(getString(R.string.food_type));
title = getResources().getString(R.string.food);
} else if (id == R.id.nav_sleep) {
setUpList(getString(R.string.lodging));
title = getResources().getString(R.string.lodging);
} else if (id == R.id.nav_petrol) {
setUpList(getString(R.string.petrol_type));
title = getResources().getString(R.string.petrol);
} else if (id == R.id.nav_map) {
Intent i = new Intent(this, MapsActivity.class);
Bundle b = new Bundle();
b.putParcelable(getResources().getString(R.string.USER_LOCATION), mLastLocation);
b.putBoolean(getString(R.string.SHOW_ALL_NEARBY_PLACES), true);
i.putExtra(getResources().getString(R.string.LOCATIONS_BUNDLE), b);
startActivity(i);
return true;
}
Fragment fragment = new ListFragment();
((ListFragment)fragment).setItems(mCurrentItems);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.fragment_frame, fragment);
ft.addToBackStack(null);
ft.commit();
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle(title);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
@Override
public void onFragmentInteraction(Uri uri) {
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == MY_PERMISSION_REQUEST_FINE_LOCATION) {
if (permissions.length > 0 &&
permissions[0].equals(Manifest.permission.ACCESS_FINE_LOCATION) &&
grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getAllPlaces();
} else {
// Permission was denied. Display an error message.
Toast.makeText(this, getString(R.string.permissions_denied_error), Toast.LENGTH_LONG).show();
}
} else if (requestCode == MY_PERMISSION_REQUEST_INTERNET) {
if (permissions.length > 0 &&
permissions[0].equals(Manifest.permission.INTERNET) &&
grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getAllPlaces();
} else {
// Permission was denied. Display an error message.
Toast.makeText(this, getString(R.string.permissions_denied_error), Toast.LENGTH_LONG).show();
}
}
}
@Override
public void onConnected(@Nullable Bundle bundle) {
if (!fromRotate) getAllPlaces();
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
private boolean isLocationEnabled() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
Log.e("LocationEabledError", ex.getMessage());
Log.e("LocationEabledError", ex.getStackTrace().toString());
}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
Log.e("LocationEabledError", ex.getMessage());
Log.e("LocationEabledError", ex.getStackTrace().toString());
}
if (!gps_enabled || !network_enabled) {
// notify user
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage(getString(R.string.gps_network_not_enabled));
dialog.setPositiveButton(getString(R.string.open_location_settings), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
});
dialog.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// Show toast telling user needs location and internet
Toast.makeText(getApplicationContext(), getString(R.string.permissions_denied_error), Toast.LENGTH_LONG).show();
}
});
dialog.show();
}
return false;
}
private void getAllPlaces() {
// Check that location services is enabled
isLocationEnabled();
// Check if the internet permission is allowed, if not request it
if(ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.INTERNET}, MY_PERMISSION_REQUEST_INTERNET);
}
else {
// Check if fine location permission is allowed, if not request it
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSION_REQUEST_FINE_LOCATION);
} else {
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
// location will be null if location services is turned off, only get data if their is a location
if (location != null) {
mLastLocation = new LatLng(location.getLatitude(), location.getLongitude());
SQLiteDatabase db = mDbHelper.getWritableDatabase();
db.execSQL(PlacesContract.SQL_DELETE_ENTRIES);
mDbHelper.onCreate(db);
db = null;
getPlaces(getString(R.string.food_type));
getPlaces(getString(R.string.lodging));
getPlaces(getString(R.string.petrol_type));
}
}
}
}
private void getPlaces(String type) {
final String typeLower = type.toLowerCase();
int radius = getSharedPreferences(getString(R.string.preference_file_key), MODE_PRIVATE).getInt(getString(R.string.preference_radius), DEFAULT_RADIUS);
String url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=" +
mLastLocation.latitude + "," + mLastLocation.longitude +
"&radius=" + radius +
"&types=" + typeLower +
"&key=" + getResources().getString(R.string.google_places_key);
Log.d("url", url);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
parseJSONObject(response, typeLower);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("VolleyError", error.getMessage());
Log.e("VolleyError", error.getStackTrace().toString());
}
});
mRequestQueue.add(request);
}
private void parseJSONObject(JSONObject object, String type) {
try {
type = type.toLowerCase();
// Create the database to read to
SQLiteDatabase db = mDbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
JSONArray results = object.getJSONArray("results");
// Go through each place in the JSON array
for (int i = 0; i < results.length(); i++) {
// For each place add the place data to values which will be put into a database
JSONObject jsonPlace = results.getJSONObject(i);
values.put(PlacesContract.PlaceEntry.COLUMN_NAME_TITLE, jsonPlace.getString("name"));
JSONObject location = jsonPlace.getJSONObject("geometry").getJSONObject("location");
values.put(PlacesContract.PlaceEntry.COLUMN_NAME_LOCATION, location.getString("lat") + " " + location.getString("lng"));
// Some places don't have a photo so just put an empty string for those
if (jsonPlace.has("photos")) {
values.put(
PlacesContract.PlaceEntry.COLUMN_NAME_IMAGE_URL,
"https://maps.googleapis.com/maps/api/place/photo?maxheight=600&photoreference=" + jsonPlace.getJSONArray("photos").getJSONObject(0).getString("photo_reference") +
"&key=" + getResources().getString(R.string.google_places_key));
} else {
values.put(PlacesContract.PlaceEntry.COLUMN_NAME_IMAGE_URL, "");
}
values.put(PlacesContract.PlaceEntry.COLUMN_NAME_ADDRESS, jsonPlace.getString("vicinity"));
values.put(PlacesContract.PlaceEntry.COLUMN_NAME_TYPE, type);
// Insert into the database
db.insert(PlacesContract.PlaceEntry.TABLE_NAME, null, values);
}
// When the food places are all gathered then show them, other items may still be downloading
if (type.equals(getString(R.string.food_type).toLowerCase())) {
// Hide progress loader
showProgressLoader(false);
// Get list of items of type food
setUpList(getString(R.string.food_type));
// Display the food list fragment
Fragment fragment = new ListFragment();
((ListFragment)fragment).setItems(mCurrentItems);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_frame, fragment).commit();
getSupportActionBar().setTitle(getResources().getString(R.string.food));
}
} catch (JSONException e) {
Log.e("parsing JSON", e.getMessage());
Log.e("parsing JSON", e.getStackTrace().toString());
}
}
private void setUpList(String type) {
type = type.toLowerCase();
mCurrentItemType = type;
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String[] projection = {
PlacesContract.PlaceEntry.COLUMN_NAME_TITLE,
PlacesContract.PlaceEntry.COLUMN_NAME_LOCATION,
PlacesContract.PlaceEntry.COLUMN_NAME_IMAGE_URL,
PlacesContract.PlaceEntry.COLUMN_NAME_ADDRESS };
String selection = PlacesContract.PlaceEntry.COLUMN_NAME_TYPE + " = ?";
String[] selectionArgs = { type };
String sortOrder = PlacesContract.PlaceEntry.COLUMN_NAME_TITLE + " ASC";
Cursor curser = db.query(
PlacesContract.PlaceEntry.TABLE_NAME,
projection,
selection,
selectionArgs,
null,
null,
sortOrder);
mCurrentItems = new ArrayList<>();
while (curser.moveToNext()) {
String[] location = curser.getString(curser.getColumnIndex(PlacesContract.PlaceEntry.COLUMN_NAME_LOCATION)).split(" ");
PlaceItem place = new PlaceItem(
curser.getString(curser.getColumnIndex(PlacesContract.PlaceEntry.COLUMN_NAME_TITLE)),
new LatLng(Double.parseDouble(location[0]), Double.parseDouble(location[1])),
curser.getString(curser.getColumnIndex(PlacesContract.PlaceEntry.COLUMN_NAME_IMAGE_URL)),
curser.getString(curser.getColumnIndex(PlacesContract.PlaceEntry.COLUMN_NAME_ADDRESS)));
place.setDistanceFromUserLocation(mLastLocation);
mCurrentItems.add(place);
}
// Order the list by the closest place first
Collections.sort(mCurrentItems, new Comparator<PlaceItem>() {
@Override
public int compare(PlaceItem o1, PlaceItem o2) {
return (int)(o1.getDistanceFrom() - o2.getDistanceFrom());
}
});
}
private void showProgressLoader(boolean show){
if (show) {
findViewById(R.id.progress_layout).setVisibility(View.VISIBLE);
} else {
findViewById(R.id.progress_layout).setVisibility(View.GONE);
}
}
}
|
/*
* This software is licensed under the MIT License
* https://github.com/GStefanowich/MC-Server-Protection
*
* Copyright (c) 2019 Gregory Stefanowich
*
* 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.
*/
package net.theelm.sewingmachine.base.commands;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.command.CommandRegistryAccess;
import net.minecraft.text.Text;
import net.theelm.sewingmachine.base.config.SewBaseConfig;
import net.theelm.sewingmachine.commands.abstraction.SewCommand;
import net.theelm.sewingmachine.config.SewConfig;
import net.theelm.sewingmachine.enums.OpLevels;
import net.theelm.sewingmachine.interfaces.CommandPredicate;
import net.theelm.sewingmachine.utilities.CommandUtils;
import net.theelm.sewingmachine.utilities.WarpUtils;
import net.minecraft.command.argument.BlockPosArgumentType;
import net.minecraft.command.argument.DimensionArgumentType;
import net.minecraft.command.argument.EntityArgumentType;
import net.minecraft.entity.Entity;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.command.CommandManager;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.GameRules;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
public final class WorldCommand implements SewCommand {
@Override
public void register(@NotNull CommandDispatcher<ServerCommandSource> dispatcher, @NotNull CommandRegistryAccess registry) {
final LiteralArgumentBuilder<ServerCommandSource> gamerules = CommandManager.literal("gamerule");
GameRules.accept(new GameRules.Visitor() {
public <T extends GameRules.Rule<T>> void visit(GameRules.Key<T> key, GameRules.Type<T> type) {
gamerules.then(CommandManager.literal(key.getName())
.executes((context) -> WorldCommand.this.queryGameRule(context, key)
).then(type.argument("value")
.executes((context) -> WorldCommand.this.setGameRule(context, key)))
);
}
});
CommandUtils.register(dispatcher, "world", builder -> builder
.requires(CommandPredicate.opLevel(OpLevels.CHEATING))
.then(CommandManager.argument("world", DimensionArgumentType.dimension())
.then(CommandManager.literal("teleport")
.then(CommandManager.argument("target", EntityArgumentType.entities())
.executes(this::teleportEntitiesTo)
)
.executes(this::teleportSelfTo)
)
.then(CommandManager.literal("setspawn")
.then(CommandManager.argument("pos", BlockPosArgumentType.blockPos())
.executes(this::updateServerSpawnToPos)
)
.executes(this::updateServerSpawnToPlayer)
)
.then(gamerules)
)
);
}
private int teleportSelfTo(@NotNull CommandContext<ServerCommandSource> context) throws CommandSyntaxException {
return this.teleportEntitiesTo(context, Collections.singleton(context.getSource().getEntity()));
}
private int teleportEntitiesTo(@NotNull CommandContext<ServerCommandSource> context) throws CommandSyntaxException {
return this.teleportEntitiesTo(context, EntityArgumentType.getEntities(context, "target"));
}
private int teleportEntitiesTo(@NotNull CommandContext<ServerCommandSource> context, @NotNull Collection<? extends Entity> entities) throws CommandSyntaxException {
ServerWorld world = DimensionArgumentType.getDimensionArgument(context, "world");
// Teleport each entity to the world spawn
for (Entity entity : entities)
WarpUtils.teleportEntity(world, entity);
// Return success
return Command.SINGLE_SUCCESS;
}
private int updateServerSpawnToPlayer(@NotNull CommandContext<ServerCommandSource> context) throws CommandSyntaxException {
ServerCommandSource source = context.getSource();
return this.updateServerSpawn(
source.getServer(),
DimensionArgumentType.getDimensionArgument(context, "world"),
BlockPos.ofFloored(source.getPosition())
);
}
private int updateServerSpawnToPos(@NotNull CommandContext<ServerCommandSource> context) throws CommandSyntaxException {
ServerCommandSource source = context.getSource();
return this.updateServerSpawn(
source.getServer(),
DimensionArgumentType.getDimensionArgument(context, "world"),
BlockPosArgumentType.getBlockPos(context, "pos")
);
}
private int updateServerSpawn(@NotNull MinecraftServer server, @NotNull ServerWorld world, @NotNull BlockPos pos) throws CommandSyntaxException {
try {
SewConfig.set(SewBaseConfig.DEFAULT_WORLD, world.getRegistryKey());
SewConfig.save();
} catch (IOException e) {
e.printStackTrace();
return 0;
}
server.getOverworld()
.setSpawnPos(pos, 0.0F);
return Command.SINGLE_SUCCESS;
}
private <T extends GameRules.Rule<T>> int setGameRule(@NotNull CommandContext<ServerCommandSource> context, GameRules.Key<T> key) throws CommandSyntaxException {
ServerCommandSource source = context.getSource();
T rule = DimensionArgumentType.getDimensionArgument(context, "world")
.getGameRules()
.get(key);
rule.set(context, "value");
source.sendFeedback(
() -> Text.translatable("commands.gamerule.set", key.getName(), rule.toString()),
true
);
return rule.getCommandResult();
}
private <T extends GameRules.Rule<T>> int queryGameRule(@NotNull CommandContext<ServerCommandSource> context, GameRules.Key<T> key) throws CommandSyntaxException {
ServerCommandSource source = context.getSource();
T rule = DimensionArgumentType.getDimensionArgument(context, "world")
.getGameRules()
.get(key);
source.sendFeedback(
() -> Text.translatable("commands.gamerule.query", key.getName(), rule.toString()),
false
);
return rule.getCommandResult();
}
}
|
package com.example.wesley.myweatherapp;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class WeatherAdapter extends ArrayAdapter<CityResults> {
private CityResults results;
private Date dateObj;
public WeatherAdapter(Activity context, ArrayList<CityResults> cityResults) {
super(context, 0, cityResults);
}
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
}
results = getItem(position);
dateObj = new Date(results.getmDay());
TextView iconView = listItemView.findViewById(R.id.Icon);
TextView dayView = listItemView.findViewById(R.id.day);
TextView highView = listItemView.findViewById(R.id.high);
TextView lowView = listItemView.findViewById(R.id.low);
String highTemp = convertTemp(results.getmHighTemp());
highView.setText(highTemp);
String lowTemp = convertTemp(results.getmLowTemp());
lowView.setText(lowTemp);
String formatedDate = formatDate(dateObj);
dayView.setText(formatedDate);
return listItemView;
}
private String convertTemp(double temp) {
double fahrenheitTemp = (9 / 5) * (temp + 32);
String mTemp; /*Double.toString(fahrenheitTemp);*/
return Double.toString(fahrenheitTemp);
}
private String formatDate(Date dateObj)
{
//Get the day from the unix time code
SimpleDateFormat dateFormat = new SimpleDateFormat("EE");
return dateFormat.format(dateObj);
}
/*private String weatherIcon(String icon)
{
String icons = String.valueOf(results.getmIconID());
switch (icons)
{
case "clear-day":
icons = R.drawable.day_clear_sunny;
break;
}
}*/
}
|
package lando.systems.ld36.entities;
import aurelienribon.tweenengine.primitives.MutableFloat;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.utils.Array;
import lando.systems.ld36.LudumDare36;
import lando.systems.ld36.ai.StateMachine;
import lando.systems.ld36.ai.Transition;
import lando.systems.ld36.ai.conditions.HealthAtOrBelowCondition;
import lando.systems.ld36.ai.conditions.NearScreenCondition;
import lando.systems.ld36.ai.states.*;
import lando.systems.ld36.levels.Level;
import lando.systems.ld36.utils.Assets;
import lando.systems.ld36.utils.Sounds;
import lando.systems.ld36.utils.Utils;
import lando.systems.ld36.utils.Statistics;
public class Enemy extends GameObject {
public boolean isMoving = false;
public MutableFloat animationTimer;
public float timer = 0f;
public Color healthColor;
public Enemy(Level level) {
super(level);
animationTimer = new MutableFloat(0f);
health = 5;
maxHealth = 5;
moveSpeed = 50;
activated = false;
name = "Unset";
}
public void initializeStates(){
// States enemy can have
WaitState wait = new WaitState(this);
WanderState wander = new WanderState(this);
ChaseAvoidState chase = new ChaseAvoidState(this);
// Conditions
NearScreenCondition nearCond = new NearScreenCondition(level.screen.camera, this);
// Transitions
Array<Transition> transitions = new Array<Transition>();
transitions.add(new Transition(wait, nearCond, chase));
// Create State Machine
stateMachine = new StateMachine(wait, transitions);
addDieState();
}
public void update(float dt) {
rightEdge = level.getLevelWidth() - (width/2);
super.update(dt);
stateMachine.update(dt);
isFacingRight = direction.x > 0;
tryAttack();
hitBounds.x = position.x + 15f;
hitBounds.y = position.y + position.z;
}
public void render(SpriteBatch batch){
super.render(batch);
// healthbar
if (showHealthBar) {
batch.setColor(Color.BLACK);
batch.draw(
Assets.white,
position.x,
position.y + height.floatValue() + position.z,
characterSpriteWidth, // Full health
5
);
float n = health / (float) maxHealth;
healthColor = Utils.hsvToRgb(((n * 120f) - 20) / 365f, 1.0f, 1.0f, healthColor);
batch.setColor(healthColor);
batch.draw(
Assets.white,
position.x,
position.y + height.floatValue() + position.z,
((float) health / maxHealth) * characterSpriteWidth, // Full health
5
);
}
batch.setColor(Color.WHITE);
}
public void tryAttack(){
// Lets make them not always try to hit you
if (MathUtils.random() < .97f) return;
if (position.dst(level.player.position) < 100){
attack();
}
}
public void getHurt(int dmg, int dir) {
Statistics.damageDealt += dmg;
super.getHurt(dmg, dir);
if (dead) {
Statistics.enemiesKilled++;
} else {
Sounds.play(Sounds.Effect.playerHitEnemy);
}
}
public void addDieState(){
DieState die = new DieState(this);
HealthAtOrBelowCondition zeroHealth = new HealthAtOrBelowCondition(this, 0);
stateMachine.addTransition(new Transition(null, zeroHealth, die));
}
}
|
package vanadis.blueprints;
import vanadis.common.ver.Version;
import vanadis.core.lang.ToString;
import vanadis.core.properties.PropertySet;
import vanadis.mvn.Coordinate;
import java.math.BigInteger;
import java.net.URI;
final class BundleBuilder {
private String group;
private String artifact;
private String artifactPrefix;
private String groupPrefix;
private static final String DOT = ".";
private Integer startLevel;
private Boolean globalProperties;
private PropertySet propertySet;
private String configurationPid;
private String repo;
private String uri;
private String version;
BundleBuilder() {
this(null, null);
}
BundleBuilder(String defaultVersion, String defaultRepo) {
this.version = defaultVersion;
this.repo = defaultRepo;
}
BundleBuilder copy() {
return new BundleBuilder(version, repo).
setUri(uri).
setArtifact(artifact).
setArtifactPrefix(artifactPrefix).
setGroup(group).
setGroupPrefix(groupPrefix).
setStartLevel(startLevel).
setArtifact(artifact);
}
BundleBuilder setVersion(String version) {
if (version != null) {
this.version = version;
}
return this;
}
BundleBuilder setRepo(String repo) {
if (repo != null) {
this.repo = repo;
}
return this;
}
BundleBuilder setConfigurationPid(String configurationPid) {
if (configurationPid != null) {
this.configurationPid = configurationPid;
}
return this;
}
BundleBuilder setUri(String uri) {
if (uri != null) {
this.uri = uri;
}
return this;
}
BundleBuilder setGroup(String group) {
if (group != null) {
this.group = group;
}
return this;
}
BundleBuilder setArtifact(String artifact) {
if (artifact != null) {
this.artifact = artifact;
}
return this;
}
BundleBuilder setArtifactPrefix(String artifactPrefix) {
if (artifactPrefix != null) {
this.artifactPrefix = artifactPrefix;
}
return this;
}
BundleBuilder setGroupPrefix(String groupPrefix) {
if (groupPrefix != null) {
this.groupPrefix = groupPrefix;
}
return this;
}
BundleBuilder setStartLevel(Integer startLevel) {
if (startLevel != null) {
this.startLevel = startLevel;
}
return this;
}
BundleBuilder addArtifactPrefix(String artifactPrefix) {
this.artifactPrefix = append(this.artifactPrefix, artifactPrefix);
return this;
}
BundleBuilder addGroupPrefix(String groupPrefix) {
this.groupPrefix = append(this.groupPrefix, groupPrefix);
return this;
}
BundleSpecification build() {
if (uri != null) {
return BundleSpecification.createFixed(URI.create(uri), startLevel, propertySet, globalProperties);
}
if (artifact == null) {
throw new IllegalStateException(this + " has no uri or artifact");
}
String group = groupPrefix == null
? notNil(this.group, "group")
: append(groupPrefix, this.group);
String artifact = artifactPrefix == null
? notNil(this.artifact, "artifact")
: append(artifactPrefix, this.artifact);
Coordinate coordinate = coordinate(group, artifact);
return BundleSpecification.create(repoUri(), coordinate,
startLevel, propertySet,
globalProperties, configurationPid);
}
BundleBuilder addPropertySet(PropertySet propertySet) {
this.propertySet = append(this.propertySet, propertySet);
return this;
}
BundleBuilder setStartLevel(BigInteger startLevel) {
if (startLevel != null) {
this.startLevel = startLevel.intValue();
}
return this;
}
BundleBuilder setGlobalProperties(Boolean globalProperties) {
if (globalProperties != null) {
this.globalProperties = globalProperties;
}
return this;
}
BundleBuilder setPropertySet(PropertySet propertySet) {
if (propertySet != null) {
this.propertySet = propertySet;
}
return this;
}
private Coordinate coordinate(String group, String artifact) {
return this.version == null
? Coordinate.unversioned(group, artifact)
: Coordinate.versioned(group, artifact, new Version(this.version));
}
private URI repoUri() {
return repo == null ? null : URI.create(repo);
}
private <T> T notNil(T t, String what) {
if (t == null) {
throw new IllegalStateException(this + " missing " + what);
}
return t;
}
private static String append(String current, String addition) {
return addition == null || addition.trim().isEmpty() ? current
: current == null ? addition
: sensiblyAppended(current, addition);
}
private static String sensiblyAppended(String current, String addition) {
boolean leftEnd = current.endsWith(DOT);
boolean rightEnd = addition.startsWith(DOT);
return leftEnd && rightEnd ? current + addition.substring(1)
: leftEnd || rightEnd ? current + addition
: current + DOT + addition;
}
private static PropertySet append(PropertySet current, PropertySet addition) {
return addition == null || addition.isEmpty() ? current
: current == null ? addition
: current.with(addition);
}
@Override
public String toString() {
return ToString.of(this, "group", group,
"artifact", artifact,
"version", version,
"artifactPrefix", artifactPrefix,
"groupPrefix", groupPrefix,
"startLevel", startLevel,
"globalProperties", globalProperties,
"propertySet", propertySet);
}
}
|
package com.suresh.learnings.twentyseventeen.april;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class CSVFileParser {
private static final String CSV_FILE_PATH = "/Downloads/nsccl_ann19.csv";
public static void main(String[] args) {
List<Security> secList = readContentsFromCsv();
System.out.println("secList ->" + secList);
}
private static List<Security> readContentsFromCsv() {
BufferedReader br = null;
List<Security> securityList = new ArrayList<Security>(10);
Path pathToFile = Paths.get(CSV_FILE_PATH);
try {
br = Files.newBufferedReader(pathToFile, StandardCharsets.ISO_8859_1);
String line = br.readLine();
String[] attributes = null;
while (line != null) {
attributes = line.split(",");
Security sec = createSecurity(attributes);
securityList.add(sec);
line = br.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
return securityList;
}
private static Security createSecurity(String[] attributes) {
Security sec = new Security();
sec.setSymbol(attributes[1]);
sec.setSecurityName(attributes[3]);
sec.setIsActive(true);
sec.setExchange("NSE");
return sec;
}
}
|
package com.sunproservices.GUI;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.security.KeyStore;
import java.security.KeyStore.PasswordProtection;
import javax.security.auth.DestroyFailedException;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import javax.swing.border.EmptyBorder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.security.core.Authentication;
import com.jgoodies.forms.factories.DefaultComponentFactory;
import com.sunproservices.Sunpro.Security;
import com.sunproservices.Sunpro.SunproUser;
/**
* @version SignIn-0.2.2
*/
public class Signin extends JDialog {
private static final long serialVersionUID = 22L;
private static SunproUser user;
private static String userName = "";
private static KeyStore.PasswordProtection password;
private final ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] { "com/sunproservices/Sunpro/Security.xml" });
private Security security;
private Authentication authentication;
final static Logger logger = LoggerFactory.getLogger(Signin.class);
/**
* Launch the application.
*/
// public static void main(String[] args) {
// try {
// Signin dialog = new Signin();
// dialog.setVisible(true);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// public static void createSignin(){
// Signin frame = new Signin();
// / frame.setVisible(true);
// }
private JPanel layout;
private JPasswordField passwordField;
private JTextField tfUserName;
private JLabel lblInvalidLogin;
/**
* Create the frame.
*/
public Signin() {
security = (Security) context.getBean("LDAP");
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
if (!attemptLogin()) System.exit(0);
super.windowClosing(e);
}
});
setResizable(false);
setPreferredSize(new Dimension(500, 250));
setName("fsignin");
setMinimumSize(new Dimension(250, 100));
setMaximumSize(new Dimension(500, 250));
setType(Type.POPUP);
setTitle("Sign in");
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setAutoRequestFocus(true);
// setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 500, 240);
setAlwaysOnTop(true);
layout = new JPanel();
JPanel signinHeader = new JPanel();
JPanel signinFields = new JPanel();
JLabel lblEmployeeSignin = DefaultComponentFactory.getInstance().createTitle("EMPLOYEE SIGNIN");
JLabel lblNote = new JLabel("Note that all fields are case sensitive");
JLabel lblUserName = new JLabel("User Name");
JLabel lblPassword = new JLabel("Password");
lblInvalidLogin = new JLabel("Invalid Name or Password entered");
JButton btnSignIn = new JButton("SIGN IN");
// btnSignIn.setMnemonic(KeyEvent.VK_ENTER);
lblInvalidLogin.setVisible(false);
KeyAdapter keyAdapter = new KeyAdapter() {
@Override public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) attemptLogin();
}
};
tfUserName = new JTextField();
passwordField = new JPasswordField();
tfUserName.addKeyListener(keyAdapter);
passwordField.addKeyListener(keyAdapter);
btnSignIn.setActionCommand("sign in");
btnSignIn.addActionListener(new ActionListener() {
@Override public void actionPerformed(ActionEvent arg0) {
attemptLogin();
}
});
layout.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(layout);
layout.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
signinHeader.setLayout(new GridLayout(2, 1, 0, 0));
signinFields.setLayout(new GridLayout(2, 3, 5, 0));
signinHeader.add(lblEmployeeSignin);
signinHeader.add(lblNote);
lblEmployeeSignin.setFont(new Font("Calibri", lblEmployeeSignin.getFont().getStyle(), 30));
lblNote.setFont(new Font("Calibri", lblNote.getFont().getStyle(), 16));
lblEmployeeSignin.setHorizontalAlignment(SwingConstants.CENTER);
lblNote.setHorizontalAlignment(SwingConstants.CENTER);
lblUserName.setHorizontalAlignment(SwingConstants.CENTER);
lblPassword.setHorizontalAlignment(SwingConstants.CENTER);
signinFields.add(lblUserName);
signinFields.add(lblPassword);
lblUserName.setFont(new Font("Calibri", lblUserName.getFont().getStyle(), 16));
lblPassword.setFont(new Font("Calibri", lblPassword.getFont().getStyle(), 16));
lblInvalidLogin.setFont(new Font("Calibri", lblInvalidLogin.getFont().getStyle() | Font.BOLD, 16));
lblInvalidLogin.setForeground(Color.RED);
lblUserName.setLabelFor(tfUserName);
lblPassword.setLabelFor(passwordField);
tfUserName.setColumns(10);
passwordField.setColumns(10);
signinFields.add(tfUserName);
signinFields.add(passwordField);
Component horizontalStrut = Box.createHorizontalStrut(20);
btnSignIn.setFont(new Font("Calibri", btnSignIn.getFont().getStyle(), 18));
layout.add(signinHeader);
layout.add(signinFields);
layout.add(horizontalStrut);
layout.add(btnSignIn);
layout.add(lblInvalidLogin);
}
private boolean attemptLogin() {
// userName = tfUserName.getText().toString();
userName = "cstewart";
// password = new PasswordProtection(passwordField.getPassword());
password = new PasswordProtection("zxc.....".toCharArray());
authentication = security.authenticate(userName, password);
if (authentication.isAuthenticated()) {
lblInvalidLogin.setVisible(false);
// Resets the fields so no more data can be pulled
passwordField = new JPasswordField();
tfUserName = new JTextField();
dispose();
// setVisible(false);
return true;
} else lblInvalidLogin.setVisible(true);
return false;
}
public static String getFirstName() {
return userName;
}
public static KeyStore.PasswordProtection getPassword() {
return password;
}
/**
* @deprecated since SignIn-0.2.2.
* replaced getUser()
* @return
*/
public SunproUser getLoginInformation() {
SunproUser.Essence empl = null ;
try {
empl= new SunproUser().new Essence();}
catch(Exception e) {
logger.error("Error has Occured while trying to create new Instance of SunproUser.Essence");
}
empl.setUsername(userName);
empl.setPassword(password.getPassword().toString());
//empl.grabInformation();
return empl.createUserDetails();
}
/**
* @since SignIn-0.2.2
* @return SunproUser that has been authenticated
*/
public SunproUser getUser() {
return (SunproUser) authentication.getPrincipal();
}
public void clearData() {
userName = "";
try {
password.destroy();
} catch (DestroyFailedException e) {
e.printStackTrace();
}
}
}
|
/**
* DNet eBusiness Suite
* Copyright: 2010-2013 Nan21 Electronics SRL. All rights reserved.
* Use is subject to license terms.
*/
package net.nan21.dnet.module.bd.business.api.uom;
import java.util.List;
import net.nan21.dnet.core.api.service.business.IEntityService;
import net.nan21.dnet.module.bd.domain.impl.uom.Uom;
import net.nan21.dnet.module.bd.domain.impl.uom.UomType;
/**
* Interface to expose business functions specific for {@link Uom} domain
* entity.
*/
public interface IUomService extends IEntityService<Uom> {
/**
* Find by unique key
*/
public Uom findByCode(String code);
/**
* Find by unique key
*/
public Uom findByName(String name);
/**
* Find by reference: type
*/
public List<Uom> findByType(UomType type);
/**
* Find by ID of reference: type.id
*/
public List<Uom> findByTypeId(String typeId);
}
|
package tw.skyarrow.ehreader.app.pref;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import tw.skyarrow.ehreader.R;
/**
* Created by SkyArrow on 2014/2/17.
*/
public class CheckUpdateErrorDialog extends DialogFragment {
public static final String TAG = "CheckUpdateErrorDialog";
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
dialog.setTitle(R.string.check_update_failed_title)
.setMessage(R.string.check_update_failed_msg)
.setPositiveButton(R.string.retry, onSubmitClick)
.setNegativeButton(R.string.cancel, null);
return dialog.create();
}
private DialogInterface.OnClickListener onSubmitClick = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
DialogFragment dialog = new CheckUpdateDialog();
dialog.show(getActivity().getSupportFragmentManager(), CheckUpdateDialog.TAG);
}
};
}
|
/*
* Copyright 2008 Kjetil Valstadsve
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package vanadis.lang.piji;
/**
* A runtime exception subclass for signalling <EM>to the developer</EM>
* that an error must be corrected. Should not be used to signal runtime
* errors attributable to user behaviour, but rather system discrepancies.
*
* @author Kjetil Valstadsve
*/
public class InternalRuntimeException extends PijiRuntimeException {
private static final long serialVersionUID = -700250451036239124L;
public InternalRuntimeException(String message) {
this(message, null);
}
public InternalRuntimeException(String message, Throwable t) {
super(message, t);
}
public InternalRuntimeException(Throwable t) {
this(t.getMessage(), t);
}
}
|
// Generated from /shared/YandexDisk/ITMO/year2019/parsers/FormatKotlin/src/main/kotlin/SimpleFunction.g4 by ANTLR 4.7.2
import org.antlr.v4.runtime.Lexer;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.TokenStream;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.atn.*;
import org.antlr.v4.runtime.dfa.DFA;
import org.antlr.v4.runtime.misc.*;
@SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"})
public class SimpleFunctionLexer extends Lexer {
static { RuntimeMetaData.checkVersion("4.7.2", RuntimeMetaData.VERSION); }
protected static final DFA[] _decisionToDFA;
protected static final PredictionContextCache _sharedContextCache =
new PredictionContextCache();
public static final int
T__0=1, T__1=2, NOT=3, COMMA=4, COLON=5, LBRACKET=6, RBRACKET=7, CURLY_LBRACKET=8,
CURLY_RBRACKET=9, EQUAL=10, VARIABLE_TYPE=11, LOGICAL_VALUE=12, LOGICAL_OPERATOR=13,
OPERATOR=14, TYPE=15, FUN=16, FOR=17, ELSE=18, IN=19, IF=20, WHILE=21,
DO=22, PRINT_FUN=23, RETURN=24, NAME=25, NUMBER=26, STR=27, EPS=28, WS=29,
NEWLINE=30;
public static String[] channelNames = {
"DEFAULT_TOKEN_CHANNEL", "HIDDEN"
};
public static String[] modeNames = {
"DEFAULT_MODE"
};
private static String[] makeRuleNames() {
return new String[] {
"T__0", "T__1", "NOT", "COMMA", "COLON", "LBRACKET", "RBRACKET", "CURLY_LBRACKET",
"CURLY_RBRACKET", "EQUAL", "VARIABLE_TYPE", "LOGICAL_VALUE", "LOGICAL_OPERATOR",
"OPERATOR", "TYPE", "FUN", "FOR", "ELSE", "IN", "IF", "WHILE", "DO",
"PRINT_FUN", "RETURN", "NAME", "NUMBER", "STR", "EPS", "WS", "NEWLINE"
};
}
public static final String[] ruleNames = makeRuleNames();
private static String[] makeLiteralNames() {
return new String[] {
null, "'+='", "'-='", "'!'", "','", "':'", "'('", "')'", "'{'", "'}'",
"'='", null, null, null, null, null, "'fun'", "'for'", "'else'", "'in'",
"'if'", "'while'", "'do'", null, "'return'"
};
}
private static final String[] _LITERAL_NAMES = makeLiteralNames();
private static String[] makeSymbolicNames() {
return new String[] {
null, null, null, "NOT", "COMMA", "COLON", "LBRACKET", "RBRACKET", "CURLY_LBRACKET",
"CURLY_RBRACKET", "EQUAL", "VARIABLE_TYPE", "LOGICAL_VALUE", "LOGICAL_OPERATOR",
"OPERATOR", "TYPE", "FUN", "FOR", "ELSE", "IN", "IF", "WHILE", "DO",
"PRINT_FUN", "RETURN", "NAME", "NUMBER", "STR", "EPS", "WS", "NEWLINE"
};
}
private static final String[] _SYMBOLIC_NAMES = makeSymbolicNames();
public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES);
/**
* @deprecated Use {@link #VOCABULARY} instead.
*/
@Deprecated
public static final String[] tokenNames;
static {
tokenNames = new String[_SYMBOLIC_NAMES.length];
for (int i = 0; i < tokenNames.length; i++) {
tokenNames[i] = VOCABULARY.getLiteralName(i);
if (tokenNames[i] == null) {
tokenNames[i] = VOCABULARY.getSymbolicName(i);
}
if (tokenNames[i] == null) {
tokenNames[i] = "<INVALID>";
}
}
}
@Override
@Deprecated
public String[] getTokenNames() {
return tokenNames;
}
@Override
public Vocabulary getVocabulary() {
return VOCABULARY;
}
public SimpleFunctionLexer(CharStream input) {
super(input);
_interp = new LexerATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache);
}
@Override
public String getGrammarFileName() { return "SimpleFunction.g4"; }
@Override
public String[] getRuleNames() { return ruleNames; }
@Override
public String getSerializedATN() { return _serializedATN; }
@Override
public String[] getChannelNames() { return channelNames; }
@Override
public String[] getModeNames() { return modeNames; }
@Override
public ATN getATN() { return _ATN; }
public static final String _serializedATN =
"\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2 \u00ec\b\1\4\2\t"+
"\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13"+
"\t\13\4\f\t\f\4\r\t\r\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22"+
"\4\23\t\23\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4\30\t\30\4\31\t\31"+
"\4\32\t\32\4\33\t\33\4\34\t\34\4\35\t\35\4\36\t\36\4\37\t\37\3\2\3\2\3"+
"\2\3\3\3\3\3\3\3\4\3\4\3\5\3\5\3\6\3\6\3\7\3\7\3\b\3\b\3\t\3\t\3\n\3\n"+
"\3\13\3\13\3\f\3\f\3\f\3\f\3\f\3\f\5\f\\\n\f\3\r\3\r\3\r\3\r\3\r\3\r\3"+
"\r\3\r\3\r\5\rg\n\r\3\16\3\16\3\16\3\16\5\16m\n\16\3\17\3\17\3\20\3\20"+
"\3\20\3\20\3\20\3\20\3\20\3\20\3\20\3\20\3\20\3\20\3\20\3\20\3\20\3\20"+
"\3\20\3\20\3\20\3\20\3\20\3\20\3\20\3\20\3\20\3\20\3\20\3\20\3\20\3\20"+
"\3\20\3\20\3\20\5\20\u0092\n\20\3\21\3\21\3\21\3\21\3\22\3\22\3\22\3\22"+
"\3\23\3\23\3\23\3\23\3\23\3\24\3\24\3\24\3\25\3\25\3\25\3\26\3\26\3\26"+
"\3\26\3\26\3\26\3\27\3\27\3\27\3\30\3\30\3\30\3\30\3\30\3\30\3\30\3\30"+
"\3\30\3\30\3\30\3\30\5\30\u00bc\n\30\3\31\3\31\3\31\3\31\3\31\3\31\3\31"+
"\3\32\3\32\7\32\u00c7\n\32\f\32\16\32\u00ca\13\32\3\33\3\33\3\33\7\33"+
"\u00cf\n\33\f\33\16\33\u00d2\13\33\5\33\u00d4\n\33\3\34\3\34\7\34\u00d8"+
"\n\34\f\34\16\34\u00db\13\34\3\34\3\34\3\35\3\35\3\36\6\36\u00e2\n\36"+
"\r\36\16\36\u00e3\3\36\3\36\3\37\6\37\u00e9\n\37\r\37\16\37\u00ea\2\2"+
" \3\3\5\4\7\5\t\6\13\7\r\b\17\t\21\n\23\13\25\f\27\r\31\16\33\17\35\20"+
"\37\21!\22#\23%\24\'\25)\26+\27-\30/\31\61\32\63\33\65\34\67\359\36;\37"+
"= \3\2\t\5\2,-//\61\61\3\2c|\5\2\62;C\\c|\3\2\63;\3\2\62;\4\2$$^^\5\2"+
"\13\13\17\17\"\"\2\u00fb\2\3\3\2\2\2\2\5\3\2\2\2\2\7\3\2\2\2\2\t\3\2\2"+
"\2\2\13\3\2\2\2\2\r\3\2\2\2\2\17\3\2\2\2\2\21\3\2\2\2\2\23\3\2\2\2\2\25"+
"\3\2\2\2\2\27\3\2\2\2\2\31\3\2\2\2\2\33\3\2\2\2\2\35\3\2\2\2\2\37\3\2"+
"\2\2\2!\3\2\2\2\2#\3\2\2\2\2%\3\2\2\2\2\'\3\2\2\2\2)\3\2\2\2\2+\3\2\2"+
"\2\2-\3\2\2\2\2/\3\2\2\2\2\61\3\2\2\2\2\63\3\2\2\2\2\65\3\2\2\2\2\67\3"+
"\2\2\2\29\3\2\2\2\2;\3\2\2\2\2=\3\2\2\2\3?\3\2\2\2\5B\3\2\2\2\7E\3\2\2"+
"\2\tG\3\2\2\2\13I\3\2\2\2\rK\3\2\2\2\17M\3\2\2\2\21O\3\2\2\2\23Q\3\2\2"+
"\2\25S\3\2\2\2\27[\3\2\2\2\31f\3\2\2\2\33l\3\2\2\2\35n\3\2\2\2\37\u0091"+
"\3\2\2\2!\u0093\3\2\2\2#\u0097\3\2\2\2%\u009b\3\2\2\2\'\u00a0\3\2\2\2"+
")\u00a3\3\2\2\2+\u00a6\3\2\2\2-\u00ac\3\2\2\2/\u00bb\3\2\2\2\61\u00bd"+
"\3\2\2\2\63\u00c4\3\2\2\2\65\u00d3\3\2\2\2\67\u00d5\3\2\2\29\u00de\3\2"+
"\2\2;\u00e1\3\2\2\2=\u00e8\3\2\2\2?@\7-\2\2@A\7?\2\2A\4\3\2\2\2BC\7/\2"+
"\2CD\7?\2\2D\6\3\2\2\2EF\7#\2\2F\b\3\2\2\2GH\7.\2\2H\n\3\2\2\2IJ\7<\2"+
"\2J\f\3\2\2\2KL\7*\2\2L\16\3\2\2\2MN\7+\2\2N\20\3\2\2\2OP\7}\2\2P\22\3"+
"\2\2\2QR\7\177\2\2R\24\3\2\2\2ST\7?\2\2T\26\3\2\2\2UV\7x\2\2VW\7c\2\2"+
"W\\\7n\2\2XY\7x\2\2YZ\7c\2\2Z\\\7t\2\2[U\3\2\2\2[X\3\2\2\2\\\30\3\2\2"+
"\2]^\7v\2\2^_\7t\2\2_`\7w\2\2`g\7g\2\2ab\7h\2\2bc\7c\2\2cd\7n\2\2de\7"+
"u\2\2eg\7g\2\2f]\3\2\2\2fa\3\2\2\2g\32\3\2\2\2hi\7~\2\2im\7~\2\2jk\7("+
"\2\2km\7(\2\2lh\3\2\2\2lj\3\2\2\2m\34\3\2\2\2no\t\2\2\2o\36\3\2\2\2pq"+
"\7D\2\2qr\7{\2\2rs\7v\2\2s\u0092\7g\2\2tu\7U\2\2uv\7j\2\2vw\7q\2\2wx\7"+
"t\2\2x\u0092\7v\2\2yz\7K\2\2z{\7p\2\2{\u0092\7v\2\2|}\7N\2\2}~\7q\2\2"+
"~\177\7p\2\2\177\u0092\7i\2\2\u0080\u0081\7E\2\2\u0081\u0082\7j\2\2\u0082"+
"\u0083\7c\2\2\u0083\u0092\7t\2\2\u0084\u0085\7U\2\2\u0085\u0086\7v\2\2"+
"\u0086\u0087\7t\2\2\u0087\u0088\7k\2\2\u0088\u0089\7p\2\2\u0089\u0092"+
"\7i\2\2\u008a\u008b\7D\2\2\u008b\u008c\7q\2\2\u008c\u008d\7q\2\2\u008d"+
"\u008e\7n\2\2\u008e\u008f\7g\2\2\u008f\u0090\7c\2\2\u0090\u0092\7p\2\2"+
"\u0091p\3\2\2\2\u0091t\3\2\2\2\u0091y\3\2\2\2\u0091|\3\2\2\2\u0091\u0080"+
"\3\2\2\2\u0091\u0084\3\2\2\2\u0091\u008a\3\2\2\2\u0092 \3\2\2\2\u0093"+
"\u0094\7h\2\2\u0094\u0095\7w\2\2\u0095\u0096\7p\2\2\u0096\"\3\2\2\2\u0097"+
"\u0098\7h\2\2\u0098\u0099\7q\2\2\u0099\u009a\7t\2\2\u009a$\3\2\2\2\u009b"+
"\u009c\7g\2\2\u009c\u009d\7n\2\2\u009d\u009e\7u\2\2\u009e\u009f\7g\2\2"+
"\u009f&\3\2\2\2\u00a0\u00a1\7k\2\2\u00a1\u00a2\7p\2\2\u00a2(\3\2\2\2\u00a3"+
"\u00a4\7k\2\2\u00a4\u00a5\7h\2\2\u00a5*\3\2\2\2\u00a6\u00a7\7y\2\2\u00a7"+
"\u00a8\7j\2\2\u00a8\u00a9\7k\2\2\u00a9\u00aa\7n\2\2\u00aa\u00ab\7g\2\2"+
"\u00ab,\3\2\2\2\u00ac\u00ad\7f\2\2\u00ad\u00ae\7q\2\2\u00ae.\3\2\2\2\u00af"+
"\u00b0\7r\2\2\u00b0\u00b1\7t\2\2\u00b1\u00b2\7k\2\2\u00b2\u00b3\7p\2\2"+
"\u00b3\u00bc\7v\2\2\u00b4\u00b5\7r\2\2\u00b5\u00b6\7t\2\2\u00b6\u00b7"+
"\7k\2\2\u00b7\u00b8\7p\2\2\u00b8\u00b9\7v\2\2\u00b9\u00ba\7n\2\2\u00ba"+
"\u00bc\7p\2\2\u00bb\u00af\3\2\2\2\u00bb\u00b4\3\2\2\2\u00bc\60\3\2\2\2"+
"\u00bd\u00be\7t\2\2\u00be\u00bf\7g\2\2\u00bf\u00c0\7v\2\2\u00c0\u00c1"+
"\7w\2\2\u00c1\u00c2\7t\2\2\u00c2\u00c3\7p\2\2\u00c3\62\3\2\2\2\u00c4\u00c8"+
"\t\3\2\2\u00c5\u00c7\t\4\2\2\u00c6\u00c5\3\2\2\2\u00c7\u00ca\3\2\2\2\u00c8"+
"\u00c6\3\2\2\2\u00c8\u00c9\3\2\2\2\u00c9\64\3\2\2\2\u00ca\u00c8\3\2\2"+
"\2\u00cb\u00d4\7\62\2\2\u00cc\u00d0\t\5\2\2\u00cd\u00cf\t\6\2\2\u00ce"+
"\u00cd\3\2\2\2\u00cf\u00d2\3\2\2\2\u00d0\u00ce\3\2\2\2\u00d0\u00d1\3\2"+
"\2\2\u00d1\u00d4\3\2\2\2\u00d2\u00d0\3\2\2\2\u00d3\u00cb\3\2\2\2\u00d3"+
"\u00cc\3\2\2\2\u00d4\66\3\2\2\2\u00d5\u00d9\7$\2\2\u00d6\u00d8\n\7\2\2"+
"\u00d7\u00d6\3\2\2\2\u00d8\u00db\3\2\2\2\u00d9\u00d7\3\2\2\2\u00d9\u00da"+
"\3\2\2\2\u00da\u00dc\3\2\2\2\u00db\u00d9\3\2\2\2\u00dc\u00dd\7$\2\2\u00dd"+
"8\3\2\2\2\u00de\u00df\3\2\2\2\u00df:\3\2\2\2\u00e0\u00e2\t\b\2\2\u00e1"+
"\u00e0\3\2\2\2\u00e2\u00e3\3\2\2\2\u00e3\u00e1\3\2\2\2\u00e3\u00e4\3\2"+
"\2\2\u00e4\u00e5\3\2\2\2\u00e5\u00e6\b\36\2\2\u00e6<\3\2\2\2\u00e7\u00e9"+
"\7\f\2\2\u00e8\u00e7\3\2\2\2\u00e9\u00ea\3\2\2\2\u00ea\u00e8\3\2\2\2\u00ea"+
"\u00eb\3\2\2\2\u00eb>\3\2\2\2\16\2[fl\u0091\u00bb\u00c8\u00d0\u00d3\u00d9"+
"\u00e3\u00ea\3\b\2\2";
public static final ATN _ATN =
new ATNDeserializer().deserialize(_serializedATN.toCharArray());
static {
_decisionToDFA = new DFA[_ATN.getNumberOfDecisions()];
for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) {
_decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i);
}
}
}
|
/**
*
*/
package excepciones;
/**
* @author susana
*
*/
@SuppressWarnings("serial")
public class ErrorPrioridadIncorrecta extends Exception {
/**
*
*/
public ErrorPrioridadIncorrecta() {
// TODO Auto-generated constructor stub
}
/**
* @param message
*/
public ErrorPrioridadIncorrecta(String message) {
super(message);
// TODO Auto-generated constructor stub
}
/**
* @param cause
*/
public ErrorPrioridadIncorrecta(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
/**
* @param message
* @param cause
*/
public ErrorPrioridadIncorrecta(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
}
|
package com.commercetools.pspadapter.payone.transaction;
import com.commercetools.pspadapter.payone.domain.ctp.CustomTypeBuilder;
import com.commercetools.pspadapter.payone.domain.ctp.PaymentWithCartLike;
import com.commercetools.pspadapter.payone.mapping.CustomFieldKeys;
import com.github.benmanes.caffeine.cache.LoadingCache;
import io.sphere.sdk.payments.Transaction;
import io.sphere.sdk.payments.TransactionType;
import io.sphere.sdk.types.CustomFields;
import io.sphere.sdk.types.Type;
import org.apache.commons.lang3.StringUtils;
import javax.annotation.Nonnull;
import java.util.Arrays;
import java.util.function.Predicate;
import java.util.stream.IntStream;
import java.util.stream.Stream;
/**
* Idempotently executes a Transaction of one Type (e.g. Charge) for a specific PaymentWithCartLike Method.
* <p>
* If no Transaction of that type in State Pending exists, the same PaymentWithCartLike is returned.
*/
public abstract class IdempotentTransactionExecutor implements TransactionExecutor {
private LoadingCache<String, Type> typeCache;
public IdempotentTransactionExecutor(@Nonnull final LoadingCache<String, Type> typeCache) {
this.typeCache = typeCache;
}
/**
* @return The Type that is supported.
*/
@Nonnull
public abstract TransactionType supportedTransactionType();
/**
* Executes a transaction idempotently.
*
* @param paymentWithCartLike payment/cart, for which transaction is executed
* @param transaction transaction to execute
* @return A new version of the PaymentWithCartLike.
*/
@Override
@Nonnull
public PaymentWithCartLike executeTransaction(@Nonnull PaymentWithCartLike paymentWithCartLike,
@Nonnull Transaction transaction) {
if (transaction.getType() != supportedTransactionType()) {
throw new IllegalArgumentException("Unsupported Transaction Type");
}
if (wasExecuted(paymentWithCartLike, transaction)) {
return paymentWithCartLike;
}
return executeIdempotent(paymentWithCartLike, transaction);
}
/**
* Whether the transaction was executed and nothing else can be done by the executor.
*
* @param paymentWithCartLike payment/cart, which has to be verified
* @param transaction transaction from {@code paymentWithCartLike}, which has to be verified
* @return <b>true</b> if transaction has been already executed
*/
protected abstract boolean wasExecuted(PaymentWithCartLike paymentWithCartLike, Transaction transaction);
/**
* Tries to execute the transaction for the first time.
* To ensure Idempotency, an InterfaceInteraction is first added to the PaymentWithCartLike that can be found later.
*
* @param paymentWithCartLike
* @param transaction
* @return A new version of the PaymentWithCartLike. If the attempt has concluded, the state of the Transaction is now either Success or Failure.
*/
protected abstract PaymentWithCartLike executeIdempotent(PaymentWithCartLike paymentWithCartLike, Transaction transaction);
/**
* Determines the next sequence number to use from already received notifications.
*
* @param paymentWithCartLike the payment with cart/order to search in
* @return 0 if no notifications received yet, else the highest sequence number received + 1
*/
protected int getNextSequenceNumber(final PaymentWithCartLike paymentWithCartLike) {
Predicate<String> isInteger = (i) -> i != null && i.matches("-?[0-9]+");
return IntStream.concat(
getCustomFieldsOfType(paymentWithCartLike, CustomTypeBuilder.PAYONE_INTERACTION_NOTIFICATION)
.map(f -> f.getFieldAsString(CustomFieldKeys.SEQUENCE_NUMBER_FIELD))
.filter(isInteger)
.mapToInt(Integer::parseInt),
paymentWithCartLike
.getPayment()
.getTransactions()
.stream()
.map(t -> StringUtils.trim(t.getInteractionId()))
.filter(isInteger)
.mapToInt(Integer::parseInt)
)
.map(i -> i + 1)
.max()
.orElse(0);
}
protected Stream<CustomFields> getCustomFieldsOfType(PaymentWithCartLike paymentWithCartLike, String... typeKeys) {
return paymentWithCartLike
.getPayment()
.getInterfaceInteractions()
.stream()
.filter(i -> Arrays.stream(typeKeys)
.map(t -> getTypeCache().get(t).toReference())
.anyMatch(t -> t.getId().equals(i.getType().getId())));
}
private LoadingCache<String, Type> getTypeCache() {
return this.typeCache;
}
}
|
package gdut.ff.gecco;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.geccocrawler.gecco.annotation.PipelineName;
import com.geccocrawler.gecco.pipeline.Pipeline;
import gdut.ff.utils.Constant;
import gdut.ff.utils.NodeUtil;
/**
*
* @author liuffei
* @date 2017-01-31
*/
@PipelineName("cnblogsPipeline")
public class CnblogsPipeline implements Pipeline<CnblogsBeanList> {
@Autowired
private Constant constant;
@Override
public void process(CnblogsBeanList beanList) {
List<CnblogsBean> blogs = beanList.getBeanList();
if(null != blogs && blogs.size() > 0) {
constant.cnblogsNodes.addAll(NodeUtil.transFromList(blogs));
for(int i = 0;i < blogs.size();i++) {
CnblogsBean blog = blogs.get(i);
System.out.println("url:"+blog.getUrl()+"->title:"+blog.getTitle());
}
}
}
}
|
package com.ryit.service.impl;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ryit.entity.Plot;
import com.ryit.mapper.PlotMapper;
import com.ryit.service.PlotService;
import com.ryit.utils.UserSession;
@Service
public class PlotServiceImp implements PlotService{
@Autowired
private PlotMapper plotMapper;
/**
* 增加小区信息
* @param Building bu
* @return
*/
public String addPlot(Plot p) {
String msg="2";
boolean boo = false;
String userName = UserSession.getAdminUser().getLoginName();
if(p.getPname()=="" || p.getAddress()=="" || p.getDescription()==""){
msg = "0";
}else{
List<Plot> list = selectAll();
if(list.size() == 0){
if(userName != null){
p.setCreated_user(userName);
p.setCreated_datetime(new Date());
p.setUpdated_user(userName);
p.setUpdated_datetime(new Date());
plotMapper.addPlot(p);
msg = "1";
}
}else{
for(Plot pt : list){
if(pt.getPname().equals(p.getPname()) & p.getAddress().equals(pt.getAddress())){
boo = true;
}
}
if(boo){
msg = "2";
}else{
if(userName != null){
p.setCreated_user(userName);
p.setCreated_datetime(new Date());
p.setUpdated_user(userName);
p.setUpdated_datetime(new Date());
plotMapper.addPlot(p);
msg = "1";
}else{
msg="3";
}
}
}
}
return msg;
}
public String delPlot(int id) {
String msg="false";
List<Plot> list = selectAll();
for(Plot p : list){
if(p.getId() == id){
msg = "true";
plotMapper.deletePlot(id);
break;
}
}
return msg;
}
/**
* 此方法用于查询 小区所有信息
* @param String pname
* @return List<Plot>
*/
public List<Plot> selectAll() {
return plotMapper.selectAll();
}
/**
* 此方法用于通过指定的条件查询小区名称
* @param String pname
* @return List<Plot>
*/
public List<Plot> findPname(String pname){
List<Plot> li = plotMapper.findPname(pname);
return li;
}
/**
* 指定修改小区的信息
* @param Plot p
* @return
*/
public String updatePlot(Plot p) {
String msg="2";
if(p.getPname()=="" || p.getAddress()=="" || p.getDescription()==""){
msg = "0";
}else{
boolean boo = false;
List<Plot> list = selectAll();
for(Plot pt : list){
if(p.getId() != pt.getId() & p.getPname().equals(pt.getPname()) & p.getAddress().equals(pt.getAddress())){
boo = true;
}
}
if(!boo){
String userName = UserSession.getAdminUser().getLoginName();
if(userName != null){
p.setUpdated_user(userName);
p.setUpdated_datetime(new Date());
plotMapper.updatePlot(p);
msg = "1";
}else{
msg = "3";
}
}
}
return msg;
}
}
|
package kodlamaio.hrms.core.utilities.annotations;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.springframework.beans.factory.annotation.Autowired;
import kodlamaio.hrms.dataAccess.abstracts.CandidateDao;
import kodlamaio.hrms.entities.concreates.Candidate;
public class UniqueIdentificationNumberValidator implements ConstraintValidator<UniqueIdentificationNumber, String> {
@Autowired
CandidateDao candidateDao;
@Override
public boolean isValid(String identificationNumber, ConstraintValidatorContext context) {
Candidate candidate = this.candidateDao.findByIdentificationNumber(identificationNumber);
if(candidate != null) {
return false;
}
return true;
}
}
|
package maximum.flow.graphics;
import maximum.flow.entity.Node;
import maximum.flow.entity.Coordinat;
import java.awt.Color;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.HashMap;
import maximum.flow.GraphUtils;
/**
*
* @author asus
*/
public class GraphGraphic extends javax.swing.JFrame {
private int nodeDistance;
public GraphGraphic() {
initComponents();
}
public void setWidthAndHeight(){
}
@Override
public void paint(Graphics g) {
nodeDistance = GraphUtils.nodes.size()*30;
setWidthAndHeight();//Düğüm sayısına göre ekran büyüklüğünün ayarlanması için.
try{
g.setColor(new Color(0,85,0));
g.fillRect(0, 0, getWidth(), getHeight());
paintNodes(g,GraphUtils.sourceNode,new ArrayList<>(),100,getHeight()/2,nodeDistance);
paintRelations(g,GraphUtils.sourceNode,new ArrayList<>());
}catch(Exception e){
}
//g.setColor(Color.red);
//g.fillOval(20, 50, 100, 100);
}
//Coordinat map
private HashMap<Node,Coordinat> coorMap = new HashMap<>();
public void paintNodes(Graphics g,Node tempRoot,ArrayList<Node> blackList, int x, int y, int nodeDistance){
blackList.add(tempRoot);
if(!coorMap.containsKey(tempRoot)){
if(tempRoot == GraphUtils.sourceNode)
drawNode(g,x,y,25,25,tempRoot.getLabel(),Color.black);
else
drawNode(g,x,y,25,25,tempRoot.getLabel(),Color.red);
coorMap.put(tempRoot, new Coordinat(x,y));
}
x += nodeDistance;
int count = 0;
for(Node node: tempRoot.getChildList())//temproot'un çizilmeyen düğümleri sayılıyor.
if(!coorMap.containsKey(node))
count++;
y -= ((count - 1)*nodeDistance)/2;//Düğümlerin nereden itibaren çizileceğini hesaplar.
for(Node node:tempRoot.getChildList())
if(!coorMap.containsKey(node)){
if(node == GraphUtils.targetNode)
drawNode(g,x,y,25,25,node.getLabel(),Color.black);
else
drawNode(g,x,y,25,25,node.getLabel(),Color.red);
coorMap.put(node, new Coordinat(x,y));
y += nodeDistance;
}
int meter = 0;
for(Node node: tempRoot.getChildList())//İlişkili olan her düğüm için eğer daha önce yapılmadıysa işlem tekrarlanıyor.
if(!blackList.contains(node)){
paintNodes(g,node,blackList,x+nodeDistance*meter++,getHeight()/2,nodeDistance);
}
}
public void drawNode(Graphics g,int x, int y,int width, int height,String label,Color color){
g.setColor(color);
g.fillOval(x, y, width, height);
g.setColor(Color.white);
g.drawString(label, x+width/2, y+height/2);
}
public void paintRelations(Graphics g,Node tempRoot,ArrayList<Node> blackList){
Coordinat coor = coorMap.get(tempRoot);
for(Node node:tempRoot.getChildList()){
String capacity = tempRoot.getLabel() + "-" + node.getLabel() + "/" + String.valueOf(tempRoot.getCapacitiesBackup().get(node)) + "-" + String.valueOf(tempRoot.getSpentCapacity(node));
drawLineBetweenNodes(g,coorMap.get(tempRoot),coorMap.get(node),capacity);
}
blackList.add(tempRoot);
for(Node node: tempRoot.getChildList())
if(!blackList.contains(node))
paintRelations(g,node,blackList);
}
public void drawLineBetweenNodes(Graphics g,Coordinat coor,Coordinat coor2,String capacity){
g.setColor(Color.black);
g.drawLine(coor.getX()+12, coor.getY()+12, coor2.getX()+ 12, coor2.getY()+12);
g.setColor(Color.white);
g.drawString(capacity, coor.getX()*2/3 + coor2.getX()*1/3 + 12 , coor.getY()*2/3 + coor2.getY()*1/3 + 12);
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 379, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 282, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(GraphGraphic.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GraphGraphic.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GraphGraphic.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GraphGraphic.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new GraphGraphic().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
}
|
/*
package com.lr.util;
import com.lr.mapper.testPaperMapper;
import com.lr.pojo.testpaper;
import org.apache.ibatis.session.SqlSession;
import org.springframework.context.ApplicationContext;
import java.util.ArrayList;
public class getSubjectType{
public static int[] getType(ArrayList<testpaper> list){
int [] arr=new int[list.size()];
for (int i=0;i<list.size();i++){
arr[i]=list.get(i).getSubjectType();
}
return arr;
}
public static void main(String [] args){
ApplicationContext ac=getApplication.getApp();
testPaperMapper mapper = ac.getBean(testPaperMapper.class);
testpaper t=new testpaper();
t.setTestPaperId("x100011");
ArrayList<testpaper> testpaper = mapper.findTestpaper(t);
int[] type = getType(testpaper);
for (int i : type){
System.out.println(i);
}
}
}
*/
|
package com.store.filter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import com.store.pojo.SysUser;
/**
* Servlet Filter implementation class login
*/
@WebFilter("/*")
public class loginfilter implements Filter {
/**
* Default constructor.
*/
public loginfilter() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
SysUser sysUser = (SysUser) httpServletRequest.getSession().getAttribute("user");
String path = httpServletRequest.getServletPath();
if (path.contains("/img.jpg")||path.contains("/page/login.jsp")||path.contains("/loginservlet")) {
chain.doFilter(request, response);
}else {
if (sysUser==null) {
httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/page/login.jsp");
return ;
}else {
chain.doFilter(request, response);
}
}
// pass the request along the filter chain
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
|
/*
* Copyright 2011 frdfsnlght <frdfsnlght@gmail.com>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.frdfsnlght.transporter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.frdfsnlght.transporter.api.LocalWorld;
import org.bukkit.World;
import org.bukkit.World.Environment;
import org.bukkit.WorldCreator;
/**
*
* @author frdfsnlght <frdfsnlght@gmail.com>
*/
public final class LocalWorldImpl implements OptionsListener, LocalWorld {
private static final Set<String> OPTIONS = new HashSet<String>();
static {
OPTIONS.add("environment");
OPTIONS.add("generator");
OPTIONS.add("seed");
OPTIONS.add("autoLoad");
}
public static boolean isValidName(String name) {
if (name.length() == 0) return false;
return ! (name.contains(".") || name.contains("*"));
}
private Options options = new Options(this, OPTIONS, "trp.world", this);
private String name;
private Environment environment;
private String generator;
private String seed;
private boolean autoLoad;
public LocalWorldImpl(String name, Environment environment, String generator, String seed) throws WorldException {
try {
setName(name);
setEnvironment(environment);
setGenerator(generator);
setSeed(seed);
autoLoad = true;
} catch (IllegalArgumentException e) {
throw new WorldException(e.getMessage());
}
}
public LocalWorldImpl(TypeMap map) throws WorldException {
try {
setName(map.getString("name"));
// try to convert old environment to new environment/generator
String envStr = map.getString("environment", "NORMAL");
if (envStr.equals("SKYLANDS")) envStr = "NORMAL";
try {
setEnvironment(Utils.valueOf(Environment.class, envStr));
} catch (IllegalArgumentException iae) {
throw new WorldException(iae.getMessage() + " environment");
}
setGenerator(map.getString("generator", null));
setSeed(map.getString("seed", null));
setAutoLoad(map.getBoolean("autoLoad", true));
} catch (IllegalArgumentException e) {
throw new WorldException(e.getMessage());
}
}
@Override
public String getName() {
return name;
}
private void setName(String name) {
if (name == null)
throw new IllegalArgumentException("name is required");
if (! isValidName(name))
throw new IllegalArgumentException("name is not valid");
this.name = name;
}
/* Begin options */
@Override
public Environment getEnvironment() {
return environment;
}
@Override
public void setEnvironment(Environment environment) {
if (environment == null) environment = Environment.NORMAL;
this.environment = environment;
}
/*
public String getEnvironment() {
return environment;
}
public void setEnvironment(String environment) {
if ((environment == null) ||
(environment.isEmpty() ||
environment.equals("-"))) environment = "NORMAL";
try {
environment = Utils.valueOf(Environment.class, environment).toString();
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("unknown or ambiguous environment");
}
this.environment = environment;
}
*/
@Override
public String getGenerator() {
return generator;
}
@Override
public void setGenerator(String generator) {
if ((generator != null) &&
(generator.isEmpty() || generator.equals("-"))) generator = null;
this.generator = generator;
}
@Override
public String getSeed() {
return seed;
}
@Override
public void setSeed(String seed) {
if ((seed != null) &&
(seed.isEmpty() || seed.equals("-"))) seed = null;
this.seed = seed;
}
@Override
public boolean getAutoLoad() {
return autoLoad;
}
@Override
public void setAutoLoad(boolean b) {
autoLoad = b;
}
public void getOptions(Context ctx, String name) throws OptionsException, PermissionsException {
options.getOptions(ctx, name);
}
public String getOption(Context ctx, String name) throws OptionsException, PermissionsException {
return options.getOption(ctx, name);
}
public void setOption(Context ctx, String name, String value) throws OptionsException, PermissionsException {
options.setOption(ctx, name, value);
}
@Override
public void onOptionSet(Context ctx, String name, String value) {
ctx.send("option '%s' set to '%s' for world '%s'", name, value, getName());
}
@Override
public String getOptionPermission(Context ctx, String name) {
return name;
}
/* End options */
public Map<String,Object> encode() {
Map<String,Object> node = new HashMap<String,Object>();
node.put("name", name);
node.put("environment", environment.toString());
node.put("generator", generator);
node.put("seed", seed);
node.put("autoLoad", autoLoad);
return node;
}
@Override
public World getWorld() {
return Global.plugin.getServer().getWorld(name);
}
public World load(Context ctx) {
World world = getWorld();
boolean loadEndpoints = (world != null);
if (world == null) {
ctx.send("loading world '%s'...", name);
WorldCreator wc = new WorldCreator(name);
wc.environment(environment);
wc.generator(generator);
if (seed != null)
try {
wc.seed(Long.parseLong(seed));
} catch (NumberFormatException e) {
wc.seed(seed.hashCode());
}
world = wc.createWorld();
if (seed == null) {
seed = world.getSeed() + "";
ctx.send("seed set to %s", seed);
}
} else {
ctx.send("world '%s' is already loaded", name);
if (seed == null)
seed = world.getSeed() + "";
}
if (loadEndpoints)
Gates.loadGatesForWorld(ctx, world);
return world;
}
public World unload() {
World world = getWorld();
if (world != null) {
Global.plugin.getServer().unloadWorld(world, true);
// Bukkit onWorldUnloaded event handler should do this, but just to be sure...
Gates.removeGatesForWorld(world);
}
return world;
}
@Override
public boolean isLoaded() {
return getWorld() != null;
}
}
|
package com.desafiofullstackunoesc.model.curso;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CursoRepository extends JpaRepository<Curso, Integer> {
}
|
import java.util.Scanner;
class bubble_case_change {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the string you want to sort: ");
String N= new String();
N=scan.nextLine();
char [] array=N.toCharArray();
bubble(array);
}
public static void bubble(char array[])
{ char temp;
for (int i=0;i<array.length;i++)
{
for (int j=i+1;j<array.length;j++)
{
if (array[i]>array[j])
{
temp=array[i];
array[i]=array[j];
array[j]=temp;
}
}
}
System.out.print("Bubble Sorted String: ");
for (int i=0;i<array.length;i++)
{
System.out.print(array[i]);
}
System.out.println("\n"+"Cases changed: ");
for (int i=0;i<array.length;i++)
{
Character c=array[i];
if (Character.isLowerCase(c))
System.out.print(Character.toUpperCase(c)+"");
else
System.out.print(Character.toLowerCase(c)+"");
}
}
}
|
package models;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;
/**
* This class runs the application and handles the models.Product I/O
*
* @version 5.0
*/
public class Driver {
private Scanner input = new Scanner(System.in);
private EmployeeAPI emp1 = new EmployeeAPI();
public Driver() {
runMenu();
}
public static void main(String[] args) {
new Driver();
}
private int mainMenu() {
System.out.println("Employee Menu");
System.out.println("---------");
System.out.println(" 1) Add Doctor");
System.out.println(" 2) List Doctors");
System.out.println(" 3) Delete Doctor");
System.out.println(" --------------------");
System.out.println(" 4) Save to XML");
System.out.println(" 5) Load to XML");
System.out.println(" 0) Exit");
System.out.print("==>> ");
int option = input.nextInt();
return option;
}
private void runMenu() {
int option = mainMenu();
while (option != 0) {
switch (option) {
case 1:
addEmployee();
break;
case 2:
listEmployees();
break;
case 3:
deleteEmployee();
break;
case 4:
try {
emp1.save();
} catch (Exception e) {
System.err.println("Error saving to file: " + e);
}
break;
case 5:
try {
emp1.load();
} catch (Exception e) {
System.err.println("Error reading from file: " + e);
}
break;
default:
System.out.println("Invalid option entered: " + option);
break;
}
System.out.println("\nPress any key to continue...");
input.nextLine();
input.nextLine();
option = mainMenu();
}
//the user chose option 0, so exit the program
System.out.println("Exiting... bye");
System.exit(0);
}
//gather the product data from the user and create a new product.
private void addEmployee() {
System.out.println("Enter the number of the employee you want to add:");
System.out.println(" 1) AdminWorker");
System.out.println(" 2) Lecturer");
System.out.println(" 3) Manager");
int emp = input.nextInt();
String y = input.nextLine();
System.out.println("Enter the first name of the employee:");
String firstName = input.nextLine();
System.out.println("Enter the second name of the employee: ");
String secondName = input.nextLine();
System.out.println("Enter the pps number of the employee: ");
String ppsNumber = input.nextLine();
if (emp == 1) {
System.out.println("Grade of this AdminWorker ");
int grade = input.nextInt();
emp1.addEmployee(new AdminWorker(firstName, secondName, ppsNumber, grade));
}
if (emp == 2) {
System.out.println("Level of this Lecturer ");
int level = input.nextInt();
emp1.addEmployee(new Lecturer(firstName, secondName, ppsNumber, level));
}
if (emp == 3) {
System.out.println("Level of this Manager ");
String dept = input.nextLine();
System.out.println("Grade of this Manager ");
int grade = input.nextInt();
emp1.addEmployee(new Manager(firstName, secondName, ppsNumber, dept, grade));
}
}
public void listEmployees() {
System.out.println(emp1.listEmployees());
}
private void deleteEmployee() {
System.out.println(emp1.listEmployees());
if (emp1.numberOfEmployees() > 0) {
System.out.print("Enter the index of the Employee to delete: ");
int index = input.nextInt();
emp1.removeEmployee(index);
} else {
System.out.println("There is no Employee for this index number");
}
}
}
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.grinder.plugin.http.tcpproxyfilter;
import java.util.concurrent.atomic.AtomicInteger;
/**
* EndPoint usage info class containing access count and filtering.
*
* @author JunHo Yoon
* @since 1.0
*/
public class EndPointInfo {
private AtomicInteger count = new AtomicInteger(0);
private boolean filtered = false;
/**
* Constructor.
*
* @param filtered
* true if filtered
*/
public EndPointInfo(boolean filtered) {
this.filtered = filtered;
}
public int getCount() {
return count.get();
}
/**
* increase count.
*/
public void inc() {
count.incrementAndGet();
}
public boolean isFiltered() {
return filtered;
}
public void setFiltered(boolean filtered) {
this.filtered = filtered;
}
/**
* Make the count zero.
*/
public void zero() {
count.set(0);
}
public void dec() {
count.decrementAndGet();
}
}
|
package interviewbit.binarysearch;
import java.util.List;
public class Median_Of_Array_GFG {
public double findMedianSortedArrays(final List<Integer> a,
final List<Integer> b) {
double d = 0;
if (a.size() <= b.size()) {
d = findMedianUtil(a, b);
} else {
d = findMedianUtil(b, a);
}
return d;
}
private double findMedianUtil(List<Integer> a, List<Integer> b) {
if (a.size() == 0) {
return medianSingle(b);
}
if (a.size() == 1) {
if (b.size() == 1) {
return mo2(a.get(0), b.get(0));
}
if (b.size() % 2 == 0) {
return mo3(a.get(0), b.get(b.size() / 2), b
.get((b.size() / 2) - 1));
}
return mo4(a.get(0), b.get((b.size() / 2) - 1),
b.get(b.size() / 2), b.get((b.size() / 2) + 1));
} else {
if (a.size() == 2) {
if (b.size() == 2) {
return mo4(a.get(0), a.get(1), b.get(0), b.get(1));
}
if (b.size() % 2 == 0) {
return mo4(Math.max(a.get(0), b.get((b.size() / 2) - 2)),
Math.min(a.get(1), b.get((b.size() / 2) + 1)), b
.get(b.size() / 2), b
.get((b.size() / 2) - 1));
}
return mo3(b.get(b.size() / 2), Math.max(a.get(0), b.get((b
.size() / 2) - 1)), Math.min(a.get(1), b
.get((b.size() / 2) + 1)));
}
}
int i_a = a.size() / 2;
int i_b = b.size() / 2;
if (a.get(i_a) <= b.get(i_b)) {
a = a.subList(i_a, a.size());
b = b.subList(0, b.size() - i_a);
return findMedianUtil(a, b);
} else {
//a = a.subList(0, i_a);
a = a.subList(0, (a.size()+1)/2);
b = b.subList(i_a, b.size());
return findMedianUtil(a, b);
}
}
private double medianSingle(List<Integer> a) {
if (a.size() == 0) {
return -1;
}
if (a.size() % 2 == 0) {
return ((a.get(a.size() / 2) + a.get((a.size() - 1) / 2)) / 2.0);
}
return (a.get(a.size() / 2));
}
private double mo2(int p, int q) {
return (p + q) / 2.0;
}
private double mo3(int p, int q, int r) {
return (p + q + r - (Math.min(p, Math.min(q, r))) - (Math.max(p, Math
.max(q, r))));
}
private double mo4(int p, int q, int r, int s) {
int max = Math.max(p, Math.max(q, Math.max(r, s)));
int min = Math.min(p, Math.min(q, Math.min(r, s)));
return ((p + q + r + s - max - min) / 2.0);
}
}
|
package gui;
import gui.excecao.ModeloNaoDeclaradoException;
import gui.excecao.PrecoDeCompraNaoDeclaradoException;
import gui.excecao.PrecoDeReparoNaoDeclaradoException;
import gui.excecao.PrecoDeVendaNaoDeclaradoException;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.layout.AnchorPane;
import negocio.entidade.Peca;
import negocio.excecao.*;
import negocio.fachada.Fachada;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import java.net.URL;
import java.util.ResourceBundle;
public class ControlePeca implements Initializable {
private Fachada fachada;
public ControlePeca(){
this.fachada = fachada.getInstance();
}
@FXML
private Button registrar;
@FXML
private AnchorPane tela;
@FXML
private Label lb1;
@FXML
private Label lb2;
@FXML
private Label lb3;
@FXML
private Label lb4;
@FXML
private Label lb5;
@FXML
private Label lb6;
@FXML
private TextField tipoTF;
@FXML
private TextField modeloTF;
@FXML
private TextField precoCompraTF;
@FXML
private TextField precoVendaTF;
@FXML
private TextField precoReparoTF;
@FXML
private TextField precoInstalacaoTF;
@Override
public void initialize(URL url, ResourceBundle rb){
//OK
}
public void addPeca(){
try {
String tipo = tipoTF.getText();
String modelo = modeloTF.getText();
double precoCompra = Double.valueOf(precoCompraTF.getText());
double precoVenda = Double.valueOf(precoVendaTF.getText());
double precoReparo = Double.valueOf(precoReparoTF.getText());
double precoInstalacao = Double.valueOf(precoInstalacaoTF.getText());
Peca peca = new Peca(tipo,modelo,precoCompra,precoVenda, precoInstalacao ,precoReparo);
this.fachada.adicionarProduto(peca);
Alert alerta = new Alert(Alert.AlertType.INFORMATION);
alerta.setTitle("Confirmacao");
alerta.setHeaderText("Cadastro de Peca Concluido");
alerta.setContentText("Peca foi cadastrada");
alerta.showAndWait();
}
catch (ProdutoRepetidoException e){
Alert alerta = new Alert(Alert.AlertType.WARNING);
alerta.setTitle("Erro");
alerta.setHeaderText("ERRO");
alerta.setContentText("Peca ja cadastrada");
alerta.showAndWait();
}
catch (ModeloNaoDeclaradoException e){
Alert alerta = new Alert(Alert.AlertType.WARNING);
alerta.setTitle("Erro");
alerta.setHeaderText("ERRO");
alerta.setContentText("Modelo nao declarado");
alerta.showAndWait();
}
catch (TipoNaoDeclaradoException e){
Alert alerta = new Alert(Alert.AlertType.WARNING);
alerta.setTitle("Erro");
alerta.setHeaderText("ERRO");
alerta.setContentText("tipo nao declarado");
alerta.showAndWait();
}
catch (PrecoDeCompraNaoDeclaradoException e){
Alert alerta = new Alert(Alert.AlertType.WARNING);
alerta.setTitle("Erro");
alerta.setHeaderText("ERRO");
alerta.setContentText("Preco de compra nao declarado");
alerta.showAndWait();
}
catch (PrecoDeReparoNaoDeclaradoException e){
Alert alerta = new Alert(Alert.AlertType.WARNING);
alerta.setTitle("Erro");
alerta.setHeaderText("ERRO");
alerta.setContentText("Preco de reparo nao declarado");
alerta.showAndWait();
}
catch (PrecoDeVendaNaoDeclaradoException e){
Alert alerta = new Alert(Alert.AlertType.WARNING);
alerta.setTitle("Erro");
alerta.setHeaderText("ERRO");
alerta.setContentText("Preco de venda nao declarado");
alerta.showAndWait();
}
catch (Exception e){
Alert alerta = new Alert(Alert.AlertType.WARNING);
alerta.setTitle("Erro");
alerta.setHeaderText("ERRO");
alerta.setContentText("Dados formatados de forma incorreta");
alerta.showAndWait();
}
}
}
|
package com.example.healthmanage.ui.activity.test;
import com.example.healthmanage.base.BaseViewModel;
public class TestViewModel extends BaseViewModel {
}
|
package com.tencent.tencentmap.mapsdk.a;
public interface kk$a {
void a();
void b();
}
|
package com.moon.moon_security.config;
import com.fasterxml.jackson.core.filter.TokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import javax.annotation.Resource;
/**
* @ClassName SecurityConfig
* @Description: TODO
* @Author zyl
* @Date 2020/11/26
* @Version V1.0
**/
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationSuccessHandler authenticationSuccessHandler;
@Autowired
private AuthenticationFailureHandler authenticationFailureHandler;
@Autowired
private LogoutSuccessHandler logoutSuccessHandler;
@Autowired
private AuthenticationEntryPoint authenticationEntryPoint;
@Autowired
private UserDetailsService userDetailsService;
// @Autowired
// private TokenFilter tokenFilter;
// @Resource
// private SmsCodeSecurityConfig smsCodeSecurityConfig;
/**
* 忽略拦截
*
* @param web
* @throws Exception
*/
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/", "/*.html", "/favicon.ico", "/css/**", "/js/**", "/fonts/**", "/layui/**", "/img/**",
"/v2/api-docs/**", "/swagger-resources/**", "/webjars/**", "/pages/**", "/druid/**", "/dashboard/**",
"/statics/**");
}
/**
* @Author: zyl
* @Description: HttpSecurity包含了原数据(主要是url)
* 通过withObjectPostProcessor将MyFilterInvocationSecurityMetadataSource和MyAccessDecisionManager注入进来
* 此url先被MyFilterInvocationSecurityMetadataSource处理,然后 丢给 MyAccessDecisionManager处理
* 如果不匹配,返回 MyAccessDeniedHandler
* @Date: 2019/3/27-17:41
* @Param: [http]
* @return: void
**/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable(); // 禁用csrf保护,开启csrf保护的时候,请求不支持GET
// 基于token,所以不需要session
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// http
// .authorizeRequests() 1
// .antMatchers( "/resources/**", "/signup" , "/about").permitAll() 2
// .antMatchers( "/admin/**").hasRole("ADMIN" ) 3
// .antMatchers( "/db/**").access("hasRole('ADMIN') and hasRole('DBA')") 4
// .anyRequest().authenticated() 5
//1、http.authorizeRequests()方法有很多子方法,每个子匹配器将会按照声明的顺序起作用。
//2、指定用户可以访问的多个url模式。特别的,任何用户可以访问以"/resources"开头的url资源,或者等于"/signup"或about
//3、任何以"/admin"开头的请求限制用户具有 "ROLE_ADMIN"角色。你可能已经注意的,尽管我们调用的hasRole方法,但是不用传入"ROLE_"前缀
//4、任何以"/db"开头的请求同时要求用户具有"ROLE_ADMIN"和"ROLE_DBA"角色。
//5、任何没有匹配上的其他的url请求,只需要用户被验证。
http.authorizeRequests().withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
@Override
public <O extends FilterSecurityInterceptor> O postProcess(O o) {
o.setSecurityMetadataSource(filterMetadataSource);
o.setAccessDecisionManager(myAccessDecisionManager);
return o;
}
}).and().
formLogin().loginPage("/login.html").loginProcessingUrl("/login")
.successHandler(authenticationSuccessHandler).failureHandler(authenticationFailureHandler).and()
//.apply(smsCodeSecurityConfig).and()
.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
http.logout()
.logoutUrl("/logout")
.logoutSuccessHandler(logoutSuccessHandler); // 登出成功处理器
// 解决不允许显示在iframe的问题
http.headers().frameOptions().disable();
http.headers().cacheControl();
// http.addFilterBefore(tokenFilter, UsernamePasswordAuthenticationFilter.class);
}
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
/**
* @MethodName: configure
* @Description: 配置userDetails的数据源,密码加密格式
* @Param: [auth]
* @Return: void
* @Author: zyl
* @Date: 2020/11/30
**/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
}
}
|
package com.aprendoz_test.data;
/**
* aprendoz_test.VistaMatriculasGraficasTotalDia
* 01/19/2015 07:58:52
*
*/
public class VistaMatriculasGraficasTotalDia {
private VistaMatriculasGraficasTotalDiaId id;
public VistaMatriculasGraficasTotalDiaId getId() {
return id;
}
public void setId(VistaMatriculasGraficasTotalDiaId id) {
this.id = id;
}
}
|
package com.cnk.travelogix.ccintegrationfacade.impl;
import org.apache.log4j.Logger;
import org.springframework.core.convert.converter.Converter;
import com.cnk.travelogix.ccintegrationfacade.SupplierCCIntegrationFacade;
import com.cnk.travelogix.ccintegrationfacade.exception.CCIntegrationErrorCodes;
import com.cnk.travelogix.ccintegrationfacade.exception.CCIntegrationException;
import com.cnk.travelogix.sapintegrations.subscribe.account.data.ResponseStatus;
import com.cnk.travelogix.sapintegrations.subscribe.account.data.SubscriberAccount;
import com.cnk.travelogix.sapintegrations.subscribe.account.data.SubscriberAccountOperationResponseData;
import com.cnk.travelogix.supplier.core.supplier.model.SupplierModel;
// TODO: Auto-generated Javadoc
/**
* The Class DefaultSupplierCCIntegrationFacade.
*/
public class DefaultSupplierCCIntegrationFacade extends AbstractCCIntegrationFacade implements SupplierCCIntegrationFacade
{
/** The Constant LOGGER. */
private static final Logger LOGGER = Logger.getLogger(DefaultSupplierCCIntegrationFacade.class);
/** The supplier subscriber account converter. */
private Converter<SupplierModel, SubscriberAccount> supplierSubscriberAccountConverter;
/**
* Creates the supplier account.
*
* @param pSupplierModel
* the supplier model
* @throws CCIntegrationException
* the CC integration exception
*/
@Override
public void createSupplierAccount(final SupplierModel pSupplierModel) throws CCIntegrationException
{
LOGGER.debug("DefaultSupplierCCIntegrationFacade : createSupplierAccount() : Entering.");
try
{
final SubscriberAccountOperationResponseData lSubscriberAccountOperationResponseData = super.createSubscriberAccount(
pSupplierModel, getSupplierSubscriberAccountConverter());
if (lSubscriberAccountOperationResponseData != null
&& lSubscriberAccountOperationResponseData.getStatus().equals(ResponseStatus.RETURN))
{
// RETRIEVE SUBSCRIBER ACC ID OR REF NUMMER AND SAVE TO MODEL
//pSupplierModel
// pSupplierModel.setSubscriberAccountRef(lSubscriberAccountOperationResponseData.getSubscriberAccountReference());
LOGGER.info("..........Subscriber Response Successfull");
}
}
catch (final CCIntegrationException e)
{
throw e;
}
catch (final Exception e)
{
// Any other exception
throw new CCIntegrationException(CCIntegrationErrorCodes.ERR_RUNTIME, e);
}
finally
{
LOGGER.debug("DefaultSupplierCCIntegrationFacade : createSupplierAccount() : Exiting");
}
}
/**
* Gets the supplier subscriber account converter.
*
* @return the supplier subscriber account converter
*/
public Converter<SupplierModel, SubscriberAccount> getSupplierSubscriberAccountConverter()
{
return supplierSubscriberAccountConverter;
}
/**
* Sets the supplier subscriber account converter.
*
* @param supplierSubscriberAccountConverter
* the supplier subscriber account converter
*/
public void setSupplierSubscriberAccountConverter(
final Converter<SupplierModel, SubscriberAccount> supplierSubscriberAccountConverter)
{
this.supplierSubscriberAccountConverter = supplierSubscriberAccountConverter;
}
}
|
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.Statement;
public class CodehubAutoSolveTable {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/uetcodehub";
// Database credentials
static String USER = "homestead";
static String PASS = "secret";
// delay time between updates
static int DELAY = 10; // default delay in minutes
static final boolean DEBUG = false;
static int RunTimes = 0;
static Connection conn = null;
static Statement stmt = null;
static String sql = "SELECT courseproblemId, tab1.problemId, tab1.courseId, tab1.submittedUser, "+
"COALESCE(tab2.finishedUser, 0) AS finishedUser FROM "+
" (SELECT courseproblemId, tab11.problemId, tab11.courseId, tab11.submittedUser "+
" FROM "+
" (SELECT problemId, courseId, COUNT(userId) AS submittedUser "+
" FROM userproblemscore "+
" GROUP BY problemId, courseId) AS tab11 "+
" LEFT JOIN courseproblems AS tab12 "+
" ON tab11.problemId=tab12.problemId AND tab11.courseId=tab12.courseId "+
" WHERE isActive=1) AS tab1 "+
"LEFT JOIN "+
" (SELECT userproblemscore.problemId, userproblemscore.courseId, "+
" COUNT(userproblemscore.userId) AS finishedUser "+
" FROM userproblemscore "+
" LEFT JOIN problems "+
" ON userproblemscore.problemId=problems.problemId "+
" WHERE userproblemscore.maxScore=problems.defaultScore "+
" GROUP BY problemId, courseId) AS tab2 "+
"ON tab1.problemId=tab2.problemId AND tab1.courseId=tab2.courseId";
@SuppressWarnings("unused")
public static void main(String[] args) {
int first_delay = 1;
/*
args[0]: Delay to start program (in second)
args[1]: Delay between 2 queries (in minute)
args[2]: User name
args[3]: Password
*/
if (args.length != 0) {
System.out.println("delay=" + args[0]);
first_delay = Integer.valueOf(args[0]);
System.out.println("timed=" + args[1]);
DELAY = Integer.valueOf(args[1]);
USER = args[2];
PASS = args[3];
}
try {
Thread.sleep(first_delay * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// STEP 2: Register JDBC driver
try {
Class.forName("com.mysql.jdbc.Driver");
// STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = (Connection) DriverManager.getConnection(DB_URL, USER, PASS);
// STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = (Statement) conn.createStatement();
String sql_create;
String sql;
// Create table if not existed
sql_create = "create table if not exists problemsolvingresult(" + "courseProblemId int PRIMARY KEY," +
" problemId int," + " courseId int," +
" submittedUser int," + " finishedUser int);";
PreparedStatement pst = (PreparedStatement) conn.prepareStatement(sql_create);
int numRowsChanged = pst.executeUpdate();
updateTable();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// finally block used to close resources
try {
if (stmt != null)
stmt.close();
} catch (SQLException se2) {
} // nothing we can do
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} // end finally try
} // end try
}
public static void updateTable() {
if (DEBUG) RunTimes++;
try {
ResultSet rs = stmt.executeQuery(sql);
//PreparedStatement pst_del = (PreparedStatement) conn.prepareStatement("DELETE FROM problemsolvingresult");
//pst_del.executeUpdate();
int cpid, pid, cid, submit, done, stt=0;
String sql_update;
// STEP 5: Extract data from result set
while (rs.next()) {
// Retrieve by column name
cpid = rs.getInt("courseProblemId");
pid = rs.getInt("problemId");
cid = rs.getInt("courseId");
submit = rs.getInt("submittedUser");
done = rs.getInt("finishedUser");
sql_update = "INSERT INTO problemsolvingresult (" + "courseProblemId, problemId, courseId, submittedUser, finishedUser) VALUES" + "("
+ cpid + "," + pid + "," + cid + "," + submit + "," + done + "); ";
// Display values
if (DEBUG) {
stt++;
System.out.println(stt+sql_update);
}
// insert
PreparedStatement pst_del = (PreparedStatement) conn.prepareStatement(
"DELETE FROM problemsolvingresult WHERE courseProblemId=" + cpid);
pst_del.executeUpdate();
PreparedStatement pstt = (PreparedStatement) conn.prepareStatement(sql_update);
pstt.executeUpdate();
}
} catch (SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
}
if (DEBUG) System.out.println("Runned: " + RunTimes);
try {
Thread.sleep(DELAY * 60000);
updateTable();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
package com.tencent.mm.plugin.downloader.model;
import com.tencent.mm.a.e;
import com.tencent.mm.plugin.cdndownloader.c.a;
import com.tencent.mm.plugin.downloader.e.b;
import com.tencent.mm.sdk.platformtools.bi;
class a$3 implements Runnable {
final /* synthetic */ a ibF;
final /* synthetic */ long ibH;
a$3(a aVar, long j) {
this.ibF = aVar;
this.ibH = j;
}
public final void run() {
FileDownloadTaskInfo cm = this.ibF.cm(this.ibH);
if (cm != null) {
a.aAk().yk(cm.url);
a.a(this.ibF, cm.url);
e.deleteFile(cm.path);
if (cm.status != 5) {
com.tencent.mm.plugin.downloader.c.a cs = c.cs(this.ibH);
cs.field_status = 5;
c.e(cs);
Long valueOf = Long.valueOf(bi.a((Long) a.b(this.ibF).get(cm.url), cs.field_startTime));
if (valueOf != null) {
b.a(this.ibH, ((((float) (cm.icq - Long.valueOf(bi.a((Long) a.a(this.ibF).get(cm.url), cs.field_startSize)).longValue())) * 1000.0f) / ((float) (System.currentTimeMillis() - valueOf.longValue()))) / 1048576.0f, (int) ((((float) cm.icq) / ((float) cm.gTK)) * 100.0f));
}
a.a(this.ibF).remove(cm.url);
a.b(this.ibF).remove(cm.url);
this.ibF.ibT.cp(this.ibH);
}
}
}
}
|
package com.jk.jkproject.ui.widget.danmaku;
import android.content.Context;
public interface DanmakuClickListener {
void onDanmakuClick(Context paramContext, DanmakuEntity paramDanmakuEntity);
void onDanmuIconClick(String paramString1, String paramString2, int paramInt);
}
|
package cache.inmemorycache.server.internal.transaction;
import com.google.inject.Singleton;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import cache.inmemorycache.server.internal.datastore.CacheValue;
import cache.inmemorycache.server.internal.datastore.Snapshot;
@Singleton
public class TransactionManager implements ITransactionManager {
private Map<String, Transaction> transactions = new HashMap<>();
private List<Transaction> inaciveTransactions = new ArrayList<>();
@Override
public synchronized Transaction getTransaction(String transactionId) {
return transactions.get(transactionId);
}
@Override
public synchronized Transaction createTransaction(Map<String, CacheValue> inMemoryMap, Map<String, Snapshot> snapshots, Map<String, Integer> valueCount) {
if (inaciveTransactions.size() == 0) {
String transactionId = UUID.randomUUID().toString();
Transaction transaction = new Transaction(transactionId, inMemoryMap, snapshots, valueCount);
transactions.put(transactionId, transaction);
return transaction;
} else {
return inaciveTransactions.remove(0);
}
}
@Override
public boolean isValidTransaction(String transactionId) {
return transactions.containsKey(transactionId);
}
@Override
public void removeTransaction(Transaction transaction) {
transactions.remove(transaction.getId());
}
@Override
public String toString() {
return "TransactionManager{" +
"transactions=" + transactions +
", inaciveTransactions=" + inaciveTransactions +
'}';
}
}
|
package hudson.plugins.buckminster;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import hudson.model.BuildListener;
/**
* A separate thread that reads the output stream of a given {@link Process} object and writes the results
* to the given {@link BuildListener}.
* @author Johannes Utzig
*
*/
public class ProcessStreamLogger extends Thread {
private Process process;
private BuildListener listener;
public ProcessStreamLogger(Process process, BuildListener listener) {
super();
this.process = process;
this.listener = listener;
}
@Override
public void run() {
BufferedReader reader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String result;
try {
while ((result = reader.readLine()) != null) {
listener.getLogger().println(result);
}
} catch (IOException e) {
listener.getLogger().println(e.toString());
e.printStackTrace(listener.getLogger());
}
}
}
|
package com.yixin.kepler.enity;/**
* Created by liushuai2 on 2018/6/7.
*/
import com.yixin.common.system.domain.BZBaseEntiy;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
* Package : com.yixin.kepler.enity
*
* @author YixinCapital -- liushuai2
* 2018年06月07日 10:03
*/
@Entity
@Table(name = "k_asset_field")
public class AssetField extends BZBaseEntiy{
@Column(name = "field_name", length = 64)
private String fieldName;
@Column(name = "field_code", length = 64)
private String fieldCode;
public String getFieldName() {
return fieldName;
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
public String getFieldCode() {
return fieldCode;
}
public void setFieldCode(String fieldCode) {
this.fieldCode = fieldCode;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.zavierdev.crudsiswa.ui.home;
import com.zavierdev.crudsiswa.auth.Session;
import com.zavierdev.crudsiswa.viewmodel.ViewModelConnectionObserver;
import com.zavierdev.crudsiswa.model.Student;
import com.zavierdev.crudsiswa.utils.DialogBox;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.table.DefaultTableModel;
/**
*
* @author tech
*/
public class HomeFrame extends javax.swing.JFrame {
private HomeFrameViewModel mainFrameViewModel = null;
private Session loginSession;
private boolean firstRun = true;
private Student selectedStudent = new Student();
private boolean stateEdit = false;
/**
* Creates new form MainFrame
* @param loginSession
*/
public HomeFrame(Session loginSession) {
this.loginSession = loginSession;
this.setVisible(true);
provideViewModel();
initComponents();
initShellActions();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
scrollPanelStudentTable = new javax.swing.JScrollPane();
tblStudent = new javax.swing.JTable();
lblName = new javax.swing.JLabel();
tfName = new javax.swing.JTextField();
lblAddress = new javax.swing.JLabel();
scrollPanelTextAreaAddress = new javax.swing.JScrollPane();
taAddress = new javax.swing.JTextArea();
btnAddEdit = new javax.swing.JButton();
btnReset = new javax.swing.JButton();
btnDelete = new javax.swing.JButton();
lblSearch = new javax.swing.JLabel();
tfSearch = new javax.swing.JTextField();
lblLogedUser = new javax.swing.JLabel();
lblUsername = new javax.swing.JLabel();
menuBar = new javax.swing.JMenuBar();
aboutMenu = new javax.swing.JMenu();
menuItemInfo = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Data Siswa");
setResizable(false);
tblStudent.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Id", "Nama", "Alamat"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
scrollPanelStudentTable.setViewportView(tblStudent);
if (tblStudent.getColumnModel().getColumnCount() > 0) {
tblStudent.getColumnModel().getColumn(2).setResizable(false);
}
lblName.setFont(new java.awt.Font("Ubuntu", 1, 15)); // NOI18N
lblName.setLabelFor(tfName);
lblName.setText("Nama");
lblName.setToolTipText("");
lblAddress.setFont(new java.awt.Font("Ubuntu", 1, 15)); // NOI18N
lblAddress.setLabelFor(tfName);
lblAddress.setText("Alamat");
lblAddress.setToolTipText("");
taAddress.setColumns(20);
taAddress.setRows(5);
scrollPanelTextAreaAddress.setViewportView(taAddress);
btnAddEdit.setText("Tambah");
btnAddEdit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddEditActionPerformed(evt);
}
});
btnReset.setText("Reset");
btnReset.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnResetActionPerformed(evt);
}
});
btnDelete.setText("Hapus");
btnDelete.setActionCommand("");
btnDelete.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDeleteActionPerformed(evt);
}
});
lblSearch.setFont(new java.awt.Font("Ubuntu", 1, 15)); // NOI18N
lblSearch.setLabelFor(tfSearch);
lblSearch.setText("Search");
lblLogedUser.setFont(new java.awt.Font("Ubuntu", 1, 15)); // NOI18N
lblLogedUser.setText("Logged User :");
lblUsername.setFont(new java.awt.Font("Ubuntu", 0, 15)); // NOI18N
lblUsername.setText("-");
aboutMenu.setText("About");
menuItemInfo.setText("Info");
menuItemInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menuItemInfoActionPerformed(evt);
}
});
aboutMenu.add(menuItemInfo);
menuBar.add(aboutMenu);
setJMenuBar(menuBar);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(16, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(lblLogedUser)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(lblUsername, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(lblAddress)
.addComponent(scrollPanelTextAreaAddress, javax.swing.GroupLayout.DEFAULT_SIZE, 297, Short.MAX_VALUE)
.addComponent(btnAddEdit, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnReset, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnDelete, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(tfName, javax.swing.GroupLayout.PREFERRED_SIZE, 297, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(lblName))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(lblSearch)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tfSearch))
.addComponent(scrollPanelStudentTable, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(27, 27, 27))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(10, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblSearch)
.addComponent(tfSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblUsername)
.addComponent(lblLogedUser))
.addGap(17, 17, 17)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(lblName)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tfName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(lblAddress)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(scrollPanelTextAreaAddress, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(12, 12, 12)
.addComponent(btnAddEdit)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnDelete)
.addGap(7, 7, 7)
.addComponent(btnReset))
.addComponent(scrollPanelStudentTable, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
.addGap(16, 16, 16))
);
lblLogedUser.getAccessibleContext().setAccessibleName("");
setSize(new java.awt.Dimension(638, 396));
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnResetActionPerformed
firstState();
}//GEN-LAST:event_btnResetActionPerformed
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
if(selectedStudent.id != null && !selectedStudent.id.isEmpty()) {
int response = DialogBox.showOptionDialog(
"Anda yakin ?",
"Data siswa ini akan dihapus !",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
if(response == JOptionPane.YES_OPTION) {
mainFrameViewModel.deleteStudent(selectedStudent);
firstState();
}
}
}//GEN-LAST:event_btnDeleteActionPerformed
private void btnAddEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddEditActionPerformed
boolean isFormError = validateStudentFormError();
Student student = new Student();
student.setName(tfName.getText());
student.setAddress(taAddress.getText());
if(!stateEdit && !isFormError) { // State Add
mainFrameViewModel.addStudent(student);
firstState();
} else if(!isFormError) { // State Update
student.setId(selectedStudent.id);
mainFrameViewModel.updateStudent(student);
firstState();
}
}//GEN-LAST:event_btnAddEditActionPerformed
private void menuItemInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemInfoActionPerformed
DialogBox.showMessageDialog("This Application Developed By :\n"+"Zavier Ferodova Al Fitroh");
}//GEN-LAST:event_menuItemInfoActionPerformed
private void provideViewModel() {
mainFrameViewModel = new HomeFrameViewModel();
}
private void initShellActions() {
tblStudent.getSelectionModel().addListSelectionListener((ListSelectionEvent lse) -> {
if(tblStudent.getSelectedRow() > -1) {
String id = tblStudent.getValueAt(tblStudent.getSelectedRow(), 0).toString();
String name = tblStudent.getValueAt(tblStudent.getSelectedRow(), 1).toString();
String address = tblStudent.getValueAt(tblStudent.getSelectedRow(), 2).toString();
selectedStudent.setId(id);
selectedStudent.setName(name);
selectedStudent.setAddress(address);
fillStudentForm(selectedStudent);
stateEdit();
}
});
tfSearch.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent de) {
performSearchStudent();
}
@Override
public void removeUpdate(DocumentEvent de) {
performSearchStudent();
}
@Override
public void changedUpdate(DocumentEvent de) {
performSearchStudent();
}
});
mainFrameViewModel.observeConnection(new ViewModelConnectionObserver() {
@Override
public void connectionStatus(boolean status) {
if(!status) {
showDatabaseErrorDialog();
} else if(status && firstRun) { // First application run
runShell();
firstRun = false;
}
}
});
}
private void runShell() {
getAndFillStudentTable();
lblUsername.setText(loginSession.getUsername());
}
private void firstState() {
tblStudent.clearSelection(); // Clear selected table row and column
selectedStudent = new Student();
btnAddEdit.setText("Tambah");
tfSearch.setText("");
tfName.setText("");
taAddress.setText("");
stateEdit = false;
getAndFillStudentTable();
}
private void stateEdit() {
stateEdit = true;
btnAddEdit.setText("Ubah");
}
private void fillStudentForm(Student student) {
tfName.setText(student.name);
taAddress.setText(student.address);
}
private void getAndFillStudentTable() {
ArrayList<Student> students = mainFrameViewModel.getStudents();
cleanStudentTableRows();
for(int i = 0; i < students.size(); i++) {
insertStudentToTable(students.get(i));
}
}
private void insertStudentToTable(Student student) {
DefaultTableModel tblModel = (DefaultTableModel) tblStudent.getModel();
String rowData[] = { student.id, student.name, student.address };
tblModel.addRow(rowData);
}
private void insertStudentsToTable(ArrayList<Student> students) {
cleanStudentTableRows();
for(int i = 0; i < students.size(); i++) {
insertStudentToTable(students.get(i));
}
}
private void cleanStudentTableRows() {
DefaultTableModel tblModel = (DefaultTableModel) tblStudent.getModel();
tblStudent.clearSelection(); // Clear selected table row and column
while(tblModel.getRowCount() > 0) {
tblModel.removeRow(0);
}
}
private void performSearchStudent() {
String keyword = tfSearch.getText();
ArrayList<Student> students = mainFrameViewModel.searchStudents(keyword);
cleanStudentTableRows();
insertStudentsToTable(students);
}
private boolean validateStudentFormError() {
boolean isError = false;
if(tfName.getText().isEmpty()) {
isError = true;
DialogBox.showMessageDialog("Silahkan isi nama !");
}
else if(taAddress.getText().isEmpty()) {
isError = true;
DialogBox.showMessageDialog("Silahkan isi alamat !");
}
return isError;
}
private void showDatabaseErrorDialog() {
int response = DialogBox.showOptionDialog(
"Error",
"Database Gagal Terhubung !\nIngin Menyambungkannya Kembali ?",
JOptionPane.YES_NO_OPTION,
JOptionPane.ERROR_MESSAGE);
if(response == JOptionPane.YES_OPTION) {
mainFrameViewModel.connectDB();
runShell();
} else {
System.exit(0); // Exit Programs
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenu aboutMenu;
private javax.swing.JButton btnAddEdit;
private javax.swing.JButton btnDelete;
private javax.swing.JButton btnReset;
private javax.swing.JLabel lblAddress;
private javax.swing.JLabel lblLogedUser;
private javax.swing.JLabel lblName;
private javax.swing.JLabel lblSearch;
private javax.swing.JLabel lblUsername;
private javax.swing.JMenuBar menuBar;
private javax.swing.JMenuItem menuItemInfo;
private javax.swing.JScrollPane scrollPanelStudentTable;
private javax.swing.JScrollPane scrollPanelTextAreaAddress;
private javax.swing.JTextArea taAddress;
private javax.swing.JTable tblStudent;
private javax.swing.JTextField tfName;
private javax.swing.JTextField tfSearch;
// End of variables declaration//GEN-END:variables
}
|
package de.adesso.gitstalker.core.processors;
import de.adesso.gitstalker.core.enums.RequestType;
import de.adesso.gitstalker.core.objects.Query;
import de.adesso.gitstalker.core.repositories.OrganizationRepository;
import de.adesso.gitstalker.core.repositories.ProcessingRepository;
import de.adesso.gitstalker.core.repositories.RequestRepository;
import lombok.NoArgsConstructor;
import java.util.HashMap;
//TODO: Still relevant?
/**
* This is the Response manager that carries the different processors within itself.
* A separate processor is created for each organization.
*/
@NoArgsConstructor
public class ResponseProcessorManager {
public static HashMap<String, OrganizationValidationProcessor> organizationValidationProcessorHashMap = new HashMap<>();
public static HashMap<String, OrganizationDetailProcessor> organizationDetailProcessorHashMap = new HashMap<>();
public static HashMap<String, MemberIDProcessor> memberIDProcessorHashMap = new HashMap<>();
public static HashMap<String, MemberProcessor> memberProcessorHashMap = new HashMap<>();
public static HashMap<String, MemberPRProcessor> memberPRProcessorHashMap = new HashMap<>();
public static HashMap<String, RepositoryProcessor> repositoryProcessorHashMap = new HashMap<>();
public static HashMap<String, TeamProcessor> teamProcessorHashMap = new HashMap<>();
public static HashMap<String, ExternalRepoProcessor> externalRepoProcessorHashMap = new HashMap<>();
public static HashMap<String, CreatedReposByMembersProcessor> createdReposByMembersProcessorHashMap = new HashMap<>();
/**
* The central routing of requests to processors is controlled here.
* A separate processor is created for each organization so that no information can be mixed.
* The processors are held as long as the organization is still being processed.
* The processors are removed on completion.
* @param organizationRepository OrganizationRepository for accessing organization.
* @param requestRepository RequestRepository for accessing requests.
* @param requestQuery Query to be processed.
*/
public void processResponse(OrganizationRepository organizationRepository, RequestRepository requestRepository, ProcessingRepository processingRepository, Query requestQuery) {
RequestType requestType = requestQuery.getQueryRequestType();
switch (requestType) {
case ORGANIZATION_VALIDATION:
if (!organizationValidationProcessorHashMap.containsKey(requestQuery.getOrganizationName())) {
organizationValidationProcessorHashMap.put(requestQuery.getOrganizationName(), new OrganizationValidationProcessor());
}
organizationValidationProcessorHashMap.get(requestQuery.getOrganizationName()).processResponse(requestQuery, requestRepository, organizationRepository, processingRepository);
break;
case ORGANIZATION_DETAIL:
if (!organizationDetailProcessorHashMap.containsKey(requestQuery.getOrganizationName())) {
organizationDetailProcessorHashMap.put(requestQuery.getOrganizationName(), new OrganizationDetailProcessor());
}
organizationDetailProcessorHashMap.get(requestQuery.getOrganizationName()).processResponse(requestQuery, requestRepository, organizationRepository, processingRepository);
break;
case MEMBER_ID:
if (!memberIDProcessorHashMap.containsKey(requestQuery.getOrganizationName())) {
memberIDProcessorHashMap.put(requestQuery.getOrganizationName(), new MemberIDProcessor());
}
memberIDProcessorHashMap.get(requestQuery.getOrganizationName()).processResponse(requestQuery, requestRepository, organizationRepository, processingRepository);
break;
case MEMBER:
if (!memberProcessorHashMap.containsKey(requestQuery.getOrganizationName())) {
memberProcessorHashMap.put(requestQuery.getOrganizationName(), new MemberProcessor());
}
memberProcessorHashMap.get(requestQuery.getOrganizationName()).processResponse(requestQuery, requestRepository, organizationRepository, processingRepository);
break;
case MEMBER_PR:
if (!memberPRProcessorHashMap.containsKey(requestQuery.getOrganizationName())) {
memberPRProcessorHashMap.put(requestQuery.getOrganizationName(), new MemberPRProcessor());
}
memberPRProcessorHashMap.get(requestQuery.getOrganizationName()).processResponse(requestQuery, requestRepository, organizationRepository, processingRepository);
break;
case REPOSITORY:
if (!repositoryProcessorHashMap.containsKey(requestQuery.getOrganizationName())) {
repositoryProcessorHashMap.put(requestQuery.getOrganizationName(), new RepositoryProcessor());
}
repositoryProcessorHashMap.get(requestQuery.getOrganizationName()).processResponse(requestQuery, requestRepository, organizationRepository, processingRepository);
break;
case TEAM:
if (!teamProcessorHashMap.containsKey(requestQuery.getOrganizationName())) {
teamProcessorHashMap.put(requestQuery.getOrganizationName(), new TeamProcessor());
}
teamProcessorHashMap.get(requestQuery.getOrganizationName()).processResponse(requestQuery, requestRepository, organizationRepository, processingRepository);
break;
case EXTERNAL_REPO:
if (!externalRepoProcessorHashMap.containsKey(requestQuery.getOrganizationName())) {
externalRepoProcessorHashMap.put(requestQuery.getOrganizationName(), new ExternalRepoProcessor());
}
externalRepoProcessorHashMap.get(requestQuery.getOrganizationName()).processResponse(requestQuery, requestRepository, organizationRepository, processingRepository);
break;
case CREATED_REPOS_BY_MEMBERS:
if (!createdReposByMembersProcessorHashMap.containsKey(requestQuery.getOrganizationName())) {
createdReposByMembersProcessorHashMap.put(requestQuery.getOrganizationName(), new CreatedReposByMembersProcessor());
}
createdReposByMembersProcessorHashMap.get(requestQuery.getOrganizationName()).processResponse(requestQuery, requestRepository, organizationRepository, processingRepository);
break;
}
}
}
|
package chap04;
public class Queue {
int max = 10;
int top = -1;
int arr[] = new int[max];
public void enque(int number){
if(top<max){
if(top>=0){
arr[top] = number;
top++;
} else if(top<0){
top=0;
arr[top] = number;
top++;
}
} else {
System.out.println("out of range");
}
}
public void reLocation(){
for(int i = 1; i<arr.length; i++){
arr[i-1] = arr[i];
}
}
public void deque (){
if(top>0){
System.out.println(arr[0]);
reLocation();
top--;
// } else if(top ==0){
// System.out.println(arr[0]);
// reLocation();
// top--;
} else if(top<=0){
System.out.println("no data");
}
}
public void clear(){
arr = new int[max];
}
public void capacity(){
System.out.println(max);
}
public void size(){
System.out.println(top);
}
public void isEmpty(){
if(top<0){
System.out.println(true);
} else {
System.out.println(false);
}
}
public void isFull(){
if(top==max){
System.out.println(true);
} else {
System.out.println(false);
}
}
public void print(){
if(top>0){
for(int i=0; i<=top; i++){
System.out.println(arr[i]);
}
} else {
System.out.println("should init");
}
}
public void init(){
arr = new int[max];
top =0;
}
public static void main(String[] args) {
Queue queue = new Queue();
queue.init();
queue.enque(1);
queue.enque(2);
queue.enque(3);
queue.enque(4);
queue.deque();
queue.deque();
queue.deque();
queue.deque();
queue.deque();
}
}
|
package IO;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class test {
public static void main(String[]args){
PrintWriter pw = null;
try {
pw = new PrintWriter(new File("NewData.csv"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
StringBuilder builder = new StringBuilder();
String ColumnNamesList = "Id,Name";
// No need give the headers Like: id, Name on builder.append
builder.append(ColumnNamesList +"\n");
builder.append("123456679"+",");
builder.append("Chola");
builder.append('\n');
pw.write(builder.toString());
pw.close();
System.out.println("done!");
}
}
|
package com.elvarg.world.model;
/**
* Represents a player's prayer book.
*
* @author relex lawl
*/
public enum Prayerbook {
NORMAL(5608, "You sense a surge of purity flow through your body!"),
CURSES(32500, "You sense a surge of power flow through your body!");
/**
* The PrayerBook constructor.
* @param interfaceId The interface id to switch prayer tab to.
* @param message The message received upon switching prayers.
*/
private Prayerbook(int interfaceId, String message) {
this.interfaceId = interfaceId;
this.message = message;
}
/**
* The interface id to switch prayer tab to.
*/
private final int interfaceId;
/**
* The message received upon switching prayers.
*/
private final String message;
/**
* Gets the interface id to set prayer tab to.
* @return The new prayer tab interface id.
*/
public int getInterfaceId() {
return interfaceId;
}
/**
* Gets the message received when switching to said prayer book.
* @return The message player will receive.
*/
public String getMessage() {
return message;
}
/**
* Gets the PrayerBook instance for said id.
* @param id The id to match to prayer book's ordinal.
* @return The prayerbook who's ordinal is equal to id.
*/
public static Prayerbook forId(int id) {
for (Prayerbook book : Prayerbook.values()) {
if (book.ordinal() == id) {
return book;
}
}
return NORMAL;
}
}
|
package com.tencent.mm.plugin.exdevice.model;
import com.tencent.mm.ab.b;
import com.tencent.mm.ab.b.a;
import com.tencent.mm.ab.e;
import com.tencent.mm.ab.l;
import com.tencent.mm.network.k;
import com.tencent.mm.network.q;
import com.tencent.mm.protocal.c.ame;
import com.tencent.mm.protocal.c.amf;
import com.tencent.mm.protocal.c.fl;
import com.tencent.mm.sdk.platformtools.x;
public final class s extends l implements k {
private e doG = null;
private String ius = null;
private b ivF = null;
public s(String str, String str2, String str3, int i) {
a aVar = new a();
aVar.dIG = new ame();
aVar.dIH = new amf();
aVar.uri = "/cgi-bin/mmbiz-bin/device/subscribestatus";
aVar.dIF = 1090;
aVar.dII = 0;
aVar.dIJ = 0;
this.ivF = aVar.KT();
ame ame = (ame) this.ivF.dID.dIL;
ame.rgu = com.tencent.mm.bk.b.Uw(str2);
ame.rgs = com.tencent.mm.bk.b.Uw(str3);
ame.jRb = i;
this.ius = str;
}
public final void a(int i, int i2, int i3, String str, q qVar, byte[] bArr) {
x.i("MicroMsg.exdevice.NetSceneHardDeviceStatusSubscribe", "onGYNetEnd netId = " + i + " errType = " + i2 + " errCode = " + i3 + str);
ad.aHe().Al(this.ius);
if (i2 == 0 && i3 == 0) {
fl flVar = ((amf) this.ivF.dIE.dIL).six;
int i4 = flVar.rfn;
if (flVar.rgv.siN) {
String str2 = flVar.rgv.siM;
}
x.i("MicroMsg.exdevice.NetSceneHardDeviceStatusSubscribe", "HardDeviceStatusSubResponse: ret=" + i4 + ",msg=" + str);
}
this.doG.a(i2, i3, str, this);
}
public final int getType() {
return 1090;
}
public final int a(com.tencent.mm.network.e eVar, e eVar2) {
this.doG = eVar2;
return a(eVar, this.ivF, this);
}
}
|
package model.manager;
import java.io.File;
import java.util.Locale;
import java.util.Optional;
import java.util.ResourceBundle;
import org.apache.log4j.Logger;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonBar.ButtonData;
import model.Lang;
import model.Report;
import javafx.scene.control.ButtonType;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.control.Alert.AlertType;
public class DialogManager {
private final static Logger LOGGER = Logger.getLogger(DialogManager.class);
private static Locale currentLang = null;
private static Lang locale = LocaleManager.getCurrentLang();
// static Image image = new Image("/images/logo.jpg");
// static ImageView imageView = new ImageView(image);
public static void checkCinfirmationLang(Lang locale) {
if (locale.getIndex() == 0) {
currentLang = LocaleManager.RU_LOCALE;
} else if (locale.getIndex() == 1) {
currentLang = LocaleManager.UA_LOCALE;
}
}
public static void showErrorDialogOnLoadFile(File file) {
checkCinfirmationLang(locale);
ResourceBundle rb = ResourceBundle.getBundle(LocaleManager.BUNDLES_FOLDER, currentLang);
String title = rb.getString("error");
String text = rb.getString("noLoadFile");
LOGGER.info("method showErrorDialogOnLoadFile with " + title + " " + text);
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle(title);
alert.setContentText(text + file.getPath());
alert.setHeaderText("");
alert.showAndWait();
}
public static void showInfoDialog(String title, String text) {
LOGGER.info("method showInfoDialog with " + title + " " + text);
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle(title);
alert.setContentText(text);
alert.setHeaderText("");
alert.showAndWait();
}
public static Report showOptionalDOCX() {
checkCinfirmationLang(locale);
ResourceBundle rb = ResourceBundle.getBundle(LocaleManager.BUNDLES_FOLDER, currentLang);
String title = rb.getString("openFile");
String textHeader = rb.getString("openFileFolder");
String setContentText = rb.getString("openFileContext");
String one = rb.getString("firstDecision");
String two = rb.getString("secondDecision");
String cancel = rb.getString("cancel");
LOGGER.info(" method showOptionalDOCX");
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle(title);
alert.setHeaderText(textHeader);
alert.setContentText(setContentText);
ButtonType buttonTypeOne = new ButtonType(one);
ButtonType buttonTypeTwo = new ButtonType(two);
ButtonType buttonTypeCancel = new ButtonType(cancel, ButtonData.CANCEL_CLOSE);
alert.getButtonTypes().setAll(buttonTypeOne, buttonTypeTwo, buttonTypeCancel);
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == buttonTypeOne) {
return Report.ONE;
} else if (result.get() == buttonTypeTwo) {
return Report.MANY;
} else {
return Report.CANCEL;
}
}
public static ButtonType wantToDelete() {
LOGGER.info("method wantToDelete ");
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
checkCinfirmationLang(locale);
ResourceBundle rb = ResourceBundle.getBundle(LocaleManager.BUNDLES_FOLDER, currentLang);
String confirmationDialog = rb.getString("confirmationDialogonDelete");
String title = rb.getString("deleteRow");
alert.setTitle(confirmationDialog);
alert.setContentText(title);
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.OK) {
return ButtonType.OK;
} else {
LOGGER.info("Cancel");
return ButtonType.CANCEL;
}
}
public static void selectPerson() {
LOGGER.info("method selectPerson ");
checkCinfirmationLang(locale);
ResourceBundle rb = ResourceBundle.getBundle(LocaleManager.BUNDLES_FOLDER, currentLang);
String title = rb.getString("error");
String text = rb.getString("selectPerson");
String headerText = rb.getString("selectPersonHeader");
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle(title);
alert.setHeaderText(headerText);
alert.setContentText(text);
alert.showAndWait();
}
public static void incorrectPassword() {
Alert alert = new Alert(Alert.AlertType.WARNING);
checkCinfirmationLang(locale);
ResourceBundle rb = ResourceBundle.getBundle(LocaleManager.BUNDLES_FOLDER, currentLang);
String text = rb.getString("inccorectPasswordorLogin");
String title = rb.getString("error");
String headerText = rb.getString("errorAuthentication");
alert.setTitle(title);
alert.setHeaderText(headerText);
alert.setContentText(text);
alert.showAndWait();
}
public static void noDatatoSave() {
LOGGER.info("method noDatatoSave with ");
Alert alert = new Alert(Alert.AlertType.WARNING);
checkCinfirmationLang(locale);
ResourceBundle rb = ResourceBundle.getBundle(LocaleManager.BUNDLES_FOLDER, currentLang);
String text = rb.getString("NoDatatoSave");
String title = rb.getString("NoDatatoSave");
alert.setTitle(title);
alert.setContentText(text);
alert.showAndWait();
}
public static void fileSuccessfully() {
LOGGER.info("method showInfoDialog with " + "file successfully written" + " ");
Alert alert = new Alert(Alert.AlertType.INFORMATION);
checkCinfirmationLang(locale);
ResourceBundle rb = ResourceBundle.getBundle(LocaleManager.BUNDLES_FOLDER, currentLang);
String text = rb.getString("fileWritten");
String title = rb.getString("titleFileWritten");
String headerText = rb.getString("saveFileHeaderText");
alert.setTitle(title);
alert.setContentText(text);
alert.setHeaderText(headerText);
alert.showAndWait();
}
public static void addThroughLoad() {
LOGGER.info("method addThroughLoad");
Alert alert = new Alert(Alert.AlertType.INFORMATION);
checkCinfirmationLang(locale);
ResourceBundle rb = ResourceBundle.getBundle(LocaleManager.BUNDLES_FOLDER, currentLang);
String text = rb.getString("addition");
String title = rb.getString("additionThrough");
String headerText = rb.getString("additionThroughLoad");
alert.setTitle(title);
alert.setContentText(text);
alert.setHeaderText(headerText);
alert.showAndWait();
}
public static void deleteEditPerson() {
LOGGER.info("method deleteEditPerson");
checkCinfirmationLang(locale);
ResourceBundle rb = ResourceBundle.getBundle(LocaleManager.BUNDLES_FOLDER, currentLang);
String noSelection = rb.getString("noSelection");
String recordTable = rb.getString("recordTable");
String pleaseSelect = rb.getString("pleaseSelect");
Alert alert = new Alert(AlertType.WARNING);
alert.setTitle(noSelection);
alert.setHeaderText(recordTable);
alert.setContentText(pleaseSelect);
alert.showAndWait();
}
public static void deleteEditVaccine() {
LOGGER.info("method deleteEditVaccine");
checkCinfirmationLang(locale);
ResourceBundle rb = ResourceBundle.getBundle(LocaleManager.BUNDLES_FOLDER, currentLang);
String noSelectionVaccine = rb.getString("noSelectionVaccine");
String recordTableVeccine = rb.getString("recordTableVeccine");
String pleaseSelectVaccine = rb.getString("pleaseSelectVaccine");
Alert alert = new Alert(AlertType.WARNING);
alert.setTitle(noSelectionVaccine);
alert.setHeaderText(recordTableVeccine);
alert.setContentText(pleaseSelectVaccine);
alert.showAndWait();
}
}
|
package com.walkerwang.algorithm.bigcompany;
import java.util.Scanner;
public class Test {
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
while(scanner.hasNextInt())
{
int num = scanner.nextInt();
for(int i=0;i<num;i++)
{
int n=scanner.nextInt();
int k=scanner.nextInt();
int[] add = new int[2*n];
int[] arry_1 = new int[n];
int[] arry_2 = new int[n];
for(int j=0;j<2*n;j++)
{
if(j<n)
{
arry_1[j]=scanner.nextInt();
}
else
{
arry_2[j-n]=scanner.nextInt();
}
}
add=comput1(arry_1,arry_2,k,n);
for(int h=0;h<add.length;h++)
{
if(h==add.length-1)
System.out.print(add[h]);
else
System.out.print(add[h]+" ");
}
System.out.println();
}
}
}
public static int[] comput1(int[] arry_1,int[] arry_2,int k,int n)
{
int[] add = new int[2*n];
for(int i=0;i<k;i++)
{
add=comput(arry_1,arry_2,n);
for(int j=0;j<2*n;j++)
{
if(j<n)
{
arry_1[j]=add[j];
}
else
{
arry_2[j-n]=add[j];
}
}
}
return add;
}
public static int[] comput(int[] arry_1,int[] arry_2,int n)
{
int[] add = new int[2*n];
int[] add1= new int[2*n];
int i=0;
for(int w=n;w>0;w--)
{
add[i++]=arry_2[w-1];
add[i++]=arry_1[w-1];
}
for(int h=0;h<2*n;h++)
{
add1[2*n-h-1]=add[h];
}
return add1;
}
}
|
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.staticUIExtensions.model;
import jetbrains.buildServer.web.openapi.PlaceId;
import org.jetbrains.annotations.NotNull;
/**
* @author Eugene Petrenko (eugene.petrenko@gmail.com)
* Date: 16.11.11 18:51
*/
public class Rule {
@NotNull private final String myRuleId;
@NotNull private final UrlMatcher myUrlMatcher;
@NotNull private final PlaceId myPlace;
@NotNull private final StaticContent myContent;
public Rule(@NotNull final String id,
@NotNull final UrlMatcher urlMatcher,
@NotNull final PlaceId place,
@NotNull final StaticContent content) {
myRuleId = id;
myUrlMatcher = urlMatcher;
myPlace = place;
myContent = content;
}
@NotNull
public String getRuleId() {
return myRuleId;
}
@NotNull
public UrlMatcher getUrlMatcher() {
return myUrlMatcher;
}
@NotNull
public PlaceId getPlace() {
return myPlace;
}
@NotNull
public StaticContent getContent() {
return myContent;
}
@Override
public String toString() {
return "Rule{" +
"myUrlMatcher=" + myUrlMatcher +
", myPlace=" + myPlace +
", myContent=" + myContent +
'}';
}
}
|
package matrix;
public class BrightnessReducer implements MatrixOperation {
private float brightnessFactor;
BrightnessReducer(){
super();
brightnessFactor = 0.75f;
}
BrightnessReducer(float factor){
super();
brightnessFactor = factor;
}
@Override
public Pixel withPixel(int x, int y, Pixel[][] matrix) {
float red = matrix[x][y].getR()*brightnessFactor;
float green = matrix[x][y].getG()*brightnessFactor;
float blue = matrix[x][y].getB()*brightnessFactor;
return new Pixel(red, green, blue);
}
}
|
package daos;
public interface LoginDAO
{
boolean isValidUser(String username, String password, String role);
boolean insertUser(String username, String password, String role);
}
|
package com.cartesian.coordinateSystem.model;
/**
* This class represent 2 Lines
*/
public record TwoLine(Line line1, Line line2) {
}
|
package com.ecommerce.domain.cortamproduto;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import com.ecommerce.domain.cores.Cor;
import com.ecommerce.domain.fotos.FotoProduto;
import com.ecommerce.domain.produtos.Produto;
import com.ecommerce.domain.tamanhos.Tamanho;
import com.fasterxml.jackson.annotation.JsonIgnore;
@Entity
public class CorTamProduto {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@JsonIgnore
@ManyToOne
private Cor cor;
@JsonIgnore
@ManyToOne
private Tamanho tamanho;
@JsonIgnore
@ManyToOne
private Produto produto;
private Integer qtdEstoque;
@OneToMany(mappedBy = "corTamProduto", cascade = CascadeType.ALL)
private List<FotoProduto> fotos;
public List<FotoProduto> getFotos() {
return fotos;
}
public void setFotos(List<FotoProduto> fotos) {
this.fotos = fotos;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Tamanho getTamanho() {
return tamanho;
}
public void setTamanho(Tamanho tamanho) {
this.tamanho = tamanho;
}
public Integer getQtdEstoque() {
return qtdEstoque;
}
public void setQtdEstoque(Integer qtdEstoque) {
this.qtdEstoque = qtdEstoque;
}
public Produto getProduto() {
return produto;
}
public void setProduto(Produto produto) {
this.produto = produto;
}
public Cor getCor() {
return cor;
}
public void setCor(Cor cor) {
this.cor = cor;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CorTamProduto other = (CorTamProduto) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
|
package py.com.progweb.redsanitaria.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
@Entity
@Table(name = "hospital")
public class Hospital {
@Id
@Column(name = "codhospital")
@Basic(optional = false)
@GeneratedValue(generator = "codhospital_id_seq", strategy = GenerationType.SEQUENCE)
@SequenceGenerator(name = "codhospital_id_seq", sequenceName = "codhospital_id_seq", allocationSize = 0)
private Integer codhospital;
@Column(name = "nombre")
@Basic(optional = false)
private String nombre;
@Column(name = "ciudad")
@Basic(optional = false)
private String ciudad;
@Column(name = "telefono")
@Basic(optional = false)
private String telefono;
@OneToMany(mappedBy="hospital")
private Set<Servicio> servicios;
@OneToOne(mappedBy = "hospital")
private ConsultaCab consultaCab;
@OneToOne
@JoinColumn(name = "codmedico", referencedColumnName = "codmedico", nullable=false, insertable = false, updatable = false)
private Medico medico;
public Hospital() {
}
public Hospital(Integer codhospital, String nombre, String ciudad, String telefono) {
this.codhospital = codhospital;
this.nombre = nombre;
this.ciudad = ciudad;
this.telefono = telefono;
}
public Integer getCodhospital() {
return codhospital;
}
public void setCodhospital(Integer codhospital) {
this.codhospital = codhospital;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getCiudad() {
return ciudad;
}
public void setCiudad(String ciudad) {
this.ciudad = ciudad;
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public Medico getMedico() {
return medico;
}
public void setMedico(Medico medico) {
this.medico = medico;
}
}
|
/*
* 2012-3 Red Hat Inc. and/or its affiliates and other contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.overlord.rtgov.activity.server;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.overlord.commons.services.ServiceRegistryUtil;
import org.overlord.rtgov.common.util.RTGovProperties;
/**
* This class represents a CDI factory for obtaining an activity store implementation.
*
*/
public final class ActivityStoreFactory {
private static final Logger LOG=Logger.getLogger(ActivityStoreFactory.class.getName());
/**
* Property defining the activity store implementation class.
*/
public static final String ACTIVITY_STORE_CLASS="ActivityStore.class";
private static ActivityStore _instance;
/**
* Private constructor.
*/
private ActivityStoreFactory() {
}
/**
* This method resets the factory.
*/
public static void clear() {
_instance = null;
}
/**
* This method returns an instance of the ActivityStore interface.
*
* @return The activity store
*/
public static ActivityStore getActivityStore() {
if (_instance == null) {
java.util.Set<ActivityStore> services=ServiceRegistryUtil.getServices(ActivityStore.class);
String clsName=(String)RTGovProperties.getProperties().get(ACTIVITY_STORE_CLASS);
for (ActivityStore as : services) {
if (LOG.isLoggable(Level.FINEST)) {
LOG.finest("Checking activity store impl="+as);
}
if (as.getClass().getName().equals(clsName)) {
// Only overwrite if instance not set
if (_instance == null) {
_instance = as;
if (LOG.isLoggable(Level.FINEST)) {
LOG.finest("Found activity store impl="+as);
}
}
break;
}
}
}
if (LOG.isLoggable(Level.FINER)) {
LOG.finer("Activity store instance="+_instance);
}
return (_instance);
}
}
|
package com.myd.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
import java.util.UUID;
@RestController
public class HelloController {
/*@RequestMapping("/hello")
public String hello(){
return "hello";
}*/
@Autowired
private RedisTemplate redisTemplate;
@GetMapping("/hello")
public String hello() {
redisTemplate.opsForValue().set("admin", "admin");
return "测试";
}
@GetMapping("/get")
public String get() {
return redisTemplate.opsForValue().get("admin").toString();
}
@RequestMapping("/uid")
String uid(HttpSession session) {
UUID uid = (UUID) session.getAttribute("uid");
if (uid == null) {
uid = UUID.randomUUID();
}
session.setAttribute("uid", uid);
return session.getId();
}
}
|
package com.example.app.Model;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
public class Countries implements Serializable {
@SerializedName("name")
public String name;
@SerializedName("alpha3Code")
public String alpha3Code;
@SerializedName("capital")
public String capital;
public Countries (String name, String alpha3Code, String capital) {
this.name = name;
this.alpha3Code = alpha3Code;
this.capital = capital;
}
@Override
public String toString() {
return "Countries{" +
" name='" + name + '\'' +
" alpha3Code='" + alpha3Code + '\'' +
" capital='" + capital + '\''+
'}';
}
public String getNome() {
return name;
}
public String getSigla() {
return alpha3Code;
}
public String getCapital() {
return capital;
}
}
|
package com.github.io24m.validate4java;
/**
* @author lk1
* @description
* @create 2021-01-29 14:53
*/
public class ValidateInfo {
private String fileName;
private Class type;
private boolean success;
private String errorMessage;
private String format;
public static ValidateInfo success() {
ValidateInfo validateResult = new ValidateInfo();
validateResult.success = true;
return validateResult;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public Class getType() {
return type;
}
public void setType(Class type) {
this.type = type;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
|
package pl.wat.wel.projekt.pumo.electronicband.SchematEditor;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import pl.wat.wel.projekt.pumo.electronicband.R;
public class Edit_elements extends AppCompatActivity {
public static final String Elements_FILE = "elements.txt";
int detector = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_elements);
}
public void addElements(View view) {
EditText editText = (EditText) findViewById(R.id.name_of_element);
EditText editText1 = (EditText) findViewById(R.id.value_of_element);
File file = new File(getFilesDir(), Elements_FILE);
Log.d("ściezka pliku:", file.toString());
try {
BufferedWriter out = new BufferedWriter(new FileWriter(file, true));
out.write(editText.getText().toString());
out.newLine();
out.write(" " + editText1.getText().toString());
out.close();
Toast.makeText(this, "Element dodany.", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Nie udało się dodać: " + e.getCause(), Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent();
intent.putExtra("tryb", 1);
setResult(RESULT_FIRST_USER, intent);
finish();
}
}
|
package cn.bh.jc.common;
/**
* 日志文件
*
* @author liubq
* @since 2018年1月25日
*/
public class SysLog {
public static ILoglisten logListen = null;
/**
* 日志
*
* @param msgs
*/
public static void log(String... msgs) {
if (msgs == null) {
return;
}
for (String msg : msgs) {
if (logListen != null) {
logListen.log(msg);
} else {
System.out.println(msg);
}
}
}
/**
* 日志
*
* @param msgs
*/
public static void log(String msg, Throwable e) {
if (msg != null) {
if (logListen != null) {
logListen.log(msg);
} else {
System.out.println(msg);
}
}
if (e != null) {
if (logListen != null) {
logListen.log(e.getMessage());
for (StackTraceElement item : e.getStackTrace()) {
logListen.log(item.toString());
}
} else {
e.printStackTrace();
}
}
}
}
|
package com.cz.android.text.layout.div;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.text.Spanned;
import android.text.TextPaint;
import androidx.annotation.NonNull;
import com.cz.android.text.Styled;
import com.cz.android.text.layout.div.chunk.TextChunk;
import java.util.ArrayList;
import java.util.List;
/**
* 文本排版layout
* 当前实现功能
* 1. 实现多行文本排版
* 2. 实现断行策略抽离
* 3. 实现span
*/
public abstract class TextLayout {
private CharSequence text;
private TextPaint paint;
TextPaint workPaint;
Paint.FontMetricsInt fitFontMetricsInt;
Paint.FontMetricsInt okFontMetricsInt;
Paint.FontMetricsInt fontMetricsInt;
private int width;
private float spacingAdd;
private static Rect tempRect = new Rect();
private Spanned spanned;
private boolean spannedText;
private List<TextChunk> textChunkList;
/**
*
* @param text 操作文本
* @param paint 绘制paint
* @param width 排版宽
* @param spacingAdd 行额外添加空间
*/
protected TextLayout(CharSequence text, TextPaint paint,
int width, float spacingAdd) {
if (width < 0)
throw new IllegalArgumentException("Layout: " + width + " < 0");
this.text = text;
this.paint = paint;
this.width = width;
workPaint = new TextPaint();
this.spacingAdd = spacingAdd;
fontMetricsInt = new Paint.FontMetricsInt();
fitFontMetricsInt = new Paint.FontMetricsInt();
okFontMetricsInt = new Paint.FontMetricsInt();
if(text instanceof Spanned)
spanned = (Spanned) text;
spannedText = text instanceof Spanned;
}
public void addTextChunk(@NonNull TextChunk textChunk){
if(null==textChunkList){
textChunkList=new ArrayList<>();
}
textChunkList.add(textChunk);
}
public void removeTextChunk(@NonNull TextChunk textChunk){
if(null!=textChunkList){
textChunkList.remove(textChunk);
}
}
public List<TextChunk> getTextChunkList() {
return textChunkList;
}
public Paint.FontMetricsInt getFitFontMetricsInt() {
return fitFontMetricsInt;
}
public Paint.FontMetricsInt getOkFontMetricsInt() {
return okFontMetricsInt;
}
public Paint.FontMetricsInt getFontMetricsInt() {
return fontMetricsInt;
}
/**
* 获得指定类型的span对象
* @param start 查找文本起始位置
* @param end 查找文本结束位置
* @param type 查找对象字节码
* @param <T>
* @return 查找元素数组
*/
public <T> T[] getSpans(int start, int end, Class<T> type) {
return spanned.getSpans(start, end, type);
}
/**
* 返回行附加空间
* @return
*/
public final float getSpacingAdd() {
return spacingAdd;
}
/**
* 返回行个数
* @return
*/
public abstract int getLineCount();
/**
* 返回文本
* @return
*/
public final CharSequence getText() {
return text;
}
/**
* 返回操作Paint对象,也是关联操作View的Paint对象
* @return
*/
public final TextPaint getPaint() {
return paint;
}
/**
* 当前操作尺寸宽度
* @return
*/
public final int getWidth() {
return width;
}
/**
* 返回当前所占高度
* @return
*/
public int getHeight() {
return getLineTop(getLineCount());
}
/**
* 返回指定行起始高
* @param line
* @return
*/
public abstract int getLineTop(int line);
/**
* 获得行结束高度,此处暂不存在行间距运算
* @param line
* @return
*/
public final int getLineBottom(int line) {
return getLineTop(line + 1);
}
/**
* 返回指定行文本Descent位置
* @param line
* @return
*/
public abstract int getLineDescent(int line);
/**
* 返回指定行起始字符
* @param line
* @return
*/
public abstract int getLineStart(int line);
/**
* 返回行结束字符
* @param line
* @return
*/
public final int getLineEnd(int line) {
return getLineStart(line + 1);
}
/**
* 返回指定y轨位置所在行
* @param vertical 纵轨位置
* @return
*/
public int getLineForVertical(int vertical) {
int high = getLineCount(), low = -1, guess;
while (high - low > 1) {
guess = (high + low) / 2;
if (getLineTop(guess) > vertical)
high = guess;
else
low = guess;
}
if (low < 0)
return 0;
else
return low;
}
/**
* 返回可见的行位置
* @param line
* @param start
* @param end
* @return
*/
private int getLineVisibleEnd(int line, int start, int end) {
CharSequence text = this.text;
char ch;
if (line == getLineCount() - 1) {
return end;
}
for (; end > start; end--) {
ch = text.charAt(end - 1);
if (ch == '\n') {
return end - 1;
}
if (ch != ' ' && ch != '\t') {
break;
}
}
return end;
}
public int getSpanStart(Object tag) {
return spanned.getSpanStart(tag);
}
public int getSpanEnd(Object tag) {
return spanned.getSpanEnd(tag);
}
public int getSpanFlags(Object tag) {
return spanned.getSpanFlags(tag);
}
public int nextSpanTransition(int start, int limit, Class type) {
return spanned.nextSpanTransition(start, limit, type);
}
/**
* Draw this Layout on the specified Canvas.
*/
public void draw(Canvas c) {
int dtop, dbottom;
synchronized (tempRect) {
if (!c.getClipBounds(tempRect)) {
return;
}
dtop = tempRect.top;
dbottom = tempRect.bottom;
}
int top = 0;
int bottom = getLineTop(getLineCount());
if (dtop > top) {
top = dtop;
}
if (dbottom < bottom) {
bottom = dbottom;
}
int first = getLineForVertical(top);
int last = getLineForVertical(bottom);
int previousLineBottom = getLineTop(first);
int previousLineEnd = getLineStart(first);
TextPaint paint = this.paint;
CharSequence buf = text;
boolean spannedText = this.spannedText;
for (int i = first; i <= last; i++) {
int start = previousLineEnd;
previousLineEnd = getLineStart(i+1);
int end = getLineVisibleEnd(i, start, previousLineEnd);
int ltop = previousLineBottom;
int lbottom = getLineTop(i+1);
previousLineBottom = lbottom;
int lbaseline = lbottom - getLineDescent(i);
int left = 0;
int x= left;
if (!spannedText) {
c.drawText(buf, start, end, x, lbaseline, paint);
} else {
Styled.drawText(c, buf, start, end, x, ltop, lbaseline, lbottom, paint, workPaint, false);
}
}
}
}
|
package com.a1tSign.techBoom.data.entity;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
import java.util.List;
@Entity
@Table (name = "cart")
@Getter
@Setter
@EqualsAndHashCode
@ToString
public class Cart {
@Id
private Long id;
@ManyToMany
@JoinTable (
name = "cart_items",
joinColumns = @JoinColumn(name = "cart_id", referencedColumnName = "user_id"),
inverseJoinColumns = @JoinColumn(name = "item_id", referencedColumnName = "id")
)
private List<Item> items;
@OneToOne (fetch = FetchType.LAZY)
@MapsId
private User user;
}
|
package com.beiyelin.projectportal.entity;
import com.beiyelin.commonsql.jpa.BaseDomainEntity;
import com.beiyelin.commonsql.jpa.MasterDataEntity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import static com.beiyelin.commonsql.constant.Repository.CODE_LENGTH;
import static com.beiyelin.commonsql.constant.Repository.NAME_LENGTH;
/**
* @Description: 费用类型
* @Author: newmann
* @Date: Created in 14:43 2018-02-21
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper=true)
@Entity
@Table(name = ExpenseType.TABLE_NAME
// ,indexes ={@Index(name=Project.TABLE_NAME +"_code",columnList = "idCard",unique = true)}
)
public class ExpenseType extends MasterDataEntity {
public static final String TABLE_NAME="s_expense_type";
private static final long serialVersionUID = 1L;
@Column(unique = true,length = CODE_LENGTH)
private String code;
@Column(unique = true,length = NAME_LENGTH)
private String name;
// @Column(nullable = false)
// private int status = 1; //按主数据状态处理
}
|
package com.goldgov.dygl.module.partymember.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.goldgov.dygl.dynamicfield.DynamicField;
import com.goldgov.dygl.dynamicfield.DynamicFieldBaseService;
import com.goldgov.dygl.module.partymember.dao.IPartyMemberDao_AA;
import com.goldgov.dygl.module.partymember.exception.NoAuthorizedFieldException;
import com.goldgov.dygl.module.partymember.service.AssessmentScoreBean;
import com.goldgov.dygl.module.partymember.service.IPartyMemberService_AA;
import com.goldgov.dygl.module.partymember.service.InfoAuditShowBean;
import com.goldgov.dygl.module.partymember.service.InfoOperateLog;
import com.goldgov.dygl.module.partymember.service.MemberInfoAudit;
import com.goldgov.dygl.module.partymember.service.PartyMemberQuery;
import com.goldgov.dygl.module.partymember.service.SynOperateLog;
import com.goldgov.dygl.module.partymember.service.UserBaseInfo;
import com.goldgov.dygl.module.partyorganization.partybranch.service.MeetingMemberBean;
import com.goldgov.gtiles.api.IUser;
import com.goldgov.gtiles.core.web.UserHolder;
import com.goldgov.gtiles.module.businessfield.service.BusinessField;
import com.goldgov.gtiles.module.businessfield.service.IBusinessFieldService;
import com.goldgov.gtiles.module.user.client.JsonMapperUtils;
import com.goldgov.gtiles.module.user.client.ResultInfo;
import com.goldgov.gtiles.module.user.client.SychorizeUserInfoBean;
import com.goldgov.gtiles.module.user.client.SynUserAndDepInfoWebservice;
import com.goldgov.gtiles.module.user.dao.IUserDao;
import com.goldgov.gtiles.module.user.service.IUserService;
import com.goldgov.gtiles.module.user.service.User;
@Service("partyMemberService_AA")
public class PartyMemberServiceImpl_AA extends DynamicFieldBaseService implements IPartyMemberService_AA{
@Autowired
@Qualifier("partyMemberDao_AA")
private IPartyMemberDao_AA partyMemberDao_AA;
@Autowired
@Qualifier("businessFieldService")
private IBusinessFieldService businessFieldService;
@Autowired
@Qualifier("userDao")
private IUserDao userDao;
@Autowired
@Qualifier("userService")
private IUserService userService;
@Override
public List<BusinessField> preAddInfo() throws NoAuthorizedFieldException {
String serviceCode = "aa";
String[] fieldNames = getFieldNames(serviceCode);
List<BusinessField> fieldList = businessFieldService.findBusinessFieldByFieldName(serviceCode, fieldNames);
return fieldList;
}
@Override
public void addInfo(Map paramMap) throws NoAuthorizedFieldException {
String serviceCode = "aa";
DynamicField dynamicField = buildDynamicField(serviceCode, paramMap);
if(dynamicField.hasField()){
partyMemberDao_AA.addInfo(dynamicField);
}
}
@Override
public void updateInfo(String entityID,Map paramMap) throws NoAuthorizedFieldException{
String serviceCode = "aa";
DynamicField dynamicField = buildDynamicField(serviceCode, paramMap);
if(dynamicField.hasField()){
dynamicField.putField(serviceCode, "LASTUPDATE_TIME",new Date());
partyMemberDao_AA.updateInfo(entityID,dynamicField);
List<UserBaseInfo> userList = partyMemberDao_AA.getUserInfos(new String[]{entityID});
IUser user = UserHolder.getUser();
InfoOperateLog deleteLog = new InfoOperateLog(userList,InfoOperateLog.OPERATE_METHOD_UPDATE,null);
String operateLogId = UUID.randomUUID().toString().replaceAll("-", "");
deleteLog.setOperateLogId(operateLogId);
deleteLog.setOperateUserId(user.getLoginName());
deleteLog.setOperateUserName(user.getName());
saveOperateLog(deleteLog);
synUserInfo(new String[]{entityID},"add",operateLogId);
}
}
public void synUserInfo(String[] aaIds,String type,String operateLogId){
List<User> userList = partyMemberDao_AA.getInfoByAAID(aaIds);
List<SychorizeUserInfoBean> beanList=new ArrayList<SychorizeUserInfoBean>();
for(User user:userList){
SychorizeUserInfoBean bean = new SychorizeUserInfoBean(user);
bean.setOrgId(user.getOrgCode());
bean.setCountStudy(user.getUserStatus());
beanList.add(bean);
}
synUserThread(beanList,type,operateLogId);
}
@Override
public List<BusinessField> findInfoById(String entityID)throws NoAuthorizedFieldException {
String serviceCode = "aa";
DynamicField dynamicField = buildDynamicField(serviceCode);
Map<String,Object> infoMap = partyMemberDao_AA.findInfoById(entityID,dynamicField);
String[] fieldNames = getFieldNames(serviceCode);
List<BusinessField> fieldList = businessFieldService.findBusinessFieldByFieldName(serviceCode, fieldNames);
if(infoMap != null && !infoMap.isEmpty()){
for (int i = 0; i < fieldList.size(); i++) {
BusinessField businessField = fieldList.get(i);
Object value = infoMap.get(businessField.getFieldName());
businessField.setFieldValue(value);
}
}
return fieldList;
}
@Override
public void deleteInfo(String[] entityIDs) {
partyMemberDao_AA.deleteInfo(entityIDs);
}
@Override
public List<Map<String, Object>> findInfoList(PartyMemberQuery query,Map<String,Object> paramMap)throws NoAuthorizedFieldException {
String serviceCode = "aa";
DynamicField dynamicField = buildDynamicField(serviceCode);
// dynamicField.getSelectFields();
List<Map<String, Object>> infoList = partyMemberDao_AA.findInfoListByPage(query, dynamicField);
query.setResultList(infoList);
String[] fieldNames = getFieldNames(serviceCode);
List<BusinessField> fieldList = businessFieldService.findBusinessFieldByFieldName(serviceCode, fieldNames, true);
query.setFieldList(fieldList);
return infoList;
}
@Override
public List<Map<String, Object>> findInfoListAndPost(PartyMemberQuery query,Map<String,Object> paramMap, Boolean isPage)throws NoAuthorizedFieldException {
String serviceCode = "aa";
DynamicField dynamicField = buildDynamicField(serviceCode);
List<Map<String, Object>> infoList = null;
if(isPage)
infoList = partyMemberDao_AA.findInfoAndPostListByPage(query, dynamicField);
else
infoList = partyMemberDao_AA.findInfoAndPostList(query, dynamicField);
query.setResultList(infoList);
String[] fieldNames = getFieldNames(serviceCode);
List<BusinessField> fieldList = businessFieldService.findBusinessFieldByFieldName(serviceCode, fieldNames, true);
query.setFieldList(fieldList);
return infoList;
}
@Override
public void addInfoFromUser(String userIds,String partyOrganizationID) {
String[] userId = userIds.split(",");
for(int i=0;i<userId.length;i++){
if(userId[i]!=null && !"".equals(userId[i])){
boolean hasMemberUser = partyMemberDao_AA.hasMemberUser(userId[i]);
if(!hasMemberUser){
partyMemberDao_AA.addInfoFromUser(userId[i],partyOrganizationID);
}
}
}
}
public void synUserThread(List<SychorizeUserInfoBean> beanList,String type,String operateLogId){
final List<SychorizeUserInfoBean> beanListFinal = beanList;
final String finalType = type;
final String finalOperateLogId = operateLogId;
Thread t = new Thread(){
public void run(){
SynUserAndDepInfoWebservice synUserServer=userService.getService();
SychorizeUserInfoBean bean = new SychorizeUserInfoBean(beanListFinal);
bean.setDistributeType(SychorizeUserInfoBean.DISTRIBUTE_TYPE_USER);
ResultInfo resultInfo=synUserServer.sychonizeUser(finalType, JsonMapperUtils.beanToJson(bean));
SynOperateLog log = new SynOperateLog(resultInfo,finalOperateLogId);
saveSynLog(log);
}
};
t.start();
}
public boolean hasMemberUser(String userId){
boolean hasMemberUser = partyMemberDao_AA.hasMemberUser(userId);
return hasMemberUser;
}
@Override
public List<String> findUserOrgID(String userId) {
List<String> organizationIDs = partyMemberDao_AA.findUserOrgID(userId);
return organizationIDs;
}
@Override
public List<Map<String, Object>> findInfoByUserIds(PartyMemberQuery query) {
List<Map<String, Object>> infoList = partyMemberDao_AA.findInfoByUserIdsByPage(query);
return infoList;
}
@Override
public List<Map<String, Object>> findInfoByUserId(String entityID) throws Exception{
return partyMemberDao_AA.findInfoByUserId(entityID);
}
@Override
public List<BusinessField> findInfoByParams(String tableName,
String markName, String entityID,String pkName) throws Exception {
DynamicField dynamicField = buildDynamicField(markName);
Map<String,Object> infoMap = partyMemberDao_AA.findInfoByParams(tableName,markName,entityID,pkName,dynamicField);
String[] fieldNames = getFieldNames(markName);
List<BusinessField> fieldList = businessFieldService.findBusinessFieldByFieldName(markName, fieldNames);
if(infoMap != null && !infoMap.isEmpty()){
for (int i = 0; i < fieldList.size(); i++) {
BusinessField businessField = fieldList.get(i);
Object value = infoMap.get(businessField.getFieldName());
businessField.setFieldValue(value);
}
}
return fieldList;
}
@Override
public List<InfoAuditShowBean> findAuditList(
PartyMemberQuery partyMemberQuery,
Map<String, List<String>> auditParam,Map<String,Object> paramMap) throws Exception {
List<InfoAuditShowBean> infoList = partyMemberDao_AA.findAuditListByPage(partyMemberQuery, auditParam);
return infoList;
}
@Override
public void saveMemberInfoAudit(MemberInfoAudit memberInfoAudit) throws Exception{
partyMemberDao_AA.saveMemberInfoAudit(memberInfoAudit);
}
@Override
public MemberInfoAudit getAuditByAAId(String aaId) throws Exception {
return partyMemberDao_AA.getAuditByAAId(aaId);
}
@Override
public void updateMemberInfoAudit(MemberInfoAudit memberInfoAudit)
throws Exception {
partyMemberDao_AA.updateMemberInfoAudit(memberInfoAudit);
}
@Override
public List<Map<String, Object>> getNotPassedList(
PartyMemberQuery partyMemberQuery, Map<String,Object> parameterMap)
throws Exception {
String serviceCode = "aa";
DynamicField dynamicField = buildDynamicField(serviceCode);
List<Map<String, Object>> infoList = partyMemberDao_AA.getNotPassedListByPage(partyMemberQuery,dynamicField);
partyMemberQuery.setResultList(infoList);
String[] fieldNames = getFieldNames(serviceCode);
List<BusinessField> fieldList = businessFieldService.findBusinessFieldByFieldName(serviceCode, fieldNames, true);
partyMemberQuery.setFieldList(fieldList);
return infoList;
}
@Override
public List<MemberInfoAudit> getAuditListByOrgId(
String partyOrganizationID, Integer auditState)
throws Exception {
return partyMemberDao_AA.getAuditListByOrgId(partyOrganizationID,auditState);
}
@Override
public List<InfoAuditShowBean> findBeforeAuditList(
PartyMemberQuery partyMemberQuery) throws Exception {
List<InfoAuditShowBean> list = partyMemberDao_AA.findBeforeAuditListByPage(partyMemberQuery);
return list;
}
@Override
public String findUserIDByAaID(String aaid) {
return partyMemberDao_AA.findUserIDByAaID(aaid);
}
public String getAaID(String partyOrgId, String userId){
String[] memberIds = partyMemberDao_AA.getAaID(partyOrgId, userId);
if(memberIds.length>0){
return memberIds[0];
}
return null;
}
@Override
public String getOrgType(String partyOrganizationID) {
return partyMemberDao_AA.getOrgType(partyOrganizationID);
}
@Override
public String getInnerDuty(String aaId) {
return partyMemberDao_AA.getInnerDuty(aaId);
}
@Override
public List<String> getOrgTypeList(String aaId,String[] orgIds) {
return partyMemberDao_AA.getOrgTypeList(aaId,orgIds);
}
@Override
public List<String> getACDutyList(String aaId,String[] orgIds) {
// TODO Auto-generated method stub
return partyMemberDao_AA.getACDutyList(aaId,orgIds);
}
@Override
public String getAAIDByLoginId(String loginId) {
// TODO Auto-generated method stub
return partyMemberDao_AA.getAAIDByLoginId(loginId);
}
@Override
public List<UserBaseInfo> getUserInfo(String aaid) {
// TODO Auto-generated method stub
return partyMemberDao_AA.getUserInfo(aaid);
}
@Override
public MeetingMemberBean fingMeetingMemberByParam(String tableName,
String entityID, String pkName) {
// TODO Auto-generated method stub
return partyMemberDao_AA.fingMeetingMemberByParam(tableName,entityID,pkName);
}
@Override
public String getHasRole(String entityID, String roleCode,String partyOrgID) {
// TODO Auto-generated method stub
return partyMemberDao_AA.getHasRole(entityID,roleCode,partyOrgID);
}
@Override
public String getOrgIdByAAId(String aaId){
return partyMemberDao_AA.getOrgIdByAAId(aaId);
}
@Override
public void updateMemberPartyOrgInfo(String partyOrgId, String partyMemberId){
partyMemberDao_AA.updateMemberPartyOrgInfo(partyOrgId, partyMemberId);
}
@Override
public void updateInfoFromUser(String userId, String partyOrganizationID) {
partyMemberDao_AA.updateInfoUser(userId,partyOrganizationID);
}
@Override
public List<UserBaseInfo> getUserInfos(String[] aaIds) {
// TODO Auto-generated method stub
return partyMemberDao_AA.getUserInfos(aaIds);
}
@Override
public void saveOperateLog(InfoOperateLog deleteLog) {
partyMemberDao_AA.saveOperateLog(deleteLog);
}
@Override
public void saveSynLog(SynOperateLog log) {
partyMemberDao_AA.saveSynLog(log);
}
@Override
public List<String> getPmAaIdListByOrgIds(String[] orgIds) {
// TODO Auto-generated method stub
return partyMemberDao_AA.getPmAaIdListByOrgIds(orgIds);
}
@Override
public List<String> getAAIDByLoginIds(String[] userIds) {
// TODO Auto-generated method stub
return partyMemberDao_AA.getAAIDByLoginIds(userIds);
}
@Override
public void updateOrderNum(Integer orderNum, String partyMemberId) {
partyMemberDao_AA.updateOrderNum(orderNum, partyMemberId);
}
@Override
public List<AssessmentScoreBean> findBeforeAssessmentList(
PartyMemberQuery partyMemberQuery,String ratedId) throws Exception {
List<AssessmentScoreBean> list = partyMemberDao_AA.findBeforeAssessmentListByPage(partyMemberQuery,ratedId);
return list;
}
@Override
public List<String> findUserIDByPoAaID(String poaaid) {
return partyMemberDao_AA.findUserIDByPoAaID(poaaid);
}
@Override
public void updateGroupID(String[] userIds, String groupID) {
partyMemberDao_AA.updateGroupID(userIds, groupID);
}
@Override
public List<String> findUserGroupID(String userId) {
return partyMemberDao_AA.findUserGroupID(userId);
}
@Override
public String getOrgIdByloginId(String loginID) {
return partyMemberDao_AA.getOrgIdByloginId(loginID);
}
}
|
package Assignment4;
import java.util.*;
//import java.util.function.Consumer;
//import java.util.stream.Collectors;
public class Assignment4Q7 {
public static void main(String[] args) {
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("Alpha", 1);
hashMap.put("Bravo", 2);
hashMap.put("Charlie", 3);
hashMap.put("Delta", 4);
Assignment4Q7 assign = new Assignment4Q7();
System.out.println(assign.convertKeyValueToString(hashMap));
}
public String convertKeyValueToString(HashMap<String, Integer> map) {
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, Integer> entry : map.entrySet()) {
sb.append(entry.getKey());
sb.append(entry.getValue());
}
return sb.toString();
// //Using Stream
// String result = map.entrySet().stream().map(entry -> entry.getKey() + entry.getValue())
// .collect(Collectors.joining(""));
// return result;
}
}
|
package com.thechema.game;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL13.*;
import org.lwjgl.opengl.*;
import static org.lwjgl.system.MemoryUtil.*;
import java.applet.Applet;
import java.applet.AudioClip;
import java.io.IOException;
import java.net.URL;
import javax.swing.*;
import com.thechema.game.graphics.Shader;
import com.thechema.game.input.Input;
import com.thechema.game.input.Menu;
import com.thechema.game.level.Level;
import com.thechema.math.Matrix4f;
//New Comment 2
//Random Comment
public class Main implements Runnable {
private int width = 800;
private int height = 600;
private Thread thread;
private boolean running = false;
private long window;
static Menu nyito;
//private TrueTypeFont font;
private Level level;
public void start(){
running = true;
thread = new Thread(this,"Game");
thread.start();
}
private void init(){
if(glfwInit() != true){
System.err.println("Could not initialize GLFW!");
return;
}
glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
window = glfwCreateWindow(width, height, "Airplane", NULL, NULL);
if(window == NULL){
System.err.println("Could not create GLFW window!");
return;
}
//ByteBuffer vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());
glfwSetWindowPos(window, 300, 100);
glfwSetKeyCallback(window, new Input());
glfwMakeContextCurrent(window);
glfwShowWindow(window);
GL.createCapabilities();
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glEnable(GL_DEPTH_TEST);
glActiveTexture(GL_TEXTURE1);
System.out.println("OpenGL: " + glGetString(GL_VERSION));
Shader.loadAll();
Matrix4f pr_matrix = Matrix4f.orthographic(-10.0f, 10.0f, -10.0f * 9.0f / 16.0f, 10.0f * 9.0f / 16.0f, -1.0f, 1.0f);
Shader.BG.setUniformMat4f("pr_matrix", pr_matrix);
Shader.BG.setUniform1i("tex", 1);
Shader.AIRPLANE.setUniformMat4f("pr_matrix", pr_matrix);
Shader.AIRPLANE.setUniform1i("tex", 1);
Shader.BUILDING.setUniformMat4f("pr_matrix", pr_matrix);
Shader.BUILDING.setUniform1i("tex", 1);
Shader.ENEMY.setUniformMat4f("pr_matrix", pr_matrix);
Shader.ENEMY.setUniform1i("tex", 1);
Shader.AMMO.setUniformMat4f("pr_matrix", pr_matrix);
Shader.AMMO.setUniform1i("tex", 1);
Shader.SCORE.setUniformMat4f("pr_matrix", pr_matrix);
Shader.SCORE.setUniform1i("tex", 1);
Shader.COIN.setUniformMat4f("pr_matrix", pr_matrix);
Shader.COIN.setUniform1i("tex", 1);
level = new Level();
}
public void run(){
init();
long lastTime = System.nanoTime();
double delta = 0.0;
double ms = 1000000000.0 / 60.0;
long timer = System.currentTimeMillis();
int updates = 0;
int frames = 0;
while(running){
long now = System.nanoTime();
delta +=(now-lastTime) / ms;
lastTime = now;
if(delta >= 1.0){
update();
updates++;
delta--;
}
render();
frames++;
if(System.currentTimeMillis() - timer > 1000){
timer += 1000;
System.out.println(updates + "ups, " + frames/10 + " fps");
updates=0;
frames = 0;
}
if(glfwWindowShouldClose(window) == true){
running= false;
}
}
glfwDestroyWindow(window);
glfwTerminate();
}
private void update(){
glfwPollEvents();
level.update();
if(level.isGameOver()){
Level.resetNumbers();
//level = new Level();
nyito.setIsRunning(false);
running = false;
}
}
private void render(){
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
level.render();
int error = glGetError();
if(error != GL_NO_ERROR)
System.out.println(error);
glfwSwapBuffers(window);
}
public static void main(String[] args) throws IOException {
nyito = new Menu();
nyito.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
nyito.setVisible(true);
}
}
|
package com.design.pattern;
public class MyPrototype implements Cloneable {
private Integer id;
private String name;
private MyPrototype() {
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
private MyPrototype(Integer id, String name) {
super();
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static void main(String[] args) throws CloneNotSupportedException {
MyPrototype m = new MyPrototype();
MyPrototype m11 =(MyPrototype) m.clone();
System.out.println(m.hashCode());
System.out.println(m11.hashCode());
}
}
|
package com.dict.hm.dictionary.ui.adapter;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.ClipDrawable;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.dict.hm.dictionary.R;
/**
* Created by hm on 15-5-28.
*/
public class NavigationDrawerAdapter extends BaseAdapter{
public static final int PERSONAL_DICT = 1;
public static final int SWITCH_DICT = 2;
public static final int LIST_PAPER = 3;
public static final int MANAGE_DICT = 4;
public static final int MANAGE_PAPER = 5;
public static final int SETTINGS = 6;
public static final int ABOUT = 7;
private Context context;
private LayoutInflater inflater;
private Resources resources;
private final int count = 12;
public NavigationDrawerAdapter(Context context) {
this.context = context;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
resources = context.getResources();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
view = inflater.inflate(R.layout.drawer_item, parent, false);
} else {
view = convertView;
}
String string;
switch (position) {
case 2: //personal dict
string = context.getString(R.string.drawer_personal_dict);
break;
case 3: //switch dict
string = context.getString(R.string.drawer_dict_switch);
break;
case 4: //list paper
string = context.getString(R.string.drawer_paper_list);
break;
case 6: //manage dict
string = context.getString(R.string.drawer_dict_manager);
break;
case 7: //manage paper
string = context.getString(R.string.drawer_paper_manager);
break;
case 9: //settings
string = context.getString(R.string.drawer_settings);
break;
case 10: //about
string = context.getString(R.string.drawer_about);
break;
case 0: //image
case 1: //space
case 5: //divider
case 8: //divider
case 11: //space
string = null;
break;
default:
string = "";
}
TextView textView = (TextView) view.findViewById(R.id.drawer_text);
textView.setText(string);
view.setBackground(null);
if (string == null) {
if (position == 0) {
view.getLayoutParams().height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
152, resources.getDisplayMetrics());
view.setBackgroundResource(R.drawable.ic_wallpaper);
} else if (position == 1 || position == 11){
view.getLayoutParams().height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
16, resources.getDisplayMetrics());
} else {
view.getLayoutParams().height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
16, resources.getDisplayMetrics());
ClipDrawable drawable = (ClipDrawable) resources.getDrawable(R.drawable.drawer_divider);
if (drawable != null) {
//set title divider height to 1dp, view's height is 16dp
int level = 10000 / 16;
drawable.setLevel(level);
}
view.setBackground(drawable);
}
}
return view;
}
@Override
public int getItemViewType(int position) {
int type;
switch (position) {
case 2: //personal dict
type = PERSONAL_DICT;
break;
case 3: //switch dict
type = SWITCH_DICT;
break;
case 4: //list paper
type = LIST_PAPER;
break;
case 6: //manage dict
type = MANAGE_DICT;
break;
case 7: //manage paper
type = MANAGE_PAPER;
break;
case 9: //settings
type = SETTINGS;
break;
case 10: //about
type = ABOUT;
break;
// case 0: //image
// case 1: //space
// case 5: //divider
// case 8: //divider
// case 11: //space
default:
type = 0;
}
return type;
}
@Override
public boolean isEnabled(int position) {
return getItemViewType(position) > 0;
}
@Override
public int getCount() {
return count;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return position;
}
}
|
package com.albabich.grad.web.vote;
import com.albabich.grad.AuthorizedUser;
import com.albabich.grad.model.Vote;
import com.albabich.grad.repository.RestaurantRepository;
import com.albabich.grad.repository.UserRepository;
import com.albabich.grad.repository.VoteRepository;
import com.albabich.grad.to.VoteTo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import javax.validation.Valid;
import java.net.URI;
import java.time.LocalDate;
import static com.albabich.grad.util.ValidationUtil.checkChangeVoteAbility;
@RestController
@RequestMapping(value = ProfileVoteController.REST_URL, produces = MediaType.APPLICATION_JSON_VALUE)
public class ProfileVoteController {
static final String REST_URL = "/rest/profile/votes";
private static final Logger log = LoggerFactory.getLogger(ProfileVoteController.class);
private final VoteRepository voteRepository;
private final UserRepository userRepository;
private final RestaurantRepository restaurantRepository;
public ProfileVoteController(VoteRepository voteRepository, UserRepository userRepository, RestaurantRepository restaurantRepository) {
this.voteRepository = voteRepository;
this.userRepository = userRepository;
this.restaurantRepository = restaurantRepository;
}
@Transactional
@PostMapping()
public ResponseEntity<Vote> createWithLocation(@RequestBody @Valid VoteTo voteTo, @AuthenticationPrincipal AuthorizedUser authUser) {
int userId = authUser.getId();
int restaurantId = voteTo.getRestaurantId();
Vote vote = new Vote(null, LocalDate.now(), restaurantRepository.getById(restaurantId));
log.info("create vote {} for user {} for restaurant {}", vote, userId, restaurantId);
vote.setUser(userRepository.getById(userId));
Vote todayVote = voteRepository.getByDateAndUser(LocalDate.now(), userId);
if (todayVote != null) {
checkChangeVoteAbility();
vote.setId(todayVote.id());
}
Vote created = voteRepository.save(vote);
URI uriOfNewResource = ServletUriComponentsBuilder.fromCurrentContextPath()
.path(REST_URL + "/{id}")
.buildAndExpand(created.getId()).toUri();
return ResponseEntity.created(uriOfNewResource).body(created);
}
}
|
package cn.chinaSoft.pandaMall.sellerCenter.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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.ResponseBody;
import cn.chinaSoft.pandaMall.common.base.ResponseModel;
import cn.chinaSoft.pandaMall.common.constant.PmConstant;
import cn.chinaSoft.pandaMall.common.entity.User;
import cn.chinaSoft.pandaMall.common.util.PropertiesUtil;
import cn.chinaSoft.pandaMall.sellerCenter.entity.SellerGoodInfo;
import cn.chinaSoft.pandaMall.sellerCenter.service.SellerService;
@Controller
@RequestMapping(value="/SellerCenter")
public class SellerController {
@Autowired
private SellerService sellerService;
@RequestMapping(value = "/getGoodsList", method = RequestMethod.POST)
@ResponseBody
private ResponseModel getGoodsList(@RequestBody SellerGoodInfo sellerGoodInfo,ModelMap map) {
// System.out.println(PropertiesUtil.getProperty("pm.good.pic.path"));
List<?> dataList=sellerService.getGoodsList(sellerGoodInfo);
ResponseModel responseModel=new ResponseModel();
if(null!=dataList) {
responseModel.setResult(PmConstant.SUCCESS);
responseModel.setDataList(dataList);
}else {
responseModel.setResult(PmConstant.FAIL);
}
return responseModel;
}
public SellerService getSellerService() {
return sellerService;
}
public void setSellerService(SellerService sellerService) {
this.sellerService = sellerService;
}
}
|
package taskLightSOEPA;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class TaskLight {
private int dimmingValue = -1;
private int toningValue = -1;
public synchronized boolean dimmingMix(int dv, int tv) {
boolean ret = true;
File file = new File("");
PrintWriter pw = null;
try {
pw = new PrintWriter(new BufferedWriter(new FileWriter(file, true)));
pw.println(fromlxToDimmingValue(dv) + "," + fromKToToningValue(tv));
pw.close();
dimmingValue = dv;
toningValue = tv;
} catch (IOException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
ret = false;
}
return ret;
}
public boolean reDimmingMix() {
return dimmingMix(dimmingValue, toningValue);
}
public int getDimmingValue() {
return dimmingValue;
}
public int getToningValue() {
return toningValue;
}
private int fromlxToDimmingValue(int dv) {
int ret = -1;
// Aさん(100,0),(600lx,3000K)
// Bさん(255,255),(1200lx,4600K)
// A+B(175,165),(900lx,3800K)
if (dv == 600) {
ret = 100;
} else if (dv == 900) {
ret = 175;
} else if (dv == 1200) {
ret = 255;
}// 適当あとで削除
else {
ret = (int) (0.2583 * (double) dv - 55.833);
if (ret < 0) {
ret = 0;
} else if (ret > 255) {
ret = 255;
}
}
return ret;
}
private int fromKToToningValue(int tv) {
int ret = -1;
// Aさん(100,0),(600lx,3000K)
// Bさん(255,255),(1200lx,4600K)
// A+B(175,165),(900lx,3800K)
if (tv == 3000) {
ret = 0;
} else if (tv == 3800) {
ret = 165;
} else if (tv == 4600) {
ret = 255;
}// 適当あとで削除
else {
ret = (int) (-6E-05 * (double) tv * (double) tv + 0.6047
* (double) tv - 1286.7);
if (ret < 0) {
ret = 0;
} else if (ret > 255) {
ret = 255;
} else if (4600 < tv) {
ret = 255;
}
}
return ret;
}
}
|
package com.tencent.mm.plugin.exdevice.ui;
import com.tencent.mm.R;
import com.tencent.mm.plugin.exdevice.ui.ExdeviceProfileUI.23;
import com.tencent.mm.ui.base.l;
import com.tencent.mm.ui.base.n.c;
class ExdeviceProfileUI$23$1 implements c {
final /* synthetic */ 23 iED;
ExdeviceProfileUI$23$1(23 23) {
this.iED = 23;
}
public final void a(l lVar) {
lVar.e(2, this.iED.iEx.getString(R.l.exdevice_profile_dis_follow));
}
}
|
package api.longpoll.bots.methods;
import api.longpoll.bots.http.HttpClient;
import api.longpoll.bots.model.objects.media.FileType;
import java.io.File;
/**
* Uploads file to VK.
* This request requires neither <b>access token</b> not <b>API version</b> as parameters.
*
* @param <Response> VK API response type.
* @see VkApiMethod
*/
public abstract class FileUploadingVkApiMethod<Response> extends VkApiMethod<Response> {
/**
* File to be uploaded to VK server.
*/
private File file;
@Override
public HttpClient getVkApiHttpClient() {
HttpClient vkApiHttpClient = super.getVkApiHttpClient();
vkApiHttpClient.setFile(getType().getKey(), file.getName(), file);
return vkApiHttpClient;
}
/**
* Gets file type.
*
* @return file type.
* @see FileType
*/
protected abstract FileType getType();
public File getFile() {
return file;
}
public FileUploadingVkApiMethod<Response> setFile(File file) {
this.file = file;
return this;
}
}
|
package de.lgohlke.pebuild;
import de.lgohlke.pebuild.config.dto.Step;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class StepExecutorConverterTest {
@Test
void shouldConvertToShellExecutor() {
Step step = new Step();
step.setName("demo");
step.setCommand("date");
step.setTimeout("1m");
StepExecutor executor = new StepExecutorConverter(step).asShellExecutor();
assertThat(executor.getCommand()).isEqualTo(step.getCommand());
assertThat(executor.getTimeout()).isEqualTo(step.getTimeoutAsDuration());
}
}
|
package com.tencent.mm.ui.contact;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Process;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.tencent.mm.R;
import com.tencent.mm.ab.e;
import com.tencent.mm.ab.l;
import com.tencent.mm.kernel.g;
import com.tencent.mm.l.a;
import com.tencent.mm.model.au;
import com.tencent.mm.model.c;
import com.tencent.mm.model.q;
import com.tencent.mm.model.s;
import com.tencent.mm.platformtools.ai;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.pluginsdk.ui.d;
import com.tencent.mm.pluginsdk.ui.d.j;
import com.tencent.mm.protocal.c.aft;
import com.tencent.mm.protocal.c.biy;
import com.tencent.mm.sdk.platformtools.BackwardSupportUtil;
import com.tencent.mm.sdk.platformtools.ag;
import com.tencent.mm.sdk.platformtools.ah;
import com.tencent.mm.storage.RegionCodeDecoder;
import com.tencent.mm.storage.ab;
import com.tencent.mm.storage.f;
import com.tencent.mm.ui.base.MMSlideDelView;
import com.tencent.mm.ui.base.n;
import com.tencent.mm.ui.f$a;
import com.tencent.mm.ui.voicesearch.b;
import com.tencent.mm.ui.w;
import com.tencent.mm.ui.x;
import java.util.LinkedList;
import java.util.List;
public class OpenIMAddressUI$a extends x implements e {
private ProgressDialog eHw = null;
List<String> gRN = new LinkedList();
d hLH = new d(new 4(this));
private int hpr;
private int hps;
private com.tencent.mm.ui.widget.e hpv;
private n.d iEm = new n.d() {
public final void onMMMenuItemSelected(MenuItem menuItem, int i) {
switch (menuItem.getItemId()) {
case 1:
case 2:
OpenIMAddressUI$a.a(OpenIMAddressUI$a.this, OpenIMAddressUI$a.this.uhj);
return;
case 7:
OpenIMAddressUI$a.c(OpenIMAddressUI$a.this, OpenIMAddressUI$a.this.uhj);
return;
default:
return;
}
}
};
private ListView kBy;
List<String> uhC = new LinkedList();
private b uhh;
private String uhj = "";
boolean uhx;
private boolean uhy = true;
private String ukY = "";
private t ukZ;
private Runnable ula = new 18(this);
static /* synthetic */ void c(OpenIMAddressUI$a openIMAddressUI$a, String str) {
au.HU();
ab Yg = c.FR().Yg(str);
if (a.gd(Yg.field_type)) {
Intent intent = new Intent();
intent.setClass(openIMAddressUI$a.getContext(), ContactRemarkInfoModUI.class);
intent.putExtra("Contact_User", Yg.field_username);
intent.putExtra("view_mode", true);
openIMAddressUI$a.getContext().startActivity(intent);
}
}
static /* synthetic */ void i(OpenIMAddressUI$a openIMAddressUI$a) {
BackwardSupportUtil.c.a(openIMAddressUI$a.kBy);
new ag().postDelayed(new 2(openIMAddressUI$a), 300);
}
public OpenIMAddressUI$a() {
super(true);
}
protected final int getLayoutId() {
return R.i.openim_address;
}
protected final View getLayoutView() {
return com.tencent.mm.kiss.a.b.EY().a(getContext(), "R.layout.openim_address", R.i.openim_address);
}
public final boolean supportNavigationSwipeBack() {
return false;
}
public final void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenuInfo contextMenuInfo) {
super.onCreateContextMenu(contextMenu, view, contextMenuInfo);
AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) contextMenuInfo;
au.HU();
ab Yg = c.FR().Yg(this.uhj);
if (Yg == null) {
com.tencent.mm.sdk.platformtools.x.e("MicroMsg.OpenIMAddressUI", "onCreateContextMenu, contact is null, username = " + this.uhj);
} else if (!q.GF().equals(Yg.field_username)) {
if (s.hc(this.uhj)) {
contextMenu.setHeaderTitle(j.a(view.getContext(), Yg.BL()));
contextMenu.add(adapterContextMenuInfo.position, 2, 0, R.l.address_delgroupcard);
} else if (!s.hr(this.uhj) && !s.hH(this.uhj)) {
contextMenu.setHeaderTitle(j.a(view.getContext(), Yg.BL()));
if (a.gd(Yg.field_type) && Yg.field_deleteFlag != 1) {
contextMenu.add(adapterContextMenuInfo.position, 7, 0, R.l.contact_info_mod_remark_labelinfo);
}
}
}
}
public final void a(int i, int i2, String str, l lVar) {
if (lVar.getType() != 453) {
if (this.eHw != null) {
this.eHw.dismiss();
this.eHw = null;
}
if (!ai.ci(getContext()) || w.a.a(getContext(), i, i2, str, 4) || i != 0 || i2 != 0) {
}
} else if (i == 0 && i2 == 0 && !((aft) ((com.tencent.mm.openim.b.c) lVar).diG.dIE.dIL).rJF.isEmpty()) {
cya();
}
}
private void cxZ() {
this.gRN = new LinkedList();
this.uhC = new LinkedList();
com.tencent.mm.bg.d.cfH();
this.gRN.add("tmessage");
this.uhC.addAll(this.gRN);
if (!this.gRN.contains("officialaccounts")) {
this.gRN.add("officialaccounts");
}
this.gRN.add("helper_entry");
if (this.ukZ != null) {
this.ukZ.dQ(this.gRN);
}
if (this.uhh != null) {
this.uhh.dQ(this.uhC);
}
}
public final void onActivityResult(int i, int i2, Intent intent) {
com.tencent.mm.sdk.platformtools.x.i("MicroMsg.OpenIMAddressUI", "onAcvityResult requestCode: %d", new Object[]{Integer.valueOf(i)});
if (i == 6 && i2 == -1) {
setResult(-1);
finish();
} else if (i2 == -1) {
switch (i) {
case 4:
setResult(-1, intent);
finish();
return;
default:
return;
}
}
}
public final void onActivityCreated(Bundle bundle) {
super.onActivityCreated(bundle);
com.tencent.mm.sdk.platformtools.x.v("MicroMsg.OpenIMAddressUI", "on address ui create");
au.DF().a(138, this);
g.Ek();
g.Eh().dpP.a(453, this);
this.ukY = getStringExtra("key_openim_acctype_id");
setMMTitle(((com.tencent.mm.openim.a.b) g.l(com.tencent.mm.openim.a.b.class)).h(this.ukY, "openim_acct_type_title", com.tencent.mm.openim.a.b.a.eui));
setBackBtn(new 1(this));
setTitleBarDoubleClickListener(this.ula);
com.tencent.mm.sdk.platformtools.x.v("MicroMsg.OpenIMAddressUI", "on address ui init view, %s", new Object[]{getResources().getDisplayMetrics()});
this.kBy = (ListView) findViewById(R.h.address_contactlist);
this.kBy.setScrollingCacheEnabled(false);
this.ukZ = new t(getContext(), "@openim.contact", this.ukY);
this.ukZ.a(new f$a() {
public final void Xb() {
OpenIMAddressUI$a openIMAddressUI$a = OpenIMAddressUI$a.this;
OpenIMAddressUI$a.this.ukZ.getCount();
openIMAddressUI$a.kBy.setVisibility(0);
OpenIMAddressUI$a.this.ukZ.cxW();
}
public final void Xa() {
}
});
this.ukZ.ugS = true;
this.ukZ.ule = this;
this.ukZ.setGetViewPositionCallback(new 12(this));
this.ukZ.setPerformItemClickListener(new MMSlideDelView.g() {
public final void t(View view, int i) {
OpenIMAddressUI$a.this.kBy.performItemClick(view, i, 0);
}
});
this.ukZ.a(new 14(this));
this.uhh = new b(getContext(), 1);
this.uhh.mA(true);
this.hpv = new com.tencent.mm.ui.widget.e(getContext());
this.kBy.setOnItemClickListener(new OnItemClickListener() {
public final void onItemClick(AdapterView<?> adapterView, View view, int i, long j) {
Object d;
String str = "MicroMsg.OpenIMAddressUI";
StringBuilder append = new StringBuilder("onItemClick ").append(i);
if (OpenIMAddressUI$a.this.uhh == null) {
d = OpenIMAddressUI$a.this.uhh;
} else {
d = Boolean.valueOf(OpenIMAddressUI$a.this.uhh.uFK);
}
com.tencent.mm.sdk.platformtools.x.i(str, append.append(d).toString());
int headerViewsCount = i - OpenIMAddressUI$a.this.kBy.getHeaderViewsCount();
String str2;
if (OpenIMAddressUI$a.this.uhh == null || !OpenIMAddressUI$a.this.uhh.uFK) {
f fVar = (f) OpenIMAddressUI$a.this.ukZ.Dy(headerViewsCount);
if (fVar != null) {
str2 = fVar.field_username;
OpenIMAddressUI$a openIMAddressUI$a = OpenIMAddressUI$a.this;
if (str2 != null && str2.length() > 0) {
if (s.hE(str2)) {
com.tencent.mm.sdk.platformtools.x.e("MicroMsg.OpenIMAddressUI", "error, 4.5 do not contain this contact %s", new Object[]{str2});
return;
}
Intent intent = new Intent();
intent.putExtra("Contact_User", str2);
if (s.hc(str2)) {
intent.putExtra("Is_group_card", true);
}
if (str2 != null && str2.length() > 0) {
e.a(intent, str2);
com.tencent.mm.bg.d.b(openIMAddressUI$a.getContext(), "profile", ".ui.ContactInfoUI", intent);
return;
}
return;
}
return;
}
return;
}
boolean qY = OpenIMAddressUI$a.this.uhh.qY(headerViewsCount);
boolean Gl = OpenIMAddressUI$a.this.uhh.Gl(headerViewsCount);
com.tencent.mm.sdk.platformtools.x.i("MicroMsg.OpenIMAddressUI", "onItemClick " + Gl);
Intent intent2;
if (Gl) {
OpenIMAddressUI$a.this.uhh.abn("");
} else if (qY) {
biy Gk = OpenIMAddressUI$a.this.uhh.Gk(headerViewsCount);
String str3 = Gk.rvi.siM;
au.HU();
ab Yg = c.FR().Yg(str3);
if (a.gd(Yg.field_type)) {
intent2 = new Intent();
intent2.putExtra("Contact_User", str3);
intent2.putExtra("Contact_Scene", 3);
if (str3 != null && str3.length() > 0) {
if (Yg.ckW()) {
h.mEJ.k(10298, str3 + ",3");
}
e.a(intent2, str3);
com.tencent.mm.bg.d.b(OpenIMAddressUI$a.this.getContext(), "profile", ".ui.ContactInfoUI", intent2);
return;
}
return;
}
Intent intent3 = new Intent();
intent3.putExtra("Contact_User", Gk.rvi.siM);
intent3.putExtra("Contact_Alias", Gk.eJM);
intent3.putExtra("Contact_Nick", Gk.rQz.siM);
intent3.putExtra("Contact_Signature", Gk.eJK);
intent3.putExtra("Contact_RegionCode", RegionCodeDecoder.aq(Gk.eJQ, Gk.eJI, Gk.eJJ));
intent3.putExtra("Contact_Sex", Gk.eJH);
intent3.putExtra("Contact_VUser_Info", Gk.rTf);
intent3.putExtra("Contact_VUser_Info_Flag", Gk.rTe);
intent3.putExtra("Contact_KWeibo_flag", Gk.rTi);
intent3.putExtra("Contact_KWeibo", Gk.rTg);
intent3.putExtra("Contact_KWeiboNick", Gk.rTh);
intent3.putExtra("Contact_KSnsIFlag", Gk.rTk.eJS);
intent3.putExtra("Contact_KSnsBgId", Gk.rTk.eJU);
intent3.putExtra("Contact_KSnsBgUrl", Gk.rTk.eJT);
if (Gk.rTl != null) {
try {
intent3.putExtra("Contact_customInfo", Gk.rTl.toByteArray());
} catch (Throwable e) {
com.tencent.mm.sdk.platformtools.x.printErrStackTrace("MicroMsg.OpenIMAddressUI", e, "", new Object[0]);
}
}
if ((Gk.rTe & 8) > 0) {
h.mEJ.k(10298, str3 + ",3");
}
com.tencent.mm.bg.d.b(OpenIMAddressUI$a.this.getContext(), "profile", ".ui.ContactInfoUI", intent3);
} else {
ab oj = OpenIMAddressUI$a.this.uhh.oj(headerViewsCount);
if (oj == null) {
com.tencent.mm.sdk.platformtools.x.e("MicroMsg.OpenIMAddressUI", "on Contact ListView ItemClick, the item contact shoud not be null. count:%d, pos:%d ", new Object[]{Integer.valueOf(OpenIMAddressUI$a.this.uhh.getCount()), Integer.valueOf(headerViewsCount)});
return;
}
str2 = oj.field_username;
if (s.hE(str2)) {
Intent intent4 = new Intent(OpenIMAddressUI$a.this.getContext(), OpenIMAddressUI.class);
intent4.putExtra("Contact_GroupFilter_Type", "@biz.contact");
OpenIMAddressUI$a.this.startActivity(intent4);
return;
}
intent2 = new Intent();
intent2.putExtra("Contact_User", str2);
intent2.putExtra("Contact_Scene", 3);
if (str2 != null && str2.length() > 0) {
com.tencent.mm.bg.d.b(OpenIMAddressUI$a.this.getContext(), "profile", ".ui.ContactInfoUI", intent2);
}
}
}
});
this.kBy.setOnItemLongClickListener(new 16(this));
this.kBy.setOnTouchListener(new 17(this));
this.kBy.setOnScrollListener(this.hLH);
this.kBy.setDrawingCacheEnabled(false);
au.HU();
c.FR().a(this.ukZ);
}
public final void onResume() {
super.onResume();
com.tencent.mm.sdk.platformtools.x.v("MicroMsg.OpenIMAddressUI", "address ui on resume");
if (this.uhy) {
this.uhy = false;
this.uhx = false;
cxZ();
this.kBy.setAdapter(this.ukZ);
this.kBy.post(new 7(this));
this.uhh.mz(false);
} else if (this.uhx) {
this.uhx = false;
com.tencent.mm.sdk.f.e.b(new Runnable() {
public final void run() {
Process.setThreadPriority(10);
OpenIMAddressUI$a.this.cya();
}
}, "AddressUI_updateUIData", 4);
}
if (this.uhh != null) {
this.uhh.onResume();
}
this.ukZ.thH = false;
ah.A(new 9(this));
}
private synchronized void cya() {
long currentTimeMillis = System.currentTimeMillis();
cxZ();
com.tencent.mm.sdk.platformtools.x.i("MicroMsg.OpenIMAddressUI", "KEVIN updateBlockList() LAST" + (System.currentTimeMillis() - currentTimeMillis));
currentTimeMillis = System.currentTimeMillis();
if (this.ukZ != null) {
com.tencent.mm.sdk.platformtools.x.v("MicroMsg.OpenIMAddressUI", "post to do refresh");
ah.A(new 5(this));
}
if (this.uhh != null) {
ah.A(new 6(this));
}
com.tencent.mm.sdk.platformtools.x.i("MicroMsg.OpenIMAddressUI", "KEVIN doRefresh() LAST" + (System.currentTimeMillis() - currentTimeMillis));
}
public final void onPause() {
super.onPause();
com.tencent.mm.sdk.platformtools.x.i("MicroMsg.OpenIMAddressUI", "AddressUI on Pause");
if (this.uhh != null) {
this.uhh.onPause();
}
this.ukZ.cxX();
ah.A(new 10(this));
}
public final void onDestroy() {
super.onDestroy();
com.tencent.mm.sdk.platformtools.x.v("MicroMsg.OpenIMAddressUI", "onDestory");
au.DF().b(138, this);
g.Ek();
g.Eh().dpP.b(453, this);
if (this.ukZ != null) {
this.ukZ.lv(true);
this.ukZ.detach();
this.ukZ.coT();
}
if (this.uhh != null) {
this.uhh.detach();
this.uhh.aYc();
}
if (au.HX() && this.ukZ != null) {
au.HU();
c.FR().b(this.ukZ);
}
}
}
|
package fr.demos.presentation;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
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 fr.demos.Data.ClimatisationDAO;
import fr.demos.Data.FileClimatisationDAO;
import fr.demos.Data.SQLClimatisationDAO;
import fr.demos.formation.today.Climatisation;
/**
* Servlet implementation class ClimController
*/
@WebServlet("/ClimController")
public class ClimController extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ClimController() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher rd = request.getRequestDispatcher("/SaisieClimatisation.jsp");
rd.forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher rd = request.getRequestDispatcher("/SaisieClimatisation.jsp");
boolean erreurs = false;
String unBoutonAction = request.getParameter("boutonAction");
if (unBoutonAction != null && unBoutonAction.equals("enregistrer")) {
String leNomAppareil = request.getParameter("NomAppareil");
String laTemperature = request.getParameter("Temperature");
String leTauxHumidité = request.getParameter("TauxHumidité");
String laPression = request.getParameter("Pression");
double tempval = 0;
double pressionval = 0;
double humiditeval = 0;
request.setAttribute("nom", leNomAppareil);
request.setAttribute("temp", laTemperature);
request.setAttribute("txh", leTauxHumidité);
request.setAttribute("press", laPression);
// conversion
try {
tempval = Double.parseDouble(laTemperature);
} catch (NumberFormatException exp) {
erreurs = true;
request.setAttribute("TempErreur", "nombre incorrect");
}
try {
pressionval = Double.parseDouble(laPression);
request.setAttribute("pressionfinal", pressionval);
} catch (NumberFormatException exps) {
erreurs = true;
request.setAttribute("pressionErreur", "nombre incorrect");
}
try {
humiditeval = Double.parseDouble(leTauxHumidité);
} catch (NumberFormatException expss) {
erreurs = true;
request.setAttribute("humiditéErreur", "incorrect");
}
// validation
// if(humiditeval>100);{
// erreurs=true;
// request.setAttribute("humiditéErreur", "valeur trop grande");
// }
if (!erreurs) {
Climatisation clim = new Climatisation(leNomAppareil, tempval, pressionval, humiditeval);
//ClimatisationDAO dao = new FileClimatisationDAO();
List<Climatisation>ListClim=null;
try {
ClimatisationDAO dao3=new SQLClimatisationDAO();
dao3.sauve(clim);
//dao.sauve(clim);
} catch (IOException exc) {
exc.printStackTrace();
request.setAttribute("RechercheDataErreur", exc.getMessage()); //le but c'est que l'utilisateur puisse voir le message d'erreur et pour ca il faut enlever les catch pour propager l'exception dans FileClimatisationDAO
} catch (Exception e) {// il sert a rien ce catch mais j'arrive pas a l'enlever la
e.printStackTrace();
}
rd = request.getRequestDispatcher("/succesClim.jsp");
}
else {
rd = request.getRequestDispatcher("/SaisieClimatisation.jsp");
}
}
rd.forward(request, response);
}
}
|
package com.example.user.myapplication.main.activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import com.example.user.myapplication.R;
import com.example.user.myapplication.util.UserSessionManager;
/**
* Created by Junho on 2016-03-14.
*/
public class UserConfig extends AppCompatActivity {
//로그아웃
//비밀번호 변경
//회원정보수정
//회원탈퇴
//추천인
//
UserSessionManager session;
private Button usrLogout;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_userconfig);
session = new UserSessionManager(this);
usrLogout = (Button)findViewById(R.id.userlogout);
usrLogout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
session.logoutUser();
finish();
}
});
}
}
|
package com.tencent.mm.g.a;
public final class jc$a {
public int opType;
}
|
package servidorArquivo;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
public class enviarArquivo implements Runnable {
Socket socket;
public enviarArquivo(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
BufferedReader leitor;
try {
leitor = new BufferedReader(new InputStreamReader(socket.getInputStream()));
File myFile = new File(leitor.readLine());
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray, 0, mybytearray.length);
OutputStream os = socket.getOutputStream();
os.write(mybytearray);
os.flush();
socket.close();
bis.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
|
package com.hit.neuruimall.service;
import com.hit.neuruimall.model.AdminUserModel;
import java.util.List;
public interface IAdminUserService {
public List<AdminUserModel> findAllUser();
public boolean validate(String username, String password);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.