text stringlengths 10 2.72M |
|---|
// http://web.stanford.edu/class/cs9/sample_probs/TwoSum.pdf
// https://stackoverflow.com/questions/2444019/how-do-i-generate-a-random-integer-between-min-and-max-in-java
import java.util.Arrays;
import java.util.Random;
/**
* This is a classic algorithmic interview question. There are many different solution routes,
* each of which involves a different technique. This handout details the problem and gives
* a few different solution routes.
* Problem Statement:
* You are given an array of n integers and a number k. Determine whether there is a pair
* of elements in the array that sums to exactly k. For example, given the array [1, 3, 7] and
* k = 8, the answer is “yes,” but given k = 6 the answer is “no.”
* */
public class T00400_TwoSum {
public static void main(String[] args) {
// target variable
int k;
int[] ds = new int[5];
int dsl = ds.length - 1;
boolean isEqual = false;
Random rand = new Random();
int x = 0;
while (x < ds.length) {
ds[x] = rand.nextInt(10 + 1 - 0) + 0;
// System.out.println(Arrays.toString(ds));
x++;
}
k = rand.nextInt(13 + 1 - 5) + 5;
System.out.println("Find two numbers in this array " + Arrays.toString(ds) + " that equate to the" +
" target value: " + k + " if possible");
int c;
while (isEqual == false) {
int z = 1;
for (int y = 0; y < dsl; y++) {
// System.out.println("y = " + y + " | DS = " + ds[y]);
for (int a = z; a <= dsl; a++) {
// System.out.println("a = " + a + " | DS = " + ds[a]);
c = ds[a] + ds[y];
if (c == k) {
isEqual = true;
// System.out.println("Find two numbers in this array " + Arrays.toString(ds) + " that equate to the" +
// " target value: " + k + " if possible");
System.out.println("Two sum found!");
System.out.println("Position (" + y + "," + a + ")" + " representing values " + ds[y] + " and " + ds[a] + " equals k (" + k + ")\n");
} else {
if (y == dsl - 1 && a == dsl && c != k && isEqual != true) {
//System.out.println("This loop has ended");
System.out.println("No two numbers in this array equate to the target value: " + k);
isEqual = true;
}
}
}
//System.out.println("----------------------------");
//System.out.println("Find two numbers in this array " + Arrays.toString(ds) + " that equate to the" +
// " target value: " + k + " if possible");
// System.out.println("----------------------------");
z++;
}
}
}
}
|
package model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="food")
public class Food {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="foodId")
private int id;
@Column(name="foodType")
private String foodType;
@Column(name="quantity")
private int quantity;
public Food() {
super();
}
public Food(String foodType, int quantity) {
this.foodType = foodType;
this.quantity = quantity;
}
public String displayFood() {
return foodType + " | " + quantity;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFoodType() {
return foodType;
}
public void setFoodType(String foodType) {
this.foodType = foodType;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
|
/**
* Copyright (c) 2004-2011 QOS.ch
* All rights reserved.
*
* 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 org.slf4j.migrator.helper;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class AbbreviatorTest {
static final char FS = '/';
static final String INPUT_0 = "/abc/123456/ABC";
static final String INPUT_1 = "/abc/123456/xxxxx/ABC";
RandomHelper rh = new RandomHelper(FS);
@Test
public void testSmoke() {
{
Abbreviator abb = new Abbreviator(2, 100, FS);
String r = abb.abbreviate(INPUT_0);
assertEquals(INPUT_0, r);
}
{
Abbreviator abb = new Abbreviator(3, 8, FS);
String r = abb.abbreviate(INPUT_0);
assertEquals("/abc/.../ABC", r);
}
{
Abbreviator abb = new Abbreviator(3, 8, FS);
String r = abb.abbreviate(INPUT_0);
assertEquals("/abc/.../ABC", r);
}
}
@Test
public void testImpossibleToAbbreviate() {
Abbreviator abb = new Abbreviator(2, 20, FS);
String in = "iczldqwivpgm/mgrmvbjdxrwmqgprdjusth";
String r = abb.abbreviate(in);
assertEquals(in, r);
}
@Test
public void testNoFS() {
Abbreviator abb = new Abbreviator(2, 100, FS);
String r = abb.abbreviate("hello");
assertEquals("hello", r);
}
@Test
public void testZeroPrefix() {
{
Abbreviator abb = new Abbreviator(0, 100, FS);
String r = abb.abbreviate(INPUT_0);
assertEquals(INPUT_0, r);
}
}
@Test
public void testTheories() {
int MAX_RANDOM_FIXED_LEN = 20;
int MAX_RANDOM_AVG_LEN = 20;
int MAX_RANDOM_MAX_LEN = 100;
for (int i = 0; i < 10000; i++) {
// System.out.println("Test number " + i);
// 0 <= fixedLen < MAX_RANDOM_FIXED_LEN
int fixedLen = rh.nextInt(MAX_RANDOM_FIXED_LEN);
// 5 <= averageLen < MAX_RANDOM_AVG_LEN
int averageLen = rh.nextInt(MAX_RANDOM_AVG_LEN) + 3;
// System.out.println("fixedLen="+fixedLen+", averageLen="+averageLen);
int maxLen = rh.nextInt(MAX_RANDOM_MAX_LEN) + fixedLen;
if (maxLen <= 1) {
continue;
}
// System.out.println("maxLen="+maxLen);
int targetLen = (maxLen / 2) + rh.nextInt(maxLen / 2) + 1;
if (targetLen > maxLen) {
targetLen = maxLen;
}
String filename = rh.buildRandomFileName(averageLen, maxLen);
Abbreviator abb = new Abbreviator(fixedLen, targetLen, FS);
String result = abb.abbreviate(filename);
assertTheory0(averageLen, filename, result, fixedLen, targetLen);
assertUsefulness(averageLen, filename, result, fixedLen, targetLen);
assertTheory1(filename, result, fixedLen, targetLen);
assertTheory2(filename, result, fixedLen, targetLen);
}
}
// result length is smaller than original length
void assertTheory0(int averageLen, String filename, String result, int fixedLen, int targetLength) {
assertTrue("filename=[" + filename + "] result=[" + result + "]", result.length() <= filename.length());
}
// if conditions allow, result length should be to target length
void assertUsefulness(int averageLen, String filename, String result, int fixedLen, int targetLength) {
int resLen = result.length();
int margin = averageLen * 4;
if (targetLength > fixedLen + margin) {
assertTrue("filename=[" + filename + "], result=[" + result + "] resultLength=" + resLen + " fixedLength=" + fixedLen + ", targetLength="
+ targetLength + ", avgLen=" + averageLen, result.length() <= targetLength + averageLen);
}
}
// result start with prefix found in filename
void assertTheory1(String filename, String result, int fixedLen, int targetLength) {
String prefix = filename.substring(0, fixedLen);
assertTrue(result.startsWith(prefix));
}
// The string /.../ is found in the result once at a position higher
// than fixedLen
void assertTheory2(String filename, String result, int fixedLen, int targetLength) {
if (filename == result) {
return;
}
int fillerIndex = result.indexOf(Abbreviator.FILLER);
assertTrue(fillerIndex >= fixedLen);
}
}
|
package data;
import static helpers.Artist.*;
import static helpers.Clock.*;
import java.util.ArrayList;
import org.newdawn.slick.opengl.Texture;
public class TowerCannon {
private float x, y, timeSinceLastShot, firingSpeed;
private int width, height, damage;
private Texture baseTexture, cannonTexture;
private Tile startTile;
private ArrayList<Projectile> projectiles;
public TowerCannon(Texture baseTexture, Tile startTile, int damage) {
this.baseTexture = baseTexture;
this.cannonTexture = QuickLoad("cannonGun");
this.startTile = startTile;
this.damage = damage;
this.x = startTile.getX();
this.y = startTile.getY();
this.width = (int) startTile.getWidth();
this.height = (int) startTile.getHeight();
this.firingSpeed = 3;
this.timeSinceLastShot = 0;
this.projectiles = new ArrayList<Projectile>();
}
private void Shoot() {
timeSinceLastShot = 0;
projectiles.add(new Projectile(QuickLoad("bullet"), x + 32, y + 32, 150, 10));
}
public void Update() {
timeSinceLastShot += Delta();
if (timeSinceLastShot > firingSpeed)
Shoot();
for (Projectile p : projectiles) {
p.Update();
}
Draw();
}
public void Draw() {
DrawQuadTex(baseTexture, x, y, width, height);
DrawQuadTexRotate(cannonTexture, x, y, width, height, 45);
}
}
|
package view.statistics;
import java.text.DateFormatSymbols;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import org.apache.log4j.Logger;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.chart.XYChart.Series;
import javafx.scene.control.ComboBox;
import model.Person;
import util.DateUtil;
public class BirthdayStatisticsController {
@FXML
private CategoryAxis xAxis = new CategoryAxis();;
@FXML
private NumberAxis yAxis = new NumberAxis();;
@FXML
private BarChart<String, Number> barChart = new BarChart<String, Number>(xAxis, yAxis);
private ObservableList<String> monthNames = FXCollections.observableArrayList();
private final static Logger LOGGER = Logger.getLogger(BirthdayStatisticsController.class);
@FXML
private void initialize() {
LOGGER.info("Get an array with the English month names.");
String[] months = DateFormatSymbols.getInstance(Locale.ENGLISH).getMonths();
LOGGER.info(" Convert it to a list and add it to our ObservableList of months.");
monthNames.addAll(Arrays.asList(months));
xAxis.setCategories(monthNames);
}
public void setPersonData(List<Person> persons) {
xAxis.setLabel("Month");
yAxis.setLabel("Pupils");
int[] monthCounter = new int[12];
for (Person p : persons) {
LOGGER.info(" PARSE birthday in a specific month. .");
int month = DateUtil.parse(p.getBirthday()).getMonthValue() - 1;
LOGGER.debug(" PARSE birthday " + month);
monthCounter[month]++;
}
XYChart.Series<String, Number> series = new XYChart.Series<>();
for (int i = 0; i < monthCounter.length; i++) {
series.getData().add(new XYChart.Data<String, Number>(monthNames.get(i), monthCounter[i]));
}
LOGGER.debug(" number of month " + monthCounter);
barChart.getData().add(series);
barChart.setTitle("Birthday Statistics");
}
} |
package edu.umass.cs.myapplication;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
private ColorPicker colorPicker;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.colorPicker = (ColorPicker) findViewById(R.id.colorPicker);
this.colorPicker.setColor(0xFFB6C1);
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
//this.imageView.setImageDrawable(getResources().getDrawable(R.drawable.test, getApplicationContext().getTheme()));
Button photoButton = (Button) this.findViewById(R.id.button1);
photoButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
int height = photo.getHeight();
int width = photo.getWidth();
imageView.setImageBitmap(photo);
String temp = String.format("Height: %d, Width: %d", height, width);
Toast.makeText(MainActivity.this, temp, Toast.LENGTH_LONG).show();
}
}
} |
package avgogen.javaast.stats;
import com.github.javaparser.ast.expr.SimpleName;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
public class SummaryStatisticsCollector {
public SummaryStatisticsCollector() {
classesCount = 0;
interfacesCount = 0;
methodsCount = 0;
enumsCount = 0;
parametersCount = 0;
avgClassNameLength = 0.0;
avgInterfaceNameLength = 0.0;
avgMethodNameLength = 0.0;
avgEnumNameLength = 0.0;
avgParameterNameLength = 0.0;
classesStatistics = new ArrayList<>();
}
public static void summarize() {
summarize(System.out);
}
public static void summarize(PrintStream out) {
out.println("Summary:");
out.println("\tTotal classes: " + classesCount);
out.println("\tTotal interfaces: " + interfacesCount);
out.println("\tTotal enums: " + enumsCount);
out.println("\tTotal methods: " + methodsCount);
out.println("\tTotal parameters: " + parametersCount);
classesStatistics.forEach(stats -> {
if (stats.getType() == 0) {
out.print("\t\tClass [" + stats.getClassName() + "]: " + stats.getFieldsCount() + " fields");
if (stats.getFieldsCount() > 0)
out.println(" with average name lendth " + stats.getAvgFieldNameLength() / stats.getFieldsCount());
else
out.println();
out.print("\t\t\t" + stats.getMethodsCount() +
" methods");
if (stats.getMethodsCount() > 0)
out.println(" with average name length " + stats.getAvgMethodNameLength() / stats.getMethodsCount());
else
out.println();
stats.getMethodsStatistics().forEach(stat -> {
out.print("\t\t\tMethod [" + stat.getMethodName() + "]: " + stat.getParametersCount() + " parameters");
if (stat.getParametersCount() > 0)
out.println(" with average name length " + stat.getAvgParameterNameLength() / stat.getParametersCount());
else
out.println();
});
}
});
classesStatistics.forEach(stats -> {
if (stats.getType() == 1) {
out.print("\t\tEnum [" + stats.getClassName() + "]: " + stats.getMethodsCount() +
" methods");
if (stats.getMethodsCount() > 0)
out.println(" with average name length " + stats.getAvgMethodNameLength() / stats.getMethodsCount());
else
out.println();
}
});
out.println("\nAverage statistics");
if (classesCount != 0) {
out.println("\tAverage class name length: " + avgClassNameLength / classesCount);
}
if (interfacesCount != 0) {
out.println("\tAverage interface name length: " + avgInterfaceNameLength / interfacesCount);
}
if (methodsCount != 0) {
out.println("\tAverage method name length: " + avgMethodNameLength / methodsCount);
}
if (enumsCount != 0) {
out.println("\tAverage enum name length: " + avgEnumNameLength / enumsCount);
}
if (parametersCount != 0) {
out.println("\tAverage parameter name length: " + avgParameterNameLength / parametersCount);
}
}
public static void newClass(SimpleName className) {
++classesCount;
avgClassNameLength += className.toString().length();
}
public static void newInterface(SimpleName interfaceName) {
++interfacesCount;
avgInterfaceNameLength += interfaceName.toString().length();
}
public static void newMethod(SimpleName methodName) {
++methodsCount;
avgMethodNameLength += methodName.toString().length();
}
public static void newEnum(SimpleName methodName) {
++enumsCount;
avgEnumNameLength += methodName.toString().length();
}
public static void newParameter(SimpleName parameterName) {
++parametersCount;
avgParameterNameLength += parameterName.toString().length();
}
public static void newClassStatistics(ClassInsideStatisticsCollector statisticsCollector) {
classesStatistics.add(statisticsCollector);
}
private static int classesCount;
private static int interfacesCount;
private static int methodsCount;
private static int enumsCount;
private static int parametersCount;
private static double avgClassNameLength;
private static double avgInterfaceNameLength;
private static double avgMethodNameLength;
private static double avgEnumNameLength;
private static double avgParameterNameLength;
private static List<ClassInsideStatisticsCollector> classesStatistics;
}
|
/*
* play - allows the users to play the game of Quest.
* Create a QuestGame object and call its method Play();
*/
public class play {
public static void main(String[] args){
QuestGame open = new QuestGame();
open.Play();
}
} |
import java.util.concurrent.ThreadLocalRandom;
public class ThreadPar implements Runnable {
private int n = 0;
private int geraRandom() {
return ThreadLocalRandom.current().nextInt();
}
public void geraPar() {
this.n = geraRandom() * 2;
}
@Override
public void run() {
while(true) {
try {
System.out.println("\nThread 2:");
geraPar();
System.out.println("Par = " + n + "\n");
Thread.sleep(500);
} catch (InterruptedException ex) {
System.out.println("Erro na Thread 2: " + ex);
}
}
}
} |
package tk.martijn_heil.elytraoptions.command.common.provider;
import com.sk89q.intake.argument.ArgumentException;
import com.sk89q.intake.argument.ArgumentParseException;
import com.sk89q.intake.argument.CommandArgs;
import com.sk89q.intake.parametric.Provider;
import com.sk89q.intake.parametric.ProvisionException;
import javax.annotation.Nullable;
import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.List;
/**
* A boolean provider, but instead of using true/false, on/off
*/
public class ToggleProvider implements Provider<Boolean>
{
@Override
public boolean isProvided()
{
return false;
}
@Nullable
@Override
public Boolean get(CommandArgs commandArgs, List<? extends Annotation> list) throws ArgumentException, ProvisionException
{
String next = commandArgs.next();
boolean activated;
if(next.equals("on"))
{
activated = true;
}
else if (next.equals("off"))
{
activated = false;
}
else
{
throw new ArgumentParseException(next + " is not a valid toggle value. Expected on/off");
}
return activated;
}
@Override
public List<String> getSuggestions(String s)
{
return Arrays.asList("off", "on");
}
}
|
package net.minecraft.entity.ai;
import net.minecraft.entity.EntityCreature;
import net.minecraft.entity.monster.EntityZombie;
public class EntityAIZombieAttack extends EntityAIAttackMelee {
private final EntityZombie zombie;
private int raiseArmTicks;
public EntityAIZombieAttack(EntityZombie zombieIn, double speedIn, boolean longMemoryIn) {
super((EntityCreature)zombieIn, speedIn, longMemoryIn);
this.zombie = zombieIn;
}
public void startExecuting() {
super.startExecuting();
this.raiseArmTicks = 0;
}
public void resetTask() {
super.resetTask();
this.zombie.setArmsRaised(false);
}
public void updateTask() {
super.updateTask();
this.raiseArmTicks++;
if (this.raiseArmTicks >= 5 && this.attackTick < 10) {
this.zombie.setArmsRaised(true);
} else {
this.zombie.setArmsRaised(false);
}
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\entity\ai\EntityAIZombieAttack.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ |
/**
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2015 Paco Avila & Josep Llort
*
* No bytes were intentionally harmed during the development of this application.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.openkm.module.jcr.stuff;
import java.io.IOException;
import java.util.Iterator;
import java.util.TimerTask;
import javax.jcr.Node;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import org.apache.jackrabbit.core.RepositoryImpl;
import org.apache.jackrabbit.core.SessionImpl;
import org.apache.jackrabbit.core.config.RepositoryConfig;
import org.apache.jackrabbit.core.config.WorkspaceConfig;
import org.apache.jackrabbit.core.data.DataIdentifier;
import org.apache.jackrabbit.core.data.GarbageCollector;
import org.apache.jackrabbit.core.data.ScanEventListener;
import org.apache.jackrabbit.core.state.ItemStateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.openkm.module.jcr.JcrRepositoryModule;
/**
* @author pavila
*/
public class DataStoreGarbageCollector extends TimerTask implements ScanEventListener {
private static Logger log = LoggerFactory.getLogger(DataStoreGarbageCollector.class);
private static volatile boolean running = false;
@SuppressWarnings("unchecked")
@Override
public void run() {
if (running) {
log.warn("*** Datastore garbage collector already running ***");
} else {
running = true;
log.info("*** Begin datastore garbage collector ***");
GarbageCollector gc = null;
Session tmp = null;
try {
// See http://wiki.apache.org/jackrabbit/DataStore
Repository rep = JcrRepositoryModule.getRepository();
RepositoryConfig rc = ((RepositoryImpl)rep).getConfig();
String name = rc.getDefaultWorkspaceName();
WorkspaceConfig wc = rc.getWorkspaceConfig(name);
tmp = SystemSession.create((RepositoryImpl)rep, wc);
// Force system garbage collection a few times before running the data store garbage collection
for (int i=0; i<5; i++) {
System.gc();
}
gc = ((SessionImpl)tmp).createDataStoreGarbageCollector();
// optional (if you want to implement a progress bar / output)
gc.setScanEventListener(this);
gc.scan();
Iterator<DataIdentifier> it = gc.getDataStore().getAllIdentifiers();
while (it.hasNext()) {
log.info("DataIdent: {}", it.next());
}
gc.stopScan();
// delete old data
int deleted = gc.deleteUnused();
log.info("Deleted garbage documents: {}", deleted);
} catch (IOException e) {
log.error(e.getMessage(), e);
} catch (IllegalStateException e) {
log.error(e.getMessage(), e);
} catch (ItemStateException e) {
log.error(e.getMessage(), e);
} catch (RepositoryException e) {
log.error(e.getMessage(), e);
} finally {
log.info("Clean temporal session and close DSGC");
try {
if (gc != null ) gc.close();
if (tmp != null) tmp.logout();
} catch (Exception e) {
log.error(e.getMessage(), e);
}
running = false;
}
}
log.info("*** End datastore garbage collector ***");
}
@Override
public void afterScanning(Node node) throws RepositoryException {
//log.info("ScanEventListener - afterScanning: "+node);
}
@Override
public void beforeScanning(Node node) throws RepositoryException {
//log.info("ScanEventListener - beforeScanning: "+node);
}
@Override
public void done() {
log.info("ScanEventListener: done");
}
}
|
package tests_dominio;
import org.junit.Assert;
import org.junit.Test;
import dominio.Hechicero;
import dominio.Humano;
import dominio.Inventario;
import dominio.Objeto;
import dominio.Personaje;
public class TestInventario {
@Test
public void testAgregarobjeto() {
Inventario inv = new Inventario();
Objeto obj = new Objeto();
inv.agregar(obj);
Assert.assertTrue(inv.estaEnInventario(obj.getId()));
Assert.assertEquals(inv.getCantidadObjetos(), 1);
Assert.assertNotEquals(inv.getObjeto(obj.getId()), null);
Assert.assertEquals(inv.getObjeto(-2), null);
Assert.assertEquals(inv.estaEnInventario(-2), false);
inv.quitarObjeto(obj);
Assert.assertEquals(inv.getCantidadObjetos(), 0);
if (inv.agregarObjeto() == null)
Assert.assertEquals(inv.getCantidadObjetos(), 1);
}
@Test
public void TestIds() {
Inventario inv = new Inventario();
Objeto obj = new Objeto();
inv.agregar(obj);
Assert.assertNotEquals(inv.getIdObjetos(), null);
Assert.assertNotEquals(inv.clonar(), null);
Objeto obj2 = new Objeto();
int ids[] = new int[20];
ids[0] = obj2.getId();
inv.reestablecerObjetos(ids);
Assert.assertTrue(inv.estaEnInventario(obj2.getId()));
Assert.assertNotEquals(inv.getObjetos(), null);
}
@Test
public void TestInventarioPersonaje() {
Personaje h = new Humano("Nico", 100, 100, 55, 20, 30, new Hechicero(0.2, 0.3, 1.5), 0, 1, 1);
Objeto obj = new Objeto();
h.getInventario().agregar(obj);
Assert.assertNotEquals(obj.getNombre(), null);
int ids[] = new int[20];
ids[0] = obj.getId();
Assert.assertEquals(h.getCantidadObjetos(), 1);
h.quitarObjeto(obj);
Assert.assertEquals(h.getCantidadObjetos(), 0);
h.reestablecerInventario(ids);
Assert.assertEquals(h.getCantidadObjetos(), 1);
h.perderObjeto(obj);
Assert.assertEquals(h.getInventario().getCantidadObjetos(), 0);
}
@Test
public void testAgregarVariosObjetos() {
int ids[] = new int[20];
Objeto obj;
for (int i = 0; i < 20; i++) {
obj = new Objeto();
ids[i] = obj.getId();
}
Inventario inv = new Inventario(ids);
Assert.assertEquals(inv.getCantidadObjetos(), 20);
}
} |
package com.weique.commonres.adapter.provider;
import com.blankj.utilcode.util.ObjectUtils;
import com.chad.library.adapter.base.provider.BaseItemProvider;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.weique.commonres.adapter.ProviderMultiAdapter;
import com.weique.commonres.base.commonbean.DynamicFormEnum;
import com.weique.commonres.base.commonbean.RecordsBean;
import com.weique.commonres.base.commonbean.SettingStyleBean;
import org.jetbrains.annotations.NotNull;
import me.jessyan.armscomponent.commonres.R;
/**
* 设置点击使用
*
* @author Administrator
*/
public class InfoEditProvider extends BaseItemProvider<RecordsBean> {
@Override
public int getItemViewType() {
return DynamicFormEnum.ItemFlagEnum.EDIT_ITEM;
}
@Override
public int getLayoutId() {
return R.layout.public_setting_click_two;
}
@Override
public void convert(@NotNull BaseViewHolder baseViewHolder, final RecordsBean recordsBean) {
try {
ProviderMultiAdapter adapter = (ProviderMultiAdapter) getAdapter();
if (ObjectUtils.isNotEmpty(recordsBean)) {
assert adapter != null;
SettingStyleBean styleBean = adapter.getGson().fromJson(recordsBean.getStyle(), SettingStyleBean.class);
if (styleBean.isVisibleView()) {
baseViewHolder.setVisible(R.id.view, true);
}
if (ObjectUtils.isNotEmpty(recordsBean.getTitile())) {
baseViewHolder.setText(R.id.tv_title, recordsBean.getTitile());
}
if (ObjectUtils.isNotEmpty(recordsBean.getDefaultValue())) {
baseViewHolder.setText(R.id.tv_two, recordsBean.getDefaultValue());
}
if (ObjectUtils.isNotEmpty(recordsBean.getValue())) {
baseViewHolder.setText(R.id.tv_two, recordsBean.getValue());
}
if (!recordsBean.isEdit()) {
baseViewHolder.setEnabled(R.id.mShadowLayout, false);
baseViewHolder.setVisible(R.id.iv_right, false);
}else {
baseViewHolder.setEnabled(R.id.mShadowLayout, true);
baseViewHolder.setVisible(R.id.iv_right, true);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package edunova;
import javax.swing.JOptionPane;
public class Zadatak1 {
//napisati program koji za tri unesena decimalna broja ispisuje
// zbroj prva dva umanjen za treći broj
public static void main(String[] args) {
double a=Double.parseDouble(JOptionPane.showInputDialog("Unesite prvi broj:"));
double b=Double.parseDouble(JOptionPane.showInputDialog("Unesite drugi broj:"));
double c=Double.parseDouble(JOptionPane.showInputDialog("Unesite treći broj:"));
double d=a+b;
double e=d-c;
System.out.println(d);
System.out.println(e);
}
}
|
package com.caorunjia.BMS.view;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Error
{
private JFrame errorFrame;
private JButton ok;
public Error()
{
JFrame.setDefaultLookAndFeelDecorated(true);
errorFrame = new JFrame("Error!!!");
JLabel lerror = new JLabel(" Format error!Please re-input!");
JButton ok = new JButton("ok");
Font dialog = new Font("Dialog",Font.BOLD,25);
lerror.setFont(dialog);
errorFrame.setBackground(Color.red);
errorFrame.add(lerror,BorderLayout.CENTER);
errorFrame.add(ok,BorderLayout.SOUTH );
ok.addActionListener(event ->{
errorFrame.setVisible(false);
});
errorFrame.setBounds(750, 300, 380, 350);
errorFrame.setVisible(true);
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
//new Error();
}
}
|
package com.icleveret.recipes.service;
import com.icleveret.recipes.component.SessionHolder;
import com.icleveret.recipes.model.User;
import java.util.List;
public interface UserService {
User add(User user, SessionHolder.SessionContainer sessionContainer);
User updateEmail(String login, String email, SessionHolder.SessionContainer sessionContainer);
User updatePassword(String login, String password, SessionHolder.SessionContainer sessionContainer);
User addRole(User user, SessionHolder.SessionContainer sessionContainer);
User deleteRole(User user, Integer roleId, SessionHolder.SessionContainer sessionContainer);
User findOne(Long userId, SessionHolder.SessionContainer sessionContainer);
User findByLogin(String login, SessionHolder.SessionContainer sessionContainern);
User findByEmail(String email, SessionHolder.SessionContainer sessionContainer);
List<User> findAll(SessionHolder.SessionContainer sessionContainer);
void delete(User user, SessionHolder.SessionContainer sessionContainer);
User getCurrentUser(SessionHolder.SessionContainer sessionContainer);
String generateNewPassword() throws NoSuchFieldException;
}
|
import org.junit.Test;
@SuppressWarnings("serial")
public class WhackAMoleView extends View {
//Draws the background for the WhackAMole minigame
@Override
public void drawBackground() {
}
//Draws the objects that will be used in the WhackAMole game, including sticks, health, etc.
public void displayObjects() {
}
}
//-----------------------------------------------------------------------------------------------------
//JUnit Tests
class WhackAMoleViewTest {
@Test
public void testDrawBackground() {
// GUI element - cannot test at this time
}
@Test
public void testDisplayObjects() {
// GUI element - cannot test at this time
}
}
|
package mainpackage;
public class PuppyTest {
public void pupAge() {
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}
public static void main(String[] args) {
PuppyTest test = new PuppyTest();
test.pupAge();
}
}
|
package com.bat.commoncode.entity;
import lombok.Data;
import java.io.Serializable;
/**
* 用于测试的结构体
*
* @author ZhengYu
* @version 1.0 2019/10/31 17:32
**/
@Data
public class CustomStructure implements Serializable {
public CustomStructure() {
}
public CustomStructure(String username, Integer age) {
this.username = username;
this.age = age;
}
private Long id;
private String username;
private Integer age;
}
|
package com.tencent.mm.ui.chatting;
import android.view.MotionEvent;
import android.view.View;
public interface ai$b {
boolean e(View view, MotionEvent motionEvent);
}
|
package Query.Plan;
import Query.Engine.QueryIndexer;
import Query.Entities.PlanTable;
import Query.Entities.RelationEdge;
import Entity.Constraint;
import Entity.QueryConstraints;
import java.util.ArrayList;
import java.util.List;
/**
* Created by liuche on 5/29/17.
*
*/
public class ExpandIntoPlan extends Plan {
private RelationEdge edge;
private QueryConstraints cons;
private List<String> getLabels(String variable, PlanTable table){
List<String> result = new ArrayList<>();
for(Plan plan : table.plans.toList()){
if(plan instanceof ScanByLabelPlan){
if(((ScanByLabelPlan) plan).variable.equals(variable)){
result.addAll(((ScanByLabelPlan) plan).labels);
}
}
if(plan instanceof FilterConstraintPlan){
if(plan.getVariable().equals(variable)){
Constraint constraint = ((FilterConstraintPlan) plan).getConstraint();
if(constraint.name.equals("nodeLabels")){
List<String> labels = (List<String>) constraint.value.val;
result.addAll(labels);
}
}
}
}
return result;
}
public ExpandIntoPlan(QueryIndexer queryIndexer, RelationEdge edge, QueryConstraints constraints, PlanTable table) {
super(queryIndexer);
this.edge = edge;
this.cons = constraints;
this.estimatedSize = table.estimatedSize;
List<String> labels1 = getLabels(edge.start, table);
List<String> labels2 = getLabels(edge.end, table);
List<String> relations = new ArrayList<>();
for(Constraint constraint : constraints.getConstraints()){
if(constraint.name.equals("rel_type")){
assert constraint.value.type.contains("List");
List<String> types = (List<String>) constraint.value.val;
relations.addAll(types);
}
}
// Size estimation for (a:A:B)-[r:R1|R2]->(b:D:E)
Integer outgoingSize = 0, incomingSize = 0;
if(!edge.direction.equals("<--")){ //Directions: -->, --, <-->
int currentSize = 0;
for(String relation : relations){
int minEdges = Integer.MAX_VALUE;
for(String label : labels1){
int edges = indexer.getOutingOfNodeRelation(label, relation);
minEdges = (minEdges < edges) ? minEdges : edges;
}
currentSize += minEdges;
}
outgoingSize = currentSize; currentSize = 0;
for(String relation : relations){
int minEdges = Integer.MAX_VALUE;
for(String label : labels2){
int edges = indexer.getIncomingOfNodeRelation(label, relation);
minEdges = (minEdges < edges) ? minEdges : edges;
}
currentSize += minEdges;
}
outgoingSize = (outgoingSize < currentSize) ? outgoingSize : currentSize;
}
if(!edge.direction.equals("-->")){ //Directions: <--, --, <-->
int currentSize = 0;
for(String relation : relations){
int minEdges = Integer.MAX_VALUE;
for(String label : labels1){
int edges = indexer.getIncomingOfNodeRelation(label, relation);
minEdges = (minEdges < edges) ? minEdges : edges;
}
currentSize += minEdges;
}
incomingSize = currentSize; currentSize = 0;
for(String relation : relations){
int minEdges = Integer.MAX_VALUE;
for(String label : labels2){
int edges = indexer.getOutingOfNodeRelation(label, relation);
minEdges = (minEdges < edges) ? minEdges : edges;
}
currentSize += minEdges;
}
incomingSize = (incomingSize < currentSize) ? incomingSize : currentSize;
}
int cost = 0;
switch (edge.direction){
case "-->" :
cost = outgoingSize;
break;
case "<--" :
cost = incomingSize;
break;
case "<-->" : case "--" :
cost = incomingSize + outgoingSize;
break;
default:
break;
}
this.estimatedSize = this.estimatedSize < cost ? this.estimatedSize : cost;
}
@Override
public void applyTo(PlanTable table) {
table.relations.add(edge.name);
table.cost += table.estimatedSize;
table.estimatedSize = this.estimatedSize;
table.plans.add(this);
super.applyTo(table);
}
@Override
public String getParams() {
return "-[" + edge.name + cons.toString() + "]-(" + edge.end + ")";
}
@Override
public String getVariable() {
return edge.start;
}
@Override
public String getName() {
return "ExpandInto";
}
public RelationEdge getRelationEdge(){
return this.edge;
}
public QueryConstraints getCons() {return this.cons;}
}
|
package com.tfjybj.integral.model;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* Created by 王梦瑶 on 2019/9/10.
*/
@Data
public class MyRankModel implements Serializable {
private String myName;
private Integer myIntegral;
private Integer myRank;
private List<RankListModel> rankListModels;
}
|
package modelo;
//Angie Valentina Córdoba A00347829
public class Licencia {
//CONSTANTES
public final static String CATE1 = "A1";
public final static String CATE2 = "A2";
public final static String CATE3 = "B1";
public final static String CATE4 = "C";
//ATRIBUTOS
private String numero;
private String estado;
private String categoria;
private double multa;
//RELACIONES
private Fecha FechaLicen;
//CONSTRUCTOR
public Licencia(String elNumero) {
numero = elNumero;
estado = "";
categoria = "";
multa = 0.0;
//OBJETOS
FechaLicen = new Fecha( 0, 0, 0, 0, 0, 0);
}
//Metodos
public String darNumero() {
return numero;
}
public void modificarNumero(String elNumero) {
numero = elNumero;
}
public String darEstado() {
return estado;
}
public void modificarEstado(String elEstado) {
estado = elEstado;
}
public String darCategoria() {
return categoria;
}
public void modificarCategoria(String laCategoria) {
categoria = laCategoria;
}
public double darMulta() {
return multa;
}
public void modificarMultas(double laMulta) {
multa = laMulta;
}
public Fecha darFechaLicen() {
return FechaLicen;
}
public void modificarFechaLicen(Fecha FechaLicen) {
this.FechaLicen = FechaLicen;
}
//REQUERIMIENTOS
//CATEGORIA
public String categoria(Vehiculo vehiculoUno, Vehiculo vehiculoDos) {
if (vehiculoUno != null || vehiculoDos != null) {
if ((vehiculoUno.darTipoVehiculo().equals("moto")) & (vehiculoDos.darTipoVehiculo().equals("carro")) || (vehiculoUno.darTipoVehiculo().equals("carro")) & (vehiculoDos.darTipoVehiculo().equals("moto"))) {
categoria = CATE4;
}
else if ((vehiculoUno.darTipoVehiculo().equals("moto")) && (vehiculoUno.darValorCilindraje() <= 125)) {
categoria = CATE1;
}
else if ((vehiculoUno.darTipoVehiculo().equals("moto")) && (vehiculoUno.darValorCilindraje() > 125)) {
categoria = CATE2;
}
else if ((vehiculoDos.darTipoVehiculo().equals("moto")) && (vehiculoUno.darValorCilindraje() <= 125)) {
categoria = CATE1;
}
else if ((vehiculoDos.darTipoVehiculo().equals("moto")) && (vehiculoDos.darValorCilindraje() > 125)) {
categoria = CATE2;
}
else if ((vehiculoUno.darTipoVehiculo().equals("carro"))) {
categoria = CATE3;
}
else if ((vehiculoDos.darTipoVehiculo().equals("carro"))) {
categoria = CATE3;
}
}
return categoria;
}
public double calcularMultaVen(Fecha vencimiento) {
FechaLicen.vencimiento();
if (vencimiento.equals("La licencia esta vencida")) {
multa = 165000;
}
else {
multa = 0;
}
return multa;
}
//ESTADO DE LA LICENCIA
public String estadoLicenia(Fecha vencimiento) {
FechaLicen.vencimiento();
if (vencimiento.equals("La licencia esta vencida")) {
estado = "Vencida";
}
else {
estado = "Activa";
}
return estado;
}
//MULTA
public double multa(Usuario Licen,Fecha vencimiento) {
FechaLicen.vencimiento();
if (vencimiento.equals("La licencia esta vencida")) {
multa = 165000;
}
else {
multa = 0;
}
if (Licen == null) {
multa = multa + 165.000;
}
return multa;
}
}
|
package com.example.proiectdam_serbansorinaalexandra.Data;
import android.content.Context;
import android.os.AsyncTask;
import com.example.proiectdam_serbansorinaalexandra.Database.DatabaseInstance;
import java.util.List;
public class GetLandmarksAsync extends AsyncTask<String, Void, List<Landmark>> {
private Context context;
public GetLandmarksAsync(Context context) {
this.context = context;
}
@Override
protected List<Landmark> doInBackground(String... strings) {
return DatabaseInstance.getInstance(context).getDatabase().landmarkDAO().getAllLandmarks();
}
}
|
package com.bytedance.sandboxapp.a.a.c;
import com.bytedance.sandboxapp.c.a.a.c;
import com.bytedance.sandboxapp.c.a.b;
import com.bytedance.sandboxapp.protocol.service.api.entity.ApiCallbackData;
public abstract class p extends c {
public p(b paramb, com.bytedance.sandboxapp.a.a.d.a parama) {
super(paramb, parama);
}
public abstract void a(a parama, com.bytedance.sandboxapp.protocol.service.api.entity.a parama1);
public final void handleApi(com.bytedance.sandboxapp.protocol.service.api.entity.a parama) {
a a1 = new a(this, parama);
if (a1.a != null) {
callbackData(a1.a);
return;
}
a(a1, parama);
}
public final class a {
public ApiCallbackData a;
public final Integer b;
public final String c;
public a(p this$0, com.bytedance.sandboxapp.protocol.service.api.entity.a param1a) {
String str = param1a.b;
Object object2 = param1a.a("requestTaskId");
if (object2 instanceof Integer) {
this.b = (Integer)object2;
} else {
if (object2 == null) {
this.a = com.bytedance.sandboxapp.c.a.a.a.a.a(str, "requestTaskId");
} else {
this.a = com.bytedance.sandboxapp.c.a.a.a.a.a(str, "requestTaskId", "Integer");
}
this.b = null;
}
Object object1 = param1a.a("operationType");
if (object1 instanceof String) {
this.c = (String)object1;
return;
}
if (object1 == null) {
this.a = com.bytedance.sandboxapp.c.a.a.a.a.a(str, "operationType");
} else {
this.a = com.bytedance.sandboxapp.c.a.a.a.a.a(str, "operationType", "String");
}
this.c = null;
}
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\bytedance\sandboxapp\a\a\c\p.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ |
package com.porsche.sell.enums;
import lombok.Getter;
/** 商品状态枚举类
* @author XuHao
* Email 15229357319@sina.cn
* create on 2018/8/8
*/
@Getter
public enum ProductStatusEnum implements CodeEnum{
/**
* 上架
*/
PRODUCT_UP(0, "上架"),
/**
* 下架
*/
PRODUCT_DOWN(1, "下架"),
;
private Integer code;
private String msg;
ProductStatusEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
}
|
package ooriented.programming.module;
public class Car extends Vehicle{
public Car() {
super();
}
}
|
package com.ld.baselibrary.base;
import android.app.Application;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import com.ld.baselibrary.util.TUtil;
import com.trello.rxlifecycle4.LifecycleProvider;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;
/**
* @author: liangduo
* @date: 2020/9/14 1:56 PM
*/
public class BaseViewModel<M extends AbsRepository> extends AndroidViewModel implements IBaseViewModel {
public M mRepository;
private UIChangeLiveData uc;
//弱引用持有---当一个对象只被弱引用实例引用(持有)时,这个对象就会被GC回收
private WeakReference<LifecycleProvider> lifecycle;
public BaseViewModel(@NonNull Application application) {
super(application);
mRepository = TUtil.getNewInstance(this, 0);
}
/**
* 当Activity/Fragment销毁时,调用此方法
*/
@Override
protected void onCleared() {
super.onCleared();
if (mRepository != null) {
mRepository.unSubscribe();
}
}
/**
* 注入RxLifecycle生命周期
*
* @param lifecycle
*/
public void injectLifecycleProvider(LifecycleProvider lifecycle) {
this.lifecycle = new WeakReference<>(lifecycle);
}
/* ---------- 以下 初始化数据 -------*/
/**
* 初始化数据
*/
public void initData() {
}
/**
* 初始化数据
*/
public void initData(Intent intent) {
}
/**
* 初始化数据
*/
public void initData(Bundle bundle) {
}
/* ---------- 以下 LifecycleObserver -------*/
@Override
public void onAny(LifecycleOwner owner, Lifecycle.Event event) {
}
@Override
public void onCreate() {
}
@Override
public void onDestroy() {
}
@Override
public void onStart() {
}
@Override
public void onStop() {
}
@Override
public void onResume() {
}
@Override
public void onPause() {
}
@Override
public void registerRxBus() {
}
@Override
public void removeRxBus() {
}
/* ---------- 以上 LifecycleObserver -------*/
/**
* 跳转容器页面
*
* @param canonicalName 规范名 : Fragment.class.getCanonicalName()
*/
public void startContainerActivity(String canonicalName) {
startContainerActivity(canonicalName, null);
}
/**
* 跳转容器页面
*
* @param canonicalName 规范名 : Fragment.class.getCanonicalName()
* @param bundle 跳转所携带的信息
*/
public void startContainerActivity(String canonicalName, Bundle bundle) {
Map<String, Object> params = new HashMap<>();
params.put(ParameterField.CANONICAL_NAME, canonicalName);
if (bundle != null) {
params.put(ParameterField.BUNDLE, bundle);
}
uc.startContainerActivityEvent.postValue(params);
}
/**
* 跳转页面
*
* @param clz 所跳转的目的Activity类
*/
public void startActivity(Class<?> clz) {
startActivity(clz, null);
}
/**
* 跳转页面
*
* @param clz 所跳转的目的Activity类
* @param bundle 跳转所携带的信息
*/
public void startActivity(Class<?> clz, Bundle bundle) {
Map<String, Object> params = new HashMap<>();
params.put(ParameterField.CLASS, clz);
if (bundle != null) {
params.put(ParameterField.BUNDLE, bundle);
}
uc.startActivityEvent.postValue(params);
}
public UIChangeLiveData getUC() {
if (uc == null) {
uc = new UIChangeLiveData();
}
return uc;
}
public final class UIChangeLiveData extends MutableLiveData {
private MutableLiveData<String> showDialogEvent;
private MutableLiveData<Void> dismissDialogEvent;
private MutableLiveData<Map<String, Object>> startActivityEvent;
private MutableLiveData<Map<String, Object>> startContainerActivityEvent;
private MutableLiveData<Void> finishEvent;
private MutableLiveData<Void> onBackPressedEvent;
public MutableLiveData<String> getShowDialogEvent() {
return showDialogEvent = createLiveData(showDialogEvent);
}
public MutableLiveData<Void> getDismissDialogEvent() {
return dismissDialogEvent = createLiveData(dismissDialogEvent);
}
public MutableLiveData<Map<String, Object>> getStartActivityEvent() {
return startActivityEvent = createLiveData(startActivityEvent);
}
public MutableLiveData<Map<String, Object>> getStartContainerActivityEvent() {
return startContainerActivityEvent = createLiveData(startContainerActivityEvent);
}
public MutableLiveData<Void> getFinishEvent() {
return finishEvent = createLiveData(finishEvent);
}
public MutableLiveData<Void> getOnBackPressedEvent() {
return onBackPressedEvent = createLiveData(onBackPressedEvent);
}
private <T> MutableLiveData<T> createLiveData(MutableLiveData<T> liveData) {
if (liveData == null) {
liveData = new MutableLiveData<>();
}
return liveData;
}
@Override
public void observe(LifecycleOwner owner, Observer observer) {
super.observe(owner, observer);
}
}
public static final class ParameterField {
public static String CLASS = "CLASS";
public static String BUNDLE = "BUNDLE";
public static String INTENT = "INTENT";
public static String CANONICAL_NAME = "CANONICAL_NAME";
public static String REQUEST_CODE = "REQUEST_CODE";
}
}
|
package com.tencent.mm.booter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MMReceivers$ToolsProcessReceiver extends BroadcastReceiver {
private static MMReceivers$a cWR = null;
public static void a(MMReceivers$a mMReceivers$a) {
cWR = mMReceivers$a;
}
public void onReceive(Context context, Intent intent) {
if (cWR != null) {
cWR.onReceive(context, intent);
}
}
}
|
package com.pgm.pro1.Database;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONObject;
import java.sql.Connection;
public class GestionBD extends SQLiteOpenHelper {
private String result,tipo;
private int aux = 0;
// private Connection conn = new Connection();
private JSONArray jarray,jsonA;
private JSONObject json_data,jObject;
private StringBuilder sb = new StringBuilder();
String sqlCrearTablaDireccion = "create table C_Direccion(id_c_direccion INTEGER PRIMARY KEY AUTOINCREMENT, direccion TEXT,capturo Text,fecha numeric)";
String sqlCrearTablaInspectores = "create table C_inspector(id_c_inspector INTEGER PRIMARY KEY AUTOINCREMENT, nombre TEXT not null,ife TEXT not null, vigente text, no_empleado int not null,vigencia NUMERIC,id_c_direccion int not null,contrasena text,capturo text,fecha numeric)";
public GestionBD(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, null, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(sqlCrearTablaDireccion);
db.execSQL(sqlCrearTablaInspectores);
Log.i("Gestionar", sqlCrearTablaDireccion);
Log.i("Gestionar", sqlCrearTablaInspectores);
ingresarDireccion(db);
ingresarInspectores(db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void ingresarDireccion(SQLiteDatabase db){
//db = this.getWritableDatabase();
try{
if(db != null){
ContentValues cv = new ContentValues();
cv.put("id_c_direccion", 1);
cv.put("direccion", "Administracion");
cv.put("capturo","");
cv.put("fecha","");
db.insert("C_Direccion", null, cv);
}
}catch (Exception e) {
Log.i("insertar", e.getMessage());
}
}
public void ingresarInspectores(SQLiteDatabase db){
if(db != null){
ContentValues cv = new ContentValues();
cv.put("id_c_inspector", 1);
cv.put("nombre", "administrador");
cv.put("ife", "");
cv.put("no_empleado", 2);
cv.put("vigencia", "");
cv.put("id_c_direccion", 1);
cv.put("contrasena", "4dm1n");
cv.put("capturo","");
cv.put("fecha","");
cv.put("vigente", "S");
db.insert("C_inspector", null, cv);
}
}
}
|
package com.tencent.mm.plugin.appbrand.appusage;
import com.tencent.mm.ab.b;
import com.tencent.mm.ab.l;
import com.tencent.mm.ab.v.a;
import com.tencent.mm.protocal.c.bvj;
class l$1 implements a {
final /* synthetic */ String dhF;
final /* synthetic */ int fmg;
final /* synthetic */ long fmh;
final /* synthetic */ l fmi;
public l$1(l lVar, String str, int i, long j) {
this.fmi = lVar;
this.dhF = str;
this.fmg = i;
this.fmh = j;
}
public final int a(int i, int i2, String str, b bVar, l lVar) {
if (!(i == 0 && i2 == 0 && ((bvj) bVar.dIE.dIL).rrI.iwS == 0) && l.a(this.fmi).isOpen()) {
l.a aVar = new l.a();
aVar.field_username = this.dhF;
aVar.field_versionType = this.fmg;
aVar.field_updateTime = this.fmh;
l.b(this.fmi).a(aVar, false, new String[]{"updateTime", "username", "versionType"});
if (!this.fmi.aq(this.dhF, this.fmg)) {
this.fmi.b("single", 3, aVar);
}
}
return 0;
}
}
|
package com.navin.melalwallet.di.context;
import android.content.Context;
import com.navin.melalwallet.ui.login.LoginActivity;
import dagger.Component;
@Component(modules = {MainActivityModule.class})
public interface ActivityComponent {
Context context();
void inject(LoginActivity loginActivity);
}
|
/**
*
*/
package br.com.nozinho.web.framwork;
import java.io.Serializable;
import java.util.List;
import br.com.nozinho.model.Entidade;
/**
* @author RodrigoAndrade
*
*/
public interface GenericController<T extends Entidade, C extends Serializable> extends Serializable{
T getEntidade();
void setEntidade(T entidade);
List<T> getEntidades();
void setEntidades(List<T> entidades);
T recuperarPorId(Object id);
List<T> recuperarTodos();
void remover();
T merge();
T salvar();
T salvarClear();
List<T> salvarLista();
}
|
package kr.ko.nexmain.server.MissingU.missionmatch.model;
import java.util.List;
import javax.validation.constraints.NotNull;
import kr.ko.nexmain.server.MissingU.common.model.CommReqVO;
/**
* @author 영환
*
*/
public class MissionMatchReqVO extends CommReqVO {
/** */
private static final long serialVersionUID = 1L;
/** 미션번호 */
private Integer mId;
/** 유형 (0=페이스매치, 1=미션매치) */
@NotNull
private Integer type;
/** 32강, 16강 선택 */
private int needRound = 16;
/** 시드권자 */
private int needSeedCount;
/** 일반사용자 */
private int needCount;
/** 성별 */
private String sex="";
/** 승자 목록 */
private List<String> winners;
private List<String> participant;
/** 미션번호 */
public Integer getmId() {
return mId;
}
/** 미션번호 */
public void setmId(Integer mId) {
this.mId = mId;
}
/** 유형 (0=페이스매치, 1=미션매치) */
public int getType() {
return type;
}
/** 유형 (0=페이스매치, 1=미션매치) */
public void setType(int type) {
this.type = type;
}
/** 32강, 16강 선택 */
public int getNeedRound() {
return needRound;
}
/** 32강, 16강 선택 */
public void setNeedRound(int needRound) {
this.needRound = needRound;
}
/** 성별 */
public String getSex() {
return sex;
}
/** 성별 */
public void setSex(String sex) {
this.sex = sex;
}
/** 승자 목록 */
public List<String> getWinners() {
return winners;
}
/** 승자 목록 */
public void setWinners(List<String> winners) {
this.winners = winners;
if(this.winners != null) {
this.needSeedCount = this.winners.size();
this.needCount = this.needRound - this.needSeedCount;
}
}
public int getNeedSeedCount() {
return this.needSeedCount;
}
public int getNeedCount() {
return this.needCount;
}
/**
* @return the participant
*/
public List<String> getParticipant() {
return participant;
}
/**
* @param participant the participant to set
*/
public void setParticipant(List<String> participant) {
this.participant = participant;
}
}
|
package mg.egg.eggc.runtime.libjava.lex;
public class UL {
/**
* La chaîne associée à la fenêtre.
*/
// private String nom ;
// tempo
public String nom;
public String getNom() {
return nom;
}
/**
* Le code de la fenètre.
*/
public int code;
/**
* La ligne de la fenêtre.
*/
public int ligne;
/**
* La colonne de la fenêtre.
*/
public int colonne;
/**
* Retourne une chaîne représentant la fenêtre courante.
*
* @return une chaîne représentant la feneêtre courante
*/
public String toString() {
return "ul: >" + nom + "<, (" + code + ")";
}
/**
* Construit une nouvelle fenètre.
*
* @param code
* le code de la fenêtre
* @param nom
* le nom de la fenêtre
*/
public UL(int code, String nom) {
this(code, nom, 0, 0);
}
/**
* Construit une nouvelle fenètre.
*
* @param code
* le code de la fenêtre
* @param nom
* le nom de la fenêtre
* @param ligne
* la ligne de la fenêtre
* @param colonne
* la colonne de la fenêtre
*/
public UL(int code, String nom, int ligne, int colonne) {
this.code = code;
this.nom = nom;
this.ligne = ligne;
this.colonne = colonne;
}
}
|
package graphic.Gui.Items;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import lorenzo.Applicazione;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.LinkedHashMap;
/**
* Created by pietro on 18/06/17.
*/
public class ClassificaGraphic {
Label[] classificaLabel;
private ImageView sfondo;
/**
* Construisci e mostra al centro del pannello la classifica finale
* @param pannello pannello sul quale viene mostrato il risultato
* @param risultati mappa con GiocatoreGraphic e pVittoria in ordine di classifica
*/
public ClassificaGraphic(LinkedHashMap<GiocatoreGraphic, Integer> risultati, Pane pannello){
AnchorPane parent = null;
classificaLabel = new Label[4];
//Carica l'FXML
try {
FXMLLoader fxmlLoader= new FXMLLoader();
fxmlLoader.setLocation(Paths.get(Applicazione.fxmlPath + "classifica_finale.fxml").toUri().toURL());
parent = fxmlLoader.load();
} catch (IOException e) {
e.printStackTrace();
}
//Recupero variabili
classificaLabel[0] = (Label) parent.lookup("#primo");
classificaLabel[1] = (Label) parent.lookup("#secondo");
classificaLabel[2] = (Label) parent.lookup("#terzo");
classificaLabel[3] = (Label) parent.lookup("#quarto");
sfondo = (ImageView) parent.lookup("#immagineSfondo");
//Popolazione classifica
GiocatoreGraphic[] giocatori = new GiocatoreGraphic[risultati.keySet().size()];
int[] pVittoria = new int[risultati.keySet().size()];
int i = 0;
for (GiocatoreGraphic giocatore : risultati.keySet()) {
giocatori[i] = giocatore;
pVittoria[i] = risultati.get(giocatore);
i= i+1;
}
//Sort
for (i = 0; i < giocatori.length-1; i++) {
for (int j = i+1; j < giocatori.length; j++) {
if(pVittoria[i]< pVittoria[j]){
int temp = pVittoria[i];
GiocatoreGraphic tempG = giocatori[i];
pVittoria[i]=pVittoria[j];
giocatori[i]=giocatori[j];
pVittoria[j]=temp;
giocatori[j]=tempG;
}
}
}
//Printa
for (i=0; i < giocatori.length; i++) {
classificaLabel[i].setText((i+1)+ " - "+giocatori[i].getNome()+" - "+pVittoria[i]);
classificaLabel[i].setTextFill(giocatori[i].getColoreGiocatore().getColore());
}
//Trasla il pannello
parent.setLayoutX((pannello.getWidth()-parent.getPrefWidth()) /2);
parent.setLayoutY((pannello.getHeight()-parent.getPrefHeight()) /2);
//Setta sfondo
sfondo.setImage(new Image("/classificaFinale.png"));
//Mostra
pannello.getChildren().add(parent);
}
}
|
package com.trust.demo.main;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.trust.demo.R;
import java.util.List;
/**
* Created by Trust on 2017/7/27.
*/
public class CoderAdapter extends BaseRecyclerAdapter {
public CoderAdapter(Context mContext) {
super(mContext);
}
@Override
protected ViewHolder initItemView(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_fragment_code,null);
return new CoderViewHolder(view);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
CoderViewHolder coderViewHolder = (CoderViewHolder) holder;
List<CoderBean> coderBeans = ml;
coderViewHolder.title.setText(coderBeans.get(position).getMsg());
coderViewHolder.time.setText(coderBeans.get(position).getTime());
coderViewHolder.logo.setImageResource(coderBeans.get(position).getImgId());
}
class CoderViewHolder extends ViewHolder{
TextView title,time;
ImageView logo;
public CoderViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.item_codetext);
time = (TextView) itemView.findViewById(R.id.item_codetime);
logo = (ImageView) itemView.findViewById(R.id.item_codelogo);
}
}
}
|
package com.tencent.mm.plugin.game.gamewebview.jsapi.biz;
import android.content.Context;
import android.content.pm.PackageInfo;
import com.tencent.mm.plugin.game.gamewebview.jsapi.a;
import com.tencent.mm.plugin.game.gamewebview.ui.d;
import com.tencent.mm.pluginsdk.model.app.p;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
public final class q extends a {
public static final int CTRL_BYTE = 25;
public static final String NAME = "getInstallState";
public final void a(d dVar, JSONObject jSONObject, int i) {
x.i("MicroMsg.GameJsApiGetNetworkType", "invoke");
Context context = dVar.getContext();
if (context == null) {
x.i("MicroMsg.GameJsApiGetNetworkType", "context is null");
} else if (jSONObject == null) {
x.i("MicroMsg.GameJsApiGetNetworkType", "data is null");
dVar.E(i, a.f("get_install_state:no_null_data", null));
} else {
JSONArray optJSONArray = jSONObject.optJSONArray("packageName");
int i2;
Map hashMap;
if (optJSONArray != null) {
JSONObject jSONObject2 = new JSONObject();
JSONObject jSONObject3 = new JSONObject();
Object obj = null;
i2 = 0;
while (true) {
try {
int i3 = i2;
if (i3 >= optJSONArray.length()) {
break;
}
String optString = optJSONArray.optString(i3);
PackageInfo packageInfo = p.getPackageInfo(context, optString);
int i4 = packageInfo == null ? 0 : packageInfo.versionCode;
String str = packageInfo == null ? "null" : packageInfo.versionName;
x.i("MicroMsg.GameJsApiGetNetworkType", "getInstallState, packageName = " + optString + ", version = " + i4 + ", versionName = " + str);
if (obj == null && i4 > 0) {
obj = 1;
}
jSONObject2.put(optString, i4);
jSONObject3.put(optString, str);
i2 = i3 + 1;
} catch (Exception e) {
}
}
hashMap = new HashMap();
hashMap.put("result", jSONObject2.toString());
hashMap.put("versionName", jSONObject3.toString());
if (obj != null) {
dVar.E(i, f("get_install_state:yes", hashMap));
return;
} else {
dVar.E(i, a.f("get_install_state:no", null));
return;
}
}
String optString2 = jSONObject.optString("packageName");
if (bi.oW(optString2)) {
x.i("MicroMsg.GameJsApiGetNetworkType", "packageName is null or nil");
dVar.E(i, a.f("get_install_state:no_null_packageName", null));
return;
}
PackageInfo packageInfo2 = p.getPackageInfo(context, optString2);
i2 = packageInfo2 == null ? 0 : packageInfo2.versionCode;
String str2 = packageInfo2 == null ? "null" : packageInfo2.versionName;
x.i("MicroMsg.GameJsApiGetNetworkType", "doGetInstallState, packageName = " + optString2 + ", version = " + i2 + ", versionName = " + str2);
if (packageInfo2 == null) {
dVar.E(i, a.f("get_install_state:no", null));
return;
}
hashMap = new HashMap();
hashMap.put("versionName", str2);
dVar.E(i, f("get_install_state:yes_" + str2, hashMap));
}
}
}
|
package io.bega.kduino.datamodel;
import com.orm.SugarRecord;
import java.util.ArrayList;
import java.util.Date;
/**
* Created by usuario on 15/07/15.
*/
public class Measurement extends SugarRecord<Measurement> {
public String date;
public BuoyDefinition buoy;
ArrayList<RawMeasurement> list = new ArrayList<>();
public Measurement(BuoyDefinition buoy, String date)
{
this.buoy = buoy;
this.date = date;
}
public ArrayList<RawMeasurement> getRawMeasurements()
{
return list;
}
public void addMeasurement(String id, String rawValue, String date)
{
RawMeasurement rawMeasurement = new RawMeasurement(this, id, rawValue, date);
list.add(rawMeasurement);
}
}
|
package com.tencent.mm.plugin.appbrand.game;
import com.tencent.mm.sdk.platformtools.x;
import java.lang.ref.WeakReference;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.egl.EGLSurface;
class GameGLSurfaceView$i {
EGL10 fbb;
EGLDisplay fbc;
EGLContext fbd;
EGLSurface fbe;
WeakReference<GameGLSurfaceView> fzn;
EGLConfig fzo;
public GameGLSurfaceView$i(WeakReference<GameGLSurfaceView> weakReference) {
this.fzn = weakReference;
}
final void afJ() {
if (this.fbe != null && this.fbe != EGL10.EGL_NO_SURFACE) {
this.fbb.eglMakeCurrent(this.fbc, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
GameGLSurfaceView gameGLSurfaceView = (GameGLSurfaceView) this.fzn.get();
if (gameGLSurfaceView != null) {
GameGLSurfaceView.d(gameGLSurfaceView).destroySurface(this.fbb, this.fbc, this.fbe);
}
this.fbe = null;
}
}
public static void az(String str, int i) {
String aA = aA(str, i);
x.e("MicroMsg.GLThread", "throwEglException tid=" + Thread.currentThread().getId() + " " + aA);
throw new RuntimeException(aA);
}
public static void n(String str, String str2, int i) {
x.w(str, aA(str2, i));
}
private static String aA(String str, int i) {
return str + " failed: " + GameGLSurfaceView$g.kk(i);
}
}
|
package com.example.demo.model;
import org.springframework.beans.factory.annotation.Autowired;
import javax.persistence.*;
import java.util.List;
@Entity
@Table(name = "student")
public class student {
@Id
@GeneratedValue
private int id;
private String name;
private String matric;
public student()
{
}
public student(int id, String name, String matric) {
this.id = id;
this.name = name;
this.matric = matric;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMatric() {
return matric;
}
public void setMatric(String matric) {
this.matric = matric;
}
@Override
public String toString() {
return "student{" +
"id=" + id +
", name='" + name + '\'' +
", matric='" + matric + '\'' +
'}';
}
@OneToMany(targetEntity = detail.class, cascade = CascadeType.ALL)
@JoinColumn(name="cp_fk", referencedColumnName ="id")
private List<detail>details;
}
|
package es.studium.practica2;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class vistaModificarArticuloDatos extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private static JTextField txDescricpion;
private static JTextField txPrecio;
private static JTextField txStock;
static String datos;
static String desc;
static String prec;
static String cant;
static String id;
static String descM;
static String precM;
static String cantM;
static vistaModificarArticuloDatos frame;
static vistaModificarArticulo vistaModificarArticulo = null;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame = new vistaModificarArticuloDatos();
frame.setVisible(true);
Mostrarchoice();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public vistaModificarArticuloDatos() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 342, 314);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblDescriocin = new JLabel("Descripción");
lblDescriocin.setBounds(47, 56, 75, 16);
contentPane.add(lblDescriocin);
JLabel lblPrecio = new JLabel("Precio");
lblPrecio.setBounds(47, 108, 61, 16);
contentPane.add(lblPrecio);
JLabel lblCantidad = new JLabel("Cantidad");
lblCantidad.setBounds(47, 163, 61, 16);
contentPane.add(lblCantidad);
txDescricpion = new JTextField();
txDescricpion.setBounds(162, 103, 130, 26);
contentPane.add(txDescricpion);
txDescricpion.setColumns(10);
txPrecio = new JTextField();
txPrecio.setBounds(162, 158, 130, 26);
contentPane.add(txPrecio);
txPrecio.setColumns(10);
txStock = new JTextField();
txStock.setBounds(162, 51, 130, 26);
contentPane.add(txStock);
txStock.setColumns(10);
JButton btnAceptar = new JButton("Aceptar");
btnAceptar.setBounds(175, 243, 117, 29);
contentPane.add(btnAceptar);
btnAceptar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object objetoPulsado = e.getSource();
if(objetoPulsado.equals(btnAceptar)) {
conseguirValores();
vistaModificarArticuloDatosConfirmacion.main(null);
}
}
});
JButton btnCancelar = new JButton("Cancelar");
btnCancelar.setBounds(46, 243, 117, 29);
contentPane.add(btnCancelar);
btnCancelar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object objetoPulsado = e.getSource();
if(objetoPulsado.equals(btnCancelar)) {
frame.dispose();
}
}
});
}
public static void Mostrarchoice()
{
desc = vistaModificarArticulo.desc;
txDescricpion.setText(desc);
prec = vistaModificarArticulo.prec;
txPrecio.setText(prec);
cant = vistaModificarArticulo.cant;
txStock.setText(cant);
}
public static void conseguirValores() {
descM = txDescricpion.getText().toString();
precM = txPrecio.getText().toString();
cantM = txStock.getText().toString();
id = vistaModificarArticulo.id;
}
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
import java.math.BigDecimal;
import java.sql.Clob;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
/**
* BRoutine generated by hbm2java
*/
public class BRoutine implements java.io.Serializable {
private BigDecimal uniqueid;
private BRoutine BRoutine;
private RResource RResource;
private String operationName;
private String operationGroup;
private BigDecimal preopTime;
private BigDecimal unitRuntime;
private BigDecimal postopTime;
private String baseMachineResource;
private Long numOperators;
private Long parallel;
private String parallelThreshold;
private String minimumParallelSubtask;
private Long useMprsIfNotLate;
private Long minOperationTime;
private BigDecimal opEstimatedQueneTime;
private BigDecimal opMininumQueneTime;
private BigDecimal baseYield;
private Long interruptible;
private Long operationType;
private Long priority;
private String queueCalendarName;
private String rampupCalendarName;
private Long transferBatchQuantity;
private Long isCrossOperation;
private Long needCheck;
private Long isCriticalOperation;
private String operationSpecification;
private Long materialCheckIn;
private Long materialCheckOut;
private Long operationCostSum;
private Long laborCost;
private Long machineCost;
private Long linkDownstreamP;
private Long linkDownstreamMinWip;
private Long linkDownstreamMaxWip;
private String unitRuntimeCostPer;
private Long unitRuntimeCostPerTime;
private String unitWipCarryCostPer;
private Long unitWipCarryCostPerTime;
private String sequenceDependentSetupType;
private String sequenceDependentSetupType2;
private String sequenceDependentSetupType3;
private String note;
private String routingType;
private String operationNote;
private BigDecimal workcoefficient;
private Date changetime;
private String changer;
private String changereason;
private BigDecimal changestate;
private Byte effective;
private String creator;
private Date createtime;
private Long dispatchgrade;
private Integer sampleqty;
private BigDecimal samplepercent;
private String operationIddesc;
private String estipretime;
private String estiruntime;
private String sampleOpid;
private Byte needSample;
private Boolean checkstate;
private String groupuid;
private String opid;
private Long optype;
private String versionid;
private String routingNote;
private BigDecimal sampleRuntime;
private Boolean needFirstcheck;
private BigDecimal checkpercent;
private String refrouting;
private String BRoutineOutUid;
private String deptid;
private String deviceuid;
private String operationContentTt;
private String ncNumber;
private String ncVersionid;
private String isSpecialOperation;
private Byte preparegrade;
private Boolean needPhoto;
private Clob operationSimpleContent;
private Clob operationContent;
private Long isStatisticCheck;
private Boolean keycount;
private Set BOperationResources = new HashSet(0);
private Set BBillOfMaterialses = new HashSet(0);
private Set BRoutines = new HashSet(0);
public BRoutine() {
}
public BRoutine(BigDecimal uniqueid) {
this.uniqueid = uniqueid;
}
public BRoutine(BigDecimal uniqueid, BRoutine BRoutine, RResource RResource, String operationName,
String operationGroup, BigDecimal preopTime, BigDecimal unitRuntime, BigDecimal postopTime,
String baseMachineResource, Long numOperators, Long parallel, String parallelThreshold,
String minimumParallelSubtask, Long useMprsIfNotLate, Long minOperationTime,
BigDecimal opEstimatedQueneTime, BigDecimal opMininumQueneTime, BigDecimal baseYield, Long interruptible,
Long operationType, Long priority, String queueCalendarName, String rampupCalendarName,
Long transferBatchQuantity, Long isCrossOperation, Long needCheck, Long isCriticalOperation,
String operationSpecification, Long materialCheckIn, Long materialCheckOut, Long operationCostSum,
Long laborCost, Long machineCost, Long linkDownstreamP, Long linkDownstreamMinWip,
Long linkDownstreamMaxWip, String unitRuntimeCostPer, Long unitRuntimeCostPerTime,
String unitWipCarryCostPer, Long unitWipCarryCostPerTime, String sequenceDependentSetupType,
String sequenceDependentSetupType2, String sequenceDependentSetupType3, String note, String routingType,
String operationNote, BigDecimal workcoefficient, Date changetime, String changer, String changereason,
BigDecimal changestate, Byte effective, String creator, Date createtime, Long dispatchgrade,
Integer sampleqty, BigDecimal samplepercent, String operationIddesc, String estipretime, String estiruntime,
String sampleOpid, Byte needSample, Boolean checkstate, String groupuid, String opid, Long optype,
String versionid, String routingNote, BigDecimal sampleRuntime, Boolean needFirstcheck,
BigDecimal checkpercent, String refrouting, String BRoutineOutUid, String deptid, String deviceuid,
String operationContentTt, String ncNumber, String ncVersionid, String isSpecialOperation,
Byte preparegrade, Boolean needPhoto, Clob operationSimpleContent, Clob operationContent,
Long isStatisticCheck, Boolean keycount, Set BOperationResources, Set BBillOfMaterialses, Set BRoutines) {
this.uniqueid = uniqueid;
this.BRoutine = BRoutine;
this.RResource = RResource;
this.operationName = operationName;
this.operationGroup = operationGroup;
this.preopTime = preopTime;
this.unitRuntime = unitRuntime;
this.postopTime = postopTime;
this.baseMachineResource = baseMachineResource;
this.numOperators = numOperators;
this.parallel = parallel;
this.parallelThreshold = parallelThreshold;
this.minimumParallelSubtask = minimumParallelSubtask;
this.useMprsIfNotLate = useMprsIfNotLate;
this.minOperationTime = minOperationTime;
this.opEstimatedQueneTime = opEstimatedQueneTime;
this.opMininumQueneTime = opMininumQueneTime;
this.baseYield = baseYield;
this.interruptible = interruptible;
this.operationType = operationType;
this.priority = priority;
this.queueCalendarName = queueCalendarName;
this.rampupCalendarName = rampupCalendarName;
this.transferBatchQuantity = transferBatchQuantity;
this.isCrossOperation = isCrossOperation;
this.needCheck = needCheck;
this.isCriticalOperation = isCriticalOperation;
this.operationSpecification = operationSpecification;
this.materialCheckIn = materialCheckIn;
this.materialCheckOut = materialCheckOut;
this.operationCostSum = operationCostSum;
this.laborCost = laborCost;
this.machineCost = machineCost;
this.linkDownstreamP = linkDownstreamP;
this.linkDownstreamMinWip = linkDownstreamMinWip;
this.linkDownstreamMaxWip = linkDownstreamMaxWip;
this.unitRuntimeCostPer = unitRuntimeCostPer;
this.unitRuntimeCostPerTime = unitRuntimeCostPerTime;
this.unitWipCarryCostPer = unitWipCarryCostPer;
this.unitWipCarryCostPerTime = unitWipCarryCostPerTime;
this.sequenceDependentSetupType = sequenceDependentSetupType;
this.sequenceDependentSetupType2 = sequenceDependentSetupType2;
this.sequenceDependentSetupType3 = sequenceDependentSetupType3;
this.note = note;
this.routingType = routingType;
this.operationNote = operationNote;
this.workcoefficient = workcoefficient;
this.changetime = changetime;
this.changer = changer;
this.changereason = changereason;
this.changestate = changestate;
this.effective = effective;
this.creator = creator;
this.createtime = createtime;
this.dispatchgrade = dispatchgrade;
this.sampleqty = sampleqty;
this.samplepercent = samplepercent;
this.operationIddesc = operationIddesc;
this.estipretime = estipretime;
this.estiruntime = estiruntime;
this.sampleOpid = sampleOpid;
this.needSample = needSample;
this.checkstate = checkstate;
this.groupuid = groupuid;
this.opid = opid;
this.optype = optype;
this.versionid = versionid;
this.routingNote = routingNote;
this.sampleRuntime = sampleRuntime;
this.needFirstcheck = needFirstcheck;
this.checkpercent = checkpercent;
this.refrouting = refrouting;
this.BRoutineOutUid = BRoutineOutUid;
this.deptid = deptid;
this.deviceuid = deviceuid;
this.operationContentTt = operationContentTt;
this.ncNumber = ncNumber;
this.ncVersionid = ncVersionid;
this.isSpecialOperation = isSpecialOperation;
this.preparegrade = preparegrade;
this.needPhoto = needPhoto;
this.operationSimpleContent = operationSimpleContent;
this.operationContent = operationContent;
this.isStatisticCheck = isStatisticCheck;
this.keycount = keycount;
this.BOperationResources = BOperationResources;
this.BBillOfMaterialses = BBillOfMaterialses;
this.BRoutines = BRoutines;
}
public BigDecimal getUniqueid() {
return this.uniqueid;
}
public void setUniqueid(BigDecimal uniqueid) {
this.uniqueid = uniqueid;
}
public BRoutine getBRoutine() {
return this.BRoutine;
}
public void setBRoutine(BRoutine BRoutine) {
this.BRoutine = BRoutine;
}
public RResource getRResource() {
return this.RResource;
}
public void setRResource(RResource RResource) {
this.RResource = RResource;
}
public String getOperationName() {
return this.operationName;
}
public void setOperationName(String operationName) {
this.operationName = operationName;
}
public String getOperationGroup() {
return this.operationGroup;
}
public void setOperationGroup(String operationGroup) {
this.operationGroup = operationGroup;
}
public BigDecimal getPreopTime() {
return this.preopTime;
}
public void setPreopTime(BigDecimal preopTime) {
this.preopTime = preopTime;
}
public BigDecimal getUnitRuntime() {
return this.unitRuntime;
}
public void setUnitRuntime(BigDecimal unitRuntime) {
this.unitRuntime = unitRuntime;
}
public BigDecimal getPostopTime() {
return this.postopTime;
}
public void setPostopTime(BigDecimal postopTime) {
this.postopTime = postopTime;
}
public String getBaseMachineResource() {
return this.baseMachineResource;
}
public void setBaseMachineResource(String baseMachineResource) {
this.baseMachineResource = baseMachineResource;
}
public Long getNumOperators() {
return this.numOperators;
}
public void setNumOperators(Long numOperators) {
this.numOperators = numOperators;
}
public Long getParallel() {
return this.parallel;
}
public void setParallel(Long parallel) {
this.parallel = parallel;
}
public String getParallelThreshold() {
return this.parallelThreshold;
}
public void setParallelThreshold(String parallelThreshold) {
this.parallelThreshold = parallelThreshold;
}
public String getMinimumParallelSubtask() {
return this.minimumParallelSubtask;
}
public void setMinimumParallelSubtask(String minimumParallelSubtask) {
this.minimumParallelSubtask = minimumParallelSubtask;
}
public Long getUseMprsIfNotLate() {
return this.useMprsIfNotLate;
}
public void setUseMprsIfNotLate(Long useMprsIfNotLate) {
this.useMprsIfNotLate = useMprsIfNotLate;
}
public Long getMinOperationTime() {
return this.minOperationTime;
}
public void setMinOperationTime(Long minOperationTime) {
this.minOperationTime = minOperationTime;
}
public BigDecimal getOpEstimatedQueneTime() {
return this.opEstimatedQueneTime;
}
public void setOpEstimatedQueneTime(BigDecimal opEstimatedQueneTime) {
this.opEstimatedQueneTime = opEstimatedQueneTime;
}
public BigDecimal getOpMininumQueneTime() {
return this.opMininumQueneTime;
}
public void setOpMininumQueneTime(BigDecimal opMininumQueneTime) {
this.opMininumQueneTime = opMininumQueneTime;
}
public BigDecimal getBaseYield() {
return this.baseYield;
}
public void setBaseYield(BigDecimal baseYield) {
this.baseYield = baseYield;
}
public Long getInterruptible() {
return this.interruptible;
}
public void setInterruptible(Long interruptible) {
this.interruptible = interruptible;
}
public Long getOperationType() {
return this.operationType;
}
public void setOperationType(Long operationType) {
this.operationType = operationType;
}
public Long getPriority() {
return this.priority;
}
public void setPriority(Long priority) {
this.priority = priority;
}
public String getQueueCalendarName() {
return this.queueCalendarName;
}
public void setQueueCalendarName(String queueCalendarName) {
this.queueCalendarName = queueCalendarName;
}
public String getRampupCalendarName() {
return this.rampupCalendarName;
}
public void setRampupCalendarName(String rampupCalendarName) {
this.rampupCalendarName = rampupCalendarName;
}
public Long getTransferBatchQuantity() {
return this.transferBatchQuantity;
}
public void setTransferBatchQuantity(Long transferBatchQuantity) {
this.transferBatchQuantity = transferBatchQuantity;
}
public Long getIsCrossOperation() {
return this.isCrossOperation;
}
public void setIsCrossOperation(Long isCrossOperation) {
this.isCrossOperation = isCrossOperation;
}
public Long getNeedCheck() {
return this.needCheck;
}
public void setNeedCheck(Long needCheck) {
this.needCheck = needCheck;
}
public Long getIsCriticalOperation() {
return this.isCriticalOperation;
}
public void setIsCriticalOperation(Long isCriticalOperation) {
this.isCriticalOperation = isCriticalOperation;
}
public String getOperationSpecification() {
return this.operationSpecification;
}
public void setOperationSpecification(String operationSpecification) {
this.operationSpecification = operationSpecification;
}
public Long getMaterialCheckIn() {
return this.materialCheckIn;
}
public void setMaterialCheckIn(Long materialCheckIn) {
this.materialCheckIn = materialCheckIn;
}
public Long getMaterialCheckOut() {
return this.materialCheckOut;
}
public void setMaterialCheckOut(Long materialCheckOut) {
this.materialCheckOut = materialCheckOut;
}
public Long getOperationCostSum() {
return this.operationCostSum;
}
public void setOperationCostSum(Long operationCostSum) {
this.operationCostSum = operationCostSum;
}
public Long getLaborCost() {
return this.laborCost;
}
public void setLaborCost(Long laborCost) {
this.laborCost = laborCost;
}
public Long getMachineCost() {
return this.machineCost;
}
public void setMachineCost(Long machineCost) {
this.machineCost = machineCost;
}
public Long getLinkDownstreamP() {
return this.linkDownstreamP;
}
public void setLinkDownstreamP(Long linkDownstreamP) {
this.linkDownstreamP = linkDownstreamP;
}
public Long getLinkDownstreamMinWip() {
return this.linkDownstreamMinWip;
}
public void setLinkDownstreamMinWip(Long linkDownstreamMinWip) {
this.linkDownstreamMinWip = linkDownstreamMinWip;
}
public Long getLinkDownstreamMaxWip() {
return this.linkDownstreamMaxWip;
}
public void setLinkDownstreamMaxWip(Long linkDownstreamMaxWip) {
this.linkDownstreamMaxWip = linkDownstreamMaxWip;
}
public String getUnitRuntimeCostPer() {
return this.unitRuntimeCostPer;
}
public void setUnitRuntimeCostPer(String unitRuntimeCostPer) {
this.unitRuntimeCostPer = unitRuntimeCostPer;
}
public Long getUnitRuntimeCostPerTime() {
return this.unitRuntimeCostPerTime;
}
public void setUnitRuntimeCostPerTime(Long unitRuntimeCostPerTime) {
this.unitRuntimeCostPerTime = unitRuntimeCostPerTime;
}
public String getUnitWipCarryCostPer() {
return this.unitWipCarryCostPer;
}
public void setUnitWipCarryCostPer(String unitWipCarryCostPer) {
this.unitWipCarryCostPer = unitWipCarryCostPer;
}
public Long getUnitWipCarryCostPerTime() {
return this.unitWipCarryCostPerTime;
}
public void setUnitWipCarryCostPerTime(Long unitWipCarryCostPerTime) {
this.unitWipCarryCostPerTime = unitWipCarryCostPerTime;
}
public String getSequenceDependentSetupType() {
return this.sequenceDependentSetupType;
}
public void setSequenceDependentSetupType(String sequenceDependentSetupType) {
this.sequenceDependentSetupType = sequenceDependentSetupType;
}
public String getSequenceDependentSetupType2() {
return this.sequenceDependentSetupType2;
}
public void setSequenceDependentSetupType2(String sequenceDependentSetupType2) {
this.sequenceDependentSetupType2 = sequenceDependentSetupType2;
}
public String getSequenceDependentSetupType3() {
return this.sequenceDependentSetupType3;
}
public void setSequenceDependentSetupType3(String sequenceDependentSetupType3) {
this.sequenceDependentSetupType3 = sequenceDependentSetupType3;
}
public String getNote() {
return this.note;
}
public void setNote(String note) {
this.note = note;
}
public String getRoutingType() {
return this.routingType;
}
public void setRoutingType(String routingType) {
this.routingType = routingType;
}
public String getOperationNote() {
return this.operationNote;
}
public void setOperationNote(String operationNote) {
this.operationNote = operationNote;
}
public BigDecimal getWorkcoefficient() {
return this.workcoefficient;
}
public void setWorkcoefficient(BigDecimal workcoefficient) {
this.workcoefficient = workcoefficient;
}
public Date getChangetime() {
return this.changetime;
}
public void setChangetime(Date changetime) {
this.changetime = changetime;
}
public String getChanger() {
return this.changer;
}
public void setChanger(String changer) {
this.changer = changer;
}
public String getChangereason() {
return this.changereason;
}
public void setChangereason(String changereason) {
this.changereason = changereason;
}
public BigDecimal getChangestate() {
return this.changestate;
}
public void setChangestate(BigDecimal changestate) {
this.changestate = changestate;
}
public Byte getEffective() {
return this.effective;
}
public void setEffective(Byte effective) {
this.effective = effective;
}
public String getCreator() {
return this.creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public Date getCreatetime() {
return this.createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public Long getDispatchgrade() {
return this.dispatchgrade;
}
public void setDispatchgrade(Long dispatchgrade) {
this.dispatchgrade = dispatchgrade;
}
public Integer getSampleqty() {
return this.sampleqty;
}
public void setSampleqty(Integer sampleqty) {
this.sampleqty = sampleqty;
}
public BigDecimal getSamplepercent() {
return this.samplepercent;
}
public void setSamplepercent(BigDecimal samplepercent) {
this.samplepercent = samplepercent;
}
public String getOperationIddesc() {
return this.operationIddesc;
}
public void setOperationIddesc(String operationIddesc) {
this.operationIddesc = operationIddesc;
}
public String getEstipretime() {
return this.estipretime;
}
public void setEstipretime(String estipretime) {
this.estipretime = estipretime;
}
public String getEstiruntime() {
return this.estiruntime;
}
public void setEstiruntime(String estiruntime) {
this.estiruntime = estiruntime;
}
public String getSampleOpid() {
return this.sampleOpid;
}
public void setSampleOpid(String sampleOpid) {
this.sampleOpid = sampleOpid;
}
public Byte getNeedSample() {
return this.needSample;
}
public void setNeedSample(Byte needSample) {
this.needSample = needSample;
}
public Boolean getCheckstate() {
return this.checkstate;
}
public void setCheckstate(Boolean checkstate) {
this.checkstate = checkstate;
}
public String getGroupuid() {
return this.groupuid;
}
public void setGroupuid(String groupuid) {
this.groupuid = groupuid;
}
public String getOpid() {
return this.opid;
}
public void setOpid(String opid) {
this.opid = opid;
}
public Long getOptype() {
return this.optype;
}
public void setOptype(Long optype) {
this.optype = optype;
}
public String getVersionid() {
return this.versionid;
}
public void setVersionid(String versionid) {
this.versionid = versionid;
}
public String getRoutingNote() {
return this.routingNote;
}
public void setRoutingNote(String routingNote) {
this.routingNote = routingNote;
}
public BigDecimal getSampleRuntime() {
return this.sampleRuntime;
}
public void setSampleRuntime(BigDecimal sampleRuntime) {
this.sampleRuntime = sampleRuntime;
}
public Boolean getNeedFirstcheck() {
return this.needFirstcheck;
}
public void setNeedFirstcheck(Boolean needFirstcheck) {
this.needFirstcheck = needFirstcheck;
}
public BigDecimal getCheckpercent() {
return this.checkpercent;
}
public void setCheckpercent(BigDecimal checkpercent) {
this.checkpercent = checkpercent;
}
public String getRefrouting() {
return this.refrouting;
}
public void setRefrouting(String refrouting) {
this.refrouting = refrouting;
}
public String getBRoutineOutUid() {
return this.BRoutineOutUid;
}
public void setBRoutineOutUid(String BRoutineOutUid) {
this.BRoutineOutUid = BRoutineOutUid;
}
public String getDeptid() {
return this.deptid;
}
public void setDeptid(String deptid) {
this.deptid = deptid;
}
public String getDeviceuid() {
return this.deviceuid;
}
public void setDeviceuid(String deviceuid) {
this.deviceuid = deviceuid;
}
public String getOperationContentTt() {
return this.operationContentTt;
}
public void setOperationContentTt(String operationContentTt) {
this.operationContentTt = operationContentTt;
}
public String getNcNumber() {
return this.ncNumber;
}
public void setNcNumber(String ncNumber) {
this.ncNumber = ncNumber;
}
public String getNcVersionid() {
return this.ncVersionid;
}
public void setNcVersionid(String ncVersionid) {
this.ncVersionid = ncVersionid;
}
public String getIsSpecialOperation() {
return this.isSpecialOperation;
}
public void setIsSpecialOperation(String isSpecialOperation) {
this.isSpecialOperation = isSpecialOperation;
}
public Byte getPreparegrade() {
return this.preparegrade;
}
public void setPreparegrade(Byte preparegrade) {
this.preparegrade = preparegrade;
}
public Boolean getNeedPhoto() {
return this.needPhoto;
}
public void setNeedPhoto(Boolean needPhoto) {
this.needPhoto = needPhoto;
}
public Clob getOperationSimpleContent() {
return this.operationSimpleContent;
}
public void setOperationSimpleContent(Clob operationSimpleContent) {
this.operationSimpleContent = operationSimpleContent;
}
public Clob getOperationContent() {
return this.operationContent;
}
public void setOperationContent(Clob operationContent) {
this.operationContent = operationContent;
}
public Long getIsStatisticCheck() {
return this.isStatisticCheck;
}
public void setIsStatisticCheck(Long isStatisticCheck) {
this.isStatisticCheck = isStatisticCheck;
}
public Boolean getKeycount() {
return this.keycount;
}
public void setKeycount(Boolean keycount) {
this.keycount = keycount;
}
public Set getBOperationResources() {
return this.BOperationResources;
}
public void setBOperationResources(Set BOperationResources) {
this.BOperationResources = BOperationResources;
}
public Set getBBillOfMaterialses() {
return this.BBillOfMaterialses;
}
public void setBBillOfMaterialses(Set BBillOfMaterialses) {
this.BBillOfMaterialses = BBillOfMaterialses;
}
public Set getBRoutines() {
return this.BRoutines;
}
public void setBRoutines(Set BRoutines) {
this.BRoutines = BRoutines;
}
}
|
package com.hesoyam.pharmacy.feedback.dto;
import com.hesoyam.pharmacy.appointment.model.CheckUp;
import com.hesoyam.pharmacy.appointment.model.Counseling;
import com.hesoyam.pharmacy.medicine.model.MedicineReservation;
public class PharmacyFeedbackDTO {
Long pharmacyId;
String pharmacyName;
Double averageRating;
Integer yourRating;
String comment;
public PharmacyFeedbackDTO() {
}
public PharmacyFeedbackDTO(MedicineReservation medicineReservation){
this.pharmacyId = medicineReservation.getPharmacy().getId();
this.pharmacyName = medicineReservation.getPharmacy().getName();
this.averageRating = medicineReservation.getPharmacy().getRating();
this.yourRating = 0;
this.comment = "";
}
public PharmacyFeedbackDTO(Counseling counseling){
this.pharmacyId = counseling.getPharmacy().getId();
this.pharmacyName = counseling.getPharmacy().getName();
this.averageRating = counseling.getPharmacy().getRating();
this.yourRating = 0;
this.comment = "";
}
public PharmacyFeedbackDTO(CheckUp checkup){
this.pharmacyId = checkup.getPharmacy().getId();
this.pharmacyName = checkup.getPharmacy().getName();
this.averageRating = checkup.getPharmacy().getRating();
this.yourRating = 0;
this.comment = "";
}
public Long getPharmacyId() {
return pharmacyId;
}
public void setPharmacyId(Long pharmacyId) {
this.pharmacyId = pharmacyId;
}
public String getPharmacyName() {
return pharmacyName;
}
public void setPharmacyName(String pharmacyName) {
this.pharmacyName = pharmacyName;
}
public Double getAverageRating() {
return averageRating;
}
public void setAverageRating(Double averageRating) {
this.averageRating = averageRating;
}
public Integer getYourRating() {
return yourRating;
}
public void setYourRating(Integer yourRating) {
this.yourRating = yourRating;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}
|
package writer;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import gradebook.GradeBook;
public abstract class Writer
{
//*****LOGGER*****//
protected final String LOGGER_NAME = "WriterLog";
protected final String LOGGER_FILE = "log/Writer.log";
protected Logger logger = null;
protected String fileName = "";
protected File file;
public Writer(String fileName)
{
initLogger();
logger.info("New Writer obj created with file name: " + fileName);
this.fileName = fileName;
}
public abstract void writeToFile(GradeBook gradeBook) throws FileNotFoundException, UnsupportedEncodingException, JsonGenerationException, JsonMappingException, IOException, Exception;
public abstract void createFile() throws IOException;
private void initLogger()
{
logger = Logger.getLogger(LOGGER_NAME);
FileHandler fh;
try
{
fh = new FileHandler(LOGGER_FILE);
logger.addHandler(fh);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
logger.info("<---Logging started!--->");
}
catch (SecurityException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
|
package com.chris.projects.fx.ftp.core;
public interface OrderBookService {
void onOrderReceived();
void onOrderCancel();
void onOrderAmend();
}
|
package LessonsJavaCore_3;
import java.util.Scanner;
public class LessonCircle {
Scanner scanner = new Scanner(System.in);
double Radius = scanner.nextDouble ();
public LessonCircle(){
}
public LessonCircle(double Radius){
this.Radius = Radius;
}
public double diameter(){
return (Radius * 2);
}
public double area(){
return Math.PI * (Radius * Radius);
}
public double length(){
return Math.PI * 2*Radius;
}
}
|
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.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 org.jclouds.tools.ebsresize.util;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.predicates.RunScriptRunning;
import org.jclouds.compute.util.ComputeUtils;
import org.jclouds.domain.Credentials;
import org.jclouds.logging.Logger;
import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.ssh.SshClient;
import org.jclouds.ssh.jsch.JschSshClient;
import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;
/**
* Allows remote command execution on instance.
*
* This is based on {@link org.jclouds.ssh.SshClient} and
* {@link org.jclouds.compute.util.ComputeUtils}, with
* some convenience methods.
*
* @see org.jclouds.ssh.SshClient
* @see org.jclouds.compute.util.ComputeUtils
*
* @author Oleksiy Yarmula
*/
public class SshExecutor {
private final Predicate<SshClient> runScriptRunning =
new RetryablePredicate<SshClient>(Predicates.not(new RunScriptRunning()),
600, 3, TimeUnit.SECONDS);
private final NodeMetadata nodeMetadata;
private final SshClient sshClient;
private final ComputeUtils utils;
public SshExecutor(NodeMetadata nodeMetadata,
Credentials instanceCredentials,
String keyPair,
InetSocketAddress socket) {
this.nodeMetadata = nodeMetadata;
this.sshClient =
new JschSshClient(socket, 60000,
instanceCredentials.account, keyPair.getBytes());
this.utils = new ComputeUtils(null, runScriptRunning, null);
}
public void connect() {
sshClient.connect();
}
public void execute(String command) {
ComputeUtils.RunScriptOnNode script = utils.runScriptOnNode(nodeMetadata,
"basicscript.sh", command.getBytes());
script.setConnection(sshClient, Logger.CONSOLE);
try {
script.call();
} catch(Exception e) {
throw new RuntimeException(e);
}
}
}
|
package controllers;
import actions.Ajax;
import actions.Authorized;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import models.Category;
import models.Comment;
import models.RateResource;
import models.Resource;
import play.libs.Json;
import play.mvc.Result;
import utilities.Dependencies;
import utilities.FormRequest;
import java.text.SimpleDateFormat;
import java.util.*;
import static java.util.Collections.sort;
import static java.util.Collections.reverse;
import static play.mvc.Results.ok;
import static utilities.FormRequest.formBody;
import static utilities.FormRequest.formGetBody;
/**
* Controllers for viewing user activity reports
*/
public class Activities {
/**
* Return latest user activity as JSON
* GET pageNumber: page number of results
* GET pageNumber: page size of results
*
* Ajax Method
* Authorization: Admin
*/
@Ajax
@Authorized({"admin"})
public static Result getUserActivity() {
FormRequest request = formGetBody();
int pageNumber = request.getInt("pageNumber", 0);
int pageSize = request.getInt("pageSize", 8);
List<Comment> comments = Dependencies.getCommentDao().findLatest((pageNumber + 1) * pageSize);
List<RateResource> rates = Dependencies.getRateResourceDao().findLatest((pageNumber + 1) * pageSize);
List<Activity> activities = activityFromComments(comments);
activities.addAll(activityFromRates(rates));
sort(activities);
reverse(activities);
int from = pageNumber * pageSize;
int to = Math.min(activities.size(), (pageNumber + 1) * pageSize);
boolean isLastPage = activities.size() - from < pageSize;
JsonNode json = serializeActivities(activities.subList(from, to), isLastPage);
return ok(json);
}
private static JsonNode serializeActivities(List<Activity> activities, boolean isLastPage) {
ObjectNode rootJson = Json.newObject();
rootJson.put("resultCount", activities.size());
ArrayNode jsonList = rootJson.putArray("results");
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy", Locale.forLanguageTag("ir"));
for (Activity activity : activities) {
ObjectNode json = jsonList.addObject();
json.put("id", activity.id);
json.put("resourceId", activity.resourceId);
json.put("resourceName", activity.resourceName);
json.put("user", activity.user);
json.put("type", activity.type);
json.put("value", activity.val);
json.put("date", dateFormat.format(activity.date));
}
if (isLastPage) {
rootJson.put("lastPage", true);
}
return rootJson;
}
private static List<Activity> activityFromComments(List<Comment> comments) {
List<Activity> activities = new ArrayList<Activity>();
for (Comment comment : comments) {
Activity activity = new Activity();
activity.id = comment.id;
activity.date = comment.date;
activity.user = comment.user.getFullName();
activity.type = "comment";
while (comment.parComment != null) {
comment = comment.parComment;
}
activity.resourceId = comment.parResource.id;
activity.resourceName = comment.parResource.name;
activities.add(activity);
}
return activities;
}
private static List<Activity> activityFromRates(List<RateResource> rates) {
List<Activity> activities = new ArrayList<Activity>();
for (RateResource rate : rates) {
Activity activity = new Activity();
activity.id = rate.id;
activity.date = rate.date;
activity.user = rate.user.getFullName();
activity.type = "rate";
activity.resourceId = rate.resource.id;
activity.resourceName = rate.resource.name;
activity.val = rate.rate;
activities.add(activity);
}
return activities;
}
private static class Activity implements Comparable<Activity> {
public int id;
public int resourceId;
public String resourceName;
public Date date;
public String user;
public String type;
public int val;
@Override
public int compareTo(Activity o) {
return date.compareTo(o.date);
}
}
}
|
package interviewTasks_Saim;
import java.util.ArrayList;
public class CompareArrays {
/*Compare arrays. Assign values of int arrayOne to int arrayTwo. And then compare if they are same/equal?
EX: int[] arrayOne = {5, 10, 15, 20}
int[] arrayTwo = {5, 10, 15, 20}
and comparision...
*/
public static void main (String [] args){
int [] num1 = {2,4,5,6};
int[] num2 = {2,4,5,6};
System.out.println(compareArrays(num1,num2));
}
public static boolean compareArrays(int[] a, int[] b ){
for (int i = 0; i < a.length; i++) {
for (int j = 0; j <b.length ; j++) {
if(a[i]==b[j]){
}
}
}
return true;
}
//MAX
/*
public static void main(String[] args) {
int[] arrayOne = {5, 10, 15, 20};
int[] arrayTwo = arrayOne; //{5, 10, 15, 20};
System.out.println(Arrays.equals(arrayOne, arrayTwo));
}
*/
}
|
package day.month10;
public class Day7 {
public static void main(String[] args) {
Day7 day7 = new Day7();
int[] arr = {2,3,1,0,2,5,3};
day7.secondNum(arr);
}
/*
* 数组中第一次出现重复的元素
*/
public void secondNum(int[] arr) {
String str = "";
for(int i = 0; i < arr.length; i++) {
if (str.indexOf(arr[i] + "") >= 0) {
System.out.println(arr[i]);
break;
}
str += arr[i];
}
}
}
|
package com.smxknife.java2.thread.forkjoin.quicksort;
/**
* @author smxknife
* 2019/9/15
*/
public class ForkJoinQuickSortDemo {
}
|
package interviewTasks_Saim.All_Arrays;
import java.util.Arrays;
public class ArrayMin {
public static void main(String[] args) {
int[] nums= {5,9,3,10,6};
System.out.println(findMin(nums));
int[] nums1 ={};
}
public static int findMin(int[] nums) {
Arrays.sort(nums);
int min = nums[0];
return min;
}
//FIND MIN WITHOUT ARRAYS.SORT
public static int findMin1(int[] nums1){
int min = nums1[0];
for (int i = 0; i < nums1.length; i++){
if(min > nums1[i]){
min =nums1[i];
}
}
return min;
}
}
|
/**
* Super Smash Browsers
*
* A game based on the Super Smash Bros. series, by Nintendo.
*
* Neil Manansala
* Professor Greg Scott
* Computer Science 3
* Assignment 6
*/
package edu.self.smash;
import edu.self.smash.contexts.*;
import edu.self.util.*;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.GraphicsConfiguration;
import java.awt.Toolkit;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.awt.image.BufferStrategy;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.Date;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* Engine Class
*/
public class Engine implements FocusListener, KeyListener, Runnable {
/**
* Properties
*/
private SandboxedProperties config;
private JFrame frame;
private JPanel panel;
private Runnable schedule;
private ScheduledExecutorService scheduler;
private Map<Integer, Boolean> inputs;
private GraphicsEnvironment environment;
private GraphicsConfiguration graphics;
private BufferStrategy buffer;
private Graphics2D canvas;
private BufferedImage capture;
private Context context;
private Context successor;
private Assets assets;
private boolean active;
private boolean focused;
private boolean capturing;
/**
* Constructor
*/
public Engine() {
config = new SandboxedProperties();
config.put("meta.name", "Super Smash Browsers");
config.put("folder.assets", "res");
config.put("folder.data", "dat");
config.put("folder.screenshots", "scr");
config.put("debug.verbosity", "FINEST");
config.putLong("video.fps.target", 24L);
config.putLong("video.fps.interval", 1000L);
config.putBoolean("audio.music", true);
config.putBoolean("audio.sounds", true);
config.putInt("metrics.height", 180);
config.putInt("metrics.width", 320);
config.putInt("metrics.scale.current", 1);
config.putInt("metrics.scale.maximum", 2);
config.putInt("metrics.scale.minimum", 0);
config.putInt("controls.ui.up", KeyEvent.VK_UP);
config.putInt("controls.ui.down", KeyEvent.VK_DOWN);
config.putInt("controls.ui.left", KeyEvent.VK_LEFT);
config.putInt("controls.ui.right", KeyEvent.VK_RIGHT);
config.putInt("controls.ui.advance", KeyEvent.VK_ENTER);
config.putInt("controls.ui.retreat", KeyEvent.VK_ESCAPE);
config.putInt("controls.p1.jump", KeyEvent.VK_W);
config.putInt("controls.p1.duck", KeyEvent.VK_S);
config.putInt("controls.p1.left", KeyEvent.VK_A);
config.putInt("controls.p1.right", KeyEvent.VK_D);
config.putInt("controls.p1.attack", KeyEvent.VK_F);
config.putInt("controls.p2.jump", KeyEvent.VK_I);
config.putInt("controls.p2.duck", KeyEvent.VK_K);
config.putInt("controls.p2.left", KeyEvent.VK_J);
config.putInt("controls.p2.right", KeyEvent.VK_L);
config.putInt("controls.p2.attack", KeyEvent.VK_SEMICOLON);
config.putInt("controls.debug.upscale", KeyEvent.VK_EQUALS);
config.putInt("controls.debug.downscale", KeyEvent.VK_MINUS);
config.putInt("controls.debug.screenshot", KeyEvent.VK_F12);
config.remaster();
config.read(config.get("folder.data") + "/config.xml");
frame = null;
panel = null;
schedule = null;
scheduler = Executors.newSingleThreadScheduledExecutor();
inputs = new ConcurrentHashMap<Integer, Boolean>();
environment = null;
graphics = null;
buffer = null;
canvas = null;
capture = null;
context = null;
successor = null;
assets = new Assets(this);
active = false;
focused = false;
capturing = false;
assets.putAudio("audio.ui.test", "/audio/ui/test.wav");
}
/**
* Accessors and Modifiers
*/
// Properties
public SandboxedProperties getConfig() {
return config;
}
// Frame Instance
public JFrame getFrame() {
return frame;
}
// Panel Instance
public JPanel getPanel() {
return panel;
}
// Inputs
public Map<Integer, Boolean> getInputs() {
return inputs;
}
public boolean getInput(int input) {
return inputs.getOrDefault(input, false);
}
public void setInput(int input, boolean flag) {
inputs.put(input, flag);
}
// Context
public Context getContext() {
return context;
}
// Graphics Environment
public GraphicsEnvironment getEnvironment() {
return environment;
}
// Graphics Configuration
public GraphicsConfiguration getGraphics() {
return graphics;
}
// Buffer
public BufferStrategy getBuffer() {
return buffer;
}
// Canvas
public Graphics2D getCanvas() {
return canvas;
}
// Assets
public Assets getAssets() {
return assets;
}
// Frame Capture
public BufferedImage getCapture() {
return capture;
}
/**
* Thread Controls
*/
public void start() {
if(!active) {
active = true;
frame = new JFrame(config.get("meta.name"));
panel = new JPanel();
frame.setVisible(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setEnabled(true);
panel.setFocusable(true);
panel.addFocusListener(this);
panel.addKeyListener(this);
Dimension minimum = new Dimension();
Dimension maximum = new Dimension();
minimum.setSize(
Math.scalb(config.getDouble("metrics.width"), config.getInt("metrics.scale.minimum")),
Math.scalb(config.getDouble("metrics.height"), config.getInt("metrics.scale.minimum"))
);
maximum.setSize(
Math.scalb(config.getDouble("metrics.width"), config.getInt("metrics.scale.maximum")),
Math.scalb(config.getDouble("metrics.height"), config.getInt("metrics.scale.maximum"))
);
panel.setMinimumSize(minimum);
panel.setMaximumSize(maximum);
frame.add(panel);
frame.pack();
rescale();
reposition();
new Thread(this, this.getClass().getName()).start();
}
}
public void stop() {
System.exit(0);
}
/**
* Thread Operations
*/
public void run() {
graphics = frame.getGraphicsConfiguration();
frame.createBufferStrategy(2);
buffer = frame.getBufferStrategy();
switchContext(new TitleContext(this));
schedule = new Runnable() {
public void run() {
if(getInput(config.getInt("controls.debug.upscale"))) {
if((config.getInt("metrics.scale.current") + 1) <= config.getInt("metrics.scale.maximum")) {
rescale(config.getInt("metrics.scale.current") + 1);
reposition();
setInput(config.getInt("controls.debug.upscale"), false);
}
}
if(getInput(config.getInt("controls.debug.downscale"))) {
if((config.getInt("metrics.scale.current") - 1) >= config.getInt("metrics.scale.minimum")) {
rescale(config.getInt("metrics.scale.current") - 1);
reposition();
setInput(config.getInt("controls.debug.downscale"), false);
}
}
if(getInput(config.getInt("controls.debug.screenshot"))) {
capturing = true;
setInput(config.getInt("controls.debug.screenshot"), false);
}
if(successor != null) {
context = successor;
successor = null;
}
context.think();
do {
canvas = (Graphics2D)buffer.getDrawGraphics();
canvas.translate(frame.getInsets().left, frame.getInsets().top);
canvas.setBackground(Color.BLACK);
canvas.clearRect(0, 0, (int)frame.getSize().getWidth(), (int)frame.getSize().getHeight());
context.draw();
canvas.dispose();
if(capturing) {
capturing = false;
capture = new BufferedImage((frame.getWidth() - frame.getInsets().left), (frame.getHeight() - frame.getInsets().top), BufferedImage.TYPE_INT_RGB);
canvas = (Graphics2D)capture.createGraphics();
context.draw();
canvas.dispose();
try {
Date now = new Date();
SimpleDateFormat timestamp = new SimpleDateFormat("YYYY-MM-dd HH.mm.ss");
File file = new File(config.get("folder.screenshots") + "/" + timestamp.format(now) + "@" + (int)Math.pow(2.0d, config.getDouble("metrics.scale.current")) + "x.png");
if(file.getParentFile() != null) {
File parent = file.getParentFile();
parent.mkdirs();
}
ImageIO.write(capture, "png", file);
}
catch(IOException exception) {
exception.printStackTrace();
}
catch(Exception exception) {
exception.printStackTrace();
}
}
} while(buffer.contentsLost());
buffer.show();
Toolkit.getDefaultToolkit().sync();
context.tick();
}
};
scheduler.scheduleAtFixedRate(schedule, 0L, (config.getLong("video.fps.interval") / config.getLong("video.fps.target")), TimeUnit.MILLISECONDS);
}
/**
* Context Switcher
*/
public void switchContext(Context newContext) {
successor = newContext;
}
/**
* Rescalers
*/
// Property-Based
public void rescale() {
rescale(config.getInt("metrics.scale.current"));
}
// Arbitrary
public void rescale(int scale) {
Dimension current = new Dimension();
current.setSize(
(frame.getInsets().left + Math.scalb(config.getDouble("metrics.width"), scale) + frame.getInsets().right),
(frame.getInsets().top + Math.scalb(config.getDouble("metrics.height"), scale) + frame.getInsets().bottom)
);
frame.setSize(current);
panel.setPreferredSize(current);
config.putInt("metrics.scale.current", scale);
}
/**
* Repositioner
*/
public void reposition() {
Dimension display = Toolkit.getDefaultToolkit().getScreenSize();
Dimension window = frame.getSize();
frame.setLocation(
(int)((display.getWidth() / 2) - (window.getWidth() / 2)),
(int)((display.getHeight() - window.getHeight()) / 3)
);
}
/**
* Frame Capturer
*/
public void capture() {
capturing = true;
}
/**
* FocusListener Interface
*/
// Focus
public void focusGained(FocusEvent event) {
focused = true;
System.out.println("Window focused.");
}
// Blur
public void focusLost(FocusEvent event) {
focused = false;
System.out.println("Window blurred.");
}
/**
* KeyListener Interface
*/
// Key Press
public void keyPressed(KeyEvent event) {
setInput(event.getKeyCode(), true);
System.out.println("Key Pressed: " + KeyEvent.getKeyText(event.getKeyCode()) + " (" + event.getKeyCode() + ")");
}
// Key Release
public void keyReleased(KeyEvent event) {
setInput(event.getKeyCode(), false);
System.out.println("Key Released: " + KeyEvent.getKeyText(event.getKeyCode()) + " (" + event.getKeyCode() + ")");
}
// Character Output (Unused)
public void keyTyped(KeyEvent event) throws UnsupportedOperationException {
// throw new UnsupportedOperationException();
}
}
|
package com.lec.ex1;
import com.lec.ex.Arithmetic; //다른 클라스를 이 파일에 가져옴
public class Ex {
public static void main(String[] args) {
Arithmetic ar = new Arithmetic();
System.out.println("합은 " + ar.sum(20));
}
}
|
package util;
import util.Exceptions.AlreadyDoneException;
import util.Exceptions.CarNotReadyExeption;
import util.Exceptions.DoubleClientException;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
/**
* Множество записей и работа с ним
*/
public class Records {
Set<Record> records;
public Records() {
records = new TreeSet<Record>();
}
/**
* Возвращает истину, если множество содержит данную запись
* @param o
* @return
*/
private boolean contain(Record o) {
Iterator<Record> it = records.iterator();
while(it.hasNext()) {
if (it.next().equals(o)) {
return true;
}
}
return false;
}
/**
* @return количество элементов в множестве
*/
public int Kolvo() {
int i;
Iterator<Record> it = records.iterator();
i = 0;
while (it.hasNext()) {
i++;
it.next();
}
return i;
}
/**
* Добавление новой записи
* @param r
* @throws DoubleClientException если запись уже существует
*/
public void add(Record r) throws DoubleClientException {
if (!contain(r)) {
records.add(r);
}
else {
throw new DoubleClientException();
}
}
/**
* Возвращает данные множества в табличном виде строк для заполнения основной таблицы
* @return
*/
public String[][] GiveClientStrings() {
if (Kolvo() == 0) {
return null;
}
String tmp[][] = new String[Kolvo()][4];
Iterator<Record> it = records.iterator();
Record tmpRecord;
int i, tmpKOD[];
i = 0;
while (it.hasNext()) {
tmpRecord = it.next();
tmp[i][0] = tmpRecord.getClient();
tmp[i][1] = tmpRecord.getCar();
tmp[i][2] = KODToString(tmpRecord.getKOD());
if (tmpRecord.isReady()) {
tmp[i][3] = "Готово";
}
else {
tmp[i][3] = "Не готово";
}
i++;
}
return tmp;
}
/**
* Возвращает данные множества в табличном виде строк для заполнения дополнительной таблицы
* @return
*/
public String[][] GiveAdminStrings() {
if (Kolvo() == 0) {
return null;
}
String tmp[][] = new String[Kolvo()][4];
Iterator<Record> it = records.iterator();
Record tmpRecord;
int i;
i = 0;
while (it.hasNext()) {
tmpRecord = it.next();
tmp[i][0] = tmpRecord.getClient();
if (tmpRecord.getMaster() != null) {
tmp[i][1] = tmpRecord.getMaster().getName();
}
else {
tmp[i][1] = "Уволен";
}
tmp[i][2] = KODToString(tmpRecord.getKOD());
tmp[i][3] = tmpRecord.getBreacking();
i++;
}
return tmp;
}
/**
* Возвращает данные множества в табличном виде строк для сохранения в файл
* готовность и вид работы, не переводятся в читабельный вид
* @return
*/
public String[][] GiveSaveStrings() {
if (Kolvo() == 0) {
return null;
}
String tmp[][] = new String[Kolvo()][6];
Iterator<Record> it = records.iterator();
Record tmpRecord;
int i;
i = 0;
while (it.hasNext()) {
tmpRecord = it.next();
tmp[i][0] = tmpRecord.getClient();
tmp[i][1] = tmpRecord.getCar();
tmp[i][2] = String.valueOf(tmpRecord.getKOD());
tmp[i][3] = tmpRecord.getBreacking();
if (tmpRecord.getMaster() != null) {
tmp[i][4] = tmpRecord.getMaster().getName();
}
else {
tmp[i][4] = "Уволен";
}
tmp[i][5] = String.valueOf(tmpRecord.isReady());
i++;
}
return tmp;
}
/**
* Возвращает описание вида работы по коду
* @param KOD
* @return
*/
public String KODToString(int KOD) {
switch (KOD) {
case 1: {
return new String("Покраска");
}
case 2: {
return new String("Кузовной ремонт");
}
case 3: {
return new String("Ремонт подвески");
}
case 4: {
return new String("Ремонт двигателя");
}
case 5: {
return new String("Развал-схождение");
}
default: {
return new String("Прочее");
}
}
}
/**
* Удаление базы данных
*/
public void Remove() {
Iterator<Record> it;
it = records.iterator();
while (it.hasNext()) {
records.remove(it.next());
it = records.iterator();
}
}
/**
* Удаление элемента базы данных по имени клиента
* @param name
* @throws CarNotReadyExeption если машина не готова ещё
*/
public void Remove(String name) throws CarNotReadyExeption {
Iterator<Record> it = records.iterator();
Record tmpRecord;
while (it.hasNext()) {
tmpRecord = it.next();
if (tmpRecord.isReady()) {
records.remove(tmpRecord);
return;
}
else {
throw new CarNotReadyExeption();
}
}
}
/**
* Установить готовность машины
* @param client
* @throws AlreadyDoneException если машину уже готова
*/
public void setReady(String client) throws AlreadyDoneException {
Iterator<Record> it = records.iterator();
Record tmp;
while (it.hasNext()) {
tmp = it.next();
if (tmp.getClient().equals(client)) {
if (!tmp.isReady()) {
tmp.setReady();
tmp.getMaster().EmployDown();
return;
}
else {
throw new AlreadyDoneException();
}
}
}
}
}
|
package com.tencent.mm.plugin.traceroute.ui;
import com.tencent.mm.R;
import com.tencent.mm.sdk.platformtools.al.a;
import com.tencent.mm.sdk.platformtools.x;
class NetworkDiagnoseAllInOneUI$3 implements a {
final /* synthetic */ NetworkDiagnoseAllInOneUI oDK;
NetworkDiagnoseAllInOneUI$3(NetworkDiagnoseAllInOneUI networkDiagnoseAllInOneUI) {
this.oDK = networkDiagnoseAllInOneUI;
}
public final boolean vD() {
NetworkDiagnoseAllInOneUI.a(this.oDK, NetworkDiagnoseAllInOneUI.k(this.oDK) + 1);
x.v("MicroMsg.NetworkDiagnoseAllInOneUI", "timer fired, percent:%d", new Object[]{Integer.valueOf(NetworkDiagnoseAllInOneUI.k(this.oDK))});
if (NetworkDiagnoseAllInOneUI.k(this.oDK) > 99) {
return false;
}
if (NetworkDiagnoseAllInOneUI.a(this.oDK) == 1) {
NetworkDiagnoseAllInOneUI.l(this.oDK).setText(this.oDK.getString(R.l.diagnose_state_doing, new Object[]{Integer.valueOf(NetworkDiagnoseAllInOneUI.k(this.oDK))}));
}
return true;
}
}
|
public interface MyAbstractList {
void add(Person person);
// /**
// * Optional
// */
// void remove(Person person);
void remove(int index);
int size();
Person get(int index);
@Override
String toString();
}
|
public class oper {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String binary[]={"1100"};
int a=6;
int b=12;
int c=++a;
int d=c*b;
int e=a%b;
System.out.println("a= " +a +", "+"b= "+b+", "+"c= "+c+", "+"d= "+d +", "+"e= "+e);
System.out.println(binary[b]);
}
}
|
/*
* Copyright © 2019 The GWT Project Authors
*
* 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.gwtproject.dom.builder.shared;
/** Builds an table element. */
public interface TableBuilder extends ElementBuilderBase<TableBuilder> {
String UNSUPPORTED_HTML =
"Table elements do not support setting inner html. Use "
+ "startTBody/startTFoot/startTHead() instead to append a table section to the table.";
/**
* The width of the border around the table.
*
* @see <a
* href="http://www.w3.org/TR/1999/REC-html401-19991224/struct/tables.html#adef-border-TABLE">W3C
* HTML Specification</a>
*/
TableBuilder border(int border);
/**
* Specifies the horizontal and vertical space between cell content and cell borders.
*
* @see <a
* href="http://www.w3.org/TR/1999/REC-html401-19991224/struct/tables.html#adef-cellpadding">W3C
* HTML Specification</a>
*/
TableBuilder cellPadding(int cellPadding);
/**
* Specifies the horizontal and vertical separation between cells.
*
* @see <a
* href="http://www.w3.org/TR/1999/REC-html401-19991224/struct/tables.html#adef-cellspacing">W3C
* HTML Specification</a>
*/
TableBuilder cellSpacing(int cellSpacing);
/**
* Specifies which external table borders to render.
*
* @see <a href="http://www.w3.org/TR/1999/REC-html401-19991224/struct/tables.html#adef-frame">W3C
* HTML Specification</a>
*/
TableBuilder frame(String frame);
/**
* Specifies which internal table borders to render.
*
* @see <a href="http://www.w3.org/TR/1999/REC-html401-19991224/struct/tables.html#adef-rules">W3C
* HTML Specification</a>
*/
TableBuilder rules(String rules);
/**
* Specifies the desired table width.
*
* @see <a
* href="http://www.w3.org/TR/1999/REC-html401-19991224/struct/tables.html#adef-width-TABLE">W3C
* HTML Specification</a>
*/
TableBuilder width(String width);
}
|
package interviews.linkedin;
import java.util.Arrays;
import java.util.HashMap;
public class CanIWin {
public static void main(String[] args) {
new CanIWin().canIWin(3, 5);
}
// replace char[] to an integer.
public boolean canIWin(int max, int total) {
if (total <= 0) return true;
if (max * (max + 1) / 2 < total) return false;
return dfs(max, total, 0, new HashMap<Integer, Boolean>());
}
private boolean dfs(int len, int total, int used, HashMap<Integer, Boolean> map) {
if(map.containsKey(used)) return map.get(used);
for(int i = 0; i < len; i++) {
int cur = (1 << i);
if((used & cur) != 0) continue;
int remain = total - i - 1;
if(remain <= 0 || !dfs(len, remain, used | cur, map)) {
map.put(used, true);
return true;
}
}
map.put(used, false);
return false;
}
public boolean canIWin2(int max, int total) {
if (total <= 0) return true;
if (max * (max + 1) / 2 < total) return false;
char[] state = new char[max];
Arrays.fill(state, '0');
return dfs(total, state, new HashMap<String, Boolean>());
}
private boolean dfs(int total, char[] state, HashMap<String, Boolean> hashMap) {
String key = new String(state);
if (hashMap.containsKey(key)) return hashMap.get(key);
for (int i = 0; i < state.length; i++) {
if (state[i] == '1') continue;
state[i] = '1';
if (total <= i + 1 || !dfs(total - i - 1, state, hashMap)) {
hashMap.put(key, true);
state[i] = '0';
return true;
}
state[i] = '0';
}
hashMap.put(key, false);
return false;
}
}
|
package com.tencent.mm.plugin.wallet.pay.ui;
import android.view.View;
import android.view.View.OnClickListener;
class WalletChangeBankcardUI$3 implements OnClickListener {
final /* synthetic */ WalletChangeBankcardUI pfC;
WalletChangeBankcardUI$3(WalletChangeBankcardUI walletChangeBankcardUI) {
this.pfC = walletChangeBankcardUI;
}
public final void onClick(View view) {
this.pfC.bNC();
}
}
|
package com.example.zhifou.controller;
import com.example.zhifou.VO.ResultVO;
import com.example.zhifou.entity.AnswerInfo;
import com.example.zhifou.entity.QuestionInfo;
import com.example.zhifou.entity.UserInfo;
import com.example.zhifou.service.AnswerService;
import com.example.zhifou.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.util.*;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
UserService userService;
@Autowired
AnswerService answerService;
@GetMapping("/register")
public String register(){
return "zhifou_register";
}
@GetMapping("/main")
public String mainPage(){
return "zhifou_main";
}
@PostMapping("/login")
@ResponseBody
public String login(@RequestBody Map<String,String> map, HttpSession session){
String userUserName = map.get("userUserName");
String userPassword = map.get("userPassword");
UserInfo userInfo = userService.login(userUserName,userPassword);
session.setAttribute("userInfo",userInfo);
if(userInfo!=null){
return "success";
}
else{
return "failed";
}
}
@PostMapping("/register/load")
@ResponseBody
public String registerLoad(@RequestBody Map<String,String> map){
String userUserName = map.get("userUserName");
String userPassword = map.get("userPassword");
String userNickName = map.get("userNickName");
UserInfo userInfo = userService.register(userUserName,userPassword,userNickName);
if(userInfo!=null){
return "success";
}
else{
return "failed";
}
}
}
|
package com.udacity.popularmovies.localdatabase;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.udacity.popularmovies.localdatabase.BookmarkContract.BookmarkEntry;
import java.util.Objects;
/**
* Created by jesse on 08/09/18.
* This is a part of the project adnd-popular-movies.
*/
public class BookmarkContentProvider extends ContentProvider {
private static final int BOOKMARKS = 100;
private static final int BOOKMARK_WITH_ID = 101;
/*
* This way UriMatcher can be accessed throughout all the provider code,
* and don't forget to set it equal to the return value
*/
private static final UriMatcher sUriMatcher = buildUriMatcher();
private static UriMatcher buildUriMatcher() {
// NO_MATCH construct a empty matcher
UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
// Add matches with addUri(String authority, String path, int code):
// Directory
uriMatcher.addURI(BookmarkContract.AUTHORITY,
BookmarkContract.PATH_MOVIES_BOOKMARKS, BOOKMARKS);
// Single item
uriMatcher.addURI(BookmarkContract.AUTHORITY,
BookmarkContract.PATH_MOVIES_BOOKMARKS + "/#", BOOKMARK_WITH_ID);
return uriMatcher;
}
// BookmarkDbHelper to provide access to the database
private BookmarkDbHelper bookmarkDbHelper;
@Override
public boolean onCreate() {
Context context = getContext();
bookmarkDbHelper = new BookmarkDbHelper(context);
return true;
}
@Nullable
@Override
public Cursor query(
@NonNull Uri uri,
@Nullable String[] projection,
@Nullable String selection,
@Nullable String[] selectionArgs,
@Nullable String sortOrder) {
// gaining access to read our underlying database
final SQLiteDatabase db = bookmarkDbHelper.getReadableDatabase();
// URI matcher to get a match number that identifies the passed in URI
int match = sUriMatcher.match(uri);
Cursor returnCursor;
switch (match) {
case BOOKMARKS:
returnCursor = db.query(
BookmarkEntry.TABLE_NAME, // table
projection, // columns
selection, // selection
selectionArgs, // selectionArgs
null, // groupBy
null, // having
sortOrder); // orderBy
break;
default:
throw new UnsupportedOperationException("Unknown Uri: " + uri);
}
// Set notification changes. It tells the cursor what content URI it was created for.
// This way, if anything changes in the URI, the cursor will know.
returnCursor.setNotificationUri(Objects.requireNonNull(getContext()).getContentResolver(), uri);
// Return a cursor with data (this cursor might be empty or full)
return returnCursor;
}
@Nullable
@Override
public String getType(@NonNull Uri uri) {
return null;
}
@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues contentValues) {
// Get access to the popular_movies database (with write privileges)
final SQLiteDatabase db = bookmarkDbHelper.getWritableDatabase();
// Write UR matching code to identify the match for the bookmarks directory
int match = sUriMatcher.match(uri);
Uri returnUri;
switch (match) {
case BOOKMARKS:
// Insert values into database
// If the insert does not work the return will bee -1. If It's success return the new row id.
long id = db.insert(BookmarkEntry.TABLE_NAME, null, contentValues);
if (id > 0){
// success
returnUri = ContentUris.withAppendedId(BookmarkEntry.CONTENT_URI, id);
}else {
// failed
throw new UnsupportedOperationException("Failed to insert row into: " + uri);
}
break;
// Default case throws an UnsupportedOperationException
default:
throw new UnsupportedOperationException("Unknown Uri: " + uri);
}
// Notify the resolver if the uri has been changed
Objects.requireNonNull(getContext()).getContentResolver().notifyChange(uri, null);
return returnUri;
}
@Override
public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
final SQLiteDatabase db = bookmarkDbHelper.getWritableDatabase();
int rowsDeleted;
int match = sUriMatcher.match(uri);
switch (match) {
case BOOKMARKS:
rowsDeleted = db.delete(BookmarkEntry.TABLE_NAME, selection, selectionArgs);
break;
case BOOKMARK_WITH_ID:
String id = uri.getPathSegments().get(1);
// Use selections/selectionArgs to filter for this ID
selection = BookmarkEntry._ID + "=?";
selectionArgs = new String[] { id };
rowsDeleted = db.delete(BookmarkEntry.TABLE_NAME, selection, selectionArgs);
break;
default:
throw new IllegalArgumentException("Delete not supported for " + uri);
}
if (rowsDeleted > 0) {
Objects.requireNonNull(getContext()).getContentResolver().notifyChange(uri, null);
}
return rowsDeleted;
}
@Override
public int update(@NonNull Uri uri,
@Nullable ContentValues contentValues,
@Nullable String selection,
@Nullable String[] selectionArgs) {
final SQLiteDatabase db = bookmarkDbHelper.getWritableDatabase();
int rowsUpdated;
int match = sUriMatcher.match(uri);
switch (match) {
case BOOKMARK_WITH_ID:
String id = uri.getPathSegments().get(1);
// Use selections/selectionArgs to filter for this ID
selection = BookmarkEntry.COLUMN_API_ID + "=?";
selectionArgs = new String[] { id };
rowsUpdated = db.update(BookmarkEntry.TABLE_NAME,
contentValues,
selection,
selectionArgs);
break;
default:
throw new IllegalArgumentException("Delete not supported for " + uri);
}
return rowsUpdated;
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.apache.webbeans.container;
import java.util.Set;
import jakarta.enterprise.inject.spi.AnnotatedType;
import jakarta.enterprise.inject.spi.Bean;
import jakarta.enterprise.inject.spi.InjectionPoint;
import jakarta.enterprise.inject.spi.InjectionTarget;
import org.apache.webbeans.component.BeanAttributesImpl;
import org.apache.webbeans.component.ManagedBean;
import org.apache.webbeans.component.creation.BeanAttributesBuilder;
import org.apache.webbeans.component.creation.ManagedBeanBuilder;
import org.apache.webbeans.config.WebBeansContext;
import org.apache.webbeans.portable.InjectionTargetImpl;
/**
* InjectionTargetFactory which validates the craeted InjectionTarget.
* This is only required if the InjectionTarget gets created manually
* via the BeanManager.
*/
public class ValidatingInjectionTargetFactory<T> extends InjectionTargetFactoryImpl<T>
{
public ValidatingInjectionTargetFactory(AnnotatedType<T> annotatedType, WebBeansContext webBeansContext)
{
super(annotatedType, webBeansContext);
}
@Override
public InjectionTarget<T> createInjectionTarget(Bean<T> bean)
{
final AnnotatedType<T> annotatedType = getAnnotatedType();
final InjectionTargetImpl<T> injectionTarget = (InjectionTargetImpl<T>) super.createInjectionTarget(bean);
final Set<InjectionPoint> injectionPoints = injectionTarget.getInjectionPoints();
try
{
getWebBeansContext().getWebBeansUtil().validate(injectionPoints, null);
}
catch (Exception e)
{
// This is really a bit weird.
// The spec does mandate an IAE instead of a CDI DefinitionException for whatever reason.
throw new IllegalArgumentException("Problem while creating InjectionTarget", e);
}
// only possible to define an interceptor if there is a default ct
if (getWebBeansContext().getWebBeansUtil().getNoArgConstructor(annotatedType.getJavaClass()) != null)
{
if (bean == null)
{
bean = getWebBeansContext().getBeanManagerImpl().getUnmanagedClassBeans().computeIfAbsent(annotatedType.getJavaClass(), c -> {
final BeanAttributesImpl<T> attributes = BeanAttributesBuilder.forContext(getWebBeansContext()).newBeanAttibutes(annotatedType).build();
ManagedBeanBuilder<T, ManagedBean<T>> managedBeanCreator
= new ManagedBeanBuilder<>(getWebBeansContext(), annotatedType, attributes, false);
return managedBeanCreator.getBean();
});
}
injectionTarget.defineInterceptorStack(bean, annotatedType, getWebBeansContext());
}
return injectionTarget;
}
}
|
package com.projeto.gestãoMP.model;
import lombok.*;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@Table(name = "tb_matériasprimas")
public class MatériasPrimas {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull(message = "Nome do produto é obrigatório")
@Size(min = 3, max = 256)
private String nome;
@NotNull(message = "Quantidade é obrigatorio")
@Min(value=0, message="Quantidade tem que ser maior que 0 gramas ")
@Max(value=1001, message="Quantidade tem que ser menor ou igual a 1000 gramas ")
private Integer valorR$;
public Object save(MatériasPrimas matériasprimas) {
// TODO Auto-generated method stub
return null;
}
public Object findById(Long id2) {
// TODO Auto-generated method stub
return null;
}
public Object findAll() {
// TODO Auto-generated method stub
return null;
}
public Object findAllByNomeContainingIgnoreCase(String nome2) {
// TODO Auto-generated method stub
return null;
}
} |
package programmers.level1;
class MidString {
public String solution(String s) {
String answer = "";
int mid = s.length()/2;
if(s.length() % 2 == 0)
answer = s.split("")[mid-1] + s.split("")[mid];
else
answer = s.split("")[mid];
return answer;
}
} |
package BaiTap;
import java.util.Scanner;
public class DemKyTu {
public static void main(String[] args) {
String str="HelloWorld";
Scanner scanner=new Scanner(System.in);
String c=scanner.nextLine();
int count=0;
for(int i=0;i<str.length();i++){
if(c.equals(str.charAt(i))){
count++;
}
}
System.out.println("Ky tu "+c+" hien thi "+count+" lan");
}
}
|
/*
* created 30.01.2006
*
* Copyright 2009, ByteRefinery
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* $Id$
*/
package com.byterefinery.rmbench.external.model;
/**
* extension of the {@link com.byterefinery.rmbench.external.model.IColumn} interface that
* adds mutator methods
*
* @author cse
*/
public interface IColumn2 extends IColumn {
/**
* @param value the new default value
*/
void setDefault(String value);
/**
* @param comment the new default comment
*/
void setComment(String value);
}
|
package za.ac.cput.Service;
import static org.junit.jupiter.api.Assertions.*;
class IPrescriptionServiceTest {
} |
package com.webcloud.service;
import java.io.File;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.text.TextUtils;
import android.widget.RemoteViews;
import android.widget.Toast;
import com.funlib.http.download.DownloadListener;
import com.funlib.http.download.DownloadStatus;
import com.funlib.http.download.UpdateDownloader;
import com.funlib.utily.Utily;
import com.webcloud.R;
import com.webcloud.WebCloudApplication;
/**
* 下载服务。
* 服务和活动共享主线程,注意避免ANR。
*
* @author bangyue
* @version [版本号, 2013-12-18]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
public class DownloadService extends Service {
public static final int NOTIFICATION_ID = 100;
public static final String START = "start";
public static final String STOP = "stop";
boolean isUpdating = false;
boolean isComplete = false;
NotificationManager mNotifMan;
Notification notification;
UpdateDownloader downloader = new UpdateDownloader();
public static void actionStart(Context ctx, String appurl) {
Intent i = new Intent(ctx, DownloadService.class);
i.putExtra("appurl", appurl);
i.setAction(START);
i.setFlags(Service.START_STICKY);//连续
ctx.startService(i);
}
public static void actionStop(Context ctx) {
Intent i = new Intent(ctx, DownloadService.class);
i.setAction(STOP);
ctx.startService(i);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
String action = intent.getAction();
String appurl = intent.getStringExtra("appurl");
if (START.equals(action)) {
if (isUpdating || TextUtils.isEmpty(appurl))
return super.onStartCommand(intent, flags, startId);
startDownloadByNotification(appurl);
} else if (STOP.equals(action)) {
stop();
}
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
public Notification initNotification() {
mNotifMan = (NotificationManager)WebCloudApplication.getInstance().getSystemService(Context.NOTIFICATION_SERVICE);
notification = new Notification(R.drawable.ic_launcher, "应用正在更新…", System.currentTimeMillis());
//屏幕亮、不可手动清空
notification.flags = Notification.FLAG_SHOW_LIGHTS | Notification.FLAG_NO_CLEAR;
//默认声音和振动
//notification.defaults = Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE;
notification.contentView =
new RemoteViews(WebCloudApplication.getInstance().getPackageName(), R.layout.comm_update_notification);
notification.contentView.setProgressBar(R.id.pbLoad, 100, 0, false);
notification.contentView.setTextViewText(R.id.tvMsg, "已下载" + 0 + "%");
//给一个空的intent,有些机型必须设置
Intent intent = new Intent();
PendingIntent contentIntent =
PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.contentIntent = contentIntent;
//点击取消
notification.contentView.setOnClickPendingIntent(R.id.btnCancel, canelPendingIntent(downloader));
return notification;
}
private PendingIntent canelPendingIntent(UpdateDownloader downloader) {
//取消下载,关闭服务
Intent intent = new Intent(getApplicationContext(), DownloadService.class);
intent.setAction(STOP);
PendingIntent pi = PendingIntent.getService(getBaseContext(), 0, intent, 0);
return pi;
}
@Override
public void onCreate() {
super.onCreate();
initNotification();
}
int percent = 0;
Runnable runPros = new Runnable() {
@Override
public void run() {
if (isComplete) {
handler.removeCallbacks(runPros);
mNotifMan.cancel(NOTIFICATION_ID);
return;
}
//更新状态栏
notification.contentView.setProgressBar(R.id.pbLoad, 100, percent, false);
notification.contentView.setTextViewText(R.id.tvMsg, "已下载" + percent + "%");
notification.defaults = 0;
mNotifMan.notify(NOTIFICATION_ID, notification);
}
};
private synchronized void startDownloadByNotification(String appurl) {
isUpdating = true;
downloader.download(null, appurl, new DownloadListener() {
@Override
public void onDownloadStatusChanged(Object tag, int index, final int status, final int percent,
final String filePath) {
//启动下载
if (status == DownloadStatus.STATUS_STARTDOWNLOADING) {
handler.post(new Runnable() {
@Override
public void run() {
notification.defaults = Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE;
mNotifMan.notify(NOTIFICATION_ID, notification);
}
});
} else if (status == DownloadStatus.STATUS_DOWNLOADING) {
DownloadService.this.percent = percent;
handler.post(runPros);
} else if (status == DownloadStatus.STATUS_COMPLETE) {
/*handler.post(new Runnable() {
@Override
public void run() {*/
isComplete = true;
handler.postDelayed(new Runnable() {
@Override
public void run() {
handler.removeCallbacks(runPros);
mNotifMan.cancel(NOTIFICATION_ID);
}
}, 1000);
Toast.makeText(getBaseContext(), "新版乐搜下载完成啦,等待安装…", Toast.LENGTH_LONG).show();
//下载完成
Intent apkintent = new Intent(Intent.ACTION_VIEW);
final Uri puri = Uri.fromFile(new File(filePath));
apkintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
apkintent.setDataAndType(puri, "application/vnd.android.package-archive");
startActivity(apkintent);
stop();
/*}
});*/
} else if (status == DownloadStatus.STATUS_NO_SDCARD || status == DownloadStatus.STATUS_STORAGE_FULL
|| status == DownloadStatus.STATUS_UNKNOWN || status == DownloadStatus.STATUS_NETERROR) {
handler.post(new Runnable() {
@Override
public void run() {
String tip = "Sorry下载失败,未知异常,请稍后重试";
if (status == DownloadStatus.STATUS_NO_SDCARD
|| status == DownloadStatus.STATUS_STORAGE_FULL) {
tip = getResources().getString(R.string.is_update_sdcard_error);
} else if (status == DownloadStatus.STATUS_NETERROR) {
tip = getResources().getString(R.string.is_update_neterror);
}
Toast.makeText(getBaseContext(), tip, Toast.LENGTH_LONG).show();
//下载出状况
/*MessageDialog msgDialog = new MessageDialog(false);
msgDialog.showDialogOK(LbsMainActivity.this,
tip,
new MessageDialogListener() {
@Override
public void onMessageDialogClick(MessageDialog dialog, int which) {
dialog.dismissMessageDialog();
mNotifMan.cancel(UpdateDownloader.NOTIFICATION_ID);
}
});*/
/*msgDialog.setDialogOKOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
mNotifMan.cancel(UpdateDownloader.NOTIFICATION_ID);
return true;
}
return false;
}
});*/
mNotifMan.cancel(NOTIFICATION_ID);
stop();
}
});
} else if (status == DownloadStatus.STATUS_CANCELED) {
Toast.makeText(getBaseContext(), "您取消了应用更新!", Toast.LENGTH_LONG).show();
}
}
},
Utily.getSDPath() + "hunanctlbs.apk");
}
private synchronized void stop() {
mNotifMan.cancel(NOTIFICATION_ID);
downloader.canceled();
isUpdating = false;
stopSelf();
}
Handler handler = new Handler();
}
|
package com.countout.portal.exception;
import org.apache.shiro.authc.AuthenticationException;
/**
* 用户验证不通过是抛出
* @author Mr.tang
*/
@SuppressWarnings("serial")
public class UserDisabledAuthcException extends AuthenticationException {
public UserDisabledAuthcException() {
}
public UserDisabledAuthcException(String message) {
super(message);
}
public UserDisabledAuthcException(Throwable cause) {
super(cause);
}
public UserDisabledAuthcException(String message, Throwable cause) {
super(message, cause);
}
}
|
package pl.ark.chr.buginator.app.error;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestParam;
import pl.ark.chr.buginator.domain.core.ErrorStatus;
import pl.ark.chr.buginator.rest.annotations.RestController;
@RestController
class ErrorResource {
private final ErrorService errorService;
ErrorResource(ErrorService errorService) {
this.errorService = errorService;
}
@GetMapping("/api/buginator/error/{id}")
ErrorDetailsDTO getDetails(@PathVariable Long id) {
return errorService.details(id);
}
@PutMapping("/api/buginator/error/{id}")
void updateStatus(@PathVariable Long id, @RequestParam("status") ErrorStatus newStatus) {
errorService.changeStatus(id, newStatus);
}
}
|
package com.tencent.mm.vending.g;
import com.tencent.mm.vending.j.a;
import com.tencent.mm.vending.j.b;
import com.tencent.mm.vending.j.c;
import com.tencent.mm.vending.j.d;
import com.tencent.mm.vending.j.e;
import com.tencent.mm.vending.j.f;
import java.util.Stack;
public final class g {
private static final a uRB = new a();
public static final c<Void> cBK() {
return new e().w(new Object[0]);
}
public static final <Var1> c<Var1> cx(Var1 var1) {
return new e().w(var1);
}
public static final <Var1, Var2> c<c<Var1, Var2>> v(Var1 var1, Var2 var2) {
return new e().w(var1, var2);
}
public static final <Var1, Var2, Var3> c<d<Var1, Var2, Var3>> a(Var1 var1, Var2 var2, Var3 var3) {
return new e().w(var1, var2, var3);
}
public static final <Var1, Var2, Var3, Var4> c<e<Var1, Var2, Var3, Var4>> a(Var1 var1, Var2 var2, Var3 var3, Var4 var4) {
return new e().w(var1, var2, var3, var4);
}
public static final <Var1, Var2, Var3, Var4, Var5> c<f<Var1, Var2, Var3, Var4, Var5>> a(Var1 var1, Var2 var2, Var3 var3, Var4 var4, Var5 var5) {
return new e().w(var1, var2, var3, var4, var5);
}
public static <$1> b<$1> cy($1 $1) {
b bVar = new b();
return a.cz($1);
}
public static <$1, $2> c<$1, $2> w($1 $1, $2 $2) {
c cVar = new c();
return a.x($1, $2);
}
public static final b cBF() {
f cBJ = f.cBJ();
Stack stack = (Stack) cBJ.uRA.get();
c cVar = stack == null ? null : stack.size() == 0 ? null : (c) ((Stack) cBJ.uRA.get()).peek();
return cVar != null ? cVar.cBF() : uRB;
}
public static final b cBL() {
b cBF = cBF();
if (cBF != null) {
cBF.cBE();
} else {
com.tencent.mm.vending.f.a.w("Vending.QuickAccess", "dummy mario", new Object[0]);
}
return cBF;
}
public static final void a(b bVar, Object... objArr) {
if (bVar == null) {
com.tencent.mm.vending.f.a.w("Vending.QuickAccess", "dummy mario", new Object[0]);
} else if (objArr.length > 0) {
bVar.v(objArr);
} else {
bVar.resume();
}
}
public static final void a(b bVar) {
if (bVar == null) {
com.tencent.mm.vending.f.a.w("Vending.QuickAccess", "dummy mario", new Object[0]);
} else {
bVar.ct(null);
}
}
public static final <_Var> void a(d<_Var> dVar) {
final b cBL = cBL();
dVar.a(new d.b<_Var>() {
public final void aF(_Var _var) {
g.a(cBL, _var);
}
}).a(new d.a() {
public final void bd(Object obj) {
cBL.ct(obj);
}
});
}
}
|
/*
*
* Copyright (c) Cox And Kings
* All rights reserved.
*
*/
package com.cnk.travelogix.operations.facades.populator;
import de.hybris.platform.commercefacades.order.data.CCPaymentInfoData;
import de.hybris.platform.commerceservices.converter.Populator;
import de.hybris.platform.core.model.order.payment.PaymentInfoModel;
/**
* The travelogix payment info populator
*/
public class TravelogixPaymentInfoPopulator implements Populator<PaymentInfoModel, CCPaymentInfoData>
{
@Override
public void populate(final PaymentInfoModel source, final CCPaymentInfoData target)
{
/*
* Assert.notNull(source, "Parameter source cannot be null."); Assert.notNull(target,
* "Parameter target cannot be null."); if (source instanceof CreditCardEMIPaymentInfoModel) {
* target.setCardType(((CreditCardPaymentInfoModel) source).getType().getCode());
* target.setCardNumber(((CreditCardPaymentInfoModel) source).getNumber());
* target.setCvvNumber(((CreditCardEMIPaymentInfoModel) source).getCvv().toString());
* target.setExpiryMonth(((CreditCardPaymentInfoModel) source).getValidToMonth());
* target.setExpiryYear(((CreditCardPaymentInfoModel) source).getValidToYear()); } else if (source instanceof
* DebitCardPaymentInfoModel) { target.setCardNumber(((DebitCardPaymentInfoModel) source).getCardNumber());
* target.setCardType(((DebitCardPaymentInfoModel) source).getCardType().getCode());
* target.setNameOnCard(((DebitCardPaymentInfoModel) source).getNameOnCard());
* target.setExpiryMonth(((DebitCardPaymentInfoModel) source).getValidToMonth());
* target.setExpiryYear(((DebitCardPaymentInfoModel) source).getValidToYear());
* target.setCvvNumber(((DebitCardPaymentInfoModel) source).getCvv());
*
* } else if (source instanceof DirectDepositPaymentInfoModel) {
* target.setChequeNo(((DirectDepositPaymentInfoModel) source).getChequeOrDDNumber());
* target.setChequeDate(((DirectDepositPaymentInfoModel) source).getChequeOrDDDate());
*
* } else if (source instanceof DirectDepositCashPaymentInfoModel) {
*
* target.setAccountNumber(((DirectDepositCashPaymentInfoModel) source).getBankAccountNumber());
*
* } else if (source instanceof FundTransferPaymentInfoModel) {
* target.setFromBankName(((FundTransferPaymentInfoModel) source).getFromBank().getName());
* target.setToBankName(((FundTransferPaymentInfoModel) source).getToBank().getName());
* target.setReferenceNumber(((FundTransferPaymentInfoModel) source).getReferenceNumber()); } else if (source
* instanceof EPOSPaymentInfoModel) { target.setCardType(((EPOSPaymentInfoModel) source).getCreditOrDebitCard());
* }
*/
}
}
|
package com.eatme.eatmeserver.business.service;
public interface BattleService {
void startActionBroadcast(String battleId, String player1Id, String player2Id);
void stopActionBroadcast(String battleId);
}
|
package com.springbootmybatis.controller;
import com.springbootmybatis.mapper.GoodClassMapper;
import com.springbootmybatis.model.GoodClassEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//商品分类表
@RestController
@RequestMapping("/goodClass")
public class GoodClassController {
@Autowired
GoodClassMapper wemall_goodsclassMapper;
@RequestMapping("/getClasses")
public List<GoodClassEntity> getAll() {
List<GoodClassEntity> wemall=wemall_goodsclassMapper.getAll();
return wemall;
}
@RequestMapping("/getOne/{id}")
public GoodClassEntity getOne(@PathVariable Long id) {
GoodClassEntity wemall=wemall_goodsclassMapper.getOne(id);
return wemall;
}
@RequestMapping("/deleteOne/{id}")
public Boolean delete(@PathVariable Long id){
return wemall_goodsclassMapper.delete(id);
}
@RequestMapping("/getGoodsAtoB/{id1}/{id2}")
public List<GoodClassEntity> getGoodsAtoB(@PathVariable Long id1, @PathVariable Long id2){
Map<String ,Object> map=new HashMap<>();
map.put("id1",id1);
map.put("id2",id2);
return wemall_goodsclassMapper.getGoodsAtoB(map);
}
@RequestMapping("/getGoodClassByName/{className}")
public List<GoodClassEntity> getGoodsClass(@PathVariable String className){
return wemall_goodsclassMapper.getClassByClassName(className);
}
}
|
package csc2227proj;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
/**
*
* @author trbot
*/
public class PrimitiveBench {
public PrimitiveBench(String[] args) {
int runs = 100000000;
int cur = 0;
if (args.length != 1) {
System.out.println("usage: java " + getClass().getSimpleName() + " CASE_NUMBER");
System.out.println("\twhere CASE_NUMBER is in {1,2,..,5}");
System.exit(-1);
}
int caseno = Integer.parseInt(args[0]);
boolean result1 = false, result2 = false;
switch (caseno) {
//case 1: break;
//case 2: break;
//case 3: break;
case 4: {
System.out.println("fetch and add");
AtomicInteger addr = new AtomicInteger(0);
for (int i=0;i<runs;i++) {
cur = addr.getAndAdd(1);
cur = addr.getAndAdd(-1);
}
if (cur != 1) throw new RuntimeException("cur = " + cur);
if (addr.get() != 0) throw new RuntimeException("addr.get() = " + addr.get());
} break;
case 5: {
System.out.println("compare and swap");
AtomicInteger addr = new AtomicInteger(0);
for (int i=0;i<runs;i++) {
result1 = addr.compareAndSet(cur, cur+1);
result2 = addr.compareAndSet(cur+1, cur);
}
if (!result1 || !result2) throw new RuntimeException("result1 = " + result1 + " result2 = " + result2);
if (addr.get() != 0) throw new RuntimeException("addr.get() = " + addr.get());
} break;
case 6: {
System.out.println("atomic updater cas");
IntHolder addr = new IntHolder(0);
AtomicIntegerFieldUpdater<IntHolder> updater = AtomicIntegerFieldUpdater.newUpdater(IntHolder.class, "v");
for (int i=0;i<runs;i++) {
result1 = updater.compareAndSet(addr, cur, cur+1);
result2 = updater.compareAndSet(addr, cur+1, cur);
}
if (!result1 || !result2) throw new RuntimeException("result1 = " + result1 + " result2 = " + result2);
if (addr.v != 0) throw new RuntimeException("addr.v = " + addr.v);
} break;
default: {
System.out.println("bad case number specified: " + caseno);
} break;
}
}
private class IntHolder {
volatile int v;
public IntHolder(final int v) {
this.v = v;
}
}
public static void main(String[] args) {
new PrimitiveBench(args);
}
}
|
package basicRest;
public class Dummy {
public static void main(String[] args) {
Dummy d=new Dummy();
}
}
|
import java.util.Scanner;
public class conditionals {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("wat is je leeftijd:");
int age = scan.nextInt();
if (age >= 18) {
System.out.println("Je bent oud genoeg om alcohol te kopen");
} else {
System.out.println("Je mag nog geen alcohol kopen");
}
}}
// Boolean teacherTalks = true;
//
// if (teacherTalks != true) {
//
// System.out.println("Ok, teacher talks");
// } else {
//
// System.out.println("teacher does not talk");
//
// }
|
/*
* [y] hybris Platform
*
* Copyright (c) 2000-2016 SAP SE
* All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* Hybris ("Confidential Information"). You shall not disclose such
* Confidential Information and shall use it only in accordance with the
* terms of the license agreement you entered into with SAP Hybris.
*/
package com.cnk.travelogix.common.facades.order.populators.hotel;
import de.hybris.platform.converters.Populator;
import de.hybris.platform.servicelayer.dto.converter.ConversionException;
import com.cnk.travelogix.common.core.cart.data.OrderHotelDetailInfoData;
import com.cnk.travelogix.common.core.cart.data.PriceInfoData;
import com.cnk.travelogix.common.core.model.OrderHotelDetailInfoModel;
import com.cnk.travelogix.common.core.model.PriceInfoModel;
/**
*
*/
public class OrderHotelPopulator implements Populator<OrderHotelDetailInfoModel, OrderHotelDetailInfoData>
{
@Override
public void populate(OrderHotelDetailInfoModel hotel, OrderHotelDetailInfoData hotelData) throws ConversionException
{
hotelData.setHotelId(hotel.getHotelId());
hotelData.setHotelName(hotel.getHotelName());
hotelData.setHotelRate(hotel.getHotelRate());
hotelData.setHotelAddress(hotel.getHotelAddress());
hotelData.setHotelCityName(hotel.getHotelCityName());
hotelData.setHotelCountryName(hotel.getHotelCountryName());
hotelData.setNumberOfAdult(hotel.getNumberOfAdult());
hotelData.setNumberOfChild(hotel.getNumberOfChild());
hotelData.setNumberOfRooms(hotel.getNumberOfrooms());
hotelData.setNumberOfNight(hotel.getNumberOfNights());
hotelData.setReservationDay(hotel.getNumberOfNights());
hotelData.setHotelCheckinDate(hotel.getHotelCheckinDate());
hotelData.setHotelCheckoutDate(hotel.getHotelCheckoutDate());
PriceInfoModel priceInfo = hotel.getPriceInfo();
if (priceInfo != null && priceInfo.getCostPrice() != null)
{
PriceInfoData priceData = new PriceInfoData();
priceData.setCostPrice(priceInfo.getCostPrice().doubleValue());
hotelData.setPriceInfo(priceData);
}
hotelData.setHotelRate(hotel.getHotelRate());
}
}
|
package com.tencent.mm.plugin.account.bind.ui;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.view.KeyEvent;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.tencent.mm.ab.e;
import com.tencent.mm.ab.l;
import com.tencent.mm.al.b;
import com.tencent.mm.g.a.sf;
import com.tencent.mm.kernel.g;
import com.tencent.mm.model.q;
import com.tencent.mm.modelsimple.BindWordingContent;
import com.tencent.mm.plugin.account.a;
import com.tencent.mm.plugin.account.a.f;
import com.tencent.mm.plugin.account.a.h;
import com.tencent.mm.plugin.account.a.j;
import com.tencent.mm.plugin.account.friend.ui.FindMContactAddUI;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.MMWizardActivity;
import com.tencent.mm.ui.base.p;
import java.util.Timer;
public class BindMobileVerifyUI extends MMWizardActivity implements e {
private String bTi;
private Timer bno;
private EditText eGC;
private Button eGE;
private BindWordingContent eGQ;
private int eGR;
private boolean eGS;
private boolean eGT;
private boolean eGb = false;
private boolean eGx = false;
private boolean eHe = false;
private TextView eHh;
private TextView eHi;
private boolean eHj = false;
private Integer eHk = Integer.valueOf(15);
private p tipDialog = null;
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
g.DF().a(132, this);
setMMTitle(j.bind_mcontact_title_verify);
this.eGQ = (BindWordingContent) getIntent().getParcelableExtra("kstyle_bind_wording");
this.eGR = getIntent().getIntExtra("kstyle_bind_recommend_show", 0);
this.eGS = getIntent().getBooleanExtra("Kfind_friend_by_mobile_flag", false);
this.eGT = getIntent().getBooleanExtra("Krecom_friends_by_mobile_flag", false);
this.eHe = getIntent().getBooleanExtra("is_bind_for_chatroom_upgrade", false);
initView();
}
public void onDestroy() {
g.DF().b(132, this);
super.onDestroy();
}
protected void onStop() {
WO();
super.onStop();
}
protected final int getLayoutId() {
return a.g.bindmcontact_verify;
}
protected final void initView() {
this.bTi = (String) g.Ei().DT().get(4097, null);
this.eGC = (EditText) findViewById(f.bind_mcontact_verify_num);
this.eHh = (TextView) findViewById(f.bind_mcontact_verify_mobile_num);
this.eHi = (TextView) findViewById(f.bind_mcontact_sms_time_hint);
this.eGb = getIntent().getBooleanExtra("is_bind_for_safe_device", false);
this.eHj = getIntent().getBooleanExtra("is_bind_for_contact_sync", false);
this.eGx = getIntent().getBooleanExtra("BIND_FOR_QQ_REG", false);
Button button = (Button) findViewById(f.bind_mcontact_verify_btn);
if (this.bTi == null || this.bTi.equals("")) {
this.bTi = (String) g.Ei().DT().get(6, null);
}
if (this.bTi != null && this.bTi.length() > 0) {
this.eHh.setVisibility(0);
this.eHh.setText(this.bTi);
}
this.eGC.setFilters(new InputFilter[]{new 1(this)});
this.eGE = (Button) findViewById(f.bind_mcontact_voice_code);
button.setVisibility(8);
this.eHi.setText(getResources().getQuantityString(h.mobileverify_send_code_tip, this.eHk.intValue(), new Object[]{this.eHk}));
if (this.bno == null) {
this.bno = new Timer();
5 5 = new 5(this);
if (this.bno != null) {
this.bno.schedule(5, 1000, 1000);
}
}
addTextOptionMenu(0, getString(j.app_nextstep), new 2(this));
setBackBtn(new 3(this));
this.eGE.setVisibility(b.mj(this.bTi) ? 0 : 8);
this.eGE.setOnClickListener(new 4(this));
}
private void WO() {
if (this.bno != null) {
this.bno.cancel();
this.bno = null;
}
}
public boolean onKeyDown(int i, KeyEvent keyEvent) {
if (keyEvent.getKeyCode() == 4 && keyEvent.getAction() == 0) {
return true;
}
return super.onKeyDown(i, keyEvent);
}
public final void a(int i, int i2, String str, l lVar) {
boolean z = true;
x.i("MicroMsg.BindMobileVerifyUI", "onSceneEnd: errType = " + i + " errCode = " + i2 + " errMsg = " + str);
if (((com.tencent.mm.plugin.account.friend.a.x) lVar).Oh() == 2) {
if (this.tipDialog != null) {
this.tipDialog.dismiss();
this.tipDialog = null;
}
boolean z2;
if (i != 0 || i2 != 0) {
if (!com.tencent.mm.plugin.account.a.a.ezo.a(this, i, i2, str)) {
switch (i2) {
case -214:
com.tencent.mm.h.a eV = com.tencent.mm.h.a.eV(str);
if (eV != null) {
eV.a(this, null, null);
}
z2 = true;
break;
case -43:
Toast.makeText(this, j.bind_mcontact_err_binded, 0).show();
z2 = true;
break;
case -41:
Toast.makeText(this, j.bind_mcontact_err_format, 0).show();
z2 = true;
break;
case -36:
Toast.makeText(this, j.bind_mcontact_err_unbinded_notbinded, 0).show();
z2 = true;
break;
case -35:
Toast.makeText(this, j.bind_mcontact_err_binded_by_other, 0).show();
z2 = true;
break;
case -34:
Toast.makeText(this, j.bind_mcontact_err_freq_limit, 0).show();
z2 = true;
break;
case -33:
com.tencent.mm.ui.base.h.a(this, j.bind_mcontact_verify_err_time_out_content, j.bind_mcontact_verify_tip, null);
z2 = true;
break;
case -32:
com.tencent.mm.ui.base.h.a(this, j.bind_mcontact_verify_err_unmatch_content, j.bind_mcontact_verify_tip, null);
z2 = true;
break;
default:
z2 = false;
break;
}
}
z2 = true;
if (!z2) {
Toast.makeText(this, getString(j.bind_mcontact_verify_err, new Object[]{Integer.valueOf(i), Integer.valueOf(i2)}), 0).show();
}
} else if (((com.tencent.mm.plugin.account.friend.a.x) lVar).Oh() != 2) {
} else {
Intent intent;
if (this.eGb) {
if (!q.GN()) {
sf sfVar = new sf();
sfVar.ccY.ccZ = true;
sfVar.ccY.cda = true;
com.tencent.mm.sdk.b.a.sFg.m(sfVar);
}
DT(1);
intent = new Intent();
intent.addFlags(67108864);
com.tencent.mm.plugin.account.a.a.ezn.e(this, intent);
} else if (this.eGx) {
DT(1);
startActivity(new Intent(this, FindMContactAddUI.class));
} else if (this.eHe) {
if (this.eGS) {
z2 = false;
} else {
z2 = true;
}
if (this.eGT) {
z = false;
}
BindMobileStatusUI.c(this, z2, z);
exit(-1);
} else {
if (!this.eHj) {
((com.tencent.mm.plugin.account.a.a.a) g.n(com.tencent.mm.plugin.account.a.a.a.class)).syncAddrBookAndUpload();
}
intent = new Intent(this, BindMobileStatusUI.class);
intent.putExtra("kstyle_bind_wording", this.eGQ);
intent.putExtra("kstyle_bind_recommend_show", this.eGR);
intent.putExtra("Kfind_friend_by_mobile_flag", this.eGS);
intent.putExtra("Krecom_friends_by_mobile_flag", this.eGT);
D(this, intent);
}
}
}
}
}
|
package com.tencent.mm.protocal;
import com.tencent.mm.protocal.c.g;
public class c$ew extends g {
public c$ew() {
super("openGameDetail", "openGameDetail", 131, true);
}
}
|
package com.nastenkapusechka.validation.util;
/**
* This enumeration is intended so that you can tell
* the annotations what you want to check in the map:
* keys or values. Otherwise, the annotation will not
* know whether to validate keys or values for it, and
* will mark the field as non-compliant with the annotation.
*
*/
public enum MapTarget {
KEYS,
VALUES,
UNKNOWN
}
|
package net.minecraft.client.resources;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;
import javax.annotation.Nullable;
import net.minecraft.client.resources.data.MetadataSerializer;
import net.minecraft.util.ResourceLocation;
public class LegacyV2Adapter implements IResourcePack {
private final IResourcePack field_191383_a;
public LegacyV2Adapter(IResourcePack p_i47182_1_) {
this.field_191383_a = p_i47182_1_;
}
public InputStream getInputStream(ResourceLocation location) throws IOException {
return this.field_191383_a.getInputStream(func_191382_c(location));
}
private ResourceLocation func_191382_c(ResourceLocation p_191382_1_) {
String s = p_191382_1_.getResourcePath();
if (!"lang/swg_de.lang".equals(s) && s.startsWith("lang/") && s.endsWith(".lang")) {
int i = s.indexOf('_');
if (i != -1) {
final String s1 = String.valueOf(s.substring(0, i + 1)) + s.substring(i + 1, s.indexOf('.', i)).toUpperCase() + ".lang";
return new ResourceLocation(p_191382_1_.getResourceDomain(), "") {
public String getResourcePath() {
return s1;
}
};
}
}
return p_191382_1_;
}
public boolean resourceExists(ResourceLocation location) {
return this.field_191383_a.resourceExists(func_191382_c(location));
}
public Set<String> getResourceDomains() {
return this.field_191383_a.getResourceDomains();
}
@Nullable
public <T extends net.minecraft.client.resources.data.IMetadataSection> T getPackMetadata(MetadataSerializer metadataSerializer, String metadataSectionName) throws IOException {
return this.field_191383_a.getPackMetadata(metadataSerializer, metadataSectionName);
}
public BufferedImage getPackImage() throws IOException {
return this.field_191383_a.getPackImage();
}
public String getPackName() {
return this.field_191383_a.getPackName();
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\client\resources\LegacyV2Adapter.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ |
package com.tencent.mm.plugin.sns.ui;
import com.tencent.mm.plugin.sns.storage.AdLandingPagesStorage.AdLandingPageComponent.component.widget.verticalviewpager.a.b;
import com.tencent.mm.plugin.sns.storage.AdLandingPagesStorage.c;
class SnsAdNativeLandingPagesUI$4 implements Runnable {
final /* synthetic */ SnsAdNativeLandingPagesUI nSR;
SnsAdNativeLandingPagesUI$4(SnsAdNativeLandingPagesUI snsAdNativeLandingPagesUI) {
this.nSR = snsAdNativeLandingPagesUI;
}
public final void run() {
SnsAdNativeLandingPagesUI.n(this.nSR);
this.nSR.setRequestedOrientation(1);
SnsAdNativeLandingPagesUI.bCS();
((b) SnsAdNativeLandingPagesUI.h(this.nSR).get(Integer.valueOf(((c) this.nSR.nRW.getFirst()).id))).bAw();
SnsAdNativeLandingPagesUI.M(this.nSR);
}
}
|
package pt.ist.sonet.domain;
import pt.ist.fenixframework.pstm.VBox;
import pt.ist.fenixframework.pstm.RelationList;
import pt.ist.fenixframework.pstm.OJBFunctionalSetWrapper;
import pt.ist.fenixframework.ValueTypeSerializationGenerator.*;
public abstract class Url_Base extends pt.ist.sonet.domain.Publication {
private void initInstance() {
initInstance(true);
}
private void initInstance(boolean allocateOnly) {
}
{
initInstance(false);
}
protected Url_Base() {
super();
}
public java.lang.String getUrl() {
pt.ist.fenixframework.pstm.DataAccessPatterns.noteGetAccess(this, "url");
return ((DO_State)this.get$obj$state(false)).url;
}
public void setUrl(java.lang.String url) {
((DO_State)this.get$obj$state(true)).url = url;
}
private java.lang.String get$url() {
java.lang.String value = ((DO_State)this.get$obj$state(false)).url;
return (value == null) ? null : pt.ist.fenixframework.pstm.ToSqlConverter.getValueForString(value);
}
private final void set$url(java.lang.String arg0, pt.ist.fenixframework.pstm.OneBoxDomainObject.DO_State obj$state) {
((DO_State)obj$state).url = (java.lang.String)((arg0 == null) ? null : arg0);
}
public java.lang.Integer getPrice() {
pt.ist.fenixframework.pstm.DataAccessPatterns.noteGetAccess(this, "price");
return ((DO_State)this.get$obj$state(false)).price;
}
public void setPrice(java.lang.Integer price) {
((DO_State)this.get$obj$state(true)).price = price;
}
private java.lang.Integer get$price() {
java.lang.Integer value = ((DO_State)this.get$obj$state(false)).price;
return (value == null) ? null : pt.ist.fenixframework.pstm.ToSqlConverter.getValueForInteger(value);
}
private final void set$price(java.lang.Integer arg0, pt.ist.fenixframework.pstm.OneBoxDomainObject.DO_State obj$state) {
((DO_State)obj$state).price = (java.lang.Integer)((arg0 == null) ? null : arg0);
}
protected void checkDisconnected() {
super.checkDisconnected();
}
protected void readStateFromResultSet(java.sql.ResultSet rs, pt.ist.fenixframework.pstm.OneBoxDomainObject.DO_State state) throws java.sql.SQLException {
super.readStateFromResultSet(rs, state);
DO_State castedState = (DO_State)state;
set$url(pt.ist.fenixframework.pstm.ResultSetReader.readString(rs, "URL"), state);
set$price(pt.ist.fenixframework.pstm.ResultSetReader.readInteger(rs, "PRICE"), state);
}
protected dml.runtime.Relation get$$relationFor(String attrName) {
return super.get$$relationFor(attrName);
}
protected pt.ist.fenixframework.pstm.OneBoxDomainObject.DO_State make$newState() {
return new DO_State();
}
protected void create$allLists() {
super.create$allLists();
}
protected static class DO_State extends pt.ist.sonet.domain.Publication.DO_State {
private java.lang.String url;
private java.lang.Integer price;
protected void copyTo(pt.ist.fenixframework.pstm.OneBoxDomainObject.DO_State newState) {
super.copyTo(newState);
DO_State newCasted = (DO_State)newState;
newCasted.url = this.url;
newCasted.price = this.price;
}
// serialization code
protected Object writeReplace() throws java.io.ObjectStreamException {
return new SerializedForm(this);
}
protected static class SerializedForm extends pt.ist.sonet.domain.Publication.DO_State.SerializedForm {
private static final long serialVersionUID = 1L;
private java.lang.String url;
private java.lang.Integer price;
protected SerializedForm(DO_State obj) {
super(obj);
this.url = obj.url;
this.price = obj.price;
}
Object readResolve() throws java.io.ObjectStreamException {
DO_State newState = new DO_State();
fillInState(newState);
return newState;
}
protected void fillInState(pt.ist.fenixframework.pstm.OneBoxDomainObject.DO_State obj) {
super.fillInState(obj);
DO_State state = (DO_State)obj;
state.url = this.url;
state.price = this.price;
}
}
}
}
|
package ParkingLotSolution;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Reader
{
public static List<String> readFile(String filepath){
List<String> inputs=new ArrayList<>();
if(filepath.length() == 0) {
System.err.println("Please provide input path");
throw new RuntimeException("File Path Not Provided");
//return null;
}
try {
File myObj = new File(filepath);
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
inputs.add(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
return inputs;
}
} |
package com.simbircite.demo.validator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.joda.time.DateTime;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.simbircite.homesecretary.entity.Users;
public class UsersValidator implements Validator {
@Override
public boolean supports(Class<?> type) {
return type.equals(Users.class);
}
@Override
public void validate(Object object, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "name", "required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "password", "required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "email", "required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "birthday", "birthday", "required");
Users user = (Users)object;
if (user.getName().length() < 4) {
errors.rejectValue("name", "name.short", "Name value is too short");
}
if (user.getPassword().length() < 6) {
errors.rejectValue("password", "password.length", "Password must be longer 5 symbols");
}
//TODO: добавить проверку на слишком старые даты
if (user.getBirthday().isAfterNow()
|| user.getBirthday().isBefore(new DateTime().minusYears(100))) {
errors.rejectValue("birthday", "birthday.incorrect", "Birthday value is incorrect");
}
if (!checkEmail(user.getEmail())) {
errors.rejectValue("email", "email.incorrect", "Email value is incorrect");
}
}
private boolean checkEmail(String email) {
Pattern pattern = Pattern.compile(".+@.+\\.[a-z]+");
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
}
|
package spi.movieorganizer.display.view.user;
import spi.movieorganizer.data.movie.UserMovieDO;
import exane.osgi.jexlib.data.manager.filter.AbstractDataObjectFilter;
public class UserMovieDataObjectFilter extends AbstractDataObjectFilter<UserMovieDO> {
private Integer selectedGenreId;
public UserMovieDataObjectFilter() {
this.selectedGenreId = null;
}
@Override
public void clearFilter() {
this.selectedGenreId = null;
}
@Override
public boolean isIncluded(final UserMovieDO userMovieDO) {
if (this.selectedGenreId == null || userMovieDO.getMovie().getGenres().contains(this.selectedGenreId))
return true;
return false;
}
public void setSelectedGenre(final Integer genreId) {
if (this.selectedGenreId != null && this.selectedGenreId.equals(genreId) == false || this.selectedGenreId == null && genreId != null) {
this.selectedGenreId = genreId;
fireDataObjectFilterUpdated();
}
}
}
|
package br.com.treinarminas.academico.Exercicios;
public class RetQtdHorasDoInteiro {
public static void main(String[] args) {
int numero = 1942;
int horas = numero / 60;
int minutos = numero % 60;
System.out.println("Horas: "+horas);
System.out.println("Minutos: "+minutos);
}
}
|
package com.mobica.rnd.parking.parkingbe.model;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.mobica.rnd.parking.parkingbe.deserializer.BooleanDeserializer;
import lombok.*;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
@Document(collection = "cars")
@Getter
@Setter
@NoArgsConstructor
@EqualsAndHashCode
@AllArgsConstructor
@Builder
public class Car {
@Id
private String id;
@DBRef
private User owner;
@Size(min = 1, max = 100)
@NotNull
private String brand;
@NotNull
@Size(min = 1, max = 100)
private String model;
@NotNull
@Size(min = 1, max = 100)
private String color;
@NotNull
@Size(min = 1, max = 100)
private String plateNumber;
@JsonDeserialize(using = BooleanDeserializer.class)
private Boolean activeState;
public Car(String id) {
this.id = id;
}
public Car(String brand, String model, String color, String plateNumber, Boolean activeState) {
this.brand = brand;
this.model = model;
this.color = color;
this.plateNumber = plateNumber;
this.activeState = activeState;
}
public Car(User owner, String brand, String model, String color, String plateNumber, Boolean activeState) {
this.owner = owner;
this.brand = brand;
this.model = model;
this.color = color;
this.plateNumber = plateNumber;
this.activeState = activeState;
}
public Car(String brand, String model, String color, String plateNumber) {
this.brand = brand;
this.model = model;
this.color = color;
this.plateNumber = plateNumber;
}
}
|
package ist.meic.ie.eventsreader;
public class EventsReaderService {
public static void main(String args[]){
EventReader eventsService = new EventReader();
eventsService.receiveEvents();
}
}
|
public class Ascensor {
private int ultimo_piso=1;
public void control(int x)throws Exception{
int a = llamada();
System.out.println("El ascensor se encuentra en el piso; "+a);
int persona = crearPersona();
System.out.println("la persona se encuentra en el piso; "+persona);
elejirpiso(x,persona);
}
public int llamada(){
return ultimo_piso;
}
public int crearPersona(){
//int persona = (int) Math.floor(Math.random()*3+1);
int persona = 3; // para hacer correr el test "eljirUnPisoQueSeaElMismoEnDondeSeEncuentra" quitar comentario a esta linea y volver comentario a ka linea de arriba.
return persona;
}
private void elejirpiso(int destino, int inicio)throws Exception{
if(destino>=4 || destino<=0){
throw new Exception(destino+" esta fuera del rango de pisos del edificio");
}
else if(destino == inicio){
throw new Exception(" debe elejir otro piso que no sea en el que se encuentra");
}
else if(inicio>ultimo_piso){
if(inicio>destino){
System.out.println("El ascensor sube hasta el piso "+inicio+" donde se encuentra la persona");
System.out.println("El asensor baja hasta el piso "+destino+" el piso que la persona elijio");
ultimo_piso=destino;
}
else if(inicio<destino){
System.out.println("El ascensor sube hasta el piso "+inicio+" donde se encuentra la persona");
System.out.println("El asensor sube hasta el piso "+destino+", el piso que la persona elijio");
ultimo_piso=destino;
}
}
else if(inicio == ultimo_piso){
if(inicio>destino){
System.out.println("El asensor baja hasta el piso "+destino+" el piso que la persona elijio");
ultimo_piso=destino;
}
else if(inicio<destino){
System.out.println("El asensor sube hasta el piso "+destino+", el piso que la persona elijio");
ultimo_piso=destino;
}
}
else if(inicio<ultimo_piso){
if(inicio>destino){
System.out.println("El ascensor baja hasta el piso "+inicio+" donde se encuentra la persona");
System.out.println("El asensor baja hasta el piso "+destino+" el piso que la persona elijio");
ultimo_piso=destino;
}
else if(inicio<destino){
System.out.println("El ascensor baja hasta el piso "+inicio+" donde se encuentra la persona");
System.out.println("El asensor sube hasta el piso "+destino+", el piso que la persona elijio");
ultimo_piso=destino;
}
}
}
}
|
/*
* 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 controller.action.getactions.personal;
import controller.action.getactions.ConcreteLink;
import controller.action.getactions.GetAction;
import controller.action.getactions.HomePage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import model.entity.Admin;
import model.entity.User;
/**
* Personal profile
* @author Sasha
*/
public class Profile extends GetAction {
/** title string key value */
private final static String TITLE = "profile.text.title";
/**
* Constructor
*/
public Profile() {
super(TITLE);
}
/**
* Output user profile page
* @return property key value
* @throws ServletException
* @throws IOException
*/
@Override
protected String doExecute() throws ServletException, IOException {
User user = (User) session.getAttribute("user");
if (user != null) {
return configManager.getProperty("path.page.user.profile");
}
Admin admin = (Admin) session.getAttribute("admin");
if (admin != null) {
return configManager.getProperty("path.page.admin.profile");
}
setMessages(null, LOGIN_PLEASE);
return configManager.getProperty(HOME_PAGE);
}
/**
* Get array list of link chain direct to current page (in fact this method
* gets link chain of its' previous page, add its' own link and return
* created array list)
*
* @return array list of links
*/
@Override
public List<ConcreteLink> getLink() {
List<ConcreteLink> links = new ArrayList<>();
links.addAll(new HomePage().getLink());
String linkValue = configManager.getProperty(PROFILE);
String linkName = TITLE;
ConcreteLink concreteLink = new ConcreteLink(linkValue, linkName);
links.add(concreteLink);
return links;
}
}
|
package com.osce.api.system.param;
import com.osce.dto.system.param.ParamDto;
import com.osce.entity.SysParam;
import java.util.List;
/**
* @ClassName: PfParamService
* @Description: 参数服务
* @Author yangtongbin
* @Date 2017/10/10 10:21
*/
public interface PfParamService {
/**
* 获取参数列表
*
* @param dto
* @return
*/
List<SysParam> listParams(ParamDto dto);
/**
* 获取参数总数
*
* @param dto
* @return
*/
Long count(ParamDto dto);
/**
* 获取所有参数
*
* @return
*/
List<SysParam> listAllParam();
/**
* 新增参数
*
* @param dto
* @return
*/
boolean addParam(SysParam dto);
/**
* 编辑参数
*
* @param dto
* @return
*/
boolean editParam(SysParam dto);
/**
* 判断是否存在参数
*
* @param paramCode 参数编码
* @param sysType 作用系统
* @return
*/
boolean isExistParam(String paramCode, String sysType);
/**
* 停用、启用参数
*
* @param list 参数id集合
* @param status 状态
* @return
*/
boolean changeStatus(List<Long> list, String status);
/**
* 根据参数编码获取参数信息
*
* @param paramCode 参数编码
* @return
*/
SysParam selectParamByCode(String paramCode);
}
|
package com.apprisingsoftware.xmasrogue.world;
import com.apprisingsoftware.xmasrogue.entity.Entities;
import com.apprisingsoftware.xmasrogue.util.Coord;
import java.util.Random;
public final class TestRoomBuilder implements MapBuilder {
protected final int width, height, originalSeed, depth;
public TestRoomBuilder(int width, int height, int depth, int originalSeed) {
this.width = width;
this.height = height;
this.depth = depth;
this.originalSeed = originalSeed;
}
@Override public MapTile[][] getMap() {
Random random = new Random((originalSeed * depth) ^ depth);
MapTile[][] map = new MapTile[width][height];
for (int x=0; x<width; x++) {
for (int y=0; y<height; y++) {
if (x == 0 || y == 0 || x == width-1 || y == height-1) {
map[x][y] = new MapTile(Terrain.DUNGEON_WALL);
}
else {
map[x][y] = new MapTile(Terrain.DUNGEON_FLOOR);
}
}
}
if (depth > 0) {
Coord upStaircaseLoc = MapAnalysis.getRandomTile(map, tile -> tile.getTerrain() == Terrain.DUNGEON_FLOOR, random);
map[upStaircaseLoc.x][upStaircaseLoc.y].setTerrain(Terrain.DOWNSTAIRS_S);
}
Coord downStaircaseLoc = MapAnalysis.getRandomTile(map, tile -> tile.getTerrain() == Terrain.DUNGEON_FLOOR, random);
map[downStaircaseLoc.x][downStaircaseLoc.y].setTerrain(Terrain.DOWNSTAIRS_S);
for (int i=0; i<10; i++) {
Coord enemyCoord = MapAnalysis.getRandomTile(map, tile -> tile.getTerrain().isOpen() && tile.getEntity() == null, random);
map[enemyCoord.x][enemyCoord.y].setEntity(Entities.RAT.make());
}
return map;
}
@Override public int getWidth() {
return width;
}
@Override public int getHeight() {
return height;
}
}
|
package com.designpattern.factory.factorymethod;
public class BmwFactory implements CarFactory {
@Override
public Car createCar() {
return new Bmw();
}
}
|
package de.espend.idea.php.annotation.tests.util;
import com.jetbrains.php.lang.PhpFileType;
import de.espend.idea.php.annotation.tests.AnnotationLightCodeInsightFixtureTestCase;
import de.espend.idea.php.annotation.util.PhpDocUtil;
import org.jetbrains.annotations.NotNull;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class PhpDocUtilTest extends AnnotationLightCodeInsightFixtureTestCase {
/**
* @see de.espend.idea.php.annotation.util.PhpDocUtil#getNamespaceForDocIdentifier
*/
public void testNamespaceIsExtractOnStopChar() {
assertEquals("Foo\\Kernel", getPsiElement("@DateTime(Foo\\Ker<caret>nel::VERSION)"));
assertEquals("Foo\\Kernel", getPsiElement("@DateTime(\\Foo\\Ker<caret>nel::VERSION)"));
assertEquals("Foo\\Kernel", getPsiElement("@DateTime(\\Foo\\Ker<caret>nel::VERSION)"));
assertEquals("Foo\\Kernel", getPsiElement("@DateTime(foo=Foo\\Ker<caret>nel::VERSION)"));
assertEquals("Foo\\Kernel", getPsiElement("@DateTime(foo={Foo\\Ker<caret>nel::VERSION)"));
assertEquals("Foo\\Kernel", getPsiElement("@DateTime({Foo\\Ker<caret>nel::VERSION)"));
assertEquals("Foo\\Kernel", getPsiElement("@DateTime(\"Foo\\Ker<caret>nel::VERSION)"));
assertEquals("Kernel", getPsiElement("@DateTime(Ker<caret>nel::VERSION)"));
}
private String getPsiElement(@NotNull String content) {
myFixture.configureByText(PhpFileType.INSTANCE, "<?php" +
"/**\n" +
" * " + content + "\n" +
"*/"
);
return PhpDocUtil.getNamespaceForDocIdentifier(
myFixture.getFile().findElementAt(myFixture.getCaretOffset())
);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.