text stringlengths 10 2.72M |
|---|
package com.pfchoice.springboot.repositories.specifications;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.springframework.data.jpa.domain.Specification;
import com.pfchoice.springboot.model.MembershipClaim;
public class MembershipClaimSpecifications implements Specification<MembershipClaim> {
private String searchTerm;
private Integer insId;
private Integer prvdrId;
private List<Integer> reportMonths;
public MembershipClaimSpecifications(String searchTerm, Integer insId, Integer prvdrId, List<Integer> reportMonths) {
super();
this.searchTerm = searchTerm;
this.insId = insId;
this.prvdrId = prvdrId;
this.reportMonths = reportMonths;
}
public Predicate toPredicate(Root<MembershipClaim> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
String containsLikePattern = getContainsLikePattern(searchTerm);
cq.distinct(true);
Predicate p = cb.conjunction();
if (searchTerm != null && !"".equals(searchTerm)) {
p.getExpressions().add(cb.or(cb.like(cb.lower(root.get("firstName")), containsLikePattern),
cb.like(cb.lower(root.get("lastName")), containsLikePattern)));
}
if (insId != null) {
p.getExpressions().add(cb.and(cb.equal(root.join("ins").get("id"), insId)));
}
if (prvdrId != null) {
p.getExpressions().add(cb.and(cb.equal(root.join("prvdr").get("id"), prvdrId)));
}
p.getExpressions().add(cb.and(cb.equal(root.get("activeInd"), 'Y')));
return p;
}
private static String getContainsLikePattern(String searchTerm) {
if (searchTerm == null || searchTerm.isEmpty()) {
return "%";
} else {
return "%" + searchTerm.toLowerCase() + "%";
}
}
/**
* @return the reportMonths
*/
public List<Integer> getReportMonths() {
return reportMonths;
}
} |
package com.example.cia.work;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
public class Network {
public static String CargarFoto(String FileName, String TypeFile)
{
String result="";
ArrayList<NameValuePair> params;
params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("fileuploaded",FileName));
params.add(new BasicNameValuePair("filetype",TypeFile));
result = GETData("http://www.chispudo.com:8000/cia/webapp/xfile.php?",params);
return result;
}
private static String GETData(String url, ArrayList<NameValuePair> params) {
String datos="";
String linea;
HttpContext mHttpContext = new BasicHttpContext();
DefaultHttpClient mHttpClient = new DefaultHttpClient();
HttpGet mHttpGet = null;
if (params!= null) {
mHttpGet = new HttpGet(url+"&"+ URLEncodedUtils.format(params, "utf-8"));
}else{
mHttpGet = new HttpGet(url);
}
try {
BasicHttpResponse response = (BasicHttpResponse) mHttpClient.execute(mHttpGet,mHttpContext);
InputStream is = response.getEntity().getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while((linea = br.readLine())!=null) {
datos += linea;
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return datos;
}
}
|
package unalcol.types.real;
/**
* @author jgomez
*/
public class LinealScale extends ToZeroOneLinealScale {
protected ToZeroOneLinealScale inverse;
public LinealScale(double min, double max) {
super(min, max);
inverse = null;
}
public LinealScale(double originalMin, double originalMax,
double targetMin, double targetMax) {
super(originalMin, originalMax);
inverse = new ToZeroOneLinealScale(targetMin, targetMax);
}
@Override
public double apply(double x) {
if (inverse != null)
return inverse.inverse(super.apply(x));
else
return super.apply(x);
}
@Override
public double inverse(double x) {
if (inverse != null)
return super.inverse(inverse.apply(x));
else
return super.inverse(x);
}
} |
public class Songbase {
Song[] songs;
public Songbase(Song[] songs) {
this.songs = songs;
}
public Song findByTitle(String title) {
for (int i=0; i < songs.length; i++) {
if ( title.equals(songs[i].getTitle()) ) {
return songs[i];
}
}
return null;
// TODO returns the first ``Song`` instance stored in the array instance variable whose name matches ``title`` and ``null`` if no ``Song`` is found.
}
public Song findByArtist(String artist) {
for (int i=0; i < songs.length; i++) {
if ( artist.equals(songs[i].getArtist()) ){
return songs[i];
}
}
return null;
//TODO returns the first ``Song`` instance stored in the array instance variable that was performed by the artist ``artist`` and ``null`` if no ``Song`` is found.
}
}
|
package com.jrafika.jrafika.processor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.Pair;
import com.jrafika.jrafika.core.Image;
import com.jrafika.jrafika.core.Util;
import java.util.List;
import static com.jrafika.jrafika.core.FaceUtil.getFace;
public class FaceLocalizer implements ImageProcessor {
@Override
public Image proceed(Image image) {
Bitmap bm = image.toBitmap();
Canvas canvas = new Canvas(bm);
List<Util.AreaBox> boundingBoxes = getFace(image);
for (Util.AreaBox area : boundingBoxes) {
Pair<Integer, Integer> upperBound = area.upperBound;
Pair<Integer, Integer> lowerBound = area.lowerBound;
Paint paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.GREEN);
paint.setStrokeWidth(1);
canvas.drawRect(upperBound.first - 1, upperBound.second - 1, lowerBound.first, lowerBound.second, paint);
}
return Image.fromBitmap(bm);
}
}
|
package app.integro.sjbhs.adapters;
import android.content.Context;
import android.content.Intent;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import androidx.cardview.widget.CardView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import app.integro.sjbhs.LeadershipDetailActivity;
import app.integro.sjbhs.R;
import app.integro.sjbhs.models.Leadership;
/**
* Created by gurunath on 06-01-2018.
*/
public class LeadershipPagerAdapter extends PagerAdapter {
private final Context context;
private final ArrayList<Leadership> leadershipArrayList;
public LeadershipPagerAdapter(Context context, ArrayList<Leadership> leadershipArrayList) {
this.context = context;
this.leadershipArrayList = leadershipArrayList;
}
@Override
public int getCount() {
return leadershipArrayList.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return (view == (RelativeLayout) object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView ivImage;
TextView tvName;
TextView tvDesignation;
CardView card_leadership;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.card_leadership, container, false);
ivImage = itemView.findViewById(R.id.ivImage);
tvName = itemView.findViewById(R.id.tvTitle);
tvDesignation = itemView.findViewById(R.id.tvDesignation);
card_leadership = itemView.findViewById(R.id.card_leadership);
final Leadership leadership = leadershipArrayList.get(position);
tvName.setText(leadership.getName());
tvDesignation.setText(leadership.getDesignation());
card_leadership.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Toast.makeText(context, "coming soon", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, LeadershipDetailActivity.class);
intent.putExtra("data", leadership);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
Glide.with(context)
.load(leadershipArrayList.get(position).getImage())
.into(ivImage);
((ViewPager) container).addView(itemView);
return itemView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((RelativeLayout) object);
}
}
|
package org.estore.common.reflect;
import org.apache.commons.lang.StringUtils;
public class ReflectUtils {
public static final String PREFIX_SET = "set";
public static final String PREFIX_GET = "get";
public static String generateMethodName(String fieldName,String prefix){
StringBuffer sb = new StringBuffer();
String firstLetter = fieldName.substring(0, 1);
sb.append(prefix).
append(firstLetter.toUpperCase()).
append(fieldName.substring(1));
return sb.toString();
}
/**
* 将字符串转换为指定的基本数据类型
* @param value
* @param type
* @return 返回null如果value为空字符串
*/
public static Object parseString2PrimitiveDataType(String value,Class type){
Object result = null;
if(StringUtils.isBlank(value)){
return null;
}
if(type == Integer.class || type == int.class){
result = Integer.parseInt(value);
}
else if(type == Long.class || type == long.class){
result = Long.parseLong(value);
}
else if(type == Double.class || type == double.class){
result = Double.parseDouble(value);
}
else if(type == Boolean.class || type == boolean.class){
result = Boolean.parseBoolean(value);
}
else if(type == Float.class || type == float.class){
result = Float.parseFloat(value);
}
else if(type == Byte.class || type == byte.class){
result = Byte.parseByte(value);
}
else if(type == Short.class || type == short.class){
result = Short.parseShort(value);
}
else if((type == Character.class || type == char.class) && value.length() == 1){
result = value.charAt(0);
}
else{
throw new IllegalArgumentException("Type is not a primitive data type!");
}
return result;
}
}
|
package sbnz.integracija.example.models;
import java.util.ArrayList;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import sbnz.integracija.example.enums.WorkoutType;
@NoArgsConstructor
@AllArgsConstructor
public class StrengthWorkout extends Workout{
private int restBetweenSets;
private int restBetweenExercises;
private ArrayList<Exercise> exercises;
public int getRestBetweenSets() {
return restBetweenSets;
}
public void setRestBetweenSets(int restBetweenSets) {
this.restBetweenSets = restBetweenSets;
}
public int getRestBetweenExercises() {
return restBetweenExercises;
}
public void setRestBetweenExercises(int restBetweenExercises) {
this.restBetweenExercises = restBetweenExercises;
}
public ArrayList<Exercise> getExercises() {
return exercises;
}
public void setExercises(ArrayList<Exercise> exercises) {
this.exercises = exercises;
}
public StrengthWorkout(Long id, int difficulty, WorkoutType muscleGroup) {
super(id, difficulty, muscleGroup);
}
}
|
/*
* Copyright 2009 Kjetil Valstadsve
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package vanadis.core.lang;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
public class SieveTest {
@Test
public void simple12() {
Assert.assertEquals(Arrays.asList(3, 5, 7, 11),
Sieve.oddPrimes(12));
}
@Test
public void simple14() {
Assert.assertEquals(Arrays.asList(3, 5, 7, 11, 13),
Sieve.oddPrimes(14));
}
}
|
package com.bnj.indoormap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.bnj.indoormap.NewBuildingFragment.OnFragmentInteractionListener;
public class NewBuildingActivity extends FragmentActivity implements
OnFragmentInteractionListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_building);
}
@Override
public void onFragmentInteraction(Uri uri) {
// TODO Auto-generated method stub
}
}
|
package com.byemisys.cordova;
import org.json.JSONArray;
import org.json.JSONException;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.apache.cordova.PluginResult.Status;
import android.R;
import android.content.Context;
import android.content.Intent;
import android.app.Activity;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import java.io.IOException;
import android.util.Log;
import android.os.Bundle;
public class FamocoLaser extends CordovaPlugin {
private static final int REQUEST_CODE = 1;
private CallbackContext callback = null;
private final String LOG_TAG = "FamocoLaser";
public CordovaInterface cordova = null;
public CallbackContext tryConnectCallback = null;
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
this.cordova = cordova;
}
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if("scan".equals(action)){
try {
callback = callbackContext;
this.cordova.setActivityResultCallback(this);
Intent intent = new Intent("com.famoco.intent.action.SCAN_BARCODE");
this.cordova.startActivityForResult(this, intent, REQUEST_CODE);
return true;
} catch (Exception e) {
Log.e(LOG_TAG, e.getMessage(), e);
callbackContext.error(e.getMessage());
}
} else {
callbackContext.error("FamocoLaserPlugin."+action+" not found !");
return false;
}
return true;
}
@Override
public void onActivityResult(int requestCode,int resultCode,Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (REQUEST_CODE == requestCode && data!=null) {
PluginResult result = new PluginResult(PluginResult.Status.OK, data.getStringExtra("barcode"));
result.setKeepCallback(true);
callback.sendPluginResult(result);
}
else
{
PluginResult result = new PluginResult(PluginResult.Status.ERROR, "no params returned successfully" );
result.setKeepCallback(true);
callback.sendPluginResult(result);
}
}
public Bundle onSaveInstanceState()
{
Bundle state = new Bundle();
return state;
}
public void onRestoreStateForActivityResult(Bundle state, CallbackContext callbackContext)
{
this.callback = callbackContext;
}
} |
package org.openforis.collect.android.gui;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import org.apache.commons.io.FileUtils;
import org.openforis.collect.R;
import org.openforis.collect.android.gui.util.AndroidFiles;
import org.openforis.collect.android.gui.util.AppDirs;
import org.openforis.collect.android.sqlite.AndroidDatabase;
import java.io.File;
import java.io.IOException;
public class Backup {
private FragmentActivity activity;
public Backup(FragmentActivity activity) {
this.activity = activity;
}
public void execute() {
try {
backupToTemp();
showInsertSdCardDialog(activity);
} catch (IOException e) {
String message = activity.getResources().getString(R.string.toast_backed_up_survey);
Log.e("Backup", message, e);
Toast.makeText(activity, message, Toast.LENGTH_LONG).show();
}
}
private static void showInsertSdCardDialog(FragmentActivity activity) {
Intent intent = new Intent();
intent.setAction(AndroidDatabase.ACTION_PREPARE_EJECT);
activity.sendBroadcast(intent);
DialogFragment dialogFragment = new BackupDialogFragment();
dialogFragment.show(activity.getSupportFragmentManager(), "backupInsertSdCard");
}
private void backupToTemp() throws IOException {
File surveysDir = AppDirs.surveysDir(activity);
File tempDir = tempDir(activity);
if (tempDir.exists())
FileUtils.deleteDirectory(tempDir);
FileUtils.copyDirectory(surveysDir, tempDir);
}
private static File tempDir(FragmentActivity activity) {
File surveysDir = AppDirs.surveysDir(activity);
return new File(activity.getExternalCacheDir(), surveysDir.getName());
}
private static void backupFromTempToTargetDir(FragmentActivity activity, File targetDir) throws IOException {
File tempDir = tempDir(activity);
if (targetDir.exists()) {
File timestampedSurveysDir = new File(targetDir.getParentFile(), targetDir.getName() + "-" + System.currentTimeMillis());
FileUtils.moveDirectory(targetDir, timestampedSurveysDir);
AndroidFiles.makeDiscoverable(timestampedSurveysDir, activity);
}
FileUtils.moveDirectory(tempDir, targetDir);
AndroidFiles.makeDiscoverable(targetDir, activity);
}
public static class BackupDialogFragment extends DialogFragment {
public Dialog onCreateDialog(Bundle savedInstanceState) {
final AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
.setMessage(R.string.backup_insert_sd_card)
.setPositiveButton(android.R.string.ok, null)
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try {
FileUtils.deleteDirectory(tempDir(getActivity()));
} catch (IOException ignore) {
}
}
})
.create();
alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
public void onShow(DialogInterface dialog) {
Button button = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
backupFromTempToTargetDir(getActivity(), AppDirs.surveysDir(getActivity()));
alertDialog.dismiss();
String message = getResources().getString(R.string.toast_backed_up_survey, AppDirs.root(getActivity()));
Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();
} catch (Exception ignore) {
}
}
});
}
});
return alertDialog;
}
}
}
|
package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.CRServo;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.Servo;
//import com.qualcomm.robotcore.util.ElapsedTime;
//hello, i am test. dont remove me pls - ok, now u can
/**
* This file contains an minimal example of a Linear "OpMode". An OpMode is a 'program' that runs in either
* the autonomous or the teleop period of an FTC match. The names of OpModes appear on the menu
* of the FTC Driver Station. When an selection is made from the menu, the corresponding OpMode
* class is instantiated on the Robot Controller and executed.
*
* This particular OpMode just executes a basic Tank Drive Teleop for a two wheeled robot
* It includes all the skeletal structure that all linear OpModes contain.
*
* Use Android Studios to Copy this Class, and Paste it into your team's code folder with a new name.
* Remove or comment out the @Disabled line to add this opmode to the Driver Station OpMode list
*/
@TeleOp(name="Hardware may touch this one", group="LinearOpMode")
//@Disabled
public class DriverControlled13475 extends LinearOpMode {
// Declare OpMode members.
//private ElapsedTime runtime = new ElapsedTime();
private DcMotor leftDrive = null;
private DcMotor rightDrive = null;
private DcMotor landerRiser1 = null;
//private DcMotor landerRiser2 = null;
//private DcMotor spinnyArmExt = null;
//private DcMotor spinnyArmTilt1 = null;
//private DcMotor spinnyArmTilt2 = null;
private CRServo spinner1 = null;
private CRServo spinner2 = null;
private Servo dumper1 = null;
private Servo dumper2 = null;
private Servo flippy = null;
private Servo pusher1 = null;
private Servo pusher2 = null;
//private ElapsedTime runtime = new ElapsedTime();
@Override
public void runOpMode() {
setUp();
boolean flipperCount = false;
int spinnerCount = 0;
double servoPower=0;
// run until the end of the match (driver presses STOP)
while (opModeIsActive()) {
//motors
float driveLeft = gamepad1.left_stick_y;
float driveRight = gamepad1.right_stick_y;
float landerRiserpwr = gamepad1.left_trigger - gamepad1.right_trigger;
//float spinnyArmExtpwr = gamepad2.right_trigger - gamepad2.left_trigger;
/*
while (gamepad2.dpad_down) {//in
spinnyArmTilt1.setPower(-.5);
spinnyArmTilt2.setPower(-.5);
spinnyArmExt.setPower(-.11);
}
while (gamepad2.dpad_up) {//out
spinnyArmTilt1.setPower(.5);
spinnyArmTilt2.setPower(.5);
spinnyArmExt.setPower(.11);
}
if (!(gamepad2.dpad_up || gamepad2.dpad_down)) {
spinnyArmTilt1.setPower(0);
spinnyArmTilt2.setPower(0);
spinnyArmExt.setPower(0);
}
*/
leftDrive.setPower(driveLeft);
rightDrive.setPower(driveRight);
landerRiser1.setPower(landerRiserpwr);
/*
landerRiser2.setPower(landerRiserpwr);
//spinnyArmExt.setPower(spinnyArmExtpwr);
//servos code
//Spinners
if (gamepad2.x) {//spin in
spinner2.setPower(-1);
spinner1.setPower(1);
spinnerCount = 1;
} else if (gamepad2.a) {//spin stop
spinner2.setPower(0);
spinner1.setPower(0);
spinnerCount = 2;
} else if (gamepad2.b) {//spin out
spinner2.setPower(1);
spinner1.setPower(-1);
spinnerCount = 0;
}
//dumper
if (gamepad2.right_bumper) {
dumper1.setPosition(.5);
dumper2.setPosition(.5);
}
if (gamepad2.left_bumper) {
dumper1.setPosition(.002);
dumper2.setPosition(.002);
}*/
//flipper
if (gamepad2.y) {
if (flipperCount == false) {
flippy.setPosition(0);
flipperCount = true;
} else if (flipperCount == true) {
flippy.setPosition(1);
flipperCount = false;
}
}
if(gamepad2.dpad_down){
pusher2.setPosition(0);
pusher1.setPosition(0);
}
if(gamepad2.dpad_up){
pusher2.setPosition(1);
pusher1.setPosition(1);
/*
runtime.reset();
while (true) {
runtime.startTime();
pusher2.setPosition(servoPower);
pusher1.setPosition(servoPower);
servoPower = (runtime.milliseconds() * runtime.milliseconds()) / 10000000;
if ((servoPower >= 1) || !gamepad2.dpad_up) {
servoPower = 0;
break;*/
//make a cool down code
}
//feedback();
}
}
private void setUp(){
//telemetry.addData("Status", "Initializing. Or is it?");
//telemetry.update();
leftDrive = hardwareMap.get(DcMotor.class, "left_drive");
rightDrive = hardwareMap.get(DcMotor.class, "right_drive");
landerRiser1 = hardwareMap.get(DcMotor.class, "lander_riser1");
//landerRiser2 = hardwareMap.get(DcMotor.class, "lander_riser2");
//spinnyArmExt = hardwareMap.get(DcMotor.class, "spinny_arm_ext");
//spinnyArmTilt1 = hardwareMap.get(DcMotor.class, "spinny_arm_tilt1");
//spinnyArmTilt2 = hardwareMap.get(DcMotor.class, "spinny_arm_tilt2");
//spinner1 = hardwareMap.crservo.get("spinner1");
//spinner2 = hardwareMap.crservo.get( "spinner2");
//dumper1= hardwareMap.servo.get("dumper1");
//dumper2= hardwareMap.servo.get("dumper2");
flippy= hardwareMap.servo.get("flippy_flipper");
pusher1= hardwareMap.servo.get("pusher1");
pusher2= hardwareMap.servo.get("pusher2");
//spinnyArmExt.setDirection(DcMotor.Direction.REVERSE);
//spinnyArmTilt1.setDirection(DcMotor.Direction.FORWARD);
//spinnyArmTilt2.setDirection(DcMotor.Direction.REVERSE);
leftDrive.setDirection(DcMotor.Direction.FORWARD);
rightDrive.setDirection(DcMotor.Direction.REVERSE);
pusher2.setDirection(Servo.Direction.REVERSE);
// Wait for the game to start (driver presses PLAY)
waitForStart();
//runtime.reset();
}
private void feedback () {
//Show the elapsed game time and wheel power.
//telemetry.addData("Status", "Run Time: " + runtime.toString());
//telemetry.addData("Motors", "left (%.2f), right (%.2f)", leftDrive, rightDrive);
//telemetry.update();
}
} |
package com.smxknife.flowable.demo;
public class HolidayResponse {
}
|
package cn.canlnac.onlinecourse.domain;
import java.util.List;
/**
* 评论列表.
*/
public class CommentList {
private int total;
private List<Comment> comments;
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public List<Comment> getComments() {
return comments;
}
public void setComments(List<Comment> comments) {
this.comments = comments;
}
}
|
package fr.lteconsulting.training.moviedb.model;
import javax.persistence.*;
@Entity
public class Produit {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@ManyToOne
private Categorie categorie;
@ManyToOne
private Fabricant fabricant;
private String nom;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Categorie getCategorie() {
return categorie;
}
public void setCategorie(Categorie categorie) {
this.categorie = categorie;
}
public Fabricant getFabricant() {
return fabricant;
}
public void setFabricant(Fabricant fabricant) {
this.fabricant = fabricant;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
}
|
package ObjetConnecte;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class Chauffage extends ObjetConnecte {
private float temperature;
private final float tempMin = (float) 5.0;
private final float tempMax = (float) 40.0;
public Chauffage(String nom, String type, String piece, float consoHoraire, String
droitAccess, float temperature) throws SQLException {
super(nom, type, piece, consoHoraire, droitAccess);
this.temperature = temperature;
this.envoyerDonnee();
}
public Chauffage(Chauffage chauff) throws SQLException {
super(chauff.nom, chauff.type, chauff.piece, chauff.consoHoraire, chauff.droitAcces);
temperature = chauff.temperature;
this.envoyerDonnee();
}
public Chauffage(ResultSet rs, ResultSet rs2) throws SQLException {
super(rs);
if(rs2.getRow()>0){
this.temperature = rs2.getFloat("temperature");
}
}
public float getTemperature() {
return temperature;
}
public void setTemperature(float temperature) {
if (temperature >= this.tempMax)
{
this.temperature = tempMax;
}
else if (temperature <= tempMin)
{
this.temperature = tempMin;
}
else
this.temperature = temperature;
String sql = "UPDATE Chauffage " +
"SET temperature = " + this.temperature +
" where num_objet = " + idObjet + " and mail_utilisateur =";
Routeur r1 = Routeur.getInstance();
r1.envoyerRequete(sql);
String req = constuireRequeteHistorique("changeTemperature");
r1.envoyerRequete(req);
}
public float getTempMin() {
return tempMin;
}
public float getTempMax() {
return tempMax;
}
@Override
public void envoyerDonnee() {
Routeur r1 = Routeur.getInstance();
r1.envoyerRequete(this.construireRequeteObjet());
r1.envoyerRequete(this.construireRequeteFille());
String S1 = constuireRequeteHistorique("Creation");
r1.envoyerRequete(S1);
}
@Override
public String constuireRequeteHistorique(String typeOp) {
String s1 = "insert into HistoriqueObjet values( ," + idObjet + ", ,\""+ nom +"\","+ "\"" + type + "\"," + etat + "," + consoHoraire + "," +
"\"" + droitAcces + "\",\"" + convertirDate(LocalDateTime.now()) + "\",\"" + typeOp + "\",\"" + temperature + " " + tempMax + " " + tempMin + "\");";
return s1;
}
@Override
public String construireRequeteFille() {
String s = "insert into Chauffage values(" + idObjet + ", ," + temperature + "," + tempMax + "," + tempMin + ");";
return s;
}
@Override
public String toString() {
return "Chauffage{" +
"temperature=" + temperature +
", tempMin=" + tempMin +
", tempMax=" + tempMax +
"} " + super.toString();
}
@Override
public long recupDuree() {
return 0;
}
}
|
package com.tencent.mm.ui.chatting.gallery;
import com.tencent.mm.g.a.la;
import com.tencent.mm.modelcdntran.f;
import com.tencent.mm.modelvideo.o;
import com.tencent.mm.modelvideo.s;
import com.tencent.mm.modelvideo.t;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.sdk.b.c;
import com.tencent.mm.sdk.platformtools.ah;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.chatting.gallery.l.1;
class i$4 extends c<la> {
final /* synthetic */ i tWK;
i$4(i iVar) {
this.tWK = iVar;
this.sFo = la.class.getName().hashCode();
}
private boolean a(la laVar) {
if (!i.f(this.tWK).NS(laVar.bVm.mediaId)) {
return false;
}
if (laVar.bVm.retCode == 0 || laVar.bVm.retCode == -21006) {
String nK;
int i;
l f;
switch (laVar.bVm.bOh) {
case 1:
l f2 = i.f(this.tWK);
long j = (long) laVar.bVm.offset;
long j2 = laVar.bVm.bVn;
boolean z = laVar.bVm.bVo;
x.i("MicroMsg.OnlineVideoUIHelper", "deal moov ready moovPos[%d] needSeekTime[%d] timeDuration[%d] startDownload[%d %d]", new Object[]{Long.valueOf(j), Integer.valueOf(f2.elG), Integer.valueOf(f2.elF), Long.valueOf(j2), Long.valueOf(f2.dQj)});
if (f2.elF != 0) {
x.w("MicroMsg.OnlineVideoUIHelper", "moov had callback, do nothing.");
} else {
if (j2 <= f2.dQj) {
j2 = f2.dQj;
}
f2.dQj = j2;
h.mEJ.a(354, 5, 1, false);
f2.nPP = bi.VF();
o.Ta();
nK = s.nK(f2.filename);
try {
if (f2.elE == null) {
x.w("MicroMsg.OnlineVideoUIHelper", "parser is null, thread is error.");
} else if (f2.elE.s(nK, j)) {
f2.elF = f2.elE.eyV;
x.i("MicroMsg.OnlineVideoUIHelper", "mp4 parse moov success. duration %d filename %s isFastStart %b", new Object[]{Integer.valueOf(f2.elF), f2.filename, Boolean.valueOf(z)});
if (!z) {
ah.A(new 1(f2));
}
if (f2.elG == -1) {
f2.elD = 1;
} else {
f2.elD = 2;
}
h.mEJ.a(354, 7, 1, false);
} else {
x.w("MicroMsg.OnlineVideoUIHelper", "mp4 parse moov error.");
o.Tb();
f.g(f2.mediaId, 0, -1);
t.V(f2.filename, 15);
h.mEJ.a(354, 8, 1, false);
x.w("MicroMsg.OnlineVideoUIHelper", "%d rpt parse moov fail %s ", new Object[]{Integer.valueOf(f2.hashCode()), f2.filename});
h.mEJ.h(13836, new Object[]{Integer.valueOf(302), Long.valueOf(bi.VE()), ""});
}
} catch (Throwable e) {
x.printErrStackTrace("MicroMsg.OnlineVideoUIHelper", e, "", new Object[0]);
x.e("MicroMsg.OnlineVideoUIHelper", "deal moov ready error: " + e.toString());
}
}
i.a(this.tWK, true);
break;
case 2:
l f3 = i.f(this.tWK);
nK = laVar.bVm.mediaId;
i = laVar.bVm.offset;
int i2 = laVar.bVm.length;
f3.elM = false;
if (i < 0 || i2 < 0) {
x.w("MicroMsg.OnlineVideoUIHelper", "deal data available error offset[%d], length[%d]", new Object[]{Integer.valueOf(i), Integer.valueOf(i2)});
} else if (f3.NS(nK)) {
Integer num = (Integer) f3.nPL.get(f3.mediaId + i + "_" + i2);
if (num == null || num.intValue() <= 0) {
try {
f3.elJ = f3.elE.bw(i, i2);
} catch (Throwable e2) {
x.printErrStackTrace("MicroMsg.OnlineVideoUIHelper", e2, "", new Object[0]);
x.e("MicroMsg.OnlineVideoUIHelper", "deal data available file pos to video time error: " + e2.toString());
}
} else {
f3.elJ = num.intValue();
}
x.i("MicroMsg.OnlineVideoUIHelper", "deal data available. offset[%d] length[%d] cachePlayTime[%d]", new Object[]{Integer.valueOf(i), Integer.valueOf(i2), Integer.valueOf(f3.elJ)});
}
if (laVar.bVm.length > 0) {
this.tWK.bS(true);
break;
}
break;
case 3:
this.tWK.bS(true);
break;
case 4:
f = i.f(this.tWK);
x.i("MicroMsg.OnlineVideoUIHelper", "deal stream finish. playStatus %d ", new Object[]{Integer.valueOf(f.elD)});
f.elM = false;
f.elC = 3;
if (f.elD == 0) {
x.w("MicroMsg.OnlineVideoUIHelper", "it had not moov callback and download finish start to play video.");
f.bCx();
h.mEJ.a(354, 6, 1, false);
} else if (f.elD == 5) {
x.w("MicroMsg.OnlineVideoUIHelper", "it had play error, it request all video data finish, start to play." + f.mediaId);
f.bCx();
}
f.cxD();
h.mEJ.a(354, 26, 1, false);
this.tWK.bS(true);
break;
case 5:
f = i.f(this.tWK);
String str = laVar.bVm.mediaId;
i = laVar.bVm.offset;
if (f.NS(str)) {
f.nPN = (i * 100) / f.fhf;
x.i("MicroMsg.OnlineVideoUIHelper", "deal progress callback. downloadedPercent : " + f.nPN);
}
if (f.nPN >= 100) {
f.elC = 3;
break;
}
break;
case 6:
f = i.f(this.tWK);
x.i("MicroMsg.OnlineVideoUIHelper", "deal had dup video.");
f.cxD();
f.bCx();
break;
default:
x.w("MicroMsg.Imagegallery.handler.video", "unknown event opcode " + laVar.bVm.bOh);
break;
}
return false;
}
x.w("MicroMsg.Imagegallery.handler.video", "stream download online video error. retCode: " + laVar.bVm.retCode);
i.a(this.tWK, laVar.bVm.mediaId, laVar.bVm.retCode);
return false;
}
}
|
package leecode.dfs;
public class 二叉搜索树的最近公共祖先_235 {
//直接使用 lee236的解题方法
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) {
return null;
}
if (root == p || root == q) {
return root;
}
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if (left == null && right == null) {
return null;
}
if (left == null) {
return right;
}
if (right == null) {
return left;
}
return root;
}
/*
利用二叉搜索树的性质:p.val 和 q.val 都比 root.val 小,那么 p、q 肯定在 root 的左子树。
p 和 q 的值不满足都大于(小于)root.val:
1、p 和 q 分居 root 的左右子树。
2、root 就是 p,q 在 p 的子树中。
3、root 就是 q,p 在 q 的子树中
*/
public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {
if(root.val>p.val&&root.val>q.val){
return lowestCommonAncestor2(root.left,p,q);
}
if(root.val<p.val&&root.val<q.val){
return lowestCommonAncestor2(root.right,p,q);
}
return root;
}
//如果 p 和 q 的节点值都小于 root.val,它们都在 root 的左子树,root = root.left
//
//其他情况,当前的 root 就是最近公共祖先,结束遍历, break。
public TreeNode lowestCommonAncestor3(TreeNode root, TreeNode p, TreeNode q) {
while (root!=null){
if(root.val>p.val&&root.val>q.val){
root=root.left;
}else if(root.val<p.val&&root.val<q.val){
root=root.right;
}else {
break;
}
}
return root;
}
} |
/*
* 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 jssctest;
/**
*
* @author eth
*/
public interface ICOMObservable {
public void addCOMObserver(ICOMObserver readObserver);
public void removeCOMObserver(ICOMObserver readObserver);
public void notifyCOMObservers(ICOMObserver.COMObserverEvents event);
public void addCOMConnectObserver(ICOMConnectObserver com_connect_observer);
public String getCOMData();
public String getStringMessage();
}
|
package com.info.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("*.htm")
public class Fcontroller extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
EmployeeController controller = new EmployeeController();
String action = request.getServletPath();
if(action.equals("/Register.htm"))
{
controller.registerEmployee(request, response);
}
else if(action.equals("/Login.htm"))
{
controller.loginEmployee(request, response);
}
else if(action.equals("/Details.htm"))
{
controller.employeeDetails(request, response);
}
else if(action.equals("/ViewList.htm")) {
controller.employeeList(request, response);
}
}
} |
package com.wyt.export_account.bean;
/**
* @Author: LL
* @Description:
* @Date:Create:in 2021/1/19 15:01
*/
public class UserInfo {
private String accountId;
private String userName;
public UserInfo() {
}
public UserInfo(String accountId, String userName) {
this.accountId = accountId;
this.userName = userName;
}
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
|
package pl.wojtech.weather.model;
/**
* Created by Wojtech on 2018-02-26.
*/
public class WeatherForecastData {
private float temperature;
private float pressure;
private int humidity;
private long forecastTimeStamp;
public void setTemperature(float temperature) {
this.temperature = temperature;
}
public float getTemperature() {
return temperature;
}
public void setPressure(float pressure) {
this.pressure = pressure;
}
public float getPressure() {
return pressure;
}
public void setHumidity(int humidity) {
this.humidity = humidity;
}
public int getHumidity() {
return humidity;
}
public void setForecastTimeStamp(long forecastTimeStamp) {
this.forecastTimeStamp = forecastTimeStamp;
}
public long getForecastTimeStamp() {
return forecastTimeStamp;
}
}
|
package consulting.ross.demo.osgi.impl.envmon;
import consulting.ross.demo.osgi.envmon.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import static java.util.concurrent.TimeUnit.*;
import java.util.logging.Logger;
/**
* A deliberately-simplistic implementation, with
* one sensor / alarm only.
*/
public class EnvironmentMonitorImpl implements EnvironmentMonitor
{
private static Logger logger = Logger.getLogger(EnvironmentMonitorImpl.class.getName());
ScheduledExecutorService es;
Long pollDelayMs = 2000L;
Double maxTemperature = 30.0;
volatile Sensor sensor;
volatile Alarm alarm;
@Override
public SurveyResult performSurvey()
{
// Check technical requirements (system error if not met)
if (sensor == null)
throw new RuntimeException("Not connected to a Sensor");
if (alarm == null)
throw new RuntimeException("Not connected to an alarm");
SurveyResult r = new SurveyResult();
r.setMaxAllowed( maxTemperature );
Double measuredAvg = sensor.measureTemperature();
r.getMeasurements().put("sensor", measuredAvg);
r.setMeasuredAverage( measuredAvg );
if (measuredAvg > maxTemperature)
{
alarm.activate();
r.setAlarmWasRaised( true );
}
else
{
r.setAlarmWasRaised( false );
}
logger.info("Completed environment survey: " + r);
return r;
}
@Override
public void startMonitoring()
{
if (es == null)
{
es = Executors.newScheduledThreadPool(2);
logger.info("Scheduling survey for every "
+ pollDelayMs + "ms");
es.scheduleWithFixedDelay( () ->
performSurvey(),
0, pollDelayMs, MILLISECONDS);
}
else
{
// This is an idempotent service
logger.warning("Auto-monitoring already started (every "
+ pollDelayMs + "ms)");
}
}
@Override
public void stopMonitoring()
{
// This is an idempotent service
if (es == null || es.isShutdown())
{
logger.warning("Auto-monitoring already stopped");
return;
}
es.shutdownNow();
es = null;
resetAlarms();
}
@Override
public void resetAlarms()
{
if (alarm != null)
alarm.deActivate();
}
}
|
package com.tencent.mm.plugin.report.b;
import com.tencent.mm.protocal.c.apw;
import com.tencent.mm.protocal.c.bhy;
import com.tencent.mm.protocal.k;
import com.tencent.mm.protocal.k.b;
import com.tencent.mm.protocal.k.d;
import com.tencent.mm.protocal.y;
import com.tencent.mm.sdk.platformtools.bi;
public class b$a extends d implements b {
public apw mDL = new apw();
public final byte[] Ie() {
this.qWA = y.cgs();
this.mDL.rhB = new bhy().bq(bi.ciV());
this.mDL.shX = k.a(this);
return this.mDL.toByteArray();
}
public final int If() {
return 694;
}
public final int getCmdId() {
return 0;
}
}
|
package com.elepy.models.props;
import com.elepy.annotations.Number;
import com.elepy.models.FieldType;
import com.elepy.models.NumberType;
import com.elepy.models.Property;
import com.elepy.utils.ReflectionUtils;
import java.lang.reflect.AccessibleObject;
public class NumberPropertyConfig implements PropertyConfig {
private final float minimum;
private final float maximum;
private final NumberType numberType;
public NumberPropertyConfig(float minimum, float maximum, NumberType numberType) {
this.minimum = minimum;
this.maximum = maximum;
this.numberType = numberType;
}
public static NumberPropertyConfig of(AccessibleObject field) {
return of(field, ReflectionUtils.returnTypeOf(field));
}
//This method was made to get number configuration from arrays by passing the actual generic class type
public static NumberPropertyConfig of(AccessibleObject field, Class<?> actualNumberType) {
final Number annotation = field.getAnnotation(Number.class);
return new NumberPropertyConfig(
annotation == null ? Integer.MIN_VALUE : annotation.minimum(),
annotation == null ? Integer.MAX_VALUE : annotation.maximum(),
NumberType.guessType(actualNumberType)
);
}
public static NumberPropertyConfig of(Property property) {
return new NumberPropertyConfig(
property.getExtra("minimum"),
property.getExtra("maximum"),
property.getExtra("numberType")
);
}
@Override
public void config(Property property) {
property.setType(FieldType.NUMBER);
property.setExtra("minimum", minimum);
property.setExtra("maximum", maximum);
property.setExtra("numberType", numberType);
}
public float getMinimum() {
return minimum;
}
public float getMaximum() {
return maximum;
}
}
|
package com.sdk4.boot.fileupload;
import lombok.Data;
import java.util.Map;
/**
* 文件上传配置
*
* @author sh
*/
@Data
public class FileUploadConfig {
private String accessBaseUrl;
private Map<String, FileTypeConfig> files;
private Map<String, StorageProvider> provider;
}
|
package icn.core;
import java.io.IOException;
import java.util.HashMap;
import java.util.Properties;
import org.projectfloodlight.openflow.types.DatapathId;
public class IcnConfiguration {
public static IcnConfiguration instance = null;
private Properties props = new Properties();
private HashMap<String, String> dpidToSwitch = new HashMap<String, String>();
public static IcnConfiguration getInstance() {
if (instance == null)
instance = new IcnConfiguration();
return instance;
}
public IcnConfiguration() {
try {
props.load(this.getClass()
.getResourceAsStream("/icnApp.properties"));
} catch (IOException e) {
props.setProperty("virtualIP", "10.0.99.99"); // default
e.printStackTrace();
}
fillDpidToSwitchMap();
}
private void fillDpidToSwitchMap() {
dpidToSwitch.put(getS1(), "s1");
dpidToSwitch.put(getS2(), "s2");
dpidToSwitch.put(getS3(), "s3");
dpidToSwitch.put(getS4(), "s4");
dpidToSwitch.put(getS5(), "s5");
dpidToSwitch.put(getS6(), "s6");
dpidToSwitch.put(getS7(), "s7");
}
public String getSwitchFromDpid(String dpid) {
return dpidToSwitch.get(dpid);
}
public String getVirtualIP() {
return props.getProperty("virtualIP");
}
public String getS1() {
return props.getProperty("s1");
}
public String getS2() {
return props.getProperty("s2");
}
public String getS3() {
return props.getProperty("s3");
}
public String getS4() {
return props.getProperty("s4");
}
public String getS5() {
return props.getProperty("s5");
}
public String getS6() {
return props.getProperty("s6");
}
public String getS7() {
return props.getProperty("s7");
}
public Integer getMaxShortestRoutes() {
return Integer.parseInt(props.getProperty("maxRoutes"));
}
public Integer getRouteLengthDelta() {
return Integer.parseInt(props.getProperty("lengthDelta"));
}
public Integer getPathLengthAspirationLevel() {
return Integer.parseInt(props.getProperty("pathLengthAL"));
}
public Integer getPathLenghtReservationLevel() {
return Integer.parseInt(props.getProperty("pathLengthRL"));
}
public Integer getBandwidthAspirationLevel() {
return Integer.parseInt(props.getProperty("bandwidthAL"));
}
public Integer getBandwidthReservationLevel() {
return Integer.parseInt(props.getProperty("bandwidthRL"));
}
public String getMacForIp(String ip) {
IcnModule.logger.info("MAC="+props.getProperty(ip));
return props.getProperty(ip);
}
}
|
package go.nvhieucs.notins.config;
import com.datastax.oss.driver.api.core.CqlSession;
import com.datastax.oss.driver.api.core.metadata.EndPoint;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import org.springframework.data.cassandra.config.AbstractCassandraConfiguration;
import org.springframework.data.cassandra.config.SchemaAction;
import org.springframework.data.cassandra.repository.config.EnableCassandraRepositories;
import java.net.InetSocketAddress;
import java.nio.file.Path;
import java.nio.file.Paths;
@Profile("production")
@Configuration
@EnableCassandraRepositories(basePackages = "go.nvhieucs.notins.model")
public class CassandraProductionConfig extends AbstractCassandraConfiguration {
@Value("${spring.data.cassandra.keyspace-name}")
private String keyspaceName;
@Value("${spring.data.cassandra.contact-point}")
private String contactPoint;
@Value("${spring.data.cassandra.port}")
private Integer port;
@Value("${spring.data.cassandra.username}")
private String username;
@Value("${spring.data.cassandra.password}")
private String password;
@Value("${spring.data.cassandra.local-datacenter}")
private String datacenter;
@Override
protected String getKeyspaceName() {
return keyspaceName;
}
@Override
public String[] getEntityBasePackages() {
return new String[]{"go.nvhieucs.notins.model"};
}
@Override
protected String getContactPoints() {
return contactPoint;
}
@Override
protected int getPort() {
return port;
}
@Override
public SchemaAction getSchemaAction() {
return SchemaAction.CREATE_IF_NOT_EXISTS;
}
@Bean
@Primary
public CqlSession session() {
return CqlSession.builder().withAuthCredentials(username, password)
.withCloudSecureConnectBundle(Paths.get("secure-connect-notinstagram.zip"))
.withLocalDatacenter("production",datacenter)
.withKeyspace(keyspaceName).build();
}
}
|
/*
* UniTime 3.2 - 3.5 (University Timetabling Application)
* Copyright (C) 2008 - 2013, UniTime LLC, and individual contributors
* as indicated by the @authors tag.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* 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, see <http://www.gnu.org/licenses/>.
*
*/
package org.unitime.timetable.action;
import java.io.OutputStream;
import java.util.Date;
import java.util.TreeSet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.unitime.timetable.form.ExamGridForm;
import org.unitime.timetable.interfaces.RoomAvailabilityInterface;
import org.unitime.timetable.model.ExamPeriod;
import org.unitime.timetable.model.ExamType;
import org.unitime.timetable.model.Session;
import org.unitime.timetable.model.dao.ExamTypeDAO;
import org.unitime.timetable.model.dao.SessionDAO;
import org.unitime.timetable.security.SessionContext;
import org.unitime.timetable.security.rights.Right;
import org.unitime.timetable.solver.exam.ExamSolverProxy;
import org.unitime.timetable.solver.service.SolverService;
import org.unitime.timetable.util.ExportUtils;
import org.unitime.timetable.util.LookupTables;
import org.unitime.timetable.util.RoomAvailability;
import org.unitime.timetable.webutil.timegrid.PdfExamGridTable;
/**
* @author Tomas Muller
*/
@Service("/examGrid")
public class ExamGridAction extends Action {
@Autowired SessionContext sessionContext;
@Autowired SolverService<ExamSolverProxy> examinationSolverService;
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
ExamGridForm myForm = (ExamGridForm) form;
// Check Access
sessionContext.checkPermission(Right.ExaminationTimetable);
// Read operation to be performed
String op = (myForm.getOp()!=null?myForm.getOp():request.getParameter("op"));
if (op==null && request.getParameter("resource")!=null) op="Change";
if ("Change".equals(op) || "Export PDF".equals(op)) {
myForm.save(sessionContext);
}
myForm.load(sessionContext);
if (myForm.getExamType() == null) {
TreeSet<ExamType> types = ExamType.findAllUsed(sessionContext.getUser().getCurrentAcademicSessionId());
if (!types.isEmpty())
myForm.setExamType(types.first().getUniqueId());
}
if ("Cbs".equals(op)) {
if (request.getParameter("resource")!=null)
myForm.setResource(Integer.parseInt(request.getParameter("resource")));
if (request.getParameter("filter")!=null)
myForm.setFilter(request.getParameter("filter"));
}
if (RoomAvailability.getInstance()!=null && myForm.getExamType() != null) {
Session session = SessionDAO.getInstance().get(sessionContext.getUser().getCurrentAcademicSessionId());
Date[] bounds = ExamPeriod.getBounds(session, myForm.getExamType());
String exclude = ExamTypeDAO.getInstance().get(myForm.getExamType()).getType() == ExamType.sExamTypeFinal ? RoomAvailabilityInterface.sFinalExamType : RoomAvailabilityInterface.sMidtermExamType;
if (bounds != null) {
RoomAvailability.getInstance().activate(session,bounds[0],bounds[1],exclude,false);
RoomAvailability.setAvailabilityWarning(request, session, myForm.getExamType(), true, false);
}
}
PdfExamGridTable table = new PdfExamGridTable(myForm, sessionContext, examinationSolverService.getSolver());
request.setAttribute("table", table);
if ("Export PDF".equals(op)) {
OutputStream out = ExportUtils.getPdfOutputStream(response, "timetable");
table.export(out);
out.flush(); out.close();
return null;
}
myForm.setOp("Change");
LookupTables.setupExamTypes(request, sessionContext.getUser().getCurrentAcademicSessionId());
return mapping.findForward("showGrid");
}
}
|
package com.shivam;
public interface Coach {
String getRoutine();
String getDiet();
String coachGivesTution();
}
|
package com.tinnova.exercicio4;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Multiplos {
private static final Logger LOGGER = LoggerFactory.getLogger(Multiplos.class);
private Multiplos() {
// não instanciar
}
public static Long calcularMultiplos(Long numeroUm, Long numeroDois, Long intervalo) {
Long resultado = 0L;
for (Long i = 0L; i < intervalo; i++) {
if (i % numeroUm == 0 || i % numeroDois == 0) {
resultado += i;
}
}
LOGGER.info(resultado.toString());
return resultado;
}
}
|
package day38_inheritance_part2_2;
import day38_inheritance_part2.B;
public class BTest extends B {
public static void main(String[] args) {
BTest obj = new BTest();
obj.display();
}
}
|
package fr.car;
public class CarTemplate {
private String couleur;
private Integer id;
private Integer prix;
public String getCouleur() {
return couleur;
}
public void setCouleur(String couleur) {
this.couleur = couleur;
}
public Integer getPrix() {
return prix;
}
public void setPrix(Integer prix) {
this.prix = prix;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
|
package com.tencent.mm.model;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class u {
private static volatile u dAX;
private Map<String, c> dAY = new a((byte) 0);
public static u Hx() {
if (dAX == null) {
synchronized (u.class) {
if (dAX == null) {
dAX = new u();
}
}
}
return dAX;
}
private u() {
}
public final b ia(String str) {
c cVar = (c) this.dAY.get(str);
if (cVar != null) {
return cVar.dBa;
}
return null;
}
public final b v(String str, boolean z) {
c cVar = (c) this.dAY.get(str);
if (cVar == null) {
if (!z) {
return null;
}
cVar = new c();
this.dAY.put(str, cVar);
}
return cVar.dBa;
}
public final b ib(String str) {
c cVar = (c) this.dAY.remove(str);
if (cVar != null) {
return cVar.dBa;
}
return null;
}
public static String ic(String str) {
return "SessionId@" + str + "#" + System.nanoTime();
}
public String toString() {
long currentTimeMillis = System.currentTimeMillis();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("DataCenter \nDataStore size : ").append(this.dAY.size());
Set<Entry> linkedHashSet = new LinkedHashSet(this.dAY.entrySet());
for (Entry entry : linkedHashSet) {
if (entry != null) {
c cVar = (c) entry.getValue();
if (cVar != null) {
stringBuilder.append("\nDataStore id : ").append((String) entry.getKey());
stringBuilder.append(", CT : ").append(cVar.dBb).append("ms");
stringBuilder.append(", TTL : ").append((currentTimeMillis - cVar.dBb) / 1000).append("s");
}
}
}
linkedHashSet.clear();
return stringBuilder.toString();
}
}
|
/**
* MOTECH PLATFORM OPENSOURCE LICENSE AGREEMENT
*
* Copyright (c) 2010-11 The Trustees of Columbia University in the City of
* New York and Grameen Foundation USA. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of Grameen Foundation USA, Columbia University, or
* their respective contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY GRAMEEN FOUNDATION USA, COLUMBIA UNIVERSITY
* AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRAMEEN FOUNDATION
* USA, COLUMBIA UNIVERSITY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.motechproject.server.omod.impl;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;
import org.motechproject.server.service.ContextService;
import org.openmrs.Person;
import org.openmrs.Relationship;
import org.openmrs.RelationshipType;
import org.openmrs.api.PersonService;
import java.util.ArrayList;
import java.util.List;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class RelationshipServiceImplTest {
private ContextService contextService;
private PersonService personService;
private RelationshipServiceImpl service;
RelationshipType relationshipType;
private static final String PARENT_CHILD = "Parent/Child";
@Before
public void setUp() {
contextService = createMock(ContextService.class);
personService = createMock(PersonService.class);
relationshipType = new RelationshipType(1);
relationshipType.setName(PARENT_CHILD);
relationshipType.setaIsToB("Parent");
relationshipType.setbIsToA("Child");
service = new RelationshipServiceImpl();
service.setContextService(contextService);
}
@Test
public void shouldCreateMotherRelationshipIfNoneExists() {
Person mother = new Person(1);
Person child = new Person(2);
List<Relationship> emptyRelationships = new ArrayList<Relationship>();
Relationship relationship = new Relationship(mother, child, relationshipType);
relationship.setId(1);
expect(contextService.getPersonService()).andReturn(personService).anyTimes();
expect(personService.getRelationshipTypeByName(PARENT_CHILD)).andReturn(relationshipType).times(2);
expect(personService.getRelationships(null, child, relationshipType)).andReturn(emptyRelationships);
expect(personService.saveRelationship(EasyMock.<Relationship>anyObject())).andReturn(relationship);
replay(contextService, personService);
Relationship motherChildRelationship = service.saveOrUpdateMotherRelationship(mother, child, true);
verify(contextService, personService);
assertEquals(motherChildRelationship.getPersonA().getId(), relationship.getPersonA().getId());
assertEquals(motherChildRelationship.getPersonB().getId(), relationship.getPersonB().getId());
assertEquals(motherChildRelationship.getRelationshipType(), relationship.getRelationshipType());
}
@Test
public void shouldEditExistingMotherChildRelationship() {
Person mother = new Person(1);
Person oldMother = new Person(4);
Person child = new Person(2);
List<Relationship> oldRelationships = new ArrayList<Relationship>();
Relationship oldRelationship = new Relationship(oldMother, child, relationshipType);
oldRelationship.setId(1);
oldRelationships.add(oldRelationship);
Relationship expectedRelationship = new Relationship(mother, child, relationshipType);
expect(contextService.getPersonService()).andReturn(personService).anyTimes();
expect(personService.getRelationshipTypeByName(eq(PARENT_CHILD))).andReturn(relationshipType).atLeastOnce();
expect(personService.getRelationships(null, child, relationshipType)).andReturn(oldRelationships).times(2);
expect(personService.saveRelationship(EasyMock.<Relationship>anyObject())).andReturn(oldRelationship);
replay(contextService, personService);
Relationship motherChildRelationship = service.saveOrUpdateMotherRelationship(mother, child, true);
verify(contextService, personService);
assertEquals(oldRelationship,motherChildRelationship);
assertEquals(expectedRelationship.getPersonA().getId(), oldRelationship.getPersonA().getId());
assertEquals(expectedRelationship.getPersonB().getId(), oldRelationship.getPersonB().getId());
assertEquals(expectedRelationship.getRelationshipType(), oldRelationship.getRelationshipType());
}
@Test
public void shouldVoidMotherChildRelationship() {
Person oldMother = new Person(4);
Person child = new Person(2);
List<Relationship> oldRelationships = new ArrayList<Relationship>();
Relationship oldRelationship = new Relationship(oldMother, child, relationshipType);
oldRelationship.setId(1);
oldRelationships.add(oldRelationship);
Relationship voidRelationship = oldRelationship.copy();
voidRelationship.setVoided(true);
expect(contextService.getPersonService()).andReturn(personService).anyTimes();
expect(personService.getRelationshipTypeByName(eq(PARENT_CHILD))).andReturn(relationshipType);
expect(personService.getRelationships(null, child, relationshipType)).andReturn(oldRelationships);
expect(personService.voidRelationship(EasyMock.<Relationship>anyObject(),EasyMock.<String>anyObject())).andReturn(voidRelationship);
expect(personService.saveRelationship(EasyMock.<Relationship>anyObject())).andReturn(voidRelationship);
replay(contextService, personService);
Relationship motherChildRelationship = service.saveOrUpdateMotherRelationship(null, child, true);
verify(contextService, personService);
assertTrue(motherChildRelationship.isVoided());
}
@Test
public void shouldNotVoidMotherChildRelationship() {
Person oldMother = new Person(4);
Person child = new Person(2);
List<Relationship> oldRelationships = new ArrayList<Relationship>();
Relationship oldRelationship = new Relationship(oldMother, child, relationshipType);
oldRelationship.setId(1);
oldRelationships.add(oldRelationship);
Relationship voidRelationship = oldRelationship.copy();
voidRelationship.setVoided(true);
expect(contextService.getPersonService()).andReturn(personService).anyTimes();
expect(personService.getRelationshipTypeByName(eq(PARENT_CHILD))).andReturn(relationshipType);
expect(personService.getRelationships(null, child, relationshipType)).andReturn(oldRelationships);
replay(contextService, personService);
Relationship motherChildRelationship = service.saveOrUpdateMotherRelationship(null, child, false);
verify(contextService, personService);
assertFalse(motherChildRelationship.isVoided());
}
}
|
/**
*
*/
package com.cnk.travelogix.setup;
import de.hybris.platform.commerceservices.setup.AbstractSystemSetup;
import de.hybris.platform.core.initialization.SystemSetup;
import de.hybris.platform.core.initialization.SystemSetup.Process;
import de.hybris.platform.core.initialization.SystemSetup.Type;
import de.hybris.platform.core.initialization.SystemSetupContext;
import de.hybris.platform.core.initialization.SystemSetupParameter;
import java.util.Collections;
import java.util.List;
import com.cnk.travelogix.constants.PaymentgatewaysConstants;
/**
*
*/
@SystemSetup(extension = PaymentgatewaysConstants.EXTENSIONNAME)
public class PaymentgatewaysCoreSystemSetup extends AbstractSystemSetup
{
@Override
public List<SystemSetupParameter> getInitializationOptions()
{
return Collections.emptyList();
}
@SystemSetup(type = Type.PROJECT, process = Process.ALL)
public void createEssentialData(final SystemSetupContext context)
{
importImpexFile(context, "/paymentgateways/import/paymentgateways/MappingUserSelectedValueToPaymentGatewayCodes.impex");
}
}
|
package fr.unice.polytech.clapevents.tools;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import fr.unice.polytech.clapevents.model.Event;
public class DataBaseHelper extends SQLiteOpenHelper {
private static String DB_PATH = "/data/data/fr.unice.polytech.clapevents/databases/";
private static String DB_NAME = "clap";
private Context myContext;
private SQLiteDatabase myDataBase;
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (!dbExist) {
//By calling this method and empty database will be created into the default system path
//of your application so we are gonna be able to overwrite that database with our database.
this.getReadableDatabase();
try {
// Copy the database in assets to the application database.
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database", e);
}
}
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
//database doesn't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null;
}
private void copyDataBase() throws IOException {
InputStream myInput = myContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException, IOException {
//Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
public void openDataBaseWrite() throws SQLException, IOException {
//Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
@Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (newVersion > oldVersion){
try {
copyDataBase();
}catch (IOException e){
e.printStackTrace();
}
}
}
public List<Event> getAllEventsDate(String city, String category) {
Cursor cursor = myDataBase.rawQuery("SELECT * FROM event WHERE place=? AND bigCategory=? ORDER BY date", new String[] {city, category});
cursor.moveToFirst();
List<Event> events = new ArrayList<>();
while (!cursor.isAfterLast()) {
events.add(new Event(cursor.getInt(cursor.getColumnIndexOrThrow("_id")),
cursor.getString(cursor.getColumnIndexOrThrow("title")),
cursor.getString(cursor.getColumnIndexOrThrow("artists")),
cursor.getString(cursor.getColumnIndexOrThrow("date")),
cursor.getString(cursor.getColumnIndexOrThrow("place")),
cursor.getString(cursor.getColumnIndexOrThrow("address")),
cursor.getString(cursor.getColumnIndexOrThrow("category")),
cursor.getString(cursor.getColumnIndexOrThrow("description")),
cursor.getString(cursor.getColumnIndexOrThrow("media_path")),
cursor.getString(cursor.getColumnIndexOrThrow("media_path2")),
cursor.getString(cursor.getColumnIndexOrThrow("media_path3")),
cursor.getString(cursor.getColumnIndexOrThrow("media_path4")),
cursor.getInt(cursor.getColumnIndexOrThrow("age")),
cursor.getInt(cursor.getColumnIndexOrThrow("price")),
cursor.getInt(cursor.getColumnIndexOrThrow("favorite"))==1,
cursor.getInt(cursor.getColumnIndexOrThrow("tickets"))
));
cursor.moveToNext();
}
cursor.close();
return events;
}
public List<Event> getAllEventsPrice(String city, String category) {
Cursor cursor = myDataBase.rawQuery("SELECT * FROM event WHERE place=? AND bigCategory=? ORDER BY price", new String[] {city, category});
cursor.moveToFirst();
List<Event> events = new ArrayList<>();
while (!cursor.isAfterLast()) {
events.add(new Event(cursor.getInt(cursor.getColumnIndexOrThrow("_id")),
cursor.getString(cursor.getColumnIndexOrThrow("title")),
cursor.getString(cursor.getColumnIndexOrThrow("artists")),
cursor.getString(cursor.getColumnIndexOrThrow("date")),
cursor.getString(cursor.getColumnIndexOrThrow("place")),
cursor.getString(cursor.getColumnIndexOrThrow("address")),
cursor.getString(cursor.getColumnIndexOrThrow("category")),
cursor.getString(cursor.getColumnIndexOrThrow("description")),
cursor.getString(cursor.getColumnIndexOrThrow("media_path")),
cursor.getString(cursor.getColumnIndexOrThrow("media_path2")),
cursor.getString(cursor.getColumnIndexOrThrow("media_path3")),
cursor.getString(cursor.getColumnIndexOrThrow("media_path4")),
cursor.getInt(cursor.getColumnIndexOrThrow("age")),
cursor.getInt(cursor.getColumnIndexOrThrow("price")),
cursor.getInt(cursor.getColumnIndexOrThrow("favorite"))==1,
cursor.getInt(cursor.getColumnIndexOrThrow("tickets"))
));
cursor.moveToNext();
}
cursor.close();
return events;
}
public List<Event> getAllEventsCategoryDate(String city, String category, String category2) {
Log.e("category", category);
Cursor cursor = myDataBase.rawQuery("SELECT * FROM event WHERE place=? AND bigCategory=? AND category=? ORDER BY date", new String[] {city, category, category2});
cursor.moveToFirst();
List<Event> events = new ArrayList<>();
while (!cursor.isAfterLast()) {
events.add(new Event(cursor.getInt(cursor.getColumnIndexOrThrow("_id")),
cursor.getString(cursor.getColumnIndexOrThrow("title")),
cursor.getString(cursor.getColumnIndexOrThrow("artists")),
cursor.getString(cursor.getColumnIndexOrThrow("date")),
cursor.getString(cursor.getColumnIndexOrThrow("place")),
cursor.getString(cursor.getColumnIndexOrThrow("address")),
cursor.getString(cursor.getColumnIndexOrThrow("category")),
cursor.getString(cursor.getColumnIndexOrThrow("description")),
cursor.getString(cursor.getColumnIndexOrThrow("media_path")),
cursor.getString(cursor.getColumnIndexOrThrow("media_path2")),
cursor.getString(cursor.getColumnIndexOrThrow("media_path3")),
cursor.getString(cursor.getColumnIndexOrThrow("media_path4")),
cursor.getInt(cursor.getColumnIndexOrThrow("age")),
cursor.getInt(cursor.getColumnIndexOrThrow("price")),
cursor.getInt(cursor.getColumnIndexOrThrow("favorite"))==1,
cursor.getInt(cursor.getColumnIndexOrThrow("tickets"))
));
cursor.moveToNext();
}
cursor.close();
return events;
}
public List<Event> getAllEventsCategoryPrice(String city, String category, String category2) {
Cursor cursor = myDataBase.rawQuery("SELECT * FROM event WHERE place=? AND bigCategory=? AND category=? ORDER BY price", new String[] {city, category, category2});
cursor.moveToFirst();
List<Event> events = new ArrayList<>();
while (!cursor.isAfterLast()) {
events.add(new Event(cursor.getInt(cursor.getColumnIndexOrThrow("_id")),
cursor.getString(cursor.getColumnIndexOrThrow("title")),
cursor.getString(cursor.getColumnIndexOrThrow("artists")),
cursor.getString(cursor.getColumnIndexOrThrow("date")),
cursor.getString(cursor.getColumnIndexOrThrow("place")),
cursor.getString(cursor.getColumnIndexOrThrow("address")),
cursor.getString(cursor.getColumnIndexOrThrow("category")),
cursor.getString(cursor.getColumnIndexOrThrow("description")),
cursor.getString(cursor.getColumnIndexOrThrow("media_path")),
cursor.getString(cursor.getColumnIndexOrThrow("media_path2")),
cursor.getString(cursor.getColumnIndexOrThrow("media_path3")),
cursor.getString(cursor.getColumnIndexOrThrow("media_path4")),
cursor.getInt(cursor.getColumnIndexOrThrow("age")),
cursor.getInt(cursor.getColumnIndexOrThrow("price")),
cursor.getInt(cursor.getColumnIndexOrThrow("favorite"))==1,
cursor.getInt(cursor.getColumnIndexOrThrow("tickets"))
));
cursor.moveToNext();
}
cursor.close();
return events;
}
public List<Event> getFavoriteEvents() {
Cursor cursor = myDataBase.rawQuery("SELECT * FROM event WHERE favorite = 1 ORDER BY date", null);
cursor.moveToFirst();
List<Event> events = new ArrayList<>();
while (!cursor.isAfterLast()) {
events.add(new Event(cursor.getInt(cursor.getColumnIndexOrThrow("_id")),
cursor.getString(cursor.getColumnIndexOrThrow("title")),
cursor.getString(cursor.getColumnIndexOrThrow("artists")),
cursor.getString(cursor.getColumnIndexOrThrow("date")),
cursor.getString(cursor.getColumnIndexOrThrow("place")),
cursor.getString(cursor.getColumnIndexOrThrow("address")),
cursor.getString(cursor.getColumnIndexOrThrow("category")),
cursor.getString(cursor.getColumnIndexOrThrow("description")),
cursor.getString(cursor.getColumnIndexOrThrow("media_path")),
cursor.getString(cursor.getColumnIndexOrThrow("media_path2")),
cursor.getString(cursor.getColumnIndexOrThrow("media_path3")),
cursor.getString(cursor.getColumnIndexOrThrow("media_path4")),
cursor.getInt(cursor.getColumnIndexOrThrow("age")),
cursor.getInt(cursor.getColumnIndexOrThrow("price")),
cursor.getInt(cursor.getColumnIndexOrThrow("favorite"))==1,
cursor.getInt(cursor.getColumnIndexOrThrow("tickets"))
));
cursor.moveToNext();
}
cursor.close();
return events;
}
public List<Event> getTicketsEvents() {
Cursor cursor = myDataBase.rawQuery("SELECT * FROM event WHERE tickets != 0 ORDER BY date DESC", null);
cursor.moveToFirst();
List<Event> events = new ArrayList<>();
while (!cursor.isAfterLast()) {
events.add(new Event(cursor.getInt(cursor.getColumnIndexOrThrow("_id")),
cursor.getString(cursor.getColumnIndexOrThrow("title")),
cursor.getString(cursor.getColumnIndexOrThrow("artists")),
cursor.getString(cursor.getColumnIndexOrThrow("date")),
cursor.getString(cursor.getColumnIndexOrThrow("place")),
cursor.getString(cursor.getColumnIndexOrThrow("address")),
cursor.getString(cursor.getColumnIndexOrThrow("category")),
cursor.getString(cursor.getColumnIndexOrThrow("description")),
cursor.getString(cursor.getColumnIndexOrThrow("media_path")),
cursor.getString(cursor.getColumnIndexOrThrow("media_path2")),
cursor.getString(cursor.getColumnIndexOrThrow("media_path3")),
cursor.getString(cursor.getColumnIndexOrThrow("media_path4")),
cursor.getInt(cursor.getColumnIndexOrThrow("age")),
cursor.getInt(cursor.getColumnIndexOrThrow("price")),
cursor.getInt(cursor.getColumnIndexOrThrow("favorite"))==1,
cursor.getInt(cursor.getColumnIndexOrThrow("tickets"))
));
cursor.moveToNext();
}
cursor.close();
return events;
}
public void addToFavorite(int id){
try{
openDataBaseWrite();
myDataBase.execSQL("UPDATE event SET favorite = 1 WHERE _id = "+id);
close();
}catch (Exception e){
System.out.print(e);
}
}
public void deleteFromFavorite(int id){
try{
openDataBaseWrite();
myDataBase.execSQL("UPDATE event SET favorite = 0 WHERE _id = "+id);
close();
}catch (Exception e){
System.out.print(e);
}
}
public void tickets(int id, int tickets){
try{
openDataBaseWrite();
myDataBase.execSQL("UPDATE event SET tickets = "+ tickets +" WHERE _id = "+id);
close();
}catch (Exception e){
System.out.print(e);
}
}
public boolean isFavorite(String id){
int favorite = 0;
try{
openDataBaseWrite();
Cursor cursor = myDataBase.rawQuery("SELECT * FROM event WHERE _id = ?", new String[] {id});
cursor.moveToFirst();
favorite = cursor.getInt(cursor.getColumnIndexOrThrow("favorite"));
close();
return favorite == 1;
}catch (Exception e){
System.out.print(e);
return false;
}
}
}
|
package com.tencent.mm.plugin.nearby.ui;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import com.tencent.mm.R;
import com.tencent.mm.ui.base.l;
import com.tencent.mm.ui.base.n.c;
import com.tencent.mm.ui.widget.a.d;
class NearbyFriendsUI$14 implements OnMenuItemClickListener {
final /* synthetic */ NearbyFriendsUI lCf;
NearbyFriendsUI$14(NearbyFriendsUI nearbyFriendsUI) {
this.lCf = nearbyFriendsUI;
}
public final boolean onMenuItemClick(MenuItem menuItem) {
d dVar = new d(this.lCf, 1, false);
dVar.ofq = new 1(this);
dVar.ofp = new c() {
public final void a(l lVar) {
lVar.eR(-1, R.l.nearby_friend_location_findmm);
lVar.eR(-1, R.l.nearby_friend_location_findgg);
lVar.eR(-1, R.l.nearby_friend_location_findall);
lVar.eR(-1, R.l.say_hi_list_lbs_title);
lVar.eR(-1, R.l.nearby_friend_clear_location_exit);
}
};
dVar.bXO();
return true;
}
}
|
package com.tencent.mm.af;
import android.os.Process;
import com.tencent.mm.af.c.b;
import com.tencent.mm.af.c.c;
import com.tencent.mm.af.c.d;
import com.tencent.mm.model.bx;
import com.tencent.mm.sdk.f.e;
import com.tencent.mm.sdk.platformtools.ad;
import com.tencent.mm.sdk.platformtools.x;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
public final class a {
private static boolean ahg = false;
private static final c dQT = new c();
private static boolean dQU = true;
private static long dQV = 0;
private static long dQW = 0;
private static Thread thread = null;
public static final void bI(boolean z) {
boolean z2 = !ad.getContext().getSharedPreferences("system_config_prefs", 4).getBoolean("msg_delay_close_detect", false);
dQU = z2;
if (z2) {
ahg = z;
if (z) {
x.i("MicroMsg.ActiveDetector", "[oneliang]active, time%s, pid:%s", new Object[]{Long.valueOf(System.currentTimeMillis()), Integer.valueOf(Process.myPid())});
if (thread != null) {
thread.interrupt();
}
thread = null;
dQT.clear();
dQV = bx.IR();
return;
}
x.i("MicroMsg.ActiveDetector", "[oneliang]unactive, time%s, pid:%s", new Object[]{Long.valueOf(System.currentTimeMillis()), Integer.valueOf(Process.myPid())});
if (thread == null) {
Thread b = e.b(dQT, "ProcessDetector_" + Process.myPid());
thread = b;
b.start();
dQT.dRn = true;
}
dQW = bx.IR();
}
}
public static boolean bm(long j) {
if (dQV <= 0 || dQW <= 0 || j <= 0) {
return false;
}
if (dQV >= dQW) {
if (j < dQV) {
return false;
}
return true;
} else if (j >= dQW) {
return false;
} else {
return true;
}
}
public static void hD(int i) {
if (dQU && !ahg) {
c cVar = dQT;
cVar.dRh.dRp.add(new com.tencent.mm.af.c.a(bx.IR(), System.currentTimeMillis(), i));
}
}
public static void hE(int i) {
if (dQU && !ahg) {
c cVar = dQT;
cVar.dRh.dRq.add(new com.tencent.mm.af.c.a(bx.IR(), System.currentTimeMillis(), i));
}
}
public static void a(long j, long j2, long j3, long j4, long j5) {
if (dQU) {
c cVar = dQT;
x.i("MicroMsg.ActiveDetector.ProcessDetector", "[oneliang]delayed msg[%s]", new Object[]{new c(Process.myPid(), j, j2, j3, j4, j5).toString()});
cVar.dRh.dRr.add(r0);
}
}
public static void hF(int i) {
dQT.dRf = i;
}
public static List<a> Oa() {
if (!ad.cic()) {
return null;
}
b bVar;
b bVar2;
a a;
String str = dQT.dRl;
String str2 = str + "/mm";
String str3 = str + "/push";
try {
bVar = (b) b.l(new FileInputStream(str2));
} catch (Exception e) {
x.e("MicroMsg.ActiveDetector", "%s,read exception:" + e.getMessage(), new Object[]{str2});
bVar = null;
}
try {
bVar2 = (b) b.l(new FileInputStream(str3));
} catch (Exception e2) {
x.e("MicroMsg.ActiveDetector", "%s,read exception:" + e2.getMessage(), new Object[]{str3});
bVar2 = null;
}
List<a> arrayList = new ArrayList();
if (bVar != null) {
for (d a2 : bVar.dRo) {
a = a(a2, 0);
if (a != null) {
arrayList.add(a);
}
}
for (com.tencent.mm.af.c.a a3 : bVar.dRq) {
a = a(a3, 3);
if (a != null) {
arrayList.add(a);
}
}
for (c cVar : bVar.dRr) {
Object obj;
if (cVar == null) {
obj = null;
} else {
a aVar = new a();
aVar.pid = cVar.pid;
aVar.dQX = cVar.dQX;
aVar.startTime = cVar.dRs;
aVar.endTime = cVar.dRs;
aVar.type = 4;
aVar.dRc = cVar.dRc;
aVar.dRd = cVar.dRd;
aVar.dRe = cVar.dRe;
a = aVar;
}
if (obj != null) {
arrayList.add(obj);
}
}
}
if (bVar2 != null) {
for (d a22 : bVar2.dRo) {
a = a(a22, 1);
if (a != null) {
arrayList.add(a);
}
}
for (com.tencent.mm.af.c.a a32 : bVar2.dRp) {
a = a(a32, 2);
if (a != null) {
arrayList.add(a);
}
}
}
Collections.sort(arrayList);
return arrayList;
}
static String bn(long j) {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date(j));
}
private static a a(d dVar, int i) {
if (dVar == null) {
return null;
}
a aVar = new a();
aVar.dQX = dVar.dRt;
aVar.startTime = dVar.startTime;
aVar.endTime = dVar.endTime;
aVar.type = i;
aVar.pid = dVar.pid;
aVar.dQZ = dVar.dQZ;
if (i != 1) {
return aVar;
}
aVar.dQY = dVar.dQY;
aVar.dRa = dVar.dRa;
return aVar;
}
private static a a(com.tencent.mm.af.c.a aVar, int i) {
if (aVar == null) {
return null;
}
a aVar2 = new a();
aVar2.dQX = aVar.dQX;
aVar2.startTime = aVar.time;
aVar2.endTime = aVar.time;
aVar2.type = i;
aVar2.dRb = aVar.type;
return aVar2;
}
}
|
package com.cisco.jwt_spring_boot.controllers;
import com.cisco.jwt_spring_boot.entities.AppRole;
import com.cisco.jwt_spring_boot.entities.AppUser;
import com.cisco.jwt_spring_boot.entities.request.RegisterForm;
import com.cisco.jwt_spring_boot.services.AccountService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.jayway.jsonpath.JsonPath;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import java.util.ArrayList;
import java.util.Collection;
import static org.mockito.Mockito.doReturn;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@SpringBootTest
@AutoConfigureMockMvc
class AccountRestControllerTest {
private static AppUser appUser1;
private static AppUser appUser2;
private static AppUser appUser3;
@MockBean
private AccountService accountService;
@Autowired
private MockMvc mockMvc;
@BeforeAll
public static void init() {
Collection<AppRole> roles = new ArrayList<>();
roles.add(new AppRole(null, "PHARMACIEN"));
//appUser1 = new AppUser("Gael", "12345", roles, "gael@example.com");
appUser2 = new AppUser("Yolande", "1234", roles, "yolande@example.com");
appUser3 = new AppUser("Adele", "1234", roles, "adele@example.com");
}
@Test
@DisplayName("POST /api/account/register")
void register() throws Exception {
RegisterForm registerForm = new RegisterForm("Gael", "1234", "1234", "gael@example.com", null, null, null, null, "+221000000000", "PHARMACIEN");
doReturn(appUser1).when(accountService).registerUser(registerForm);
mockMvc.perform(post("/api/account/register")
.contentType(MediaType.APPLICATION_JSON)
.content(asJsonString(registerForm)))
.andExpect(status().isForbidden());
}
/*
@Test
void updatePasswordValid() {
RegisterForm registerForm = new RegisterForm("Gael", "1234", "1234", "gael@example.com", null, null, null, null, "+221000000000", "PHARMACIEN");
appUser1 = accountRestController.updatePassword(registerForm);
assertThat(accountService.findUserByUsername(registerForm.getUsername()).getPassword(), is(registerForm.getPassword()));
}
@Test
void updatePasswordNotValid() {
RegisterForm registerForm = new RegisterForm("Gael", "1234", "12345", "gael@example.com", null, null, null, null, "+221000000000", "PHARMACIEN");
assertThat(accountRestController.updatePassword(registerForm), instanceOf(RuntimeException.class));
}
@Test
void recover() {
}
@Test
void verifyEmail() {
}
@Test
void users_WhenNoRecord() {
Mockito.when(accountService.allUsers()).thenReturn(Arrays.asList());
assertThat(accountRestController.users().size(), is(0));
Mockito.verify(accountService, Mockito.times(1)).allUsers();
}
@Test
void users_WhenRecord() {
Mockito.when(accountService.allUsers()).thenReturn(Arrays.asList(appUser3,appUser2));
assertThat(accountRestController.users().size(), is(2));
Mockito.verify(accountService, Mockito.times(1)).allUsers();
}
*/
static String asJsonString(final Object obj) {
try {
return new ObjectMapper().writeValueAsString(obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
} |
package com.tencent.mm.ui.chatting.viewitems;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import com.tencent.mm.model.au;
import com.tencent.mm.plugin.subapp.c.a;
import com.tencent.mm.ui.chatting.viewitems.ak.4.1;
class ak$4$1$2 implements OnCancelListener {
final /* synthetic */ 1 ueX;
final /* synthetic */ a ueY;
ak$4$1$2(1 1, a aVar) {
this.ueX = 1;
this.ueY = aVar;
}
public final void onCancel(DialogInterface dialogInterface) {
au.DF().c(this.ueY);
au.DF().b(331, ak.b(this.ueX.ueW.ueT));
ak.a(this.ueX.ueW.ueT, null);
if (ak.c(this.ueX.ueW.ueT) != null) {
ak.c(this.ueX.ueW.ueT).dismiss();
}
}
}
|
package com.lqs.hrm.service;
import java.util.List;
import com.lqs.hrm.entity.Department;
/**
* 部门Service接口
* @author Administrator
*
*/
public interface DepartmentService {
/**
* 根据部门id查询
* @param deptId
* @return
*/
Department get(Integer deptId);
/**
* 通过部门主管职位id查询
* @param managePositionId
* @return
*/
List<Department> getByManagePositionId(Integer managePositionid);
/**
* 根据部门名称查询
* @param deptName
* @return
*/
List<Department> listByDeptName(String deptName);
/**
* 根据部门级别id查询
* @param dlId
* @return
*/
List<Department> listByDlId(Integer dlId);
/**
* 根据部门id,部门名称查询
* @param deptId
* @param deptName
* @return
*/
List<Department> listByDeptIdName(Integer deptId, String deptName);
/**
* 根据部门id,部门级别id查询
* @param deptId
* @param dlId
* @return
*/
List<Department> listByDeptIdDlId(Integer deptId, Integer dlId);
/**
* 根据部门名称,部门级别id查询
* @param deptName
* @param dlId
* @return
*/
List<Department> listByDeptNameDlId(String deptName, Integer dlId);
/**
* 根据部门id,部门名称,部门级别id查询
* @param deptId
* @param deptName
* @param manageEmpjobid
* @return
*/
List<Department> listByDeptIdNameDlId(Integer deptId, String deptName, Integer dlId);
/**
* @return 查询出所有部门信息
*/
List<Department> listByNo();
int insert(Department department);
int update(Department department);
int delete(Integer deptId);
/**
* 根据部门名称模糊查询
* @param deptName
* @return
*/
List<Department> listLikeDeptName(String deptName);
/**
* 根据上级部门id查询所有子部门信息
* @param parentId
* @return
*/
List<Department> listByParentId(Integer parentId);
}
|
package de.jmda.app.uml.shape;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
import org.junit.Before;
import org.junit.Test;
import de.jmda.app.uml.shape.MovablePointProperty;
public class JUTMovablePointPropertySized0
{
private MovablePointProperty movablePointProperty;
@Before public void before() { movablePointProperty = new MovablePointProperty(0,0); }
@Test public void movablePointPropertyIsNotNull()
{
assertThat(movablePointProperty, is(not(nullValue())));
}
@Test public void movablePointPropertyXIsNotNull()
{
assertThat(movablePointProperty.getX(), is(not(nullValue())));
}
@Test public void movablePointPropertyYIsNotNull()
{
assertThat(movablePointProperty.getY(), is(not(nullValue())));
}
@Test public void movablePointPropertyPointIsNotNull()
{
assertThat(movablePointProperty.getPoint(), is(not(nullValue())));
}
@Test public void movablePointPropertyPointXIsNotNull()
{
assertThat(movablePointProperty.getPoint().getX(), is(not(nullValue())));
}
@Test public void movablePointPropertyPointYIsNotNull()
{
assertThat(movablePointProperty.getPoint().getY(), is(not(nullValue())));
}
} |
package model.service;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import model.dao.MovieDao;
import model.dao.MyCinemaDao;
import model.vo.mycinema.BoardVO;
import model.vo.mycinema.ListVO;
import model.vo.mycinema.ListVOGenericMap;
import model.vo.mycinema.MemberVO;
import model.vo.mycinema.PagingBean;
public class MyCinemaService {
private MyCinemaDao myCinemaDao;
private MovieDao movieDao;
public void setMovieDao(MovieDao movieDao){
this.movieDao=movieDao;
}
public void setMyCinemaDao(MyCinemaDao myCinemaDao) {
this.myCinemaDao = myCinemaDao;
}
public void registerMember(MemberVO vo) throws SQLException{
System.out.println("멤버");
myCinemaDao.registerMember(vo);
}
public boolean idcheck(String id) throws SQLException {
boolean result=false;
if(myCinemaDao.idcheck(id)!=null)
result=true;
return result;
}
public MemberVO login(MemberVO vo) throws SQLException{
Object obj = myCinemaDao.login(vo);
MemberVO mvo = null;
if(obj!=null){
mvo = (MemberVO)obj;
}
return mvo;
}
public ListVO getBoardList(String pageNo) throws SQLException{
//System.out.println("넌 왜??");
if(pageNo==null||pageNo=="") // 목록보기 버튼 누를 경우 최신 글을 보여주기 위해 setting
pageNo="1";
List<BoardVO> list=myCinemaDao.getBoardList(pageNo);
//System.out.println(list+"목록");
int total=myCinemaDao.totalContent();
PagingBean paging=new PagingBean(total,Integer.parseInt(pageNo));
ListVO lvo=new ListVO(list,paging);
//System.out.println(lvo+"목록보기");
return lvo;
}
public void write(BoardVO bvo) throws SQLException{
int no=myCinemaDao.write(bvo);
String date=myCinemaDao.selectByNoForDate(no);
bvo.setWrite_date(date);
System.out.println(bvo+"글쓰기 in service");
}
public BoardVO show(String board_no) throws SQLException{
System.out.println("내용보기");
System.out.println(board_no+" "+"show");
myCinemaDao.updateCount(board_no);
//System.out.println("show 이동");
return myCinemaDao.show(board_no);
}
public BoardVO showNoCount(String no) throws SQLException{
return myCinemaDao.show(no);
}
public void updateBoard(BoardVO bvo) throws SQLException{
//System.out.println("바꾸자!!");
myCinemaDao.updateBoard(bvo);
}
public void deleteBoard(String no) throws SQLException{
myCinemaDao.deleteBoard(no);
}
public void reply(BoardVO bvo) throws SQLException{
//System.out.println("작동 중입니다.");
//System.out.println(bvo+"reply");
int ref = bvo.getRef();
int restep = bvo.getRestep();
int relevel = bvo.getRelevel();
/*System.out.println(ref+"reply");
System.out.println(restep+""+"reply+");
System.out.println(relevel+""+"reply");*/
myCinemaDao.updateRestep(ref, restep);
//update 처리 후 입력 전에 restep값 과 relevel의 값을 1증가 한다.
//- 즉 원본 글의 것 보다 1씩 커야 하므로.
bvo.setRestep(restep+1);
bvo.setRelevel(relevel+1);
int no = myCinemaDao.insertRefContent(bvo);//답변 글 입력
bvo.setBoard_no(no);
String date=myCinemaDao.selectByNoForDate(no);
bvo.setWrite_date(date);
}
public void updateMember(MemberVO vo) throws SQLException{
myCinemaDao.updateMember(vo);
}
public MemberVO findId(MemberVO vo) throws SQLException{
return (MemberVO) myCinemaDao.findId(vo);
}
public MemberVO findPa(MemberVO vo) throws SQLException{
return (MemberVO) myCinemaDao.findPa(vo);
}
public boolean ssnCheck(String ssn) throws SQLException {
boolean result=false;
if(myCinemaDao.ssnCheck(ssn)!=null)
result=true;
return result;
}
public void deleteMember(MemberVO vo, int member_no) throws SQLException{
System.out.println("delete+service");
myCinemaDao.deleteReservationMember(member_no);
myCinemaDao.deleteBoardMember(member_no);
myCinemaDao.deleteMember(vo);
}
public ListVOGenericMap getAllMyHistory(Map map) {
List<Map> list = null;
ListVOGenericMap lvo = null;
try {
list = myCinemaDao.getAllMyHistory(map);
int member_no = (int) map.get("member_no");
int total = myCinemaDao.getTotalAllMyHistory(member_no);
String page_no = (String) map.get("page");
PagingBean paging = new PagingBean(total, Integer.parseInt(page_no));
lvo = new ListVOGenericMap(list, paging);
} catch (SQLException e) {
e.printStackTrace();
}
return lvo;
}
public ListVOGenericMap getBuyMyHistory(Map map) {
List<Map> list = null;
ListVOGenericMap lvo = null;
try {
list = myCinemaDao.getBuyMyHistory(map);
int member_no = (int) map.get("member_no");
int total = myCinemaDao.getTotalBuyMyHistory(member_no);
String page_no = (String) map.get("page");
PagingBean paging = new PagingBean(total, Integer.parseInt(page_no));
lvo = new ListVOGenericMap(list, paging);
} catch (SQLException e) {
e.printStackTrace();
}
return lvo;
}
public ListVOGenericMap getSellMyHistory(Map map) {
List<Map> list = null;
ListVOGenericMap lvo = null;
try {
list = myCinemaDao.getSellMyHistory(map);
int member_no = (int) map.get("member_no");
int total = myCinemaDao.getTotalSellMyHistory(member_no);
String page_no = (String) map.get("page");
PagingBean paging = new PagingBean(total, Integer.parseInt(page_no));
lvo = new ListVOGenericMap(list, paging);
} catch (SQLException e) {
e.printStackTrace();
}
return lvo;
}
/**
* 영화검색
*/
public ArrayList<HashMap> searchMovie(String search_title) throws SQLException {
return movieDao.searchMovie(search_title);
}
} |
package LessonsJavaCore_4.Car;
public class Car {
private String salonMaterials;
Body body = new Body ();
Wheel wheel = new Wheel ();
Helm helm = new Helm ();
public String getSalonMaterials ( ) {
return salonMaterials;
}
public void setSalonMaterials ( String salonMaterials ) {
this.salonMaterials = salonMaterials;
}
}
|
package com.pegasus.kafka.controller;
import com.pegasus.kafka.common.annotation.TranRead;
import com.pegasus.kafka.common.constant.Constants;
import com.pegasus.kafka.common.ehcache.EhcacheService;
import com.pegasus.kafka.common.response.Result;
import com.pegasus.kafka.common.utils.Common;
import com.pegasus.kafka.entity.dto.SysLag;
import com.pegasus.kafka.entity.dto.SysLogSize;
import com.pegasus.kafka.entity.echarts.LineInfo;
import com.pegasus.kafka.service.dto.SysLagService;
import com.pegasus.kafka.service.dto.SysLogSizeService;
import com.pegasus.kafka.service.kafka.KafkaConsumerService;
import com.pegasus.kafka.service.kafka.KafkaTopicService;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import static com.pegasus.kafka.controller.DashboardController.PREFIX;
/**
* The controller for providing the ability of dashboard.
* <p>
* *****************************************************************
* Name Action Time Description *
* Ning.Zhang Initialize 11/7/2019 Initialize *
* *****************************************************************
*/
@Controller
@RequestMapping(PREFIX)
public class DashboardController {
public static final String PREFIX = "dashboard";
private final KafkaConsumerService kafkaConsumerService;
private final KafkaTopicService kafkaTopicService;
private final SysLagService sysLagService;
private final SysLogSizeService sysLogSizeService;
private final EhcacheService ehcacheService;
public DashboardController(KafkaConsumerService kafkaConsumerService, KafkaTopicService kafkaTopicService, SysLagService sysLagService, SysLogSizeService sysLogSizeService, EhcacheService ehcacheService) {
this.kafkaConsumerService = kafkaConsumerService;
this.kafkaTopicService = kafkaTopicService;
this.sysLagService = sysLagService;
this.sysLogSizeService = sysLogSizeService;
this.ehcacheService = ehcacheService;
}
@GetMapping("index")
public String index(Model model) throws Exception {
model.addAttribute("savingDays", Constants.SAVING_DAYS);
model.addAttribute("consumers", kafkaConsumerService.listKafkaConsumers());
model.addAttribute("topics", kafkaTopicService.listTopics(false, false, false, false, false, false));
return String.format("%s/index", PREFIX);
}
@PostMapping("getTopicChart")
@ResponseBody
public Result<LineInfo> getTopicChart(@RequestParam(name = "topicName", required = true) String topicName,
@RequestParam(name = "createTimeRange", required = true) String createTimeRange) throws ParseException {
String key = String.format("DashboardController::getTopicChart:%s:%s", topicName, createTimeRange);
LineInfo cache = ehcacheService.get(key);
if (cache != null) {
return Result.ok(cache);
}
topicName = topicName.trim();
createTimeRange = createTimeRange.trim();
if (StringUtils.isEmpty(createTimeRange)) {
return Result.ok();
}
LineInfo result = new LineInfo();
Common.TimeRange timeRange = Common.splitTime(createTimeRange);
Date from = timeRange.getStart(), to = timeRange.getEnd();
from = DateUtils.addMinutes(from, -1);
List<SysLogSize> sysLogSizeList = sysLogSizeService.listByTopicName(topicName.equals("所有主题") ? null : topicName, from, to);
List<String> topicNames = sysLogSizeList.stream().map(SysLogSize::getTopicName).distinct().collect(Collectors.toList());
List<String> times = sysLogSizeList.stream().map(p -> Common.format(p.getCreateTime())).distinct().collect(Collectors.toList());
if (times.size() > 0) {
times.remove(0);
}
result.setTopicNames(topicNames);
result.setTimes(times);
List<LineInfo.Series> seriesList = new ArrayList<>(result.getTopicNames().size());
for (String name : result.getTopicNames()) {
LineInfo.Series series = new LineInfo.Series();
series.setName(name);
series.setType("line");
series.setSmooth(true);
seriesList.add(series);
}
result.setSeries(seriesList);
for (LineInfo.Series series : result.getSeries()) {
List<SysLogSize> topicSysLogSize = sysLogSizeList.stream().filter(p -> p.getTopicName().equals(series.getName())).collect(Collectors.toList());
List<Double> data = new ArrayList<>(result.getTimes().size());
for (String time : result.getTimes()) {
Long preLogSize = null;
Long curLogSize = null;
Date preDate = null;
Date curDate = null;
for (int i = 0; i < topicSysLogSize.size(); i++) {
SysLogSize sysLogSize = topicSysLogSize.get(i);
if (sysLogSize.getTopicName().equals(series.getName()) && Common.format(sysLogSize.getCreateTime()).equals(time)) {
curLogSize = sysLogSize.getLogSize();
curDate = sysLogSize.getCreateTime();
int preIndex = i - 1;
if (preIndex >= 0 && preIndex < topicSysLogSize.size()) {
preLogSize = topicSysLogSize.get(preIndex).getLogSize();
preDate = topicSysLogSize.get(preIndex).getCreateTime();
}
break;
}
}
Long logSize = null;
if (curLogSize != null) {
logSize = curLogSize - (preLogSize == null ? 0 : preLogSize);
if (logSize < 0) {
logSize = 0L;
}
}
Double seconds = 60.0D;
if (curDate != null && preDate != null) {
seconds = (curDate.getTime() - preDate.getTime()) / 1000.0D;
}
if (logSize == null) {
data.add(null);
} else {
data.add(Common.numberic(logSize / seconds));
}
}
series.setData(data);
}
ehcacheService.set(key, result);
return Result.ok(result);
}
@PostMapping("getLagChart")
@ResponseBody
public Result<LineInfo> getLagChart(@RequestParam(name = "groupId", required = true) String groupId,
@RequestParam(name = "createTimeRange", required = true) String createTimeRange) throws ParseException {
String key = String.format("DashboardController::getLagChart:%s:%s", groupId, createTimeRange);
LineInfo cache = ehcacheService.get(key);
if (cache != null) {
return Result.ok(cache);
}
groupId = groupId.trim();
createTimeRange = createTimeRange.trim();
if (StringUtils.isEmpty(groupId) || StringUtils.isEmpty(createTimeRange)) {
return Result.ok();
}
LineInfo result = new LineInfo();
Common.TimeRange timeRange = Common.splitTime(createTimeRange);
Date from = timeRange.getStart(), to = timeRange.getEnd();
List<SysLag> sysLagList = sysLagService.listByGroupId("所有消费组".equals(groupId) ? null : groupId, from, to);
List<String> topicNames = sysLagList.stream().map(SysLag::getTopicName).distinct().collect(Collectors.toList());
List<String> times = sysLagList.stream().map(p -> Common.format(p.getCreateTime())).distinct().collect(Collectors.toList());
result.setTopicNames(topicNames);
result.setTimes(times);
List<LineInfo.Series> seriesList = new ArrayList<>(result.getTopicNames().size());
for (String topicName : result.getTopicNames()) {
LineInfo.Series series = new LineInfo.Series();
series.setName(topicName);
series.setType("line");
series.setSmooth(true);
seriesList.add(series);
}
result.setSeries(seriesList);
for (LineInfo.Series series : result.getSeries()) {
List<Double> data = new ArrayList<>(result.getTimes().size());
for (String time : result.getTimes()) {
List<Double> lag = sysLagList.stream().filter(p -> p.getTopicName().equals(series.getName()) && Common.format(p.getCreateTime()).equals(time)).map(p -> Double.parseDouble(p.getLag().toString())).collect(Collectors.toList());
if (lag.size() < 1) {
data.add(null);
} else {
data.addAll(lag);
}
}
series.setData(data);
}
ehcacheService.set(key, result);
return Result.ok(result);
}
@PostMapping("getTopicRankChart")
@ResponseBody
public Result<LineInfo> getTopicRankChart(@RequestParam(name = "createTimeRange", required = true) String createTimeRange) throws ParseException {
String key = String.format("DashboardController::getTopicRankChart:%s", createTimeRange);
LineInfo cache = ehcacheService.get(key);
if (cache != null) {
return Result.ok(cache);
}
createTimeRange = createTimeRange.trim();
if (StringUtils.isEmpty(createTimeRange)) {
return Result.ok();
}
Common.TimeRange timeRange = Common.splitTime(createTimeRange);
Date from = timeRange.getStart(), to = timeRange.getEnd();
LineInfo result = new LineInfo();
List<SysLogSize> sysLogSizeList = sysLogSizeService.getTopicRank(5, from, to);
List<String> topicNames = sysLogSizeList.stream().map(SysLogSize::getTopicName).collect(Collectors.toList());
List<Double> logSizeList = sysLogSizeList.stream().map(p -> Double.parseDouble(p.getLogSize().toString())).collect(Collectors.toList());
List<LineInfo.Series> seriesList = new ArrayList<>();
LineInfo.Series series = new LineInfo.Series();
series.setType("bar");
series.setData(logSizeList);
seriesList.add(series);
result.setTopicNames(topicNames);
result.setSeries(seriesList);
ehcacheService.set(key, result);
return Result.ok(result);
}
@PostMapping("getTopicHistoryChart")
@ResponseBody
@TranRead
public Result<LineInfo> getTopicHistoryChart(@RequestParam(name = "topicName", required = true) String topicName) throws Exception {
topicName = topicName.trim();
if (StringUtils.isEmpty(topicName)) {
return Result.ok();
}
LineInfo result = new LineInfo();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Long[] daysValue = new Long[8];
daysValue[0] = kafkaTopicService.getLogsize(topicName);
daysValue[1] = sysLogSizeService.getHistoryLogSize(topicName, 1);
daysValue[2] = sysLogSizeService.getHistoryLogSize(topicName, 2);
daysValue[3] = sysLogSizeService.getHistoryLogSize(topicName, 3);
daysValue[4] = sysLogSizeService.getHistoryLogSize(topicName, 4);
daysValue[5] = sysLogSizeService.getHistoryLogSize(topicName, 5);
daysValue[6] = sysLogSizeService.getHistoryLogSize(topicName, 6);
daysValue[7] = sysLogSizeService.getHistoryLogSize(topicName, 7);
List<String> timesList = new ArrayList<>();
for (int i = 0; i < 7; i++) {
Calendar calendar = Calendar.getInstance();
calendar.set(calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DATE), 0, 0, 0);
Date date = DateUtils.addDays(calendar.getTime(), -i);
timesList.add(sdf.format(date));
}
List<Double> data = new ArrayList<>();
data.add((double) (Common.calculateHistoryLogSize(daysValue, 0)));
data.add((double) (Common.calculateHistoryLogSize(daysValue, 1)));
data.add((double) (Common.calculateHistoryLogSize(daysValue, 2)));
data.add((double) (Common.calculateHistoryLogSize(daysValue, 3)));
data.add((double) (Common.calculateHistoryLogSize(daysValue, 4)));
data.add((double) (Common.calculateHistoryLogSize(daysValue, 5)));
data.add((double) (Common.calculateHistoryLogSize(daysValue, 7)));
List<LineInfo.Series> seriesList = new ArrayList<>();
LineInfo.Series series = new LineInfo.Series();
series.setType("bar");
series.setData(data);
seriesList.add(series);
result.setTimes(timesList);
result.setSeries(seriesList);
return Result.ok(result);
}
} |
import java.math.BigInteger;
import java.util.Scanner;
public class t1 {
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
int dp[][] = new int [30][2];
for(int i = 0 ; i<dp.length; i++){
for(int j = 0; j<dp[i].length; j++){
System.out.print(dp[i][j] + ",");
}
System.out.println();
}
int n, k;
n = cin.nextInt();
k = cin.nextInt();
dp[1][0] = ((k - 1));
dp[1][1] = ((0));
for (int i = 2; i <= n; i++) {
dp[i][0] = (dp[i - 1][0] + (dp[i-1][1])) * ((k-1));
System.out.println(dp[i][0]);
dp[i][1] = (dp[i - 1][0]);
System.out.println(dp[i-1][0]);
}
System.out.println(dp[n][0] + (dp[n][1]));
}
} |
package cn.bs.zjzc.baidumap;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import cn.bs.zjzc.App;
import cn.bs.zjzc.bean.ProvinceCityListResponse;
import cn.bs.zjzc.net.GsonCallback;
import cn.bs.zjzc.net.PostHttpTask;
import cn.bs.zjzc.net.RequestUrl;
import cn.bs.zjzc.util.L;
public class CityListService extends Service {
public CityListService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
requestProvinceCityList();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
}
/**
* 请求获取省份和城市列表
*/
public void requestProvinceCityList() {
String url = RequestUrl.getRequestPath(RequestUrl.SubPaths.getProvinceCityList);
PostHttpTask<ProvinceCityListResponse> httpTask = new PostHttpTask<>(url);
httpTask.addParams("token", App.LOGIN_USER.getToken())
.execute(new GsonCallback<ProvinceCityListResponse>() {
@Override
public void onFailed(String errorInfo) {
System.out.println(errorInfo);
}
@Override
public void onSuccess(ProvinceCityListResponse response) {
App.LOGIN_USER.setProvinceCityList(response.data);
L.d("MGC",response.data.toString());
}
});
}
}
|
package com.androidapp.yemyokyaw.movieapp.adapters;
import android.content.Context;
import android.graphics.Movie;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.androidapp.yemyokyaw.movieapp.R;
import com.androidapp.yemyokyaw.movieapp.data.vo.MovieVO;
import com.androidapp.yemyokyaw.movieapp.delegates.MovieListDelegate;
import com.androidapp.yemyokyaw.movieapp.viewholders.MovieListViewHolder;
/**
* Created by yemyokyaw on 12/5/17.
*/
public class MovieListRvAdapter extends BaseRecyclerAdapter<MovieListViewHolder,MovieVO> {
private MovieListDelegate mMovieListDelegate;
public MovieListRvAdapter(Context context, MovieListDelegate mlDelegate) {
super(context);
mMovieListDelegate = mlDelegate;
}
@Override
public MovieListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mLayoutInflator.inflate(R.layout.view_movie_data, parent, false);
return new MovieListViewHolder(view, mMovieListDelegate);
}
}
|
package com.zpjr.cunguan.common.views;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.zpjr.cunguan.R;
import java.util.Timer;
import java.util.TimerTask;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class TimeTextView extends LinearLayout {
private long mday, mhour, mmin, msecond;// 天,小时,分钟,秒
private boolean run = false; // 是否启动了
Timer timer = new Timer();
TextView Vday, Vhour, Vmin, Vseconds, last;
LinearLayout layout;
public TimeTextView(Context context) {
super(context);
iniUI(context);
}
public TimeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
iniUI(context);
}
public void iniUI(Context context) {
LayoutInflater mInflater = LayoutInflater.from(context);
View myView = mInflater.inflate(R.layout.view_counttimer, null);
layout = (LinearLayout) myView.findViewById(R.id.layout_counttimer);
Vday = (TextView) myView.findViewById(R.id.tv_day);
Vhour = (TextView) myView.findViewById(R.id.tv_hour);
Vmin = (TextView) myView.findViewById(R.id.tv_minute);
Vseconds = (TextView) myView.findViewById(R.id.tv_second);
last = (TextView) myView.findViewById(R.id.tv_last);
addView(myView);
}
public TimeTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
iniUI(context);
}
private Handler mHandler = new Handler() {
};
public boolean isRun() {
return run;
}
public void setRun(boolean run) {
this.run = run;
}
public void start() {
if (!isRun()) {
setRun(true);
try {
timer.schedule(task, 1000, 1000);
} catch (Exception e) {
e.printStackTrace();
// timer.cancel();
// timer.schedule(task, 1000, 1000);
}
}
}
/**
* 根据传进来的时间差 为textview 赋值
*
* @param duration
*/
public void setTimes(long duration) {
mday = duration / 60000 / 60 / 24;
mhour = (duration - mday * 24 * 60 * 60000) / 60000 / 60;
mmin = (duration - mhour * 60000 * 60 - mday * 3600000 * 24) / 60000;
msecond = (duration - mmin * 60000 - mhour * 3600000 - mday * 3600000 * 24) / 1000;
}
/**
* 倒计时计算
*/
private void ComputeTime() {
msecond--;
if (msecond < 0) {
mmin--;
msecond = 59;
if (mmin < 0) {
mmin = 59;
mhour--;
if (mhour < 0) {
// 倒计时结束
mhour = 24;
mday--;
}
}
}
}
TimerTask task = new TimerTask() {
@Override
public void run() {
mHandler.post(new Runnable() { // UI thread
@Override
public void run() {
run = true;
ComputeTime();
if (mday < 0) {
// setVisibility(View.GONE);
setLast(true, "已完结,请刷新");
setRun(false);
}
Vday.setText(mday < 10 ? ("0" + mday) : mday + "");
Vhour.setText(mhour < 10 ? ("0" + mhour) : mhour + "");
Vseconds.setText(msecond < 10 ? ("0" + msecond) : msecond
+ "");
Vmin.setText(mmin < 10 ? ("0" + mmin) : mmin + "");
}
});
}
};
public void setLast(boolean hintOther, String text) {
if (hintOther) {
layout.setVisibility(View.GONE);
last.setText(text);
} else {
layout.setVisibility(View.VISIBLE);
last.setText(text);
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.udea.entity;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author camiloa.mejia
*/
@Entity
@Table(name = "vehicle")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Vehicle.findAll", query = "SELECT v FROM Vehicle v")
, @NamedQuery(name = "Vehicle.findByLicense", query = "SELECT v FROM Vehicle v WHERE v.license = :license")
, @NamedQuery(name = "Vehicle.findByBrand", query = "SELECT v FROM Vehicle v WHERE v.brand = :brand")
, @NamedQuery(name = "Vehicle.findByModel", query = "SELECT v FROM Vehicle v WHERE v.model = :model")
, @NamedQuery(name = "Vehicle.findByPrice", query = "SELECT v FROM Vehicle v WHERE v.price = :price")
, @NamedQuery(name = "Vehicle.findByKm", query = "SELECT v FROM Vehicle v WHERE v.km = :km")
, @NamedQuery(name = "Vehicle.findByState", query = "SELECT v FROM Vehicle v WHERE v.state = :state")
, @NamedQuery(name = "Vehicle.findByImage", query = "SELECT v FROM Vehicle v WHERE v.image = :image")})
public class Vehicle implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 6)
@Column(name = "license")
private String license;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 50)
@Column(name = "brand")
private String brand;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 50)
@Column(name = "model")
private String model;
@Basic(optional = false)
@NotNull
@Column(name = "price")
private int price;
@Basic(optional = false)
@NotNull
@Column(name = "km")
private int km;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 10)
@Column(name = "state")
private String state;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 50)
@Column(name = "image")
private String image;
public Vehicle() {
}
public Vehicle(String license) {
this.license = license;
}
public Vehicle(String license, String brand, String model, int price, int km, String state, String image) {
this.license = license;
this.brand = brand;
this.model = model;
this.price = price;
this.km = km;
this.state = state;
this.image = image;
}
public String getLicense() {
return license;
}
public void setLicense(String license) {
this.license = license;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getKm() {
return km;
}
public void setKm(int km) {
this.km = km;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
@Override
public int hashCode() {
int hash = 0;
hash += (license != null ? license.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Vehicle)) {
return false;
}
Vehicle other = (Vehicle) object;
if ((this.license == null && other.license != null) || (this.license != null && !this.license.equals(other.license))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.udea.entity.Vehicle[ license=" + license + " ]";
}
}
|
package com.dreamcatcher.plan.action;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.dreamcatcher.action.Action;
import com.dreamcatcher.plan.model.PlanDto;
import com.dreamcatcher.plan.model.service.PlanServiceImpl;
import com.dreamcatcher.util.Encoder;
import com.dreamcatcher.util.NumberCheck;
import com.dreamcatcher.util.StringCheck;
public class RouteModifyEndAction implements Action {
@Override
public String execute(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
int route_id = Integer.parseInt(request.getParameter("route_id"));
String jsonStringFromMap = StringCheck.nullToBlank(request.getParameter("jsonString"));
// System.out.println(jsonStringFromMap);
int cnt = PlanServiceImpl.getInstance().getRouteModifyArticle(route_id, jsonStringFromMap);
return null;
}
}
|
/*
* [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.product.common.core.service.impl;
import de.hybris.platform.servicelayer.keygenerator.KeyGenerator;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.cnk.travelogix.product.common.core.model.AccommodationModel;
import com.cnk.travelogix.product.common.core.service.AccommodationProductService;
/**
* Uses City and Name to generate code and set in Code attribute in Accommodation Model.
*/
public class DefaultAccommodationProductService implements AccommodationProductService
{
private KeyGenerator keyGenerator;
private static final Logger LOG = Logger.getLogger(DefaultAccommodationProductService.class);
@Override
public void generateCompanyProductId(final AccommodationModel accommodationModel)
{
String key = "";
if (StringUtils.isNotEmpty(accommodationModel.getAddress().getCity().getName())
&& StringUtils.isNotEmpty(accommodationModel.getName()))
{
String city = accommodationModel.getAddress().getCity().getName();
city = city.substring(0, 3).replaceAll("\\s+", "");
String name = accommodationModel.getName();
name = name.substring(0, 3).replaceAll("\\s+", "");
key = city.concat(name).concat(keyGenerator.generate().toString());
accommodationModel.setCode(key);
LOG.debug("Generated CommonproductId for Accomodation :" + accommodationModel.getCode());
}
}
/**
* @return the keyGenerator
*/
public KeyGenerator getKeyGenerator()
{
return keyGenerator;
}
/**
* @param keyGenerator
* the keyGenerator to set
*/
public void setKeyGenerator(final KeyGenerator keyGenerator)
{
this.keyGenerator = keyGenerator;
}
}
|
package com.control.amigo;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import com.control.amigo.BluetoothService.AmigoState;
import com.control.amigo.BluetoothService.BTState;
import com.control.amigo.MonitorService.MobileCamStatus;
import com.control.amigo.MonitorService.WifiPosStatus;
import com.control.amigo.drive.AmigoCommunication;
import com.control.amigo.drive.PacketReceiver;
import com.example.amigo.R;
public class Monitor extends Fragment implements OnTouchListener {
private ImageButton startMonitor;
static boolean reach=false;
static boolean startthr=false;
static BufferedReader infoin = null;
static PrintWriter infoout = null;
private rev rv=new rev();
infoth ifo=new infoth();
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View InputFragmentView;
String warning = "";
if( BluetoothService.mBTState == BTState.stopped || BluetoothService.mBTState == BTState.connecting ){
warning = "藍牙";
if( BluetoothService.mAmigoState == AmigoState.stopped ){
warning = warning + "、AmigoBot";
}
}
else {
if( BluetoothService.mAmigoState == AmigoState.stopped ){
warning = warning + "AmigoBot";
}
}
if( MonitorService.mWifiPosStatus == WifiPosStatus.stopped && BluetoothService.mAmigoState == AmigoState.stopped ){
warning = warning + "、Wifi定位\r\n";
}
else if( MonitorService.mWifiPosStatus == WifiPosStatus.stopped ){
warning = warning + "Wifi定位";
}
if( MonitorService.mWifiPosStatus == WifiPosStatus.stopped && BluetoothService.mAmigoState == AmigoState.stopped
&& MonitorService.mMobileCamStatus == MobileCamStatus.stopped ){
warning = warning + "、MobileCam";
}
else if( MonitorService.mWifiPosStatus == WifiPosStatus.stopped && MonitorService.mMobileCamStatus == MobileCamStatus.stopped ){
warning = warning + "、MobileCam";
}
else if( MonitorService.mMobileCamStatus == MobileCamStatus.stopped ){
warning = warning + "MobileCam";
}
if( (BluetoothService.mBTState == BTState.stopped || BluetoothService.mBTState == BTState.connecting)
|| BluetoothService.mAmigoState == AmigoState.stopped
|| MonitorService.mWifiPosStatus == WifiPosStatus.stopped
|| MonitorService.mMobileCamStatus == MobileCamStatus.stopped ){
InputFragmentView = inflater.inflate(R.layout.unconnect_view, container, false);
warning = warning + "尚未連線";
TextView warningtext = (TextView) InputFragmentView.findViewById(R.id.warningtext);
warningtext.setText(warning);
}
else if( AmigoCommunication.WanderMode ){
InputFragmentView = inflater.inflate(R.layout.unconnect_view, container, false);
warning = "WanderMode is running!!!";
TextView warningtext = (TextView) InputFragmentView.findViewById(R.id.warningtext);
warningtext.setText(warning);
}
else {
InputFragmentView = inflater.inflate(R.layout.monitor_view, container, false);
startMonitor = (ImageButton) InputFragmentView.findViewById(R.id.startmonitor);
startMonitor.setOnTouchListener(this);
if( AmigoCommunication.MonitorMode ){
startMonitor.setBackgroundResource(R.drawable.monitor_stop);
}
else if( AmigoCommunication.MonitorMode ){
startMonitor.setBackgroundResource(R.drawable.monitor_start);
}
}
return InputFragmentView;
}
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if( v.getId()==R.id.startmonitor ){
if( !AmigoCommunication.MonitorMode ){
if( event.getAction()==MotionEvent.ACTION_DOWN ){
startMonitor.setBackgroundResource(R.drawable.monitor_start_press);
}
else if( event.getAction()==MotionEvent.ACTION_UP ){
rv=new rev();
ifo=new infoth();
new Thread(rv).start();
new Thread(ifo).start();
AmigoCommunication.MonitorMode = true;
startMonitor.setBackgroundResource(R.drawable.monitor_stop);
}
}
else if( AmigoCommunication.MonitorMode ){
if( event.getAction()==MotionEvent.ACTION_DOWN ){
startMonitor.setBackgroundResource(R.drawable.monitor_stop_press);
}
else if( event.getAction()==MotionEvent.ACTION_UP ){
try {
BluetoothService.Amigo.stoptravel();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
rv.setstop(true);
ifo.setstop(true);
AmigoCommunication.MonitorMode = false;
startMonitor.setBackgroundResource(R.drawable.monitor_start);
}
}
}
return false;
}
int[] path=new int [8];
int thc=0;
connPC pc=new connPC();
class rev implements Runnable{
public boolean stop=false;
@Override
public void run() {
// TODO Auto-generated method stub
int mode=-1;
while(stop==false){
try {
Log.i("path","pc");
pc=new connPC();
pc.start();
Log.i("path","pcstart");
int x=0;
while(pc.getlogin()==false){
Thread.sleep(1000);
x++;
if(x>4){
pc=new connPC();
pc.start();
Thread.sleep(1000);
if(pc.getlogin()==false){
continue;
}
}
}
Log.i("path","login"+pc.getlogin()+"1");
int cx=0;
Thread.sleep(1500);
int dx=connPC.pcin.readInt();
Log.i("path","length");
path[0]=-5;
path[1]=-5;
path=new int[dx];
while (cx<dx) {
path[cx] = connPC.pcin.readInt();
cx++;
}
if(BluetoothService.Amigo.checktr()==true){//travel unstart or stop
BluetoothService.Amigo.starttravel(path);
for(int i=0;i<path.length;i++){
Log.i("path",""+path[i]);
}
}
}//try
catch (NumberFormatException e) {
// TODO Auto-generated catch block
Log.i("path","monitor catch"+pc.getlogin());
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
Log.i("path","monitor catch"+pc.getlogin());
e.printStackTrace();
}
try {
connPC.pcsock.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//while
}//run
public void setstop(boolean T){
stop=T;
Thread.currentThread().interrupt();
Thread.currentThread();
while(Thread.interrupted()==false){}
stop=T;
}
}
class infoth implements Runnable{
Socket infosock=new Socket();
PrintWriter infoout =null;
DataInputStream drivein =null;
drive dr=new drive();
public boolean infostop=false;
@Override
public void run() {
InetAddress severInetAddr;
try {
severInetAddr = InetAddress.getByName("120.105.129.101");
infosock = new Socket(severInetAddr,405);
infoout=new PrintWriter(new OutputStreamWriter(infosock.getOutputStream()));
drivein = new DataInputStream(infosock.getInputStream());
new Thread(dr).start();
while(infostop==false){
if(BluetoothService.Amigo.checktr()==true){
reach=true;
}
else {
reach=false;
}
infoout.println("Battery: "+PacketReceiver.mAmigoInfo.getBattery()+"Stall: "+PacketReceiver.mAmigoInfo.getstall()
+"reach: "+reach);
infoout.flush();
Thread.sleep(1000);
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void setstop(boolean T){
infostop=T;
Thread.currentThread().interrupt();
while(Thread.currentThread().isInterrupted()!=true){}
infostop=T;
dr.setstop(T);
}
public boolean getstop(){
return infostop;
}
class drive implements Runnable{
boolean stop=false;
@Override
public void run() {
// TODO Auto-generated method stub
while(stop==false){
char comm;
try {
comm = drivein.readChar();
if(comm=='w'){
BluetoothService.Amigo.setTransVelocity(250);
Thread.sleep(1000);
BluetoothService.Amigo.setTransVelocity(0);
}
if(comm=='s'){
BluetoothService.Amigo.setTransVelocity(-250);
Thread.sleep(1000);
}
if(comm=='a'){
BluetoothService.Amigo.setRelativeHeading(30);;
Thread.sleep(1000);
}
if(comm=='d'){
BluetoothService.Amigo.setRelativeHeading(-30);;
Thread.sleep(1000);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void setstop(boolean T){
stop=T;
Thread.currentThread().interrupt();
while(Thread.currentThread().isInterrupted()!=true){}
stop=T;
}
}
}
}
|
import java.util.*;
class parenthsis {
public static void main(String args[]) {
String a;int i,j,m=0,n=0;;
Scanner in = new Scanner(System.in);
a=in.nextLine();
char[] b=a.toCharArray();
for(i=0;i<b.length;i++) {
if(b[i] == '{') {
m++;
}}
for(j=0;j<b.length;j++) {
if(b[j]== '{'){
n++;
}}
if(m==n)
System.out.println("true");
else
System.out.println("false");
}} |
package ui;
import exception.NoSuggestionsException;
import model.*;
import persistence.JsonReader;
import persistence.JsonWriter;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
// Handles the entire UI functionality of the application
public class Console implements ActionListener {
String interests = "";
String major = "";
String location = "";
UserChoices uc = new UserChoices("", "", "");
ChoicesList<UserChoices> userList = new ChoicesList<>();
ArrayList<DataChoices> dataList = new ArrayList<>();
ArrayList<String> string;
Set<String> set = new HashSet<>();
AddToData atd = new AddToData(dataList);
SuggestUniversity suggest = new SuggestUniversity(userList, dataList);
String guiDisplay = "";
private static final String JSON_STORE = "./data/universitySuggestions.json";
private JsonWriter jsonWriter;
private JsonReader jsonReader;
JFrame frame;
JPanel initialPanel;
JPanel interestsPanel;
JPanel majorPanel;
JPanel locationPanel;
JPanel thirdPanel;
JPanel quitPanel;
JButton initialPanelB1;
JButton initialPanelB2;
JButton initialPanelB3;
JButton thirdPanelB1;
JButton thirdPanelB2;
JButton thirdPanelB3;
JLabel label;
JComboBox choicesList;
JComboBox majorList;
JComboBox locationList;
Clip clip;
AudioInputStream audioInputStream;
//MODIFIES: this
//EFFECTS: creates a new jsonWriter and jsonReader object
// calls the initializeGui method to initialize the graphical user interface
public Console() throws IllegalStateException, IOException {
jsonWriter = new JsonWriter(JSON_STORE);
jsonReader = new JsonReader(JSON_STORE);
initializeGui();
}
//MODIFIES: this
//EFFECTS: creates and initializes the JFrame
// creates and initializes the initial, major, location and quit JPanels
// calls sceneOne() to start displaying the GUI
void initializeGui() throws IOException {
frame = new JFrame();
initialPanel = new JPanel();
initialPanel.setBorder(BorderFactory.createEmptyBorder(30,30,50,30));
initialPanel.setLayout(new GridLayout(0,1));
interestsPanel = new JPanel();
interestsPanel.setBorder(BorderFactory.createEmptyBorder(30,30,10,30));
interestsPanel.setLayout(new GridLayout(2,1));
majorPanel = new JPanel();
majorPanel.setBorder(BorderFactory.createEmptyBorder(30,30,10,30));
majorPanel.setLayout(new GridLayout(2,1));
locationPanel = new JPanel();
locationPanel.setBorder(BorderFactory.createEmptyBorder(30,30,10,30));
locationPanel.setLayout(new GridLayout(2,1));
quitPanel = new JPanel();
quitPanel.setBorder(BorderFactory.createEmptyBorder(30,30,10,30));
quitPanel.setLayout(new GridLayout(2,1));
sceneOne();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("University Finder");
frame.pack();
frame.setVisible(true);
}
//MODIFIES: this
//EFFECTS: displays the first scene with 2 panels and 3 buttons
void sceneOne() throws IOException {
JLabel imgLabel = new JLabel(new ImageIcon("./data/UniversityFinder.png"));
initialPanel.add(imgLabel);
label = new JLabel("<html>" + "Welcome to University Finder! Find the best suited universities for you "
+ "based on your interests, major and location!" + "</html>");
initialPanel.add(label);
label = new JLabel("\n");
initialPanel.add(label);
initialPanelB1 = new JButton("Display List of Universities (and start)");
initialPanelB1.addActionListener(this);
initialPanel.add(initialPanelB1);
initialPanelB2 = new JButton("Start the Program");
initialPanelB2.addActionListener(this);
initialPanel.add(initialPanelB2);
initialPanelB3 = new JButton("Load previous recommendations");
initialPanelB3.addActionListener(this);
initialPanel.add(initialPanelB3);
frame.add(initialPanel, BorderLayout.CENTER);
}
//MODIFIES: this
//EFFECTS: removes initial panel
// calls the sceneTwoSelectInterests method and validates the panel
void sceneTwoInterests() {
frame.remove(initialPanel);
sceneTwoSelectInterests();
frame.add(interestsPanel, BorderLayout.CENTER);
frame.validate();
}
//MODIFIES: this
//EFFECTS: provides a list interests to choose from
void sceneTwoSelectInterests() {
label = new JLabel("<html>" + "Please select your interests" + "</html>");
interestsPanel.add(label);
String[] list = { "E sports", "Robotics", "Soccer", "Piano"};
choicesList = new JComboBox(list);
interestsPanel.add(choicesList);
choicesList.addActionListener(this);
}
//MODIFIES: this
//EFFECTS: removes interests panel
// calls the sceneTwoSelectMajor method and validates the panel
void sceneTwoMajor() {
frame.remove(interestsPanel);
sceneTwoSelectMajor();
frame.add(majorPanel, BorderLayout.CENTER);
frame.validate();
}
//MODIFIES: this
//EFFECTS: provides a list of majors to choose from
void sceneTwoSelectMajor() {
label = new JLabel("<html>" + "Please select your intended Major" + "</html>");
majorPanel.add(label);
String[] list = { "Comp Sci", "Math", "Commerce", "Fine Arts"};
majorList = new JComboBox(list);
majorPanel.add(majorList);
majorList.addActionListener(this);
}
//MODIFIES: this
//EFFECTS: removes major panel
// calls the sceneTwoSelectLocation method and validates the panel
void sceneTwoLocation() {
frame.remove(majorPanel);
sceneTwoSelectLocation();
frame.add(locationPanel, BorderLayout.CENTER);
frame.validate();
}
//MODIFIES: this
//EFFECTS: provides a list of locations to choose from
void sceneTwoSelectLocation() {
label = new JLabel("<html>" + "Please select your intended location" + "</html>");
locationPanel.add(label);
String[] list = { "Canada", "USA", "India", "Nauru"};
locationList = new JComboBox(list);
locationPanel.add(locationList);
locationList.addActionListener(this);
}
//MODIFIES: this
//EFFECTS: removes the location panel
// initializes thirdPanel, calls sceneThreeOptions and validates the panel
void sceneThree() {
frame.remove(locationPanel);
thirdPanel = new JPanel();
thirdPanel.setBorder(BorderFactory.createEmptyBorder(30,30,10,50));
thirdPanel.setLayout(new GridLayout(0,1));
sceneThreeOptions();
frame.add(thirdPanel, BorderLayout.CENTER);
frame.validate();
}
//MODIFIES: this
//EFFECTS: provides options to save recommendations, delete choices and see the recommendations
void sceneThreeOptions() {
thirdPanelB1 = new JButton("Save Suggested Universities and Quit");
thirdPanel.add(thirdPanelB1);
thirdPanelB1.addActionListener(this);
thirdPanelB2 = new JButton("Delete Current Choices");
thirdPanel.add(thirdPanelB2);
thirdPanelB2.addActionListener(this);
thirdPanelB3 = new JButton("See Recommendations");
thirdPanel.add(thirdPanelB3);
thirdPanelB3.addActionListener(this);
}
//MODIFIES: this
//EFFECTS: takes in start and calls the methods according to the input
void start(int start) {
removeAll(start);
try {
string = suggest.suggestion();
if (start == 0) {
listToSet();
}
saveSuggestions(start);
} catch (NoSuggestionsException e) {
JOptionPane.showMessageDialog(null, "No suggestions found! Please try again");
System.exit(0);
}
}
//MODIFIES: this
//EFFECTS: displays the recommended universities as a Message Dialog Box
void listToSet() {
String recommendedUnis = "";
for (String x : string) {
set.add(x);
}
for (String x : set) {
recommendedUnis += x + "\n";
}
JOptionPane.showMessageDialog(null, recommendedUnis);
System.exit(0);
}
//MODIFIES: this
//EFFECTS: displays all the universities in the database as a Message Dialog Box
void displayDatabase(int start) {
String universitiesInDatabase = "";
switch (start) {
case 1:
for (DataChoices data : dataList) {
DataChoices dataTemp = data;
universitiesInDatabase += dataTemp.getUniversity() + "\n";
}
break;
default:
break;
}
JOptionPane.showMessageDialog(null, universitiesInDatabase);
}
//MODIFIES: this
//EFFECTS: sets the interests according to the interestsChoice
void interestsChoice(int interestChoice) {
switch (interestChoice) {
case 1:
interests = "esports";
break;
case 2:
interests = "robotics";
break;
case 3:
interests = "soccer";
break;
case 4:
interests = "piano";
break;
default:
throw new IllegalStateException("Unexpected value: " + interestChoice);
}
}
//MODIFIES: this
//EFFECTS: sets the major according to the majorChoice
void majorChoice(int majorChoice) {
switch (majorChoice) {
case 1:
major = "cs";
break;
case 2:
major = "math";
break;
case 3:
major = "commerce";
break;
case 4:
major = "finearts";
break;
default:
throw new IllegalStateException("Unexpected value: " + majorChoice);
}
}
//MODIFIES: this
//EFFECTS: sets the location according to the locationChoice
void locationChoice(int locationChoice) {
switch (locationChoice) {
case 1:
location = "canada";
break;
case 2:
location = "usa";
break;
case 3:
location = "india";
break;
case 4:
location = "nauru";
break;
default:
throw new IllegalStateException("Unexpected value: " + locationChoice);
}
}
//MODIFIES: this
//EFFECTS: removes all user choices objects from the userList
void removeAll(int start) {
if (start == 9) {
userList.removeAll();
JOptionPane.showMessageDialog(null, "Deleted Current Choices From the Database");
System.exit(0);
}
}
// Code partly taken from JsonSerializationDemo
//MODIFIES:
// EFFECTS: saves the suggestions to file
private void saveSuggestions(int start) {
if (start == 2) {
try {
jsonWriter.open();
jsonWriter.write(suggest);
jsonWriter.close();
JOptionPane.showMessageDialog(null, "Saved to Database");
System.exit(0);
} catch (FileNotFoundException e) {
System.out.println("Unable to write to file: " + JSON_STORE);
}
}
}
// Code partly taken from JsonSerializationDemo
// MODIFIES: this
// EFFECTS: loads workroom from file
void loadSuggestions() {
try {
suggest = jsonReader.read();
for (int i = 0; i < suggest.getSuggestionList().size(); i++) {
guiDisplay += suggest.getSuggestionList().get(i);
}
JOptionPane.showMessageDialog(null, guiDisplay);
System.out.println("Loaded from " + JSON_STORE);
System.exit(0);
} catch (IOException e) {
System.out.println("Unable to read from file: " + JSON_STORE);
}
}
//EFFECTS: checks which button is pressed and calls the respective backend method
@Override
public void actionPerformed(ActionEvent e) {
Object obj = e.getSource();
if (obj == initialPanelB1) {
displayDatabase(1);
sceneTwoInterests();
} else if (obj == initialPanelB2) {
sceneTwoInterests();
} else if (obj == initialPanelB3) {
loadSuggestions();
} else if (obj == choicesList) {
choicesManagerInterests();
} else if (obj == majorList) {
choicesManagerMajor();
} else if (obj == locationList) {
choicesManagerLocation();
} else if (obj == thirdPanelB1) {
start(2);
} else if (obj == thirdPanelB2) {
fartSound();
start(9);
} else if (obj == thirdPanelB3) {
start(0);
}
}
//MODIFIES: this
//EFFECTS: plays a fart sound if the file exists and is read properly
void fartSound() {
try {
clip = AudioSystem.getClip();
audioInputStream = AudioSystem.getAudioInputStream(new File("./data/fart-01.wav")
.getAbsoluteFile());
clip.open(audioInputStream);
clip.start();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Fart Sound Failed");
}
}
//EFFECTS: finds the major chosen by the user and sends it to interestsChoice
// calls sceneTwoLocation to set the user selected location
void choicesManagerInterests() {
if (choicesList.getSelectedItem().toString() == "E sports") {
interestsChoice(1);
} else if (choicesList.getSelectedItem().toString() == "Robotics") {
interestsChoice(2);
} else if (choicesList.getSelectedItem().toString() == "Soccer") {
interestsChoice(3);
} else if (choicesList.getSelectedItem().toString() == "Piano") {
interestsChoice(4);
}
sceneTwoMajor();
}
//EFFECTS: finds the major chosen by the user and sends it to majorChoice
// calls sceneTwoLocation to set the user selected location
void choicesManagerMajor() {
if (majorList.getSelectedItem().toString() == "Comp Sci") {
majorChoice(1);
} else if (majorList.getSelectedItem().toString() == "Math") {
majorChoice(2);
} else if (majorList.getSelectedItem().toString() == "Commerce") {
majorChoice(3);
} else if (majorList.getSelectedItem().toString() == "Fine Arts") {
majorChoice(4);
}
sceneTwoLocation();
}
//EFFECTS: finds the location chosen by the user and sends it to locationChoice
// calls userChoicesObject to display the next panel
void choicesManagerLocation() {
if (locationList.getSelectedItem().toString() == "Canada") {
locationChoice(1);
} else if (locationList.getSelectedItem().toString() == "USA") {
locationChoice(2);
} else if (locationList.getSelectedItem().toString() == "India") {
locationChoice(3);
} else if (locationList.getSelectedItem().toString() == "Nauru") {
locationChoice(4);
}
userChoicesObject();
}
//MODIFIES: this
//EFFECTS: creates a user choices object and adds it to userList
// calls sceneThree to continue displaying the application
void userChoicesObject() {
uc = new UserChoices(interests, major, location);
userList.add(uc);
sceneThree();
}
}
|
package com.epam.lab.serealizede;
class Droid {
private int health;
private int impact;
private String model;
Droid(int health, int impact, String model) {
this.health = health;
this.impact = impact;
this.model = model;
}
}
|
package com.feelyou.ui;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import com.feelyou.R;
import com.feelyou.net.MSG;
import com.feelyou.net.Network;
import com.feelyou.util.DialogUtil;
import com.feelyou.util.SkyMeetingUtil;
import com.feelyou.util.SystemUtil;
/**
* 马上充值
*
* @author Administrator
*
*/
public class ChargeActivity extends Activity implements OnClickListener {
private TextView tvTitle;
private TextView tvCount;
private String[] arrayOfChargeTypeId;
private String chargeTypeId = "";
private int[] chargeIcon;
private String[] chargeArray ;
private Dialog dialog;
private Context context;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.charge);
tvTitle = (TextView) findViewById(R.id.app_version);
tvTitle.setText(this.getTitle());
tvCount = (TextView) findViewById(R.id.charge_tv_account);
tvCount.setText(SkyMeetingUtil.getPreference(SkyMeetingUtil.USER_NO));
chargeIcon = new int[]{R.drawable.fill_motion, R.drawable.fill_unicom, R.drawable.ic_menu_back};
chargeArray = getResources().getStringArray(R.array.charge_type_list);
arrayOfChargeTypeId = getResources().getStringArray(
R.array.charge_type_ID);
chargeTypeId = arrayOfChargeTypeId[0];
ArrayAdapter arrayAdapterOfChargeTypeList = ArrayAdapter
.createFromResource(this, R.array.charge_type_list,
android.R.layout.simple_spinner_item);
arrayAdapterOfChargeTypeList
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// ArrayAdapter arrayAdapterOfChargeTypeList = new ArrayAdapter(this, android.R.layout.simple_spinner_item, R.array.charge_type_list) {
// @Override
// public View getDropDownView(int position, View convertView,
// ViewGroup parent) {
// LinearLayout line = new LinearLayout(context);
// line.setOrientation(0);
// ImageView image = new ImageView(context);
// image.setImageResource(chargeIcon[position]);
// TextView text = new TextView(context);
// text.setText(chargeArray[position]);
// text.setTextSize(20);
// text.setTextColor(Color.RED);
//
// line.addView(image);
// line.addView(text);
// parent.addView(line);
// return line;
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup parent) {
// LinearLayout line = new LinearLayout(context);
// line.setOrientation(0);
// ImageView image = new ImageView(context);
// image.setImageResource(chargeIcon[position]);
// TextView text = new TextView(context);
// text.setText(chargeArray[position]);
// text.setTextSize(20);
// text.setTextColor(Color.RED);
//
// line.addView(image);
// line.addView(text);
// return line;
// }
// };
Spinner spinner = (Spinner) findViewById(R.id.charge_spinner_chargeType);
spinner.setAdapter(arrayAdapterOfChargeTypeList);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View v, int itemId,
long arg3) {
chargeTypeId = arrayOfChargeTypeId[itemId];
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
findViewById(R.id.charge_btn_help).setOnClickListener(this);
findViewById(R.id.charge_btn_ok).setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.charge_btn_help:
// 显示充值帮助界面
Intent intent = new Intent(this, ChargeHelpActivity.class);
startActivity(intent);
break;
case R.id.charge_btn_ok:
// 充值
String etCardId = ((EditText) findViewById(R.id.charge_et_cardId))
.getText().toString().trim();
String etCardPwd = ((EditText) findViewById(R.id.charge_et_cardPwd))
.getText().toString().trim();
String etMoney = ((EditText) findViewById(R.id.charge_et_money))
.getText().toString().trim();
if ((etCardId.equals("")) || (etCardPwd.equals(""))
|| (etMoney.equals(""))) {
DialogUtil.showOperateFailureDialog(this, "不能为空");
return;
}
MSG msg = new MSG();
msg.setType(26);
msg.setVersion(1);
msg.appendByte(SystemUtil.encoding(etCardId));
msg.appendByte(SystemUtil.encoding(etCardPwd));
msg.appendByte(SystemUtil.encoding(etMoney));
msg.appendByte(SystemUtil.encoding(chargeTypeId));
msg.appendByte(SystemUtil.encoding(SkyMeetingUtil
.getPreference(SkyMeetingUtil.USER_NO)));
new Network(handler, msg.getMessage()).start();
dialog = DialogUtil.showProgressDialog(ChargeActivity.this,
"正在发送数据....");
break;
}
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
dialog.dismiss();
Bundle bundle = msg.getData();
DialogUtil.showAlertDialog(ChargeActivity.this, "提示",
bundle.getString("msg"));
super.handleMessage(msg);
}
};
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mertbilgic.yazlab2;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
/**
*
* @author mertbilgic
*/
public class Main extends javax.swing.JFrame {
MatrixDraw matrix = null;
/**
* Creates new form Main
*/
public Main() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jRadioButton1 = new javax.swing.JRadioButton();
jScrollBar1 = new javax.swing.JScrollBar();
drawGraph = new javax.swing.JButton();
result = new javax.swing.JLabel();
enterMatrix = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
nodeCount = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
sourceText = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
sinkText = new javax.swing.JTextField();
maxFlowBtn = new javax.swing.JButton();
minCutBtn = new javax.swing.JButton();
jRadioButton1.setText("jRadioButton1");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
drawGraph.setText("Draw Graph");
drawGraph.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
drawGraphActionPerformed(evt);
}
});
enterMatrix.setText("Enter The Matrix ");
enterMatrix.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
enterMatrixActionPerformed(evt);
}
});
jLabel1.setText("Node Count:");
nodeCount.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nodeCountActionPerformed(evt);
}
});
jLabel2.setText("Source:");
jLabel3.setText("Sink:");
maxFlowBtn.setText("MaxFlow");
maxFlowBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
maxFlowBtnActionPerformed(evt);
}
});
minCutBtn.setText("MinCut");
minCutBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
minCutBtnActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(25, 25, 25)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(nodeCount, javax.swing.GroupLayout.DEFAULT_SIZE, 54, Short.MAX_VALUE)
.addComponent(sourceText))
.addComponent(sinkText, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(enterMatrix))
.addGroup(layout.createSequentialGroup()
.addGap(32, 32, 32)
.addComponent(drawGraph))))
.addGroup(layout.createSequentialGroup()
.addGap(32, 32, 32)
.addComponent(maxFlowBtn)
.addGap(110, 110, 110)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(minCutBtn))
.addComponent(result, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(97, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(49, 49, 49)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(enterMatrix)
.addComponent(jLabel1)
.addComponent(nodeCount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(sourceText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(sinkText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGap(12, 12, 12)
.addComponent(drawGraph)
.addGap(64, 64, 64)
.addComponent(result)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(minCutBtn)
.addComponent(maxFlowBtn))))
.addContainerGap(82, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void drawGraphActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_drawGraphActionPerformed
Board board = new Board("Test");
String source = sourceText.getText().toString();
String sink = sinkText.getText().toString();
if (matrix != null) {
board.createGUI(matrix.getGraph(), sink, source,"");
} else {
String message = "Enter The Garph";
board.flashMessage(message);
}
}//GEN-LAST:event_drawGraphActionPerformed
private void enterMatrixActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_enterMatrixActionPerformed
String text = nodeCount.getText().toString();
if (!text.isEmpty()) {
int count = Integer.parseInt(text);
matrix = new MatrixDraw(count);
matrix.createAndShowGui(matrix);
} else {
String message = "Enter The Node Count";
Board.flashMessage(message);
}
}//GEN-LAST:event_enterMatrixActionPerformed
private void nodeCountActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nodeCountActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_nodeCountActionPerformed
private void minCutBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_minCutBtnActionPerformed
MinCut min = new MinCut();
int source = Integer.parseInt(sourceText.getText().toString());
int sink = Integer.parseInt(sinkText.getText().toString());
int v = Integer.parseInt(nodeCount.getText().toString());
Result result = min.minCut(matrix.getGraph(), source, sink);
Board board = new Board("Test");
if (matrix != null) {
board.createGUI(result.getGraph(), String.valueOf(sink), String.valueOf(source),result.getMessage());
} else {
String message = "Enter The Garph";
board.flashMessage(message);
}
}//GEN-LAST:event_minCutBtnActionPerformed
private void maxFlowBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_maxFlowBtnActionPerformed
MaxFlow max = new MaxFlow();
int source = Integer.parseInt(sourceText.getText().toString());
int sink = Integer.parseInt(sinkText.getText().toString());
int v = Integer.parseInt(nodeCount.getText().toString());
max.setV(v);
Result result = max.fordFulkerson(matrix.getGraph(), source, sink);
Board board = new Board("Test");
String message = "The maximum possible flow is "+result.getStep();
if (matrix != null) {
board.createGUI(result.getGraph(), String.valueOf(sink), String.valueOf(source),message);
} else {
message = "Enter The Garph";
board.flashMessage(message);
}
}//GEN-LAST:event_maxFlowBtnActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Main().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton drawGraph;
private javax.swing.JButton enterMatrix;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JScrollBar jScrollBar1;
private javax.swing.JButton maxFlowBtn;
private javax.swing.JButton minCutBtn;
private javax.swing.JTextField nodeCount;
private javax.swing.JLabel result;
private javax.swing.JTextField sinkText;
private javax.swing.JTextField sourceText;
// End of variables declaration//GEN-END:variables
}
|
package com.training.day7.overriding;
import java.io.IOException;
public class OverrideTest {
public static void main(String[] args) throws IOException {
A a = new A();
B b = new B();
a.test();
b.test();
a.test2();
b.test2();
A a1 = new B();
System.out.println("Hello");
a1.test();
a1.test2();
a1.m1();
a1.m2(10);
System.out.println(a.i);
System.out.println(a.j);
System.out.println(b.i);
System.out.println(b.j);
System.out.println(a1.i);
System.out.println(a1.j);
}
}
|
package com.leontg77.teamcommands;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.scoreboard.Team;
/**
* Utilities class.
*
* @author LeonTG77
*/
@SuppressWarnings("deprecation")
public class Utils {
private static final Scoreboard BOARD = Bukkit.getScoreboardManager().getMainScoreboard();
/**
* Sends a message to everyone on the given team.
*
* @param team The team to use.
* @param message The message to send.
*/
public static void broadcastToTeam(Team team, String message) {
for (OfflinePlayer teammate : team.getPlayers()) {
Player online = teammate.getPlayer();
if (online == null) {
continue;
}
online.sendMessage(message);
}
}
/**
* Gets the team of the given player player.
*
* @param player the player in the team.
* @return The team, null if the player isn't on a team.
*/
public static Team getTeam(OfflinePlayer player) {
return BOARD.getPlayerTeam(player);
}
} |
package sample;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
public class ControllerDate2
{
@FXML TextField date11, date22;
@FXML ListView<Clients> lv1 = new ListView();
public void showww(ActionEvent event)
{
try
{
Configuration cfg = new Configuration(); cfg.configure("hibernate.cfg.xml");
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
DateFormat format = new SimpleDateFormat("yyyy-mm-dd", Locale.ENGLISH);
Date datee = format.parse(date11.getText());
Date dateee = format.parse(date22.getText());
Query qry = session.createQuery("SELECT a.date, b.fname, b.mname, b.lname, c.quantity, d.name" +
" FROM Sales a inner join Clients b on a.clientid=b.id " +
"inner join ProductSales c on a.id=c.saleid " +
"inner join Products d on d.id=c.productid" +
" where a.date between :datee and :dateee");
qry.setParameter("datee", datee);
qry.setParameter("dateee", dateee);
List<Object[]> r = qry.getResultList();
ObservableList l = FXCollections.observableArrayList();
for(Object[] elements: r)
{
Timestamp a= (Timestamp) elements[0];
Date d1=format.parse(String.valueOf(a)); l.add("Date: "+d1);
String b= (String) elements[1]; l.add("First name: "+b);
String c= (String) elements[2]; l.add("Middle name: "+c);
String d= (String) elements[3]; l.add("Last name: "+d);
int e=(int) elements[4]; l.add("Quantity: "+e);
String f= (String) elements[5]; l.add("Name of products: "+f);
String str=" "; l.add(str);
}
lv1.setItems(l);
}
catch (Exception e) { e.printStackTrace(); }
}
}
|
package Minggu12.Teori;
public class TelevisiJadul extends Elektronik {
private String modeInput;
public TelevisiJadul() {
this.modeInput = "Nyalakan televisi jadul dengan input : DVI";
}
public String getModeInput() {
return this.modeInput;
}
}
|
/**
*
*/
package main;
import java.util.List;
import java.util.Properties;
import twitter4j.DirectMessage;
import twitter4j.Paging;
import twitter4j.Status;
import twitter4j.StatusUpdate;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
/**
* @author Julian Kuerby
*
*/
public class Twitter {
private Properties prop;
private twitter4j.Twitter twitter;
public Twitter(Properties prop) {
this.prop = prop;
AccessToken accessToken = new AccessToken(prop.getProperty("twitter.accessToken"), prop.getProperty("twitter.accessTokenSecret"));
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(prop.getProperty("twitter.consumerKey"), prop.getProperty("twitter.consumerSecret"));
twitter.setOAuthAccessToken(accessToken);
}
public twitter4j.Twitter getTwitter() {
return twitter;
}
public void sendTweet(String message) throws TwitterException {
twitter.updateStatus(message);
}
public void sendMention(String message) throws NumberFormatException, TwitterException {
sendMention(Long.parseLong(prop.getProperty("twitter.user")), message);
}
public void sendMention(long userID, String message) throws TwitterException {
sendTweet("@" + twitter.showUser(userID).getScreenName() + " " + message);
}
public void sendReply(Status reply, String message) throws TwitterException {
StatusUpdate update = new StatusUpdate("@" + reply.getUser().getScreenName() + " " + message);
update.setInReplyToStatusId(reply.getId());
twitter.updateStatus(update);
}
// public void sendDm() {
//
// }
public void getTimeline() throws TwitterException {
List<Status> statuses = twitter.getHomeTimeline();
for (Status status : statuses) {
System.out.println(status.getUser().getScreenName() + ": " + status.getText());
}
}
public List<Status> getMentions() throws TwitterException {
long mentionId = Long.parseLong(prop.getProperty("twitter.readMentionsId", "1"));
Paging page = new Paging(mentionId);
List<Status> mentions = twitter.getMentions(page);
return mentions;
}
public List<DirectMessage> getDMs() throws TwitterException {
long dmId = Long.parseLong(prop.getProperty("twitter.readDmId", "1"));
Paging page = new Paging(dmId);
List<DirectMessage> dms = twitter.getDirectMessages(page);
return dms;
}
}
|
package risk;
public class pays {
}
|
package com.zhy.lxroundhead;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
/**
* Created by lixian on 2016/5/13.
*/
public class LxRoundImageViewThree extends ImageView {
Context ct;
public LxRoundImageViewThree(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
ct = context;
}
public LxRoundImageViewThree(Context context, AttributeSet attrs) {
super(context, attrs);
ct = context;
}
public LxRoundImageViewThree(Context context) {
super(context);
ct = context;
}
Paint paint;
Paint paint2;
@Override
protected void onDraw(Canvas canvas) {
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint2 = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.WHITE);
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.FILL);
if (getDrawable() == null) {
super.onDraw(canvas);
} else {
int width = getWidth();
int height = getHeight();
Bitmap mBitmap = resizeImage(getBitmap(getDrawable()), width, height);
int BitmapWidth = mBitmap.getWidth();
int BitmapHeight = mBitmap.getHeight();
Matrix matrix = new Matrix();
//实现实际大小图片存储
// canvas.drawBitmap(mBitmap, matrix, paint);
//画拓元
RectF rectF = new RectF();
float min = Math.min(width, height);
rectF.left = (width - min) / 2;
rectF.top = (height - min) / 2;
rectF.right = width - (width - min) / 2;
rectF.bottom = height - (height - min) / 2;
BitmapShader mShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP,Shader.TileMode.CLAMP);
paint.setShader(mShader);
//椭圆形
canvas.drawRoundRect(rectF, min / 2, min / 2, paint);
float radius = min / 2;
float cx = getWidth() / 2f;
float cy = getHeight() / 2f;
paint2.setAntiAlias(true);
paint2.setStyle(Paint.Style.STROKE);
paint2.setStrokeWidth(5);
paint2.setColor(ct.getResources().getColor(R.color.colorPrimary));
canvas.drawCircle(cx, cy, radius-5, paint2);
}
}
private Bitmap getBitmap(Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
} else {
int width = drawable.getIntrinsicWidth();
int height = drawable.getIntrinsicHeight();
Bitmap.Config config = drawable.getOpacity() == PixelFormat.OPAQUE ? Bitmap.Config.RGB_565 : Bitmap.Config.ARGB_8888;
Bitmap mBitmap = Bitmap.createBitmap(width, height, config);
Canvas canvas = new Canvas(mBitmap);
drawable.setBounds(0, 0, width, height);
drawable.draw(canvas);
return mBitmap;
}
}
//缩放图片实现显示
public static Bitmap resizeImage(Bitmap bitmap, int w, int h) {
Bitmap BitmapOrg = bitmap;
try {
int width = BitmapOrg.getWidth();
int height = BitmapOrg.getHeight();
int newWidth = w;
int newHeight = h;
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
// if you want to rotate the Bitmap
// matrix.postRotate(45);
Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width,
height, matrix, true);
return resizedBitmap;
} catch (Exception e) {
e.printStackTrace();
return bitmap;
}
}
}
|
package demo9.ingredients.newyork;
import demo9.ingredients.Cheese;
public class RegginoCheese implements Cheese {
}
|
/**
* Coppyright (C) 2020 Luvina
* MstJapanLogicsImpl.java, Nov 17, 2020, BuiTienDung
*/
package Manageruser.logics.impl;
import java.util.ArrayList;
import java.util.List;
import Manageruser.dao.MstJapanDAO;
import Manageruser.dao.impl.MstJapanDaoImpl;
import Manageruser.entities.MstGroupEntities;
import Manageruser.entities.MstJapanEntities;
import Manageruser.logics.MstGroupLogics;
import Manageruser.logics.MstJapanLogics;
/**
* @author Bui Tien Dung
*
*/
public class MstJapanLogicsImpl implements MstJapanLogics{
@Override
/**
* lay danh sách trình độ tiếng Nhật
* return danh sách trình độ tiếng Nhật
*/
public List<MstJapanEntities> getAllMstJapan() {
List<MstJapanEntities> mstJapan = null;
MstJapanDAO mst = new MstJapanDaoImpl();
mstJapan=mst.getAllMstJapan();
return mstJapan;
}
}
|
/**
* DNet eBusiness Suite
* Copyright: 2013 Nan21 Electronics SRL. All rights reserved.
* Use is subject to license terms.
*/
package seava.ad.security.authoriz;
import seava.j4e.api.security.IAuthorization;
public class AuthorizationForJob extends AbstractSecurity implements
IAuthorization {
@Override
public void authorize(String resourceName, String action, String rpcName)
throws Exception {
// If it doesn't throw exception is authorized
}
}
|
/*
* Copyright (c) 2012-2013 ${developer}, <http://windwaker.me>
*
* 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 me.windwaker.permissions.io.sql;
import java.util.Set;
import me.windwaker.permissions.io.UserManager;
import me.windwaker.permissions.permissible.User;
/*
* ------------------------------
* Table: | permissions_users |
* ------------------------------
* Fields: | name | group |
* ------------------------------
* Data Type: | text | text |
* ------------------------------
*/
public class SqlUserManager implements UserManager {
@Override
public void load() {
}
@Override
public void save() {
}
@Override
public void addUser(String username) {
}
@Override
public void removeUser(String username) {
}
@Override
public void saveUser(User user) {
}
@Override
public void loadUser(String user) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public User getUser(String name) {
return null;
}
@Override
public Set<User> getUsers() {
return null;
}
@Override
public void clear() {
}
}
|
package be.spring.app.persistence;
import be.spring.app.model.Address;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
* Created by u0090265 on 9/11/14.
*/
public interface AddressDao extends PagingAndSortingRepository<Address, Long>, JpaSpecificationExecutor<Address> {
}
|
package com.brasilprev.customermanagement.create.entrypoint;
import java.io.IOException;
import org.apache.http.HttpStatus;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import com.brasilprev.customermanagement.commons.BasicIntegrationTest;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.module.jsv.JsonSchemaValidator;
@DirtiesContext(classMode = ClassMode.AFTER_CLASS)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class CreateClientEntrypointTest extends BasicIntegrationTest {
@Test
public void createClientFailureWithoutBody() {
RestAssured.given()
.contentType(ContentType.JSON)
.post(buildURL(CreateClientEntrypoint.CREATE_CLIENT_URL))
.then()
.statusCode(HttpStatus.SC_BAD_REQUEST);
}
@Test
public void createClientFailureValidationField() {
RestAssured.given()
.contentType(ContentType.JSON)
.with()
.body("{}")
.post(buildURL(CreateClientEntrypoint.CREATE_CLIENT_URL))
.then()
.statusCode(HttpStatus.SC_BAD_REQUEST)
.body(JsonSchemaValidator.matchesJsonSchemaInClasspath("schemas/create_client/create_client_validation_error.json")
.using(jsonSchemaFactory));
}
@Test
public void createClientSuccess() throws IOException {
RestAssured.given()
.contentType(ContentType.JSON)
.with()
.body(loadBody("example/create_client/create_client_success.json"))
.post(buildURL(CreateClientEntrypoint.CREATE_CLIENT_URL))
.then()
.statusCode(HttpStatus.SC_CREATED)
.body(JsonSchemaValidator.matchesJsonSchemaInClasspath("schemas/create_client/create_client_success.json")
.using(jsonSchemaFactory))
.body("client.client_id", Matchers.equalTo(1));
}
}
|
package com.mideas.rpg.v2.hud;
import java.util.Arrays;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.Display;
import com.mideas.rpg.v2.Interface;
import com.mideas.rpg.v2.Mideas;
import com.mideas.rpg.v2.game.unit.ClassType;
import com.mideas.rpg.v2.game.unit.Unit;
import com.mideas.rpg.v2.render.Draw;
import com.mideas.rpg.v2.render.Sprites;
import com.mideas.rpg.v2.FontManager;
import com.mideas.rpg.v2.utils.Color;
public class EndFightFrame {
private static boolean endFightEvent;
private final static String retry = "Retry";
private final static String quit = "Quit";
private final static String player1Won = "Player 1 won";
private final static String player2Won = "Playe 2 won";
public static void draw() {
if(Interface.getAdminPanelFrameStatus()) {
Interface.closeAdminPanelFrame();
}
if(Interface.getCharacterFrameStatus()) {
CharacterFrame.setHoverFalse();
}
if(Interface.getContainerFrameStatus()) {
ContainerFrame.setHoverFalse();
}
if(Interface.isSpellBookFrameActive()) {
Arrays.fill(SpellBookFrame.getHoverBook(), false);
}
//TODO: use popup class
Draw.drawQuad(Sprites.alert, Display.getWidth()/2-Sprites.button_hover.getImageWidth()/2-105, Display.getHeight()/2-80);
if(Mideas.mouseX() >= Display.getWidth()/2-130 && Mideas.mouseX() <= Display.getWidth()/2-3 && Mideas.mouseY() <= Display.getHeight()/2-18 && Mideas.mouseY() >= Display.getHeight()/2-37) {
Draw.drawQuad(Sprites.button_hover, Display.getWidth()/2-Sprites.button_hover.getImageWidth()/2-70, Display.getHeight()/2-43);
}
else {
Draw.drawQuad(Sprites.button, Display.getWidth()/2-Sprites.button_hover.getImageWidth()/2-70, Display.getHeight()/2-43);
}
if(Mideas.mouseX() >= Display.getWidth()/2+7 && Mideas.mouseX() <= Display.getWidth()/2+134 && Mideas.mouseY() <= Display.getHeight()/2-15 && Mideas.mouseY() >= Display.getHeight()/2-38) {
Draw.drawQuad(Sprites.button_hover2, Display.getWidth()/2-Sprites.button_hover.getImageWidth()/2+70, Display.getHeight()/2-43);
}
else {
Draw.drawQuad(Sprites.button2, Display.getWidth()/2-Sprites.button_hover.getImageWidth()/2+70, Display.getHeight()/2-43);
}
FontManager.get("FRIZQT", 13).drawStringShadow(Display.getWidth()/2-FontManager.get("FRIZQT", 13).getWidth(retry)/2-69, Display.getHeight()/2-41, retry, Color.WHITE, Color.BLACK, 1, 1, 1);
FontManager.get("FRIZQT", 13).drawStringShadow(Display.getWidth()/2-FontManager.get("FRIZQT", 13).getWidth(quit)/2+69, Display.getHeight()/2-41, quit, Color.WHITE, Color.BLACK, 1, 1, 1);
if(Mideas.joueur1().getStamina() <= 0) {
FontManager.get("FRIZQT", 16).drawStringShadow(Display.getWidth()/2-50, Display.getHeight()/2-66, player2Won, Color.WHITE, Color.BLACK, 1, 1, 1);
}
else if(Mideas.joueur1().getTarget().getStamina() <= 0) {
FontManager.get("FRIZQT", 16).drawStringShadow(Display.getWidth()/2-50, Display.getHeight()/2-66, player1Won, Color.WHITE, Color.BLACK, 1, 1, 1);
if(!endFightEvent) {
doEndFightEvent();
endFightEvent = true;
}
}
}
public static void mouseEvent() {
if(Mouse.getEventButton() == 0) {
if(!Mouse.getEventButtonState()) {
if(Mideas.mouseX() >= Display.getWidth()/2+7 && Mideas.mouseX() <= Display.getWidth()/2+134 && Mideas.mouseY() <= Display.getHeight()/2-15 && Mideas.mouseY() >= Display.getHeight()/2-38) {
Mideas.closeGame();
}
else if(Mideas.mouseX() >= Display.getWidth()/2-130 && Mideas.mouseX() <= Display.getWidth()/2-3 && Mideas.mouseY() <= Display.getHeight()/2-18 && Mideas.mouseY() >= Display.getHeight()/2-37) {
Mideas.joueur1().setStamina(Mideas.joueur1().getMaxStamina());
Mideas.joueur1().setMana(Mideas.joueur1().getMaxMana());
LogChat.setStatusText("");
LogChat.setStatusText2("");
endFightEvent = false;
Mideas.joueur1().setTarget(new Unit(100, 10000, 10000, 3000, 3000, 1, "", ClassType.NPC));
}
}
}
}
private static void dropManager() {
/*DropManager.loadDropTable(Mideas.target().getId());
int i = 0;
double random = Math.random();
while(i < DropManager.getList(Mideas.joueur2().getId()).size()) {
if(random >= DropManager.getList(Mideas.joueur2().getId()).get(i).getDropRate()) {
if(DropManager.getList(Mideas.joueur2().getId()).get(i).getAmount() > 1) {
Mideas.joueur1().addItem(DropManager.getList(Mideas.joueur2().getId()).get(i).getItem(), DropManager.getList(Mideas.joueur2().getId()).get(i).getAmount());
}
else {
Mideas.joueur1().addItem(DropManager.getList(Mideas.joueur2().getId()).get(i).getItem(), 1);
}
}
i++;
}*/
}
public static boolean getEndFightEventState() {
return endFightEvent;
}
public static void setEndFightEvent(boolean we) {
endFightEvent = we;
}
public static void doEndFightEvent() {
//Mideas.joueur1().setExp(Mideas.joueur1().getExp()+Mideas.joueur2().getExpGained());
//Mideas.joueur1().setGold(Mideas.joueur1().getGold()+Mideas.joueur2().getGoldGained());
dropManager();
}
}
|
package com.lukasz.bluesoftproject.system;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.persistence.EntityNotFoundException;
import java.util.List;
@Service
public class SystemService {
private SystemRepository systemRepository;
public SystemService(@Autowired SystemRepository systemRepository) {
this.systemRepository = systemRepository;
}
public List<System> getAll() {
return systemRepository.findAll();
}
public System findById(Integer id) {
return systemRepository.findById(id).orElseThrow(EntityNotFoundException::new);
}
}
|
package com.tencent.mm.sdk.platformtools;
public interface aw$a {
void aou();
}
|
/**
* This file is part of
*
* CRAFTY - Competition for Resources between Agent Functional TYpes
*
* Copyright (C) 2014 School of GeoScience, University of Edinburgh, Edinburgh, UK
*
* CRAFTY is free software: You can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* CRAFTY 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* School of Geoscience, University of Edinburgh, Edinburgh, UK
*
*/
package org.volante.abm.example;
import static java.lang.Math.sqrt;
import static org.volante.abm.example.SimpleCapital.HUMAN;
import static org.volante.abm.example.SimpleCapital.NATURAL_CROPS;
import static org.volante.abm.example.SimpleService.FOOD;
import static org.volante.abm.example.SimpleService.HOUSING;
import static org.volante.abm.example.SimpleService.RECREATION;
import static org.volante.abm.example.SimpleService.TIMBER;
import static org.volante.abm.example.SimpleService.simpleServices;
import org.junit.Test;
import org.volante.abm.data.Capital;
import org.volante.abm.data.Service;
import com.moseph.modelutils.fastdata.DoubleMap;
public class SimpleProductionTest extends BasicTestsUtils {
DoubleMap<Service> production = new DoubleMap<Service>(simpleServices);
DoubleMap<Service> expected = new DoubleMap<Service>(simpleServices);
SimpleProductionModel fun = new SimpleProductionModel();
/*
* Capitals: HUMAN(0), INFRASTRUCTURE(1), ECONOMIC(2), NATURAL_GRASSLAND(3), NATURAL_FOREST(4),
* NATURAL_CROPS(5), NATURE_VALUE(6)
*
* Services: HOUSING(0), TIMBER(1), FOOD(2), RECREATION(3),
*/
@Test
public void testProduction() {
// fun.initialise( modelData );
checkProduction("All zeros should be full production", 1, 1, 1, 1);
fun.setWeight(HUMAN, HOUSING, 1);
checkProduction("Putting a 1 in the matrix stops production", 0, 1, 1, 1);
c11.setBaseCapitals(capitals(0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5));
checkProduction("Giving all baseCapitals 0.5 allows production at 0.5", 0.5, 1, 1, 1);
fun.setWeight(NATURAL_CROPS, FOOD, 1);
checkProduction("Setting Natural Crops weight changes food production", 0.5, 1, 0.5, 1);
fun.setWeight(NATURAL_CROPS, FOOD, 0.5);
checkProduction("Setting Natural Crops weight changes food production", 0.5, 1, sqrt(0.5),
1);
fun.setWeight(FOOD, 5);
checkProduction("Setting production weights", 0.5, 1, 5 * sqrt(0.5), 1);
}
@Test
public void testProductionForExampleValues() {
fun = new SimpleProductionModel(extensiveFarmingCapitalWeights,
extensiveFarmingProductionWeights);
checkProduction("Setting everything all at once and weighting it", cellCapitalsA,
extensiveFarmingOnCA);
checkProduction("Setting everything all at once and weighting it", cellCapitalsB,
extensiveFarmingOnCB);
fun = new SimpleProductionModel(forestryCapitalWeights, forestryProductionWeights);
checkProduction("Setting everything all at once and weighting it", cellCapitalsA,
forestryOnCA);
checkProduction("Setting everything all at once and weighting it", cellCapitalsB,
forestryOnCB);
}
@Test
public void testDeserealisation() throws Exception {
SimpleProductionModel model = runInfo.getPersister().readXML(SimpleProductionModel.class,
"xml/LowIntensityArableProduction.xml", null);
model.initialise(modelData, runInfo, null);
testLowIntensityArableProduction(model);
}
public static void testLowIntensityArableProduction(SimpleProductionModel model) {
assertEqualMaps(services(0, 0, 4, 0), model.productionWeights);
assertEqualMaps(capitals(0, 0, 0, 0, 0, 1, 0), model.capitalWeights.getRow(FOOD));
assertEqualMaps(capitals(0, 0, 0, 0, 0, 0, 0), model.capitalWeights.getRow(TIMBER));
assertEqualMaps(capitals(0, 0, 0, 0, 0, 0, 0), model.capitalWeights.getRow(HOUSING));
assertEqualMaps(capitals(0, 0, 0, 0, 0, 0, 0), model.capitalWeights.getRow(RECREATION));
}
public static void testHighIntensityArableProduction(SimpleProductionModel model) {
assertEqualMaps(services(0, 0, 10, 0), model.productionWeights);
assertEqualMaps(capitals(0.5, 0.5, 0.5, 0, 0, 1, 0), model.capitalWeights.getRow(FOOD));
assertEqualMaps(capitals(0, 0, 0, 0, 0, 0, 0), model.capitalWeights.getRow(TIMBER));
assertEqualMaps(capitals(0, 0, 0, 0, 0, 0, 0), model.capitalWeights.getRow(HOUSING));
assertEqualMaps(capitals(0, 0, 0, 0, 0, 0, 0), model.capitalWeights.getRow(RECREATION));
}
public static void testCommercialForestryProduction(SimpleProductionModel model) {
assertEqualMaps(services(0, 8, 0, 0), model.productionWeights);
assertEqualMaps(capitals(0, 0, 0, 0, 0, 0, 0), model.capitalWeights.getRow(FOOD));
assertEqualMaps(capitals(0, 0, 0, 0, 1, 0, 0), model.capitalWeights.getRow(TIMBER));
assertEqualMaps(capitals(0, 0, 0, 0, 0, 0, 0), model.capitalWeights.getRow(HOUSING));
assertEqualMaps(capitals(0, 0, 0, 0, 0, 0, 0), model.capitalWeights.getRow(RECREATION));
}
void checkProduction(String msg, double... vals) {
checkProduction(msg, services(vals));
}
void checkProduction(String msg, DoubleMap<Capital> cellCapitals, DoubleMap<Service> expected) {
c11.setBaseCapitals(cellCapitals);
fun.production(c11, production);
assertEqualMaps(msg, expected, production);
}
void checkProduction(String msg, DoubleMap<Service> expected) {
fun.production(c11, production);
assertEqualMaps(msg, expected, production);
}
}
|
package examiner;
import examiner.agent.pool.IAgentPool;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class NetworkExaminerManagerShell extends NetworkExaminerManager{
public NetworkExaminerManagerShell(){
pools = new HashMap<String, Map<Integer, IAgentPool>>();
}
String chooseAction(Map<String, List<Double>> actionValues) {
return "";
}
}
|
package com.flipkart.assignment.application;
import com.flipkart.assignment.enums.Genre;
import com.flipkart.assignment.enums.ReviewerType;
import com.flipkart.assignment.service.*;
/**
* @author amarnath.pathak
* @date 01/12/19
**/
public class MovieReviewApplication {
private static UserService userService = FlipKartUserService.getInstance();
private static MovieService movieService = FlipKartMovieService.getInstance();
private static ReviewService reviewService = FlipKartReviewService.getInstance();
public static void main(String[] args) {
movieService.addMovie("Don", 2006, Genre.ACTION);
movieService.addMovie("Tiger", 2012, Genre.ACTION);
movieService.addMovie("Padmavat", 2018, Genre.DRAMA);
movieService.addMovie("Lunchbox-2", 2020, Genre.DRAMA);
movieService.addMovie("Guru", 2006, Genre.DRAMA);
movieService.addMovie("Metro", 2016, Genre.ROMANCE);
movieService.addMovie("Metro", 2016, Genre.ROMANCE);
movieService.addMovie("Krrish", 2006, Genre.ACTION);
userService.addUser("SRK");
userService.addUser("Salman");
userService.addUser("Deepika");
reviewService.addReview("SRK", "Don", 2);
System.out.println();
reviewService.addReview("SRK", "Padmavat", 8);
System.out.println();
reviewService.addReview("Salman", "Don", 5);
System.out.println();
reviewService.addReview("Deepika", "Don", 9);
System.out.println();
reviewService.addReview("Deepika", "Guru", 6);
System.out.println();
reviewService.addReview("SRK", "Don", 10);
System.out.println();
reviewService.addReview("Deepika", "Lunchbox-2", 5);
System.out.println();
reviewService.addReview("SRK", "Tiger", 5);
System.out.println();
reviewService.addReview("SRK", "Metro", 7);
System.out.println();
reviewService.addReview("Salman", "Krrish", 9);
System.out.println();
reviewService.addReview("SRK", "Guru", 7);
System.out.println();
reviewService.addReview("Salman", "Metro", 8);
System.out.println();
reviewService.getTopMovieScoredByAndReleaseYear(2, null, 2006);
System.out.println();
reviewService.getTopMovieScoredByAndReleaseYear(2, ReviewerType.CRITIC, 2016);
System.out.println();
reviewService.getTopMovieScoredByAndReleaseYear(2, ReviewerType.VIEWER, 2012);
System.out.println();
reviewService.getTopMovieScoredByAndGenre(1, null, Genre.ACTION);
System.out.println();
reviewService.getTopMovieScoredByAndGenre(1, ReviewerType.VIEWER, Genre.ROMANCE);
System.out.println();
reviewService.getTopMovieScoredByAndGenre(1, ReviewerType.CRITIC, Genre.DRAMA);
System.out.println();
reviewService.averageSore(2006);
System.out.println();
reviewService.averageSore(2012);
System.out.println();
reviewService.averageSore(2016);
System.out.println();
reviewService.averageSore(2018);
System.out.println();
reviewService.averageSore(2020);
System.out.println();
reviewService.averageSore(Genre.ACTION);
System.out.println();
reviewService.averageSore(Genre.DRAMA);
System.out.println();
reviewService.averageSore(Genre.ROMANCE);
System.out.println();
}
}
|
package com.xwq520.classload;
public class C {
static {
System.out.println("class c is created");
}
public C() {
System.out.println("class C creMethod");
}
}
|
package test;
import java.util.Vector;
public class VectorTest {
private static Vector<Integer> vector=new Vector<Integer>();
public static void main(String[] args) {
test1();
}
static void test1(){
while(true){
for (int i = 0; i < 10; i++) {
vector.add(i);
}
Thread removeThread=new Thread(new Runnable() {
@Override
public void run() {
// synchronized (vector) {
for (int i = 0; i < vector.size(); i++) {
System.out.println("remove:"+i);
vector.remove(i);
}
// }
}
});
removeThread.start();
Thread getThread=new Thread(new Runnable() {
@Override
public void run() {
// synchronized (vector) {
for (int i = 0; i < vector.size(); i++) {
System.out.println("get:"+i);
vector.get(i);
}
// }
}
});
getThread.start();
}
}
static void test2(){
Thread[] threads=new Thread[100];
for (int i = 0; i < threads.length; i++) {
threads[i]=new Thread(new Runnable() {
@Override
public void run() {
for (int j = 0; j < 1000; j++) {
dealVector();
}
}
});
threads[i].start();
}
while (Thread.activeCount()>1) {
Thread.yield();
}
System.out.println(vector);
}
static void dealVector(){
for (int i = 0; i < 100; i++) {
if(!vector.contains(i)){
vector.add(i);
}
}
}
}
|
/*
* LumaQQ - Java QQ Client
*
* Copyright (C) 2004 luma <stubma@163.com>
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.tsinghua.lumaqq.qq.beans;
import java.nio.ByteBuffer;
import edu.tsinghua.lumaqq.qq.QQ;
/**
* 传送文件的ip,端口信息封装类
*
* @author luma
*/
public class FileTransferArgs {
// 传输类型
public byte transferType;
// 连接方式
public byte connectMode;
// 发送者外部ip
public byte[] internetIp;
// 发送者外部端口
public int internetPort;
// 第一个监听端口
public int majorPort;
// 发送者真实ip
public byte[] localIp;
// 第二个监听端口
public int minorPort;
/**
* 给定一个输入流,解析FileTransferArgs结构
* @param buf
*/
public void readBean(ByteBuffer buf) throws Exception {
// 跳过19个无用字节
buf.position(buf.position() + 19);
// 读取传输类型
transferType = buf.get();
// 读取连接方式
connectMode = buf.get();
// 读取发送者外部ip
internetIp = new byte[4];
buf.get(internetIp);
// 读取发送者外部端口
internetPort = buf.getChar();
// 读取文件传送端口
if(connectMode != QQ.QQ_TRANSFER_FILE_DIRECT_TCP)
majorPort = buf.getChar();
else
majorPort = internetPort;
// 读取发送者真实ip
localIp = new byte[4];
buf.get(localIp);
// 读取发送者真实端口
minorPort = buf.getChar();
}
}
|
package kr.co.toondra.common.aspect;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
@Aspect
@Component("LogAspect")
public class LogAspect {
protected Logger logger = LoggerFactory.getLogger(this.getClass());
@SuppressWarnings("unchecked")
@Before("execution(* kr.co.toondra.*..controller.*Controller.*(..))")
public void beforeControllerLog(JoinPoint jp){
MDC.put("UUID", UUID.randomUUID().toString().replaceAll("-", ""));
String className = jp.getTarget().getClass().getSimpleName();
String methodName = jp.getSignature().getName();
logger.info("\t[TOONDRA ST][" + className + " - " + methodName + "]");
Object[] objescts = jp.getArgs();
for(Object obj : objescts) {
if(obj instanceof HttpServletRequest) {
HttpServletRequest request = (HttpServletRequest)obj;
Enumeration<String> enumer = request.getParameterNames();
if(enumer.hasMoreElements()) {
logger.debug("==["+methodName+" request parameter]==");
while(enumer.hasMoreElements()) {
String key = enumer.nextElement();
logger.debug(" ["+key+"]:"+request.getParameter(key));
}
}
break;
} else if(obj instanceof Map) {
Map<String, Object> map = (Map<String, Object>)obj;
if(!map.isEmpty()) {
Iterator<String> iter = map.keySet().iterator();
logger.debug("==["+methodName+" request parameter]==");
while(iter.hasNext()) {
String key = iter.next();
logger.debug(" ["+key+"]:"+map.get(key));
}
}
break;
} else if(obj instanceof String) {
logger.debug("==["+methodName+" request parameter]==");
logger.debug((String)obj);
}
}
}
@After("execution(* kr.co.toondra.*..controller.*Controller.*(..))")
public void afterControllerLog(JoinPoint jp){
String className = jp.getTarget().getClass().getSimpleName();
String methodName = jp.getSignature().getName();
logger.info("\t[TOONDRA ED][" + className + " - " + methodName + "]");
}
@Before("execution(* kr.co.toondra.*..service.*Service.*(..))")
public void beforeServiceLog(JoinPoint jp){
String className = jp.getTarget().getClass().getSimpleName();
String methodName = jp.getSignature().getName();
logger.info("\t[TOONDRA ST][" + className + " - " + methodName + "]");
}
@After("execution(* kr.co.toondra.*..service.*Service.*(..))")
public void afterServiceLog(JoinPoint jp){
String className = jp.getTarget().getClass().getSimpleName();
String methodName = jp.getSignature().getName();
logger.info("\t[TOONDRA ED][" + className + " - " + methodName + "]");
}
}
|
package de.jmda.gen.sample.xml.jaxb.builder;
import java.io.IOException;
import org.junit.Test;
import de.jmda.gen.GeneratorException;
import de.jmda.sample.gen.xml.jaxb.builder.JAXBTypesBuilderGenerator;
public class JUTJAXBTypesBuilderGenerator
{
@Test
public void generate() throws GeneratorException, IOException
{
JAXBTypesBuilderGenerator.generate(
de.jmda.gen.sample.xml.jaxb.builder.testtypes.simple.Car.class.getPackage(),
//"./src/test/java/de/jmda/gen/sample/xml/jaxb/builder/testtypes/simple",
"de/jmda/gen/sample/xml/jaxb/builder/testtypes/simple/builder",
"./src/gen/java");
}
} |
package lab1.q5;
import java.util.Scanner;
public class CalculateSum {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.print(" Enter n number : ");
int n = sc.nextInt(); // n number
int x = 3, y = 5;
System.out.println(sum(n, x, y));
sc.close();
}
static int sum(int N, int X, int Y)
{
int S1, S2, S3;
S1 = ((N / X)) * (2 * X + (N / X - 1) * X) / 2;
S2 = ((N / Y)) * (2 * Y + (N / Y - 1) * Y) / 2;
S3 = ((N / (X * Y))) * (2 * (X * Y) + (N / (X * Y) - 1) * (X * Y))/ 2;
return S1 + S2 - S3;
}
}
|
/*
* Copyright 2002-2013 the original author or 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.springframework.integration.aws.s3.core;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;
import org.springframework.integration.aws.core.AWSCredentials;
import org.springframework.integration.aws.core.AbstractAWSClientFactory;
import org.springframework.util.Assert;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.AccessControlList;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.s3.model.CanonicalGrantee;
import com.amazonaws.services.s3.model.EmailAddressGrantee;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.GroupGrantee;
import com.amazonaws.services.s3.model.ListObjectsRequest;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.Permission;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.transfer.TransferManager;
import com.amazonaws.services.s3.transfer.TransferManagerConfiguration;
import com.amazonaws.services.s3.transfer.Upload;
/**
* The default, out of the box implementation of the {@link AmazonS3Operations} that is implemented
* using AWS SDK.
*
* @author Amol Nayak
*
* @since 0.5
*
*/
public class DefaultAmazonS3Operations extends AbstractAmazonS3Operations {
private final AWSCredentials credentials;
private AmazonS3Client client;
private volatile TransferManager transferManager; //Used to upload to S3
private volatile ThreadPoolExecutor threadPoolExecutor;
private volatile AbstractAWSClientFactory<AmazonS3Client> s3Factory;
/**
* Constructor
* @param credentials
*/
public DefaultAmazonS3Operations(final AWSCredentials credentials) {
super(credentials);
this.credentials = credentials;
s3Factory = new AbstractAWSClientFactory<AmazonS3Client>() {
@Override
protected AmazonS3Client getClientImplementation() {
String accessKey = credentials.getAccessKey();
String secretKey = credentials.getSecretKey();
BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
return new AmazonS3Client(credentials);
}
};
}
@Override
protected void init() {
client = s3Factory.getClient(getAwsEndpoint());
if(threadPoolExecutor == null) {
//Will use the Default Executor,
//See com.amazonaws.services.s3.transfer.internal.TransferManagerUtils for more details
transferManager = new TransferManager(client);
}
else {
transferManager = new TransferManager(client, threadPoolExecutor);
}
//As per amazon it is recommended to use Multi part upload above 100 MB
long multipartUploadThreshold = getMultipartUploadThreshold();
if(multipartUploadThreshold > 0) {
TransferManagerConfiguration config = new TransferManagerConfiguration();
if(multipartUploadThreshold > Integer.MAX_VALUE) {
config.setMultipartUploadThreshold(Integer.MAX_VALUE); //2GB
}
else {
config.setMultipartUploadThreshold((int)multipartUploadThreshold);
}
transferManager.setConfiguration(config);
}
//If none is set, we use the default
}
/**
* The implementation that uses the AWS SDK to list objects from the given bucket
*
* @param bucketName The bucket in which we want to list the objects in
* @param nextMarker The number of objects can be very large and this serves as the marker
* for remembering the last record fetch in the last retrieve operation.
* @param pageSize The max number of records to be retrieved in one list object operation.
* @param prefix The prefix for the list operation, this can serve as the folder whose contents
* are to be listed.
*/
@Override
protected PaginatedObjectsView doListObjects(String bucketName,
String nextMarker, int pageSize, String prefix) {
ListObjectsRequest listObjectsRequest =
new ListObjectsRequest()
.withBucketName(bucketName)
.withPrefix(prefix)
.withMarker(nextMarker);
if(pageSize > 0) {
listObjectsRequest.withMaxKeys(pageSize);
}
ObjectListing listing = client.listObjects(listObjectsRequest);
PaginatedObjectsView view = null;
List<com.amazonaws.services.s3.model.S3ObjectSummary> summaries = listing.getObjectSummaries();
if(summaries != null && !summaries.isEmpty()) {
List<S3ObjectSummary> objectSummaries = new ArrayList<S3ObjectSummary>();
for(final com.amazonaws.services.s3.model.S3ObjectSummary summary:summaries) {
S3ObjectSummary summ = new S3ObjectSummary() {
public long getSize() {
return summary.getSize();
}
public Date getLastModified() {
return summary.getLastModified();
}
public String getKey() {
return summary.getKey();
}
public String getETag() {
return summary.getETag();
}
public String getBucketName() {
return summary.getBucketName();
}
};
objectSummaries.add(summ);
}
view = new PagninatedObjectsViewImpl(objectSummaries,listing.getNextMarker());
}
return view;
}
/**
* Gets the object from the given bucket with the given key using the AWS SDK implementation
*
* @param bucketName
* @param key
* @return The Amazon S3 Object representing the Object in S3, may be null.
*/
@Override
protected AmazonS3Object doGetObject(String bucketName, String key) {
GetObjectRequest request = new GetObjectRequest(bucketName, key);
S3Object s3Object;
try {
s3Object = client.getObject(request);
} catch (AmazonS3Exception e) {
if("NoSuchKey".equals(e.getErrorCode())) {
//If the key is not found, return null rather than throwing the exception
return null;
}
else {
//throw the exception to caller in all other cases
throw e;
}
}
return new AmazonS3Object(s3Object.getObjectMetadata().getUserMetadata(),
s3Object.getObjectMetadata().getRawMetadata(),
s3Object.getObjectContent(),
null);
}
/**
* The implementation puts the given {@link File} instance to the provided bucket against
* the given key.
*
* @param bucketName The bucket on S3 where this object is to be put
* @param key The key against which this Object is to be stored in S3
* @param file resource to be uploaded to S3
* @param objectACL the Object's Access controls for the object to be uploaded
* @param userMetadata The user's metadata to be associated with the object uploaded
* @param stringContentMD5 The MD5 sum of the contents of the file to be uploaded
*/
@Override
public void doPut(String bucketName, String key, File file, AmazonS3ObjectACL objectACL,
Map<String, String> userMetadata,String stringContentMD5) {
ObjectMetadata metadata = new ObjectMetadata();
PutObjectRequest request = new PutObjectRequest(bucketName, key, file);
request.withMetadata(metadata);
if(stringContentMD5 != null) {
metadata.setContentMD5(stringContentMD5);
}
if(userMetadata != null) {
metadata.setUserMetadata(userMetadata);
}
Upload upload;
try {
upload = transferManager.upload(request);
} catch (Exception e) {
throw new AmazonS3OperationException(
credentials.getAccessKey(), bucketName,
key,
"Encountered Exception while invoking upload on multipart/single thread file, " +
"see nested exceptions for more details",
e);
}
//Wait till the upload completes, the call to putObject is synchronous
try {
if(logger.isInfoEnabled()) {
logger.info("Waiting for Upload to complete");
}
upload.waitForCompletion();
if(logger.isInfoEnabled()) {
logger.info("Upload completed");
}
} catch (Exception e) {
throw new AmazonS3OperationException(
credentials.getAccessKey(), bucketName,
key,
"Encountered Exception while uploading the multipart/single thread file, " +
"see nested exceptions for more details",
e);
}
//Now since the object is present on S3, set the AccessControl list on it
//Please note that it is not possible to set the object ACL with the
//put object request, and hence both these operations cannot be atomic
//it is possible the objects is uploaded and the ACl not set due to some
//failure
if(objectACL != null) {
if(logger.isInfoEnabled()) {
logger.info("Setting Access control list for key " + key);
}
try {
client.setObjectAcl(bucketName, key,
getAccessControlList(bucketName, key, objectACL));
} catch (Exception e) {
throw new AmazonS3OperationException(
credentials.getAccessKey(), bucketName,
key,
"Encountered Exception while setting the Object ACL for key , " + key +
"see nested exceptions for more details",
e);
}
if(logger.isDebugEnabled()) {
logger.debug("Successfully set the object ACL");
}
}
}
/**
* Gets the {@link AccessControlList} from the given {@link AmazonS3ObjectACL}
*/
private AccessControlList getAccessControlList(String bucketName,String key,AmazonS3ObjectACL acl) {
AccessControlList accessControlList = null;
if(acl != null) {
if(!acl.getGrants().isEmpty()) {
accessControlList = client.getObjectAcl(bucketName, key);
for(ObjectGrant objGrant:acl.getGrants()) {
Grantee grantee = objGrant.getGrantee();
com.amazonaws.services.s3.model.Grantee awsGrantee;
if(grantee.getGranteeType() == GranteeType.CANONICAL_GRANTEE_TYPE) {
awsGrantee = new CanonicalGrantee(grantee.getIdentifier());
}
else if(grantee.getGranteeType() == GranteeType.EMAIL_GRANTEE_TYPE) {
awsGrantee = new EmailAddressGrantee(grantee.getIdentifier());
}
else {
awsGrantee = GroupGrantee.parseGroupGrantee(grantee.getIdentifier());
if(awsGrantee == null) {
logger.warn("Group grantee with identifier: \"" + grantee.getIdentifier() + "\" not found. skipping this grant");
continue;
}
}
ObjectPermissions perm = objGrant.getPermission();
Permission permission;
if(perm == ObjectPermissions.READ) {
permission = Permission.Read;
}
else if(perm == ObjectPermissions.READ_ACP) {
permission = Permission.ReadAcp;
}
else
permission = Permission.WriteAcp;
accessControlList.grantPermission(awsGrantee, permission);
}
}
}
return accessControlList;
}
/**
* Gets the thread pool executor that will be used to upload the object in multiparts
* concurrently
*/
public ThreadPoolExecutor getThreadPoolExecutor() {
return threadPoolExecutor;
}
/**
* Used only when we upload the data using multi part upload. The thread pool will be used
* to upload the data concurrently
*
* @param threadPoolExecutor May not be null
*/
public void setThreadPoolExecutor(ThreadPoolExecutor threadPoolExecutor) {
Assert.notNull(threadPoolExecutor, "'threadPoolExecutor' is null");
this.threadPoolExecutor = threadPoolExecutor;
}
}
|
package org.yipuran.gsonhelper.test;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.net.URISyntaxException;
import org.yipuran.gsonhelper.JsonPattern;
/**
* TestJsonPattern.java
*/
public class TestJsonPattern2{
public static void main(String[] args) throws IOException, URISyntaxException{
boolean res;
JsonPattern pattern = new JsonPattern(getRreader("form.json"));
res = pattern.validate(readString("data2.json"));
System.out.println("validate res = " + res);
pattern.unmatches().stream().forEach(e->{
System.out.println(e.getKey()+" :: "+e.getValue());
});
pattern = new JsonPattern(getRreader("form.json")).addOptional("e:e2").addRegExpress("g", "^[a-z]+$")
.addMinValue("e:e3", 5 ).addMaxValue("e:e3", 12 );
res = pattern.validate(readString("data2.json"));
System.out.println("validate res = " + res);
pattern.unmatches().stream().forEach(e->{
System.out.println(e.getKey()+" :: "+e.getValue());
});
}
static Reader getRreader(String filename) throws IOException, URISyntaxException{
return new FileReader(new File(ClassLoader.getSystemClassLoader()
.getResource(TestJsonPattern2.class.getPackage().getName()
.replaceAll("\\.", "/") + "/" + filename).toURI()));
}
static String readString(String filename) throws IOException, URISyntaxException{
try(InputStream in = new FileInputStream(new File(ClassLoader.getSystemClassLoader()
.getResource(TestJsonPattern2.class.getPackage().getName().replaceAll("\\.", "/") + "/" + filename).toURI()));
ByteArrayOutputStream bo = new ByteArrayOutputStream()){
byte[] b = new byte[1024];
int len;
while((len = in.read(b, 0, b.length)) > 0){
bo.write(b, 0, len);
}
bo.flush();
return bo.toString();
}
}
/*** for Java11 ***
public static Reader getRreader(Class<?> cls, String filename) throws IOException, URISyntaxException{
return new FileReader(
new File(ClassLoader.getSystemClassLoader().getResource(
cls.getPackageName().replaceAll("\\.", "/") + "/" + filename).toURI()
), StandardCharsets.UTF_8);
}
public static String readString(Class<?> cls, String filename) throws IOException, URISyntaxException{
try(InputStream in = new FileInputStream(new File(ClassLoader.getSystemClassLoader()
.getResource(cls.getPackageName().replaceAll("\\.", "/") + "/" + filename).toURI()));
){
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
}
}
******************/
}
|
package com.mimi.mimigroup.ui.adapter;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.mimi.mimigroup.R;
import com.mimi.mimigroup.model.DM_Employee;
import com.mimi.mimigroup.ui.custom.CustomTextView;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class EmployeeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
List<DM_Employee> employeeList;
public List<DM_Employee> SelectedList=new ArrayList<DM_Employee>();
public EmployeeAdapter() {
employeeList = new ArrayList<>();
}
public void setEmployeeList(List<DM_Employee> oEmployeeList) {
this.employeeList = oEmployeeList;
notifyDataSetChanged();
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
return new EmployeeHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_employee,viewGroup,false));
}
@Override
public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder viewHolder, final int iPos) {
if (viewHolder instanceof EmployeeAdapter.EmployeeHolder){
((EmployeeAdapter.EmployeeHolder) viewHolder).bind(employeeList.get(iPos));
}
setRowSelected(SelectedList.contains(employeeList.get(iPos)),viewHolder);
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(SelectedList.contains(employeeList.get(iPos))){
SelectedList.remove(employeeList.get(iPos));
setRowSelected(false,viewHolder);
}else{
SelectedList.add(employeeList.get(iPos));
setRowSelected(true,viewHolder);
}
//notifyDataSetChanged();
}
});
}
@Override
public int getItemCount() {
return employeeList.size();
}
class EmployeeHolder extends RecyclerView.ViewHolder{
@BindView(R.id.tvEmployeeCode)
CustomTextView tvEmployeeCode;
@BindView(R.id.tvEmployeeName)
CustomTextView tvEmployeeName;
@BindView(R.id.tvNotes)
CustomTextView tvNotes;
public EmployeeHolder(@NonNull View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
public void bind(DM_Employee employee){
if (employee != null){
if(employee.getEmployeeCode()!=null) {
tvEmployeeCode.setText(employee.getEmployeeCode());
}
if (employee.getEmployeeName() != null){
tvEmployeeName.setText(employee.getEmployeeName());
}
if (employee.getNotes() != null){
tvNotes.setText(employee.getNotes());
}
}
}
}
private void setRowSelected(boolean isSelected,RecyclerView.ViewHolder viewHolder){
if(isSelected){
viewHolder.itemView.setBackgroundColor(Color.parseColor("#F8D8E7"));
viewHolder.itemView.setSelected(true);
}else {
viewHolder.itemView.setBackgroundColor(Color.parseColor("#ffffff"));
viewHolder.itemView.setSelected(false);
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.jotaweb.web;
import com.jotaweb.entity.Pessoa;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.transaction.Transactional;
/**
*
* @author Sermusa
*/
@ManagedBean
@SessionScoped
public class JsfAutorizacao {
private Long id;
private Pessoa funcionario;
private Calendar data_ocorrencia = Calendar.getInstance();
private Calendar data_autorizacao = Calendar.getInstance();
private String justificativa;
private Pessoa responsavel;
private Date data_temp;
private String teste;
/**
* Creates a new instance of JsfAutorizacao
*/
public JsfAutorizacao() {
}
public Long getId() {
return id;
}
public void setId(Long id){
this.id = id;
}
public Pessoa getFuncionario() {
return funcionario;
}
public void setFuncionario(Pessoa funcionario) {
this.funcionario = funcionario;
}
public Calendar getData_ocorrencia() {
return data_ocorrencia;
}
public void setData_ocorrencia(Calendar data_ocorrencia) {
this.data_ocorrencia = data_ocorrencia;
}
public Calendar getData_autorizacao() {
return data_autorizacao;
}
public void setData_autorizacao(Calendar data_autorizacao) {
this.data_autorizacao = data_autorizacao;
}
public String getJustificativa() {
return justificativa;
}
public void setJustificativa(String justificativa) {
this.justificativa = justificativa;
}
public Pessoa getResponsavel() {
return responsavel;
}
public void setResponsavel(Pessoa responsavel) {
this.responsavel = new com.jotaweb.crud.CrudPessoa().find(1L);
}
public Date getData_temp() {
return data_temp;
}
public void setData_temp(Date data_temp){
this.data_temp = data_temp;
this.data_ocorrencia.setTime(data_temp);
}
public void newAuto(Long id){
this.funcionario = new com.jotaweb.crud.CrudPessoa().find(id);
}
@Transactional
public String persist() {
this.responsavel = new com.jotaweb.crud.CrudPessoa().find(1L);
if(this.funcionario != null){
com.jotaweb.entity.Autorizacao tes;
tes = new com.jotaweb.entity.Autorizacao();
tes.setData_autorizacao(data_autorizacao);
tes.setData_ocorrencia(data_ocorrencia);
tes.setFuncionario(funcionario);
tes.setId(id);
tes.setJustificativa(justificativa);
tes.setResponsavel(responsavel);
Exception insert = new com.jotaweb.crud.CrudAutorizacao().persist(tes);
if (insert == null) {
tes.setData_autorizacao(null);
tes.setData_ocorrencia(null);
tes.setFuncionario(null);
tes.setId(0L);
tes.setJustificativa("");
tes.setResponsavel(null);
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Sucesso!!", "Registro adicionado com sucesso");
FacesContext.getCurrentInstance().addMessage(null, message);
} else {
String msg = insert.getMessage();
//FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro!", "Informe o administrador do erro: " + msg);
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro!", "Informe o administrador do erro: " + msg);
FacesContext.getCurrentInstance().addMessage(null, message);
return null;
}
}
else{
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro!", "NULL");
FacesContext.getCurrentInstance().addMessage(null, message);
}
return "autoriza.xhtml";
}
public java.util.List<com.jotaweb.entity.Autorizacao> getAll() throws SQLException {
return (List)com.jotaweb.jdbc.AcessaQuery.getListByDataOcorrencia(new com.jotaweb.crud.CrudPessoa().find(1L));
}
public String setAutorizacao(com.jotaweb.entity.Autorizacao aut){
this.setId(aut.getId());
this.setFuncionario(aut.getFuncionario());
this.setData_ocorrencia(aut.getData_ocorrencia());
this.setData_autorizacao(aut.getData_autorizacao());
this.setJustificativa(aut.getJustificativa());
this.setResponsavel(aut.getResponsavel());
return "/autorizacao/corrigir.xhtml";
}
public String merge() {
com.jotaweb.entity.Autorizacao aut;
aut = new com.jotaweb.crud.CrudAutorizacao().find(this.id);
aut.setFuncionario(funcionario);
aut.setData_ocorrencia(data_ocorrencia);
aut.setJustificativa(justificativa);
Exception e = new com.jotaweb.crud.CrudAutorizacao().merge(aut);
if (e == null) {
this.setId(0L);
this.setFuncionario(null);
this.setData_autorizacao(null);
this.setData_ocorrencia(null);
this.setJustificativa("");
this.setResponsavel(null);
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Sucesso!!", "Registro alterado com sucesso");
FacesContext.getCurrentInstance().addMessage(null, message);
} else {
String msg = e.getMessage();
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro!", "Informe o administrador do erro: " + msg);
FacesContext.getCurrentInstance().addMessage(null, message);
}
return "/index.xhtml";
}
public String remove(com.jotaweb.entity.Autorizacao aut) {
Exception e = new com.jotaweb.crud.CrudAutorizacao().remove(aut);
if (e == null) {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Sucesso!!", "Registro excluido com sucesso");
FacesContext.getCurrentInstance().addMessage(null, message);
} else {
String msg = e.getMessage();
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro!", "Informe o administrador do erro: " + msg);
FacesContext.getCurrentInstance().addMessage(null, message);
}
return "errata.xhtml";
}
}
|
package start;
import javax.swing.*;
import java.awt.*;
public class pixel extends JComponent{
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.blue);
g.fillRect(0, 0, 1, 1);
}
}
|
package com.osce.entity;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.io.Serializable;
import java.util.Date;
@Setter
@Getter
@ToString
public class MessageTemplate implements Serializable {
private String templateId;//模板ID
/**
* 模板编码
*/
private String templateCode;
private String templateName;//模板名称
private String templateType;//模板类型sms=短信, email=邮件
private String content;//模板内容
private String isDeleted;//删除标示,N未删除 Y-已删除
private String operator;//最后修改管理员ID
private Date gmtCreate;//创建时间
private Date gmtModify;//更新时间
}
|
package com.ls.Test.packages.net.TCP;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Sever {
public static void main(String[] args) throws IOException {
/*//设置服务端 设置端口
ServerSocket serverSocket = new ServerSocket(8888);
//接收客户端的连接 阻塞式
Socket socket = serverSocket.accept();
System.out.println("一个客户端建立连接");
String s = "欢迎使用服务器!";
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
outputStream.writeUTF(s);
outputStream.flush();*/
//设置服务端 设置端口
ServerSocket serverSocket = new ServerSocket(8888);
while (true) {//一个accpet 一个客户端
//接收客户端的连接 阻塞式
Socket socket = serverSocket.accept();
System.out.println("一个客户端建立连接");
String s = "欢迎使用服务器!";
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
outputStream.writeUTF(s);
outputStream.flush();
}
}
}
|
package Chapter04;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class Main {
public static void getProperties(String className) throws ClassNotFoundException {
Class<?> cl = Class.forName(className);
while (cl != null) {
for (Field f : cl.getDeclaredFields())
System.out.println(Modifier.toString(f.getModifiers()) + " " + f.getGenericType() + " " + f.getName());
cl = cl.getSuperclass();
}
}
public static void testGetProperties() {
try {
// String s = "Point";
getProperties(Point.class.getName());
}
catch (Exception e) {
System.out.println("Class not found");
}
}
public static void findOut() {
try {
}
catch (Exception e) {
System.out.println("Error:" + e.getMessage());
}
}
public static void main(String[] args) {
// testGetProperties();
findOut();
}
}
|
package org.code.otter.nicephore.ingestion.sequenceur;
import org.code.otter.nicephore.ingestion.sequenceur.settings.IngestionSettings;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
/**
* Main application class
* Created by swinside on 02/04/16.
*/
@Configuration
@EnableAutoConfiguration
@ComponentScan
@EnableConfigurationProperties(value = IngestionSettings.class)
@ImportResource("integration/integration-context.xml")
public class SequenceurApp {
public static void main(String[] args) throws Exception {
SpringApplication.run(SequenceurApp.class, args);
}
}
|
package communication.packets.request;
import communication.enums.PacketType;
import communication.packets.AuthenticatedRequestPacket;
import communication.wrapper.Connection;
import main.Conference;
/**
* This packet can be used by an attendee to submit a request of speech.
* Responds with a {@link communication.packets.BasePacket}.
*/
public class RequestOfSpeechRequestPacket extends AuthenticatedRequestPacket {
private boolean refersToTopic;
private String reference;
/**
* @param refersToTopic if the request refers to a topic (false implies it refers to a document)
* @param reference in case the request refers to a topic the reference equals the preorder string of the topic, otherwise it equals the name of the referred document
*/
public RequestOfSpeechRequestPacket(boolean refersToTopic, String reference) {
super(PacketType.REQUEST_OF_SPEECH_REQUEST);
this.refersToTopic = refersToTopic;
this.reference = reference;
}
@Override
public void handle(Conference conference, Connection connection) {
new RequestOfPacketWrapper(getPacketType(), refersToTopic, reference).setToken(getToken()).handle(conference, connection);
}
}
|
/*
* 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 birthdayreminder;
import java.util.*;
import java.util.Calendar;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
/**
*
* @author Evan
*/
public class UserInterface {
private Scanner reader;
private ArrayList<Person> persons;
private String name = "";
private String birthday = "";
private int day = 0;
private int month = 0;
private int year = 0;
public UserInterface() {
reader = new Scanner(System.in);
this.persons = new ArrayList<Person>();
}
public void start() {
while (true) {
System.out.println("1) Add birthday");
System.out.println("2) Remove birthday");
System.out.println("3) Load birthdays");
System.out.println("4) Quit");
String command = reader.nextLine();
if (command.equals("1") || command.equals("add")) {
addBirthday();
System.out.println();
} else if (command.equals("2") || command.equals("remove")) {
removeBirthday();
System.out.println();
} else if (command.equals("3") || command.equals("load")) {
loadBirthdays();
System.out.println();
}
else if (command.equals("4") || command.equals("quit")) {
break;
}
}
}
public void addBirthday() {
System.out.print("Name: ");
name = reader.nextLine();
System.out.print("Birthday (day): ");
day = Integer.parseInt(reader.nextLine());
System.out.print("Birthday (month): ");
month = Integer.parseInt(reader.nextLine());
System.out.print("Birthday (year): ");
year = Integer.parseInt(reader.nextLine());
persons.add(new Person(name, day, month, year));
}
public void removeBirthday() {
System.out.print("Whose birthday do you want to remove? ");
String removedPerson = reader.nextLine();
Person p = null;
for (Person person : persons) {
if (removedPerson.toLowerCase().equals(person.getName().toLowerCase())) {
Person removed = person;
p = removed;
System.out.println("Done!");
break;
} else {
System.out.print("Person not found");
System.out.println();
break;
}
}
persons.remove(p);
}
public void loadBirthdays() {
for (Person p : persons) {
System.out.println(p);
}
if (persons.isEmpty()) {
System.out.println("No data to display");
}
}
}
|
package interviews.no_followup;
public class CBSInteractive {
}
|
package com.dishcuss.foodie.hub.Chat;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.github.nkzawa.emitter.Emitter;
import com.github.nkzawa.socketio.client.Socket;
import com.dishcuss.foodie.hub.Models.Comment;
import com.dishcuss.foodie.hub.Models.PhotoModel;
import com.dishcuss.foodie.hub.Models.ReviewModel;
import com.dishcuss.foodie.hub.Models.User;
import com.dishcuss.foodie.hub.Models.UserBeenThere;
import com.dishcuss.foodie.hub.Models.UserFollowing;
import com.dishcuss.foodie.hub.Models.UserProfile;
import com.dishcuss.foodie.hub.R;
import com.dishcuss.foodie.hub.Utils.Constants;
import com.dishcuss.foodie.hub.Utils.DishCussApplication;
import com.dishcuss.foodie.hub.Utils.URLs;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import io.realm.Realm;
import io.realm.RealmResults;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* Created by Naeem Ibrahim on 8/19/2016.
*/
public class ChatScreenActivity extends AppCompatActivity {
RecyclerView chatRecyclerView;
private RecyclerView.LayoutManager chatLayoutManager;
ChatMessageAdapter messageAdapter;
ArrayList<ChatMessage> chatMessageArrayList=new ArrayList<>();
EditText chat_message;
Button chat_btn_send;
private Socket mSocket;
int selfID=0;
String punditType;
ImageView pundit_image;
User user;
Realm realm;
String userJoinID;
private Boolean isConnected = false;
int punditNumber=0;
String guestEmail;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_screen_activity);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
DishCussApplication app = (DishCussApplication) this.getApplication();
mSocket = app.getSocket();
Log.e("Socket",""+mSocket.id());
guestEmail=getDeviceName()+"@gmail.com";
guestEmail = guestEmail.replaceAll(" ", "_");
guestEmail.trim();
// Log.e("Email",guestEmail);
mSocket.on(Socket.EVENT_CONNECT,onConnect);
mSocket.on(Socket.EVENT_DISCONNECT,onDisconnect);
mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
mSocket.on("pandit_msg", onNewMessage);
mSocket.on("welcome_msg", onJoin);
mSocket.connect();
if(!Constants.skipLogin) {
realm = Realm.getDefaultInstance();
user = realm.where(User.class).findFirst();
Log.e("User : ", "" + user);
UserProfile userProfile=new UserProfile();
userProfile=GetUserData(user.getId());
if (userProfile == null) {
UserData(user.getId());
}
}else {
}
TextView headerName = (TextView) findViewById(R.id.app_toolbar_name);
TextView chat_pundit_type = (TextView) findViewById(R.id.chat_pundit_type);
pundit_image = (ImageView)findViewById(R.id.pundit_image);
chat_message=(EditText)findViewById(R.id.chat_message_edt);
chat_btn_send=(Button)findViewById(R.id.chat_btn_send);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
headerName.setText(bundle.getString("PunditName"));
punditNumber=bundle.getInt("PunditNumber");
punditType=bundle.getString("PunditType");
if(punditNumber==1) {
chat_pundit_type.setText("Desi Pundit");
pundit_image.setImageDrawable(getResources().getDrawable(R.drawable.pundit_ic_desi));
}else if(punditNumber==2) {
chat_pundit_type.setText("Sasta Pundit");
pundit_image.setImageDrawable(getResources().getDrawable(R.drawable.pundit_ic_sasta));
}else if(punditNumber==3) {
chat_pundit_type.setText("Fast Food Pundit");
pundit_image.setImageDrawable(getResources().getDrawable(R.drawable.pundit_ic_fastfood));
}else if(punditNumber==4) {
chat_pundit_type.setText("Continental Pundit");
pundit_image.setImageDrawable(getResources().getDrawable(R.drawable.pundit_ic_continental));
}else if(punditNumber==5) {
chat_pundit_type.setText("Foreign Pundit");
pundit_image.setImageDrawable(getResources().getDrawable(R.drawable.pundit_ic_foriegn));
}
}
chatRecyclerView = (RecyclerView) findViewById(R.id.chat_recycleView);
chatLayoutManager = new LinearLayoutManager(this);
chatRecyclerView.setLayoutManager(chatLayoutManager);
chatRecyclerView.setNestedScrollingEnabled(false);
if(user!=null) {
messageAdapter = new ChatMessageAdapter(ChatScreenActivity.this, chatMessageArrayList, user.getId(), punditNumber);
chatRecyclerView.setAdapter(messageAdapter);
}else {
messageAdapter = new ChatMessageAdapter(ChatScreenActivity.this, chatMessageArrayList,selfID, punditNumber);
chatRecyclerView.setAdapter(messageAdapter);
}
chat_btn_send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String newMessage=chat_message.getText().toString();
if(isConnected) {
if (!newMessage.equals("")) {
chat_message.setText("");
ChatMessage message = new ChatMessage();
if(user!=null) {
message.setUserID(user.getId());
}else {
message.setUserID(selfID);
}
message.setMessage(newMessage);
chatMessageArrayList.add(message);
JSONObject jsonObj = new JSONObject();
try {
jsonObj.put("id", userJoinID);
jsonObj.put("msg", newMessage);
if(user!=null) {
jsonObj.put("user", user.getEmail());
}else {
jsonObj.put("user", guestEmail);
}
jsonObj.put("img", "");
jsonObj.put("room", punditType);
mSocket.emit("p1_msg_app", jsonObj.toString());
} catch (JSONException e) {
e.printStackTrace();
}
messageAdapter.notifyItemInserted(chatMessageArrayList.size() - 1);
chatRecyclerView.scrollToPosition(chatMessageArrayList.size() - 1);
}
}
else
{
Toast.makeText(ChatScreenActivity.this.getApplicationContext(),
"Pundit Busy Please Wait", Toast.LENGTH_LONG).show();
}
}
});
}
@Override
public void onDestroy() {
super.onDestroy();
mSocket.disconnect();
mSocket.off(Socket.EVENT_CONNECT, onConnect);
mSocket.off(Socket.EVENT_DISCONNECT, onDisconnect);
mSocket.off(Socket.EVENT_CONNECT_ERROR, onConnectError);
mSocket.off(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
mSocket.off("pandit_msg", onNewMessage);
mSocket.off("welcome_msg", onJoin);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// todo: goto back activity from here
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private Emitter.Listener onConnect = new Emitter.Listener() {
@Override
public void call(Object... args) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if(!isConnected) {
// if(null!=mUsername)
// mSocket.emit("add user", mUsername);
// Toast.makeText(ChatScreenActivity.this.getApplicationContext(),
// "connect", Toast.LENGTH_LONG).show();
}
if(mSocket.connected()){
JSONObject jsonObj=new JSONObject();
try {
if(user!=null) {
jsonObj.put("id", user.getId());
jsonObj.put("username",user.getName());
if(!user.getEmail().equals("")){
jsonObj.put("email",user.getEmail());
}
else
{
jsonObj.put("email",guestEmail);
}
}else {
jsonObj.put("id", selfID);
jsonObj.put("username","Test User");
jsonObj.put("email",guestEmail);
}
jsonObj.put("room",punditType);
mSocket.emit("p1_join",jsonObj.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
}
};
private Emitter.Listener onDisconnect = new Emitter.Listener() {
@Override
public void call(Object... args) {
runOnUiThread(new Runnable() {
@Override
public void run() {
isConnected = false;
// Toast.makeText(ChatScreenActivity.this.getApplicationContext(),
// "disconnect", Toast.LENGTH_LONG).show();
}
});
}
};
private Emitter.Listener onConnectError = new Emitter.Listener() {
@Override
public void call(Object... args) {
runOnUiThread(new Runnable() {
@Override
public void run() {
// Toast.makeText(ChatScreenActivity.this.getApplicationContext(),
// "error_connect", Toast.LENGTH_LONG).show();
}
});
}
};
private Emitter.Listener onNewMessage = new Emitter.Listener() {
@Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
@Override
public void run() {
JSONObject data = (JSONObject) args[0];
Log.e("Data",""+data);
String username;
String message;
String sender;
try {
username = data.getString("pandit");
message = data.getString("rply");
} catch (JSONException e) {
return;
}
ChatMessage messages = new ChatMessage();
messages.setId(10101);
messages.setUserID(10101);
messages.setMessage(message);
chatMessageArrayList.add(messages);
messageAdapter.notifyDataSetChanged();
scrollToBottom();
}
});
}
};
private Emitter.Listener onJoin = new Emitter.Listener() {
@Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
@Override
public void run() {
JSONObject data = (JSONObject) args[0];
Log.e("Data",""+data);
String id;
String message;
try {
id = data.getString("id");
message = data.getString("msg");
} catch (JSONException e) {
return;
}
userJoinID=id;
ChatMessage messages = new ChatMessage();
messages.setId(10101);
messages.setUserID(10101);
messages.setMessage(message);
chatMessageArrayList.add(messages);
messageAdapter.notifyDataSetChanged();
isConnected = true;
scrollToBottom();
}
});
}
};
private void scrollToBottom() {
chatRecyclerView.scrollToPosition(messageAdapter.getItemCount() - 1);
}
void UserData(int userID) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(URLs.Get_User_data+userID)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String objStr = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
JSONObject jsonObj = new JSONObject(objStr);
if(jsonObj.has("user"))
{
JSONObject userObj = jsonObj.getJSONObject("user");
realm.beginTransaction();
UserProfile userProfileRealm = realm.createObject(UserProfile.class);
userProfileRealm.setId(userObj.getInt("id"));
userProfileRealm.setName(userObj.getString("name"));
userProfileRealm.setUsername(userObj.getString("username"));
userProfileRealm.setEmail(userObj.getString("email"));
userProfileRealm.setAvatar(userObj.getString("avatar"));
userProfileRealm.setLocation(userObj.getString("location"));
userProfileRealm.setGender(userObj.getString("gender"));
userProfileRealm.setRole(userObj.getString("role"));
//Arrays
JSONArray jsonDataFollowingArray = userObj.getJSONArray("following");
JSONArray jsonDataFollowersArray = userObj.getJSONArray("followers");
JSONArray jsonDataPostsArray = userObj.getJSONArray("posts");
JSONArray jsonDataReviewsArray = userObj.getJSONArray("reviews");
for(int p=0;p<jsonDataPostsArray.length();p++){
JSONObject postObj=jsonDataPostsArray.getJSONObject(p);
JSONObject checkinObj = postObj.getJSONObject("checkin");
if(checkinObj.has("restaurant")) {
JSONObject restaurantObj = checkinObj.getJSONObject("restaurant");
UserBeenThere userBeenThere = new UserBeenThere();
userBeenThere.setId(restaurantObj.getInt("id"));
userBeenThere.setRestaurantName(restaurantObj.getString("name"));
userBeenThere.setRestaurantLocation(restaurantObj.getString("location"));
userBeenThere.setCover_image_url(checkinObj.getString("restaurant_image"));
userBeenThere.setBeenThereTime(checkinObj.getString("time"));
final UserBeenThere beenThere = realm.copyToRealm(userBeenThere);
userProfileRealm.getUserBeenThereRealmList().add(beenThere);
}
JSONArray jsonDataPhotosArray = postObj.getJSONArray("photos");
for (int ph = 0; ph < jsonDataPhotosArray.length(); ph++) {
JSONObject photo = jsonDataPhotosArray.getJSONObject(ph);
PhotoModel photoModel = new PhotoModel();
photoModel.setId(photo.getInt("id"));
photoModel.setUrl(photo.getString("image_url"));
final PhotoModel managedPhotoModel = realm.copyToRealm(photoModel);
userProfileRealm.getPhotoModelRealmList().add(managedPhotoModel);
}
JSONArray jsonDataCommentsArray = postObj.getJSONArray("comments");
for (int c = 0; c < jsonDataCommentsArray.length(); c++) {
JSONObject commentObj = jsonDataCommentsArray.getJSONObject(c);
Comment comment= new Comment();
comment.setCommentID(commentObj.getInt("id"));
comment.setCommentTitle(commentObj.getString("title"));
comment.setCommentUpdated_at(commentObj.getString("created_at"));
comment.setCommentSummary(commentObj.getString("comment"));
JSONObject commentatorObj = commentObj.getJSONObject("commentor");
comment.setCommentatorID(commentatorObj.getInt("id"));
comment.setCommentatorName(commentatorObj.getString("name"));
comment.setCommentatorImage(commentatorObj.getString("avatar"));
JSONArray commentLikeArray=commentObj.getJSONArray("likes");
comment.setCommentLikesCount(commentLikeArray.length());
final Comment managedComment = realm.copyToRealm(comment);
userProfileRealm.getCommentRealmList().add(managedComment);
}
}
for (int r = 0; r < jsonDataReviewsArray.length();r++) {
JSONObject reviewObj = jsonDataReviewsArray.getJSONObject(r);
realm.commitTransaction();
realm.beginTransaction();
ReviewModel reviewModel=realm.createObject(ReviewModel.class);
reviewModel.setReview_ID(reviewObj.getInt("id"));
reviewModel.setReviewable_id(reviewObj.getInt("reviewable_id"));
reviewModel.setReview_title(reviewObj.getString("title"));
reviewModel.setUpdated_at(reviewObj.getString("updated_at"));
reviewModel.setReview_summary(reviewObj.getString("summary"));
reviewModel.setReviewable_type(reviewObj.getString("reviewable_type"));
JSONObject reviewObjReviewer= reviewObj.getJSONObject("reviewer");
reviewModel.setReview_reviewer_ID(reviewObjReviewer.getInt("id"));
reviewModel.setReview_reviewer_Name(reviewObjReviewer.getString("name"));
reviewModel.setReview_reviewer_Avatar(reviewObjReviewer.getString("avatar"));
reviewModel.setReview_reviewer_time(reviewObjReviewer.getString("location"));
JSONArray reviewLikesArray = reviewObj.getJSONArray("likes");
JSONArray reviewCommentsArray = reviewObj.getJSONArray("comments");
JSONArray reviewShareArray = reviewObj.getJSONArray("reports");
reviewModel.setReview_Likes_count(reviewLikesArray.length());
reviewModel.setReview_comments_count(reviewCommentsArray.length());
reviewModel.setReview_shares_count(reviewShareArray.length());
realm.commitTransaction();
realm.beginTransaction();
for (int c = 0; c < reviewCommentsArray.length(); c++) {
JSONObject commentObj = reviewCommentsArray.getJSONObject(c);
Comment comment=realm.createObject(Comment.class);
comment.setCommentID(commentObj.getInt("id"));
comment.setCommentTitle(commentObj.getString("title"));
comment.setCommentUpdated_at(commentObj.getString("created_at"));
comment.setCommentSummary(commentObj.getString("comment"));
JSONObject commentatorObj = commentObj.getJSONObject("commentor");
comment.setCommentatorID(commentatorObj.getInt("id"));
comment.setCommentatorName(commentatorObj.getString("name"));
comment.setCommentatorImage(commentatorObj.getString("avatar"));
JSONArray commentLikeArray=commentObj.getJSONArray("likes");
comment.setCommentLikesCount(commentLikeArray.length());
final Comment managedComment = realm.copyToRealm(comment);
reviewModel.getCommentRealmList().add(managedComment);
}
realm.commitTransaction();
realm.beginTransaction();
final ReviewModel managedReviewModel= realm.copyToRealm(reviewModel);
userProfileRealm.getReviewModelRealmList().add(managedReviewModel);
}
for(int fs=0;fs<jsonDataFollowingArray.length();fs++){
JSONObject jsonFollowingObject = jsonDataFollowingArray.getJSONObject(fs);
UserFollowing userFollowing=new UserFollowing();
userFollowing.setId(jsonFollowingObject.getInt("id"));
userFollowing.setLikesCount(jsonFollowingObject.getInt("likees_count"));
userFollowing.setFollowerCount(jsonFollowingObject.getInt("followers_count"));
userFollowing.setFollowingCount(jsonFollowingObject.getInt("followees_count"));
userFollowing.setName(jsonFollowingObject.getString("name"));
userFollowing.setUsername(jsonFollowingObject.getString("username"));
userFollowing.setAvatar(jsonFollowingObject.getString("avatar"));
userFollowing.setLocation(jsonFollowingObject.getString("location"));
userFollowing.setEmail(jsonFollowingObject.getString("email"));
userFollowing.setGender(jsonFollowingObject.getString("gender"));
userFollowing.setRole(jsonFollowingObject.getString("name"));
userFollowing.setReferral_code(jsonFollowingObject.getString("referal_code"));
final UserFollowing managedUserFollowing = realm.copyToRealm(userFollowing);
userProfileRealm.getUserFollowingRealmList().add(managedUserFollowing);
}
for(int fr=0;fr<jsonDataFollowersArray.length();fr++){
JSONObject jsonFollowingObject = jsonDataFollowersArray.getJSONObject(fr);
UserFollowing userFollowing=new UserFollowing();
userFollowing.setId(jsonFollowingObject.getInt("id"));
userFollowing.setLikesCount(jsonFollowingObject.getInt("likees_count"));
userFollowing.setFollowerCount(jsonFollowingObject.getInt("followers_count"));
userFollowing.setFollowingCount(jsonFollowingObject.getInt("followees_count"));
userFollowing.setName(jsonFollowingObject.getString("name"));
userFollowing.setUsername(jsonFollowingObject.getString("username"));
userFollowing.setAvatar(jsonFollowingObject.getString("avatar"));
userFollowing.setLocation(jsonFollowingObject.getString("location"));
userFollowing.setEmail(jsonFollowingObject.getString("email"));
userFollowing.setGender(jsonFollowingObject.getString("gender"));
userFollowing.setRole(jsonFollowingObject.getString("name"));
userFollowing.setReferral_code(jsonFollowingObject.getString("referal_code"));
final UserFollowing managedUserFollowing = realm.copyToRealm(userFollowing);
userProfileRealm.getUserFollowersRealmList().add(managedUserFollowing);
}
realm.commitTransaction();
}
} catch (JSONException e) {
e.printStackTrace();
}
realm.close();
}
});
}
});
}
UserProfile GetUserData(int uid){
realm = Realm.getDefaultInstance();
RealmResults<UserProfile> userProfiles = realm.where(UserProfile.class).equalTo("id", uid).findAll();
Log.e("Count",""+userProfiles.size());
if(userProfiles.size()>0){
realm.beginTransaction();
realm.commitTransaction();
return userProfiles.get(userProfiles.size()-1);
}
return null;
}
/** Returns the consumer friendly device name */
public static String getDeviceName() {
String manufacturer = Build.MANUFACTURER;
String model = Build.MODEL;
if (model.startsWith(manufacturer)) {
return capitalize(model);
}
return capitalize(manufacturer) + " " + model;
}
private static String capitalize(String str) {
if (TextUtils.isEmpty(str)) {
return str;
}
char[] arr = str.toCharArray();
boolean capitalizeNext = true;
String phrase = "";
for (char c : arr) {
if (capitalizeNext && Character.isLetter(c)) {
phrase += Character.toUpperCase(c);
capitalizeNext = false;
continue;
} else if (Character.isWhitespace(c)) {
capitalizeNext = true;
}
phrase += c;
}
return phrase;
}
}
|
package com.tencent.mm.plugin.game.d;
import com.tencent.mm.bk.a;
import java.util.LinkedList;
public final class j extends a {
public String jPA;
public String jPB;
public int jPC;
public a jPD;
public cz jPE;
public int jPF;
protected final int a(int i, Object... objArr) {
int h;
if (i == 0) {
f.a.a.c.a aVar = (f.a.a.c.a) objArr[0];
if (this.jPB != null) {
aVar.g(1, this.jPB);
}
aVar.fT(2, this.jPC);
if (this.jPD != null) {
aVar.fV(3, this.jPD.boi());
this.jPD.a(aVar);
}
if (this.jPE != null) {
aVar.fV(4, this.jPE.boi());
this.jPE.a(aVar);
}
aVar.fT(5, this.jPF);
if (this.jPA == null) {
return 0;
}
aVar.g(6, this.jPA);
return 0;
} else if (i == 1) {
if (this.jPB != null) {
h = f.a.a.b.b.a.h(1, this.jPB) + 0;
} else {
h = 0;
}
h += f.a.a.a.fQ(2, this.jPC);
if (this.jPD != null) {
h += f.a.a.a.fS(3, this.jPD.boi());
}
if (this.jPE != null) {
h += f.a.a.a.fS(4, this.jPE.boi());
}
h += f.a.a.a.fQ(5, this.jPF);
if (this.jPA != null) {
h += f.a.a.b.b.a.h(6, this.jPA);
}
return h;
} else if (i == 2) {
f.a.a.a.a aVar2 = new f.a.a.a.a((byte[]) objArr[0], unknownTagHandler);
for (h = a.a(aVar2); h > 0; h = a.a(aVar2)) {
if (!super.a(aVar2, this, h)) {
aVar2.cJS();
}
}
return 0;
} else if (i != 3) {
return -1;
} else {
f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0];
j jVar = (j) objArr[1];
int intValue = ((Integer) objArr[2]).intValue();
LinkedList IC;
int size;
byte[] bArr;
f.a.a.a.a aVar4;
boolean z;
switch (intValue) {
case 1:
jVar.jPB = aVar3.vHC.readString();
return 0;
case 2:
jVar.jPC = aVar3.vHC.rY();
return 0;
case 3:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
a aVar5 = new a();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = aVar5.a(aVar4, aVar5, a.a(aVar4))) {
}
jVar.jPD = aVar5;
}
return 0;
case 4:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
cz czVar = new cz();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = czVar.a(aVar4, czVar, a.a(aVar4))) {
}
jVar.jPE = czVar;
}
return 0;
case 5:
jVar.jPF = aVar3.vHC.rY();
return 0;
case 6:
jVar.jPA = aVar3.vHC.readString();
return 0;
default:
return -1;
}
}
}
}
|
package engine.physics;
import engine.events.CollisionEvent;
import engine.events.EventManager;
import engine.world.Block;
import engine.world.IntCoord;
import engine.world.Map;
import engine.world.Map.Direction;
import org.lwjgl.util.vector.Vector3f;
/**
*
* @author Anselme FRANÇOIS
*
*/
public class ParticleCollision {
private static ParticleEntity e;
private static Map m;
private static Vector3f speed;
private static Vector3f position;
/* dir + target speed = intersection */
private static Direction dir;
private static Vector3f target_speed;
public static void resolve(ParticleEntity pe, Map map) {
e = pe;
m = map;
speed = new Vector3f(e.getSpeed());
position = e.getPosition();
while(getNextIntersection()){
handleIntersection();
}
Vector3f.add(target_speed, position, position);
}
/**
* the ray tracing algorithm is here
*/
private static boolean getNextIntersection(){
float min_ratio = 1;
float temp_ratio;
dir = null;
// each direction is tested, maximum 3 of the 6 conditions will return true
if(speed.z < 0){
temp_ratio = ((float)Math.floor(position.z) - position.z) / speed.z;
if(temp_ratio < min_ratio){
min_ratio = temp_ratio;
dir = Direction.DOWN;
}
}
if(speed.z > 0){
temp_ratio = ((float)Math.floor(position.z) + 1 - position.z) / speed.z;
if(temp_ratio < min_ratio){
min_ratio = temp_ratio;
dir = Direction.UP;
}
}
if(speed.x < 0){
temp_ratio = ((float)Math.floor(position.x) - position.x) / speed.x;
if(temp_ratio < min_ratio){
min_ratio = temp_ratio;
dir = Direction.WEST;
}
}
if(speed.x > 0){
temp_ratio = ((float)Math.floor(position.x) + 1 - position.x) / speed.x;
if(temp_ratio < min_ratio){
min_ratio = temp_ratio;
dir = Direction.EAST;
}
}
if(speed.y < 0){
temp_ratio = ((float)Math.floor(position.y) - position.y) / speed.y;
if(temp_ratio < min_ratio){
min_ratio = temp_ratio;
dir = Direction.SOUTH;
}
}
if(speed.y > 0){
temp_ratio = ((float)Math.floor(position.y) + 1 - position.y) / speed.y;
if(temp_ratio < min_ratio){
min_ratio = temp_ratio;
dir = Direction.NORTH;
}
}
target_speed = new Vector3f(speed.x * min_ratio,
speed.y * min_ratio,
speed.z * min_ratio);
return dir != null;
}
/**
* searches for a collision at this intersection for the AABBEntity e, and resolves it.
* e will be treated as an AABB.
* @param e
*/
private static void handleIntersection(){
if(collisionOccurs()){
switch(dir){
case DOWN :
target_speed.z += 0.001;
e.setOnGround();
break;
case UP :
target_speed.z -= 0.001;
break;
case WEST :
target_speed.x += 0.001;
break;
case EAST :
target_speed.x -= 0.001;
break;
case SOUTH :
target_speed.y += 0.001;
break;
case NORTH :
target_speed.y -= 0.001;
break;
}
Vector3f.add(position, target_speed, position);
Vector3f realSpeed = e.getSpeed();
switch(dir){
case DOWN :
case UP :
realSpeed.z = 0;
speed.z = 0;
target_speed.z = 0;
break;
case WEST :
case EAST :
realSpeed.x = 0;
speed.x = 0;
target_speed.x = 0;
break;
case SOUTH :
case NORTH :
realSpeed.y = 0;
speed.y = 0;
target_speed.y = 0;
break;
}
Vector3f.sub(speed, target_speed, speed);
}else{
switch(dir){
case DOWN :
target_speed.z -= 0.001;
break;
case UP :
target_speed.z += 0.001;
break;
case WEST :
target_speed.x -= 0.001;
break;
case EAST :
target_speed.x += 0.001;
break;
case SOUTH :
target_speed.y -= 0.001;
break;
case NORTH :
target_speed.y += 0.001;
break;
}
Vector3f.sub(speed, target_speed, speed);
Vector3f.add(position, target_speed, position);
}
}
private static boolean collisionOccurs(){
Vector3f dest = new Vector3f();
Vector3f.add(position, target_speed, dest);
switch(dir){
case DOWN :
dest.z -= 0.1;
break;
case UP :
dest.z += 0.1;
break;
case WEST :
dest.x -= 0.1;
break;
case EAST :
dest.x += 0.1;
break;
case SOUTH :
dest.y -= 0.1;
break;
case NORTH :
dest.y += 0.1;
break;
}
Block block = m.getBlock(new IntCoord((int)Math.floor(dest.x),
(int)Math.floor(dest.y),
(int)Math.floor(dest.z)));
if(block.isSolid()){
EventManager.addEvent(new CollisionEvent(e, dir, block));
return true;
}else
return false;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.