text
stringlengths
10
2.72M
package com.per.iroha.service.impl; import com.per.iroha.mapper.UserMapper; import com.per.iroha.model.User; import com.per.iroha.service.UserService; import com.per.iroha.util.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import redis.clients.jedis.Jedis; import java.util.Calendar; @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; Jedis jedis = new Jedis(); @Override public void register(User user) { userMapper.userRegister(user); } @Override public boolean md5Password(User user, int salt) { String password = userMapper.findByUsername(user.getUsername()).getPassword(); String md5 = StringUtils.getMD5Str(password + salt,null); return md5.equals(user.getPassword()); } @Override public User findByName(String username) { return userMapper.findByUsername(username); } @Override public User findById(int userId) { return userMapper.findByUserId(userId); } @Override public boolean hasUser(String username) { User user = userMapper.findByUsername(username); return user != null; } //打卡签到 @Override public void checkIn(int userId) { Calendar cal = Calendar.getInstance();//得到当前时间 int month = cal.get(Calendar.MONTH) + 1; int day = cal.get(Calendar.DATE);//日 // jedis.set(userId + "checkInTableOf" + month,"0","nx","ex",60 * 60 * 24 * 31); jedis.setbit(userId + "checkInTableOf" + month,day,"1"); // System.out.println(jedis.get(userId + "checkInTableOf" + month)); } @Override public long getTable(int userId, int month) { return jedis.bitcount(userId + "checkInTableOf" + month); } }
package com.gmail.fedmanddev; import org.bukkit.inventory.ItemStack; public final class VillagerTrade { private ItemStack item1; private ItemStack item2; private ItemStack rewardItem; public VillagerTrade(ItemStack item1, ItemStack item2, ItemStack rewardItem) { this.item1 = item1; this.item2 = item2; this.rewardItem = rewardItem; } public VillagerTrade(ItemStack item1, ItemStack rewardItem) { this.item1 = item1; this.rewardItem = rewardItem; } public static boolean hasItem2(VillagerTrade villagerTrade) { return villagerTrade.item2 != null; } public static ItemStack getItem1(VillagerTrade villagerTrade) { return villagerTrade.item1; } public static ItemStack getItem2(VillagerTrade villagerTrade) { return villagerTrade.item2; } public static ItemStack getRewardItem(VillagerTrade villagerTrade) { return villagerTrade.rewardItem; } }
package dev.soapy.worldheightbooster.mixin.worldgen; import dev.soapy.worldheightbooster.WorldHeightBooster; import net.minecraft.world.level.levelgen.carver.CaveWorldCarver; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import java.util.Random; @Mixin(CaveWorldCarver.class) public class MixinCaveWorldCarver { /** * @author SoapyXM */ @Overwrite public int getCaveY(Random random) { return random.nextInt(random.nextInt(WorldHeightBooster.WORLD_HEIGHT - 12) + 8); } }
package com.arkinem.libraryfeedbackservice.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import com.arkinem.libraryfeedbackservice.dao.FeedbackDao; import com.arkinem.libraryfeedbackservice.model.QuestionDto; import com.arkinem.libraryfeedbackservice.model.Vote; @Service public class FeedbackService { private final FeedbackDao feedbackDao; @Autowired public FeedbackService(@Qualifier("fakeDao") FeedbackDao feedbackDao) { this.feedbackDao = feedbackDao; } public int insertQuestion(QuestionDto questionDto) { return feedbackDao.insertQuestion(questionDto); } public int insertVote(Vote vote) { return feedbackDao.insertVote(vote); } public List<QuestionDto> selectAllQuestions() { return feedbackDao.selectAllQuestions(); } }
package com.tencent.mm.plugin.webview.ui.tools; import com.tencent.mm.plugin.webview.ui.tools.WebViewUI.23; import com.tencent.mm.sdk.platformtools.x; class WebViewUI$23$25 implements Runnable { final /* synthetic */ int Xt; final /* synthetic */ 23 pZM; WebViewUI$23$25(23 23, int i) { this.pZM = 23; this.Xt = i; } public final void run() { this.pZM.pZJ.setProgressBarIndeterminateVisibility(false); x.d("MicroMsg.WebViewUI", "[cpan] set title pb visibility:%d", new Object[]{Integer.valueOf(this.Xt)}); if (this.Xt != 0) { this.pZM.pZJ.pXB.finish(); } else if (!WebViewUI.c(this.pZM.pZJ) && !WebViewUI.d(this.pZM.pZJ)) { this.pZM.pZJ.pXB.start(); } } }
package capstone.abang.com.Car_Renter.Home; import android.content.Intent; import android.support.v4.app.NotificationCompat; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.CardView; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.firebase.ui.database.FirebaseRecyclerAdapter; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.nostra13.universalimageloader.core.ImageLoader; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import capstone.abang.com.Models.CDFile; import capstone.abang.com.Models.ReservationFile; import capstone.abang.com.Models.UDFile; import capstone.abang.com.R; import capstone.abang.com.Utils.UniversalImageLoader; public class RenterNotifActivity extends AppCompatActivity { private RecyclerView recyclerView; private FirebaseDatabase firebaseDatabase; private DatabaseReference myRef; private FirebaseRecyclerAdapter<ReservationFile, RenterNotifActivity.RenterNotifViewHolder> mFirebaseDatabase; private FirebaseAuth mAuth; private String userID; private String message; private Date date; private String formattedDate; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_renter_notif); initImageLoader(); date = Calendar.getInstance().getTime(); SimpleDateFormat df = new SimpleDateFormat("MMM dd, yyyy EEE"); formattedDate = df.format(date); recyclerView = findViewById(R.id.notif_recycler_view); mAuth = FirebaseAuth.getInstance(); userID = mAuth.getCurrentUser().getUid(); firebaseDatabase = FirebaseDatabase.getInstance(); myRef = firebaseDatabase.getReference("ReservationFile"); recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext())); mFirebaseDatabase = new FirebaseRecyclerAdapter<ReservationFile, RenterNotifActivity.RenterNotifViewHolder> (ReservationFile.class, R.layout.layout_model_notification, RenterNotifActivity.RenterNotifViewHolder.class, myRef) { @Override protected void populateViewHolder(RenterNotifActivity.RenterNotifViewHolder viewHolder, final ReservationFile model, int position) { if(userID.equals(model.getResRenterCode())) { if(model.getResNotifyRenter().equalsIgnoreCase("Unseen")) { viewHolder.cardView.setCardBackgroundColor(getResources().getColor(R.color.notifcard)); viewHolder.setSeen(model.getResNotifyRenter()); } if (model.getResStatus().equalsIgnoreCase("Pending")) { viewHolder.cardView.setVisibility(View.GONE); } else if(model.getResStatus().equalsIgnoreCase("Approved")) { message = "responded to your request."; setOwnerName(viewHolder, model, message); setCarImage(viewHolder, model); viewHolder.setSeen(model.getResNotifyRenter() + " " + model.getResNotifyRenterTime()); viewHolder.setNotifdate(formattedDate.toString()); } else if(model.getResStatus().equalsIgnoreCase("Declined")) { message = "responded to your request."; setOwnerName(viewHolder, model, message); setCarImage(viewHolder, model); viewHolder.setSeen(model.getResNotifyRenter() + " " + model.getResNotifyRenterTime()); viewHolder.setNotifdate(formattedDate.toString()); } else if(model.getResStatus().equalsIgnoreCase("Cancelled")){ message = "cancelled the booking request!"; setOwnerName(viewHolder, model, message); setCarImage(viewHolder, model); viewHolder.setSeen(model.getResNotifyRenter() + " " + model.getResNotifyRenterTime()); viewHolder.setNotifdate(formattedDate.toString()); } else if (model.getResStatus().equalsIgnoreCase("Done")) { viewHolder.setNotifmessage("Booking has ended"); setCarImage(viewHolder, model); viewHolder.setNotifdate(formattedDate.toString()); viewHolder.setSeen(model.getResNotifyRenter() + " " + model.getResNotifyRenterTime()); viewHolder.setNotifdate(model.getResDateStart()); } } else viewHolder.cardView.setVisibility(View.GONE); viewHolder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Calendar cal = Calendar.getInstance(); int hour = cal.get(Calendar.HOUR_OF_DAY); int minute = cal.get(Calendar.MINUTE); boolean isPM = (hour >= 12); String holder = String.format("%02d:%02d %s", (hour == 12 || hour == 0) ? 12 : hour % 12, minute, isPM ? "PM" : "AM"); final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("ReservationFile"); if(model.getResNotifyRenter().equalsIgnoreCase("Unseen")) { databaseReference.child(model.getResCode()).child("resNotifyRenter").setValue("Seen"); databaseReference.child(model.getResCode()).child("resNotifyRenterTime").setValue(holder); } Intent intent = new Intent(getApplicationContext(), RenterNotifDetailsActivity.class); intent.putExtra("carcode", model.getResCarCode()); intent.putExtra("ownercode", model.getResOwnerCode()); intent.putExtra("reservationcode", model.getResCode()); startActivity(intent); } }); } }; recyclerView.setAdapter(mFirebaseDatabase); } private void setOwnerName(final RenterNotifViewHolder viewHolder, final ReservationFile model, final String message) { DatabaseReference reference = FirebaseDatabase.getInstance().getReference("UDFile"); reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for(DataSnapshot ds : dataSnapshot.getChildren()) { if(model.getResStatus().equalsIgnoreCase("Cancelled")){ viewHolder.setNotifmessage("You " + message); break; } else { if (model.getResOwnerCode().equalsIgnoreCase(ds.getValue(UDFile.class).getUDUserCode())) { viewHolder.setNotifmessage(ds.getValue(UDFile.class).getUDFullname() + " " + message); break; } } } } @Override public void onCancelled(DatabaseError databaseError) { } }); } private void setCarImage(final RenterNotifViewHolder viewHolder, final ReservationFile model){ DatabaseReference reference = FirebaseDatabase.getInstance().getReference("CDFile"); reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for(DataSnapshot ds: dataSnapshot.getChildren()){ if(model.getResCarCode().equalsIgnoreCase(ds.getValue(CDFile.class).getCDCode())){ viewHolder.setImage(ds.getValue(CDFile.class).getCDPhoto()); } } } @Override public void onCancelled(DatabaseError databaseError) { } }); } private void initImageLoader() { UniversalImageLoader universalImageLoader = new UniversalImageLoader(getApplicationContext()); ImageLoader.getInstance().init(universalImageLoader.getConfig()); } public static class RenterNotifViewHolder extends RecyclerView.ViewHolder { private final ImageView carimage; private final TextView notifmessage; private final TextView notifdate; private final TextView notifseen; private final CardView cardView; private LinearLayout modelLayout; public RenterNotifViewHolder(final View itemView) { super(itemView); carimage = itemView.findViewById(R.id.notif_car_image); notifmessage = itemView.findViewById(R.id.notif_message); notifdate = itemView.findViewById(R.id.notif_date); notifseen = itemView.findViewById(R.id.notif_seen); cardView = itemView.findViewById(R.id.cardviewnotif); modelLayout = itemView.findViewById(R.id.notif_model_layout); } private void setNotifmessage(String title) { notifmessage.setText(title); } private void setNotifdate(String date) { notifdate.setText(date); } private void setSeen(String seen) { notifseen.setText(seen); } private void setImage(String title) { UniversalImageLoader.setImage(title, carimage, null, ""); } } }
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot; import edu.wpi.first.wpilibj.Compressor; import edu.wpi.first.cameraserver.CameraServer; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj.DoubleSolenoid; import edu.wpi.first.wpilibj.I2C; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.PowerDistributionPanel; import edu.wpi.first.wpilibj.TimedRobot; import edu.wpi.first.wpilibj.VictorSP; import edu.wpi.first.wpilibj.DoubleSolenoid.Value; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import frc.robot.subsystems.ControlPanel; import frc.robot.subsystems.ControlPanel.ControlPanelState; import frc.util.ColourSensor; import frc.util.UltrasonicI2C; /** * The VM is configured to automatically run this class, and to call the functions corresponding to * each mode, as described in the TimedRobot documentation. If you change the name of this class or * the package after creating this project, you must also update the build.gradle file in the * project. */ public class Robot extends TimedRobot { private static final String kDefaultAuto = "Default"; private static final String kCustomAuto = "My Auto"; private String m_autoSelected; private final SendableChooser<String> m_chooser = new SendableChooser<>(); public final static double kJoystickDeadband = 0.2; DigitalInput lowSwitch = new DigitalInput(0); DigitalInput portSwitch = new DigitalInput(1); DigitalInput highSwitch = new DigitalInput(2); UltrasonicI2C usi2cl; UltrasonicI2C usi2cr; double steering; double power; double throttle; enum ArmPos { LOW, MEDIUM, HIGH, IDLE, } ArmPos armPos; ArmPos desiredArmPos; /** * This function is run when the robot is first started up and should be used * for any initialization code. */ @Override public void robotInit() { CameraServer.getInstance().startAutomaticCapture(0); cPanel = new ControlPanel(spinny, spinnySolenoid); armPos = ArmPos.HIGH; //desiredArmPos = ArmPos.IDLE; m_chooser.setDefaultOption("Default Auto", kDefaultAuto); m_chooser.addOption("My Auto", kCustomAuto); SmartDashboard.putData("Auto choices", m_chooser); I2C.Port i2cp = I2C.Port.kOnboard; I2C usLinkl = new I2C(i2cp, 0x14); I2C usLinkr = new I2C(i2cp, 0x13); usi2cl = new UltrasonicI2C(usLinkl); usi2cr = new UltrasonicI2C(usLinkr); } VictorSP leftDrive = new VictorSP(0); // two controllers off pwm splitter VictorSP rightDrive = new VictorSP(1); int autoSeconds = 0; VictorSP arm = new VictorSP(7); VictorSP intake = new VictorSP(5); VictorSP spinny = new VictorSP(3); Joystick stick = new Joystick(0); Joystick pad = new Joystick(1); Compressor comp = new Compressor(0); DoubleSolenoid intakeSolenoid = new DoubleSolenoid(2, 3); DoubleSolenoid spinnySolenoid = new DoubleSolenoid(0, 1); PowerDistributionPanel PDP = new PowerDistributionPanel(1); ControlPanel cPanel; public static final int ARM_POS_NONE = 0; public static final int ARM_POS_HIGH = 1; public static final int ARM_POS_PORT = 2; public static final int ARM_POS_LOW = 3; int armCommand = ARM_POS_NONE; /** * This function is called every robot packet, no matter the mode. Use this for * items like diagnostics that you want ran during disabled, autonomous, * teleoperated and test. * * <p> * This runs after the mode specific periodic functions, but before LiveWindow * and SmartDashboard integrated updating. */ @Override public void robotPeriodic() { UltrasonicI2C.usResults resultsr = usi2cr.getResults(); double resr = resultsr.getResult(); SmartDashboard.putNumber("Distance right", resr); UltrasonicI2C.usResults resultsl = usi2cl.getResults(); double resl = resultsl.getResult(); SmartDashboard.putNumber("Distance left", resl); double current = PDP.getTotalCurrent(); double voltage = PDP.getVoltage(); SmartDashboard.putNumber("Current", current); SmartDashboard.putNumber("Voltage", voltage); int batteryState = 0; if (current < 5) { if (voltage < 12.05) { batteryState = 2; SmartDashboard.putString("Battery", "!!!ALARM!!!"); } else if (voltage < 12.15) { batteryState = 1; SmartDashboard.putString("Battery", "Warning"); } else { batteryState = 0; SmartDashboard.putString("Battery", "Healthy"); } } } /** * Our own function that we call at the *start* of each periodic scan. * In here we monitor and update our sensors. * * For sending data to teh SmartDashboard you should probably put it in * robotPeriodic() with is run at the *end* of each scan. */ public void updatePeriodic() { // Scan the sensors and process/count/whatever the information coming in. ColourSensor.getInstance().update(); usi2cl.update(); usi2cr.update(); } /** * This autonomous (along with the chooser code above) shows how to select * between different autonomous modes using the dashboard. The sendable chooser * code works with the Java SmartDashboard. If you prefer the LabVIEW Dashboard, * remove all of the chooser code and uncomment the getString line to get the * auto name from the text box below the Gyro * * <p> * You can add additional auto modes by adding additional comparisons to the * switch structure below with additional strings. If using the SendableChooser * make sure to add them to the chooser code above as well. */ @Override public void autonomousInit() { m_autoSelected = m_chooser.getSelected(); // m_autoSelected = SmartDashboard.getString("Auto Selector", kDefaultAuto); System.out.println("Auto selected: " + m_autoSelected); } /** This function is called periodically during autonomous. */ @Override public void autonomousPeriodic() { updatePeriodic(); cPanel.update(); switch (m_autoSelected) { case kCustomAuto: // Put custom auto code here break; case kDefaultAuto: default: // Put default auto code here break; } if(autoSeconds<= 80){ leftDrive.set(0.5); rightDrive.set(-0.5); } autoSeconds++; if(autoSeconds > 80){ leftDrive.set(0); rightDrive.set(0); } } /** This function is called once when teleop is enabled. */ @Override public void teleopInit() { comp.start(); intakeSolenoid.set(Value.kForward); } private boolean lastSpinnyPadButton = false; /** This function is called periodically during operator control. */ @Override public void teleopPeriodic() { updatePeriodic(); cPanel.update(); if (stick.getPOV() == 45) { usWallFollower(false, true); } else if (stick.getPOV() == 135) { usWallFollower(true, true); } else if (stick.getPOV() == 225) { usWallFollower(true, false); } else if (stick.getPOV() == 315) { usWallFollower(false, false); } else { throttle = (-1 * stick.getThrottle() + 1) / 2; steering = stick.getX() * throttle; power = -1 * stick.getY() * throttle; if (steering > -kJoystickDeadband && steering < kJoystickDeadband) { steering = 0; } if (power > -kJoystickDeadband && power < kJoystickDeadband) { power = 0; } if (cPanel.getRotating() && (power == 0)) { power = -0.1; } steerPriority(power + steering, power - steering); } // steering = -stick.getX(); // power = stick.getY(); // throttle = (((stick.getThrottle() * -1) + 1) / 2); // deadZoneCorrection(); // leftDrive.set(-(steering + power) * throttle); // rightDrive.set(-(steering - power) * throttle); boolean padMove = false; if (pad.getPOV() >= 0) { padMove = true; } if (( stick.getRawButton(11) || pad.getRawButton(2) )) { armPos = ArmPos.LOW; armLow(); if (padMove) { armCommand = ARM_POS_LOW; } else { armCommand = ARM_POS_NONE; } } else if((stick.getRawButton(9) || pad.getRawButton(3) )) { armPort(); if (padMove) { armCommand = ARM_POS_PORT; } else { armCommand = ARM_POS_NONE; } } else if((stick.getRawButton(7) || pad.getRawButton(4) )) { armPos = ArmPos.HIGH; armHigh(); if (padMove) { armCommand = ARM_POS_HIGH; } else { armCommand = ARM_POS_NONE; } } else if (armCommand != ARM_POS_NONE) { if (armCommand == ARM_POS_LOW) { armLow(); if(lowSwitch.get()) { armCommand = ARM_POS_NONE; } } else if (armCommand == ARM_POS_PORT) { armPort(); if((!portSwitch.get() || highSwitch.get())) { armCommand = ARM_POS_NONE; } } else if (armCommand == ARM_POS_HIGH) { armHigh(); if(highSwitch.get()) { armCommand = ARM_POS_NONE; } } else { armCommand = ARM_POS_NONE; armIdle(); } } else { armIdle(); } // System.out.println(armPos); if (pad.getRawButton(1) && !lastSpinnyPadButton) { if (cPanel.getExtended()) { cPanel.setDesiredState(ControlPanelState.RETRACTED); } else { cPanel.setDesiredState(ControlPanelState.EXTENDED); } } lastSpinnyPadButton = pad.getRawButton(1); if(cPanel.getExtended() == true) { if ((cPanel.getState() == ControlPanelState.MANUAL_ANTICLOCKWISE) || (cPanel.getState() == ControlPanelState.EXTENDED)) { if(stick.getRawButton(3)) { cPanel.setDesiredState(ControlPanelState.MANUAL_ANTICLOCKWISE); } else { cPanel.setDesiredState(ControlPanelState.EXTENDED); } } if ((cPanel.getState() == ControlPanelState.MANUAL_CLOCKWISE) || (cPanel.getState() == ControlPanelState.EXTENDED)) { if(stick.getRawButton(4)) { cPanel.setDesiredState(ControlPanelState.MANUAL_CLOCKWISE); } else { cPanel.setDesiredState(ControlPanelState.EXTENDED); } } if (cPanel.getRotating() == false) { if (stick.getRawButton(1)) { cPanel.setDesiredState(ControlPanelState.ROTATION_CONTROL); } else if(stick.getRawButton(2)) { cPanel.setDesiredState((ControlPanelState.POSITION_CONTROL)); } } intake.set(0); intakeSolenoid.set(Value.kForward); } else { if((stick.getTrigger() || pad.getRawButton(7))) { // Intake balls // Solenoid retracted // motor intaking intake.set(-1); intakeSolenoid.set(Value.kReverse); } else if(( stick.getRawButton(2) || pad.getRawButton(8) )) { // Eject balls // Solenoid extended // motor outputting intake.set(1); } else if(pad.getRawButton(5)) { // Eject jammed ball only // Solenoid retracted // motor outputting intake.set(1); } else { intake.set(0); intakeSolenoid.set(Value.kForward); } } } private double lastError = 0; private double outSpeed = 0; private void usWallFollower(boolean reverse, boolean right) { UltrasonicI2C.usResults resultsr = usi2cr.getResults(); UltrasonicI2C.usResults resultsl = usi2cl.getResults(); double aimPos = 300; // how far away from the wall we want to be in mm double pgain = 0.00025; // how fast we correct ourselves double dgain = 0.005; // change in gain double speed = 1; double leftPower; double rightPower; double accRate = 0.08; // Tuning for 6035 main robot. speed = 1.0; aimPos = 350; pgain = 0.0005; dgain = 0.02 ; double power = speed; if (reverse) { power = -speed; } outSpeed = outSpeed + Math.min( Math.max((power - outSpeed), -accRate), accRate); double dirPGain = pgain; double dirDGain = dgain; if (outSpeed < 0) { dirPGain = -dirPGain; dirDGain = -dirDGain; } double error = 0; if (right) { error = resultsr.getResult() - aimPos; // how far off from aimPos we are } else { error = aimPos - resultsl.getResult(); // how far off from aimPos we are } double delta = 0; if ((right && resultsr.getNew()) || (!right && resultsl.getNew())) { delta = error - lastError; // the change between error and lastError lastError = error; } steering = (error * dirPGain) + (delta * dirDGain); double pOutput = error * dirPGain; double dOutput = delta * dirDGain; SmartDashboard.putNumber("pOutput", pOutput); SmartDashboard.putNumber("dOutput", dOutput); SmartDashboard.putNumber("Error", error); leftPower = outSpeed + steering; rightPower = outSpeed - steering; steerPriority(leftPower, rightPower); } private void steerPriority(double left, double right) { if (left - right > 2) { left = 1; right = -1; } else if (right - left > 2) { left = -1; right = 1; } else if (Math.max(right, left) > 1) { left = left - (Math.max(right,left) - 1); right = right - (Math.max(right,left) - 1); } else if (Math.min(right, left) < -1) { left = left - (Math.min(right,left) + 1); right = right - (Math.min(right,left) + 1); } SmartDashboard.putNumber("leftPower", left); SmartDashboard.putNumber("rightPower", left); SmartDashboard.putNumber("SteerLeft", left-right); leftDrive.set(left); rightDrive.set(-right); } /** This function is called once when the robot is disabled. */ @Override public void disabledInit() { } /** This function is called periodically when disabled. */ @Override public void disabledPeriodic() { updatePeriodic(); } /** This function is called once when test mode is enabled. */ @Override public void testInit() { } /** This function is called periodically during test mode. */ @Override public void testPeriodic() { updatePeriodic(); } // void deadZoneCorrection() { // if (steering > -kJoystickDeadband && steering < kJoystickDeadband) { // steering = 0; // } // if (power > -kJoystickDeadband && power < kJoystickDeadband) { // power = 0; // } // } void armLow() { if((!lowSwitch.get())) { arm.set(1); armPos = ArmPos.LOW; } else { armIdle(); } } void armPort() { if((portSwitch.get() && !highSwitch.get())) { arm.set(-1); } else { armIdle(); } } void armHigh() { if((!highSwitch.get())) { arm.set(-1); } else { armIdle(); } } void armIdle() { arm.set(0); } }
package com.smxknife.java.ex11; /** * @author smxknife * 2018/11/16 */ public class NewIntegerTest { public static void main(String[] args) { System.out.println(Integer.valueOf(0x80000000)); } }
package p3.factory; import p3.logic.game.Game; import p3.logic.objects.*; /** Class "ZombieFactory": * * creates zombies. * works as "PlantFactory" * * */ public class ZombieFactory { private static Zombie[] avaliableZombies = { new ZNormal(), new ZAthlete(), new ZBucket() }; public static Zombie getZombie(String zombieSymbol, int y, int i, Game game) { Zombie zombie = null; switch (zombieSymbol.toUpperCase()) { case "Z": zombie = new ZNormal(y, i, game); break; case "X": zombie = new ZAthlete(y, i, game); break; case "W": zombie = new ZBucket(y, i, game); break; } return zombie; } public static Zombie loadZombie(String zombieSymbol, int x, int y, int hp, int freq, Game game) { Zombie zombie = null; switch (zombieSymbol.toUpperCase()) { case "Z": zombie = new ZNormal(x, y, hp, freq, game); break; case "X": zombie = new ZAthlete(x, y, hp, freq, game); break; case "W": zombie = new ZBucket(x, y, hp, freq, game); break; } return zombie; } public static String listAvaliableZombies() { String text = "Avaliable zombies: \n"; int i = 0; do { text += "Symbol: [" + avaliableZombies[i].getSymbol() + "]: Dmg = " + avaliableZombies[i].getDMG() + " Hp = " + avaliableZombies[i].getHP() + " Freq = " + avaliableZombies[i].getFreq() + "\n"; ++i; } while (i < avaliableZombies.length); return text; } public static int getAvaliableZombies() { return ZombieFactory.avaliableZombies.length; } public static String getSymbol(int i) { return ZombieFactory.avaliableZombies[i].getSymbol(); } }
package com.ross.spark.api.transform; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.api.java.function.FlatMapFunction; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; public class MapPartitionDemo { public static void main(String[] args){ SparkConf conf = new SparkConf().setAppName("mapPartition").setMaster("local"); JavaSparkContext sc = new JavaSparkContext(conf); List<String> list = Arrays.asList( "张三1", "李四1", "王五1", "张三2", "李四2", "王五2", "张三3", "李四3", "王五3", "张三4"); JavaRDD<String> rdd = sc.parallelize(list, 3); JavaRDD<String> mapPartitionRdd = rdd.mapPartitions(new FlatMapFunction<Iterator<String>, String>() { int count = 0; @Override public Iterator<String> call(Iterator<String> stringIterator) throws Exception { List<String> list = new ArrayList<>(); while(stringIterator.hasNext()){ list.add("分区索引:" + count++ + "\t" + stringIterator.next()); } return list.iterator(); } }); // 从集群获取数据到本地内存中 List<String> result = mapPartitionRdd.collect(); result.forEach(System.out::println); sc.close(); } }
package vanadis.objectmanagers; /** * Information about an expose point. * * @see ObjectManager#getExposedServices() * @see ObjectManager#getInjectedServices() * @see ObjectManager#getConfigureSummaries() */ public interface ExposedServiceSummary extends ManagedFeatureSummary { }
package com.chris.projects.fx.ftp.config; import com.chris.projects.fx.ftp.core.SpotOrderBookService; import com.chris.projects.fx.ftp.core.SpotOrderController; import com.chris.projects.fx.ftp.core.SpotOrderProcessor; import com.chris.projects.fx.ftp.fix.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn; import quickfix.Application; import quickfix.MessageCracker; @Configuration public class FTPConfig { private static final Logger LOG = LoggerFactory.getLogger(FTPConfig.class); @Bean public SpotOrderController spotOrderController(FixSender ftpFixSender) { LOG.info("Initialize spotOrderController"); return new SpotOrderController(ftpFixSender); } @Bean public SpotOrderProcessor spotOrderProcessor(SpotOrderController spotOrderController) { LOG.info("Initialize spotOrderProcessor"); return new SpotOrderProcessor(spotOrderController); } @Bean public SpotOrderBookService spotOrderBookService(SpotOrderProcessor spotOrderProcessor) { LOG.info("Initialize spotOrderBookService"); return new SpotOrderBookService(spotOrderProcessor); } @Bean public FTPFixProperties ftpFixProperties() { LOG.info("Initialize ftpFixProperties"); return new FTPFixProperties(); } @Bean @DependsOn("ftpFixProperties") public FixSender ftpFixSender(FTPFixProperties ftpFixProperties) { LOG.info("Initialize FixSender"); return new FTPFixMessageSender(ftpFixProperties.getSenderCompId(), ftpFixProperties.getTargetCompId()); } @Bean @DependsOn("spotOrderBookService") public MessageCracker ftpFixMessageReceiver(SpotOrderBookService orderBookService){ LOG.info("Initialize MessageCracker"); return new FTPFixMessageReceiver(orderBookService); } @Bean public FixApplication ftpFixApplication(MessageCracker ftpFixMessageReceiver) { LOG.info("Initialize FixApplication"); return new FixApplication(ftpFixMessageReceiver); } @Bean public FixSessionConnector fixSessionConnector(FTPFixProperties ftpFixProperties, Application fixApplication) { LOG.info("Creating fix session connector"); FixSessionConnector fixSessionConnector = new FixSessionConnector(ftpFixProperties.getConfigFile(), ftpFixProperties.isAcceptor(), fixApplication, new FixConnectorFactoryImpl()); fixSessionConnector.start(); return fixSessionConnector; } }
/* Initialize mid element as head and initialize a counter as 0. Traverse the list from head, while traversing increment the counter and change mid to mid->next whenever the counter is odd. So the mid will move only half of the total length of the list. */ package LinkedList.SinglyLinkedList.MiddleOfLinkedList; public class LinkedListMidd { Node head; class Node { int data; Node next; Node(int data) { this.data = data; this.next = null; } } // Push Element to the Back of the LinkedList void append(int data) { if (head == null) { head = new Node(data); return; } Node temp = head; while (temp.next != null) { temp = temp.next; } temp.next = new Node(data); return; } void middleNode() { if (head == null) { System.out.println("List is Empty"); } Node temp = head; Node middle = head; int count = 0; while (temp != null) { if (count % 2 != 0) { middle = middle.next; } temp = temp.next; count++; } if (middle != null) { System.out.println(middle.data); } return; } public static void main(String[] args) { LinkedListMidd list = new LinkedListMidd(); list.append(1); list.append(2); list.append(3); list.append(4); list.append(5); list.append(6); list.append(7); list.middleNode(); } }
/* * ********************************************************* * Copyright (c) 2019 @alxgcrz All rights reserved. * This code is licensed under the MIT license. * Images, graphics, audio and the rest of the assets be * outside this license and are copyrighted. * ********************************************************* */ package com.codessus.ecnaris.ambar.models.combate; import com.codessus.ecnaris.ambar.helpers.CombatManager; public class Turno { private int valorAleatorioParaCalcularAtaqueEnTurno, valorAleatorioParaCalcularDefensaEnTurno; private int tiradaAtaque, tiradaDefensa, damage; // ------ CONSTRUCTOR ---------- // private Turno() { valorAleatorioParaCalcularAtaqueEnTurno = CombatManager.generateRandomValueBetweenOneToTen(); valorAleatorioParaCalcularDefensaEnTurno = CombatManager.generateRandomValueBetweenOneToTen(); } // ------ CONSTRUCTOR ---------- // public Turno( int valorAtaqueAtacante, int valorDefensaDefensor ) { this(); tiradaAtaque = valorAtaqueAtacante + valorAleatorioParaCalcularAtaqueEnTurno; tiradaDefensa = valorDefensaDefensor + valorAleatorioParaCalcularDefensaEnTurno; } public int getTiradaAtaque() { return tiradaAtaque; } public int getTiradaDefensa() { return tiradaDefensa; } public int getDamage() { return damage <= 0 ? 0 : damage; } public void setDamage( int damage ) { this.damage += damage; } public boolean ataqueEsCritico() { return valorAleatorioParaCalcularAtaqueEnTurno == 10; } public boolean empateAndCritico() { return getTiradaAtaque() == getTiradaDefensa() & ataqueEsCritico(); } @Override public String toString() { return "Turno{" + "valorAleatorioParaCalcularAtaqueEnTurno=" + valorAleatorioParaCalcularAtaqueEnTurno + ", valorAleatorioParaCalcularDefensaEnTurno=" + valorAleatorioParaCalcularDefensaEnTurno + ", tiradaAtaque=" + tiradaAtaque + ", tiradaDefensa=" + tiradaDefensa + ", damage=" + damage + '}'; } }
package com.example.bonboru.nfc2eth; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.app.Fragment; import android.support.annotation.Nullable; import android.support.v4.content.LocalBroadcastManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.io.File; public class AccountFragment extends Fragment { public AccountFragment() { // Required empty public constructor } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(getActivity()); localBroadcastManager.registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { ((TextView) getView().findViewById(R.id.address)).setText(intent.getStringExtra("address")); } }, new IntentFilter("eth.address")); localBroadcastManager.registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { ((TextView)getView().findViewById(R.id.balance)).setText(Double.toString(intent.getDoubleExtra("balance", 0))); } }, new IntentFilter("eth.balance")); localBroadcastManager.registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(getActivity(), "Wrong Password", Toast.LENGTH_SHORT).show(); checkAccount(); } }, new IntentFilter("eth.wrongPassword")); } @Override public void onStart() { super.onStart(); checkAccount(); } private void checkAccount() { if (EthService.account == null) { File file = new File(getActivity().getFilesDir() + "/account.json"); if (!file.exists()) { final View dialogView = getActivity().getLayoutInflater().inflate(R.layout.dialog_create_account, null); new AlertDialog.Builder(getActivity()) .setTitle("Create New Account") .setView(dialogView) .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String password = ((EditText) dialogView.findViewById(R.id.create_password)).getText().toString(); String password_confirm = ((EditText) dialogView.findViewById(R.id.create_password_confirm)).getText().toString(); if (!password.equals(password_confirm)) { Toast.makeText(getActivity(), "Not Match", Toast.LENGTH_SHORT).show(); return; } Intent intent = new Intent(getActivity(), EthService.class); intent.setAction("account.createAccount"); intent.putExtra("password", password); getActivity().startService(intent); } }) .setCancelable(false) .show(); } else { final View dialogView = getActivity().getLayoutInflater().inflate(R.layout.dialog_unlock_account, null); new AlertDialog.Builder(getActivity()) .setTitle("Unlock Account") .setView(dialogView) .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String password = ((EditText) dialogView.findViewById(R.id.unlock_password)).getText().toString(); Intent intent = new Intent(getActivity(), EthService.class); intent.setAction("account.unlockAccount"); intent.putExtra("password", password); getActivity().startService(intent); } }) .setCancelable(false) .show(); } } } @Override public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_account, container, false); } }
package com.tencent.tencentmap.mapsdk.a; import com.tencent.tencentmap.mapsdk.a.sf.1; public final class ub { private 1 a; public ub(1 1) { this.a = 1; } public final void a(int i) { this.a.b(i); } public final void a(boolean z) { this.a.d(z); } public final boolean a() { return this.a.k(); } public final void b(int i) { this.a.c(i); } public final void b(boolean z) { this.a.a(z); } public final boolean b() { return this.a.g(); } public final void c(boolean z) { this.a.b(z); } public final void d(boolean z) { this.a.c(z); } }
package com.tencent.mm.pluginsdk.ui.tools; import android.media.MediaPlayer; import android.media.MediaPlayer.OnPreparedListener; class VideoSurfaceView$2 implements OnPreparedListener { final /* synthetic */ VideoSurfaceView qUd; VideoSurfaceView$2(VideoSurfaceView videoSurfaceView) { this.qUd = videoSurfaceView; } public final void onPrepared(MediaPlayer mediaPlayer) { VideoSurfaceView.d(this.qUd); if (VideoSurfaceView.e(this.qUd) != null) { VideoSurfaceView.e(this.qUd).iy(); } VideoSurfaceView.a(this.qUd, mediaPlayer.getVideoWidth()); VideoSurfaceView.b(this.qUd, mediaPlayer.getVideoHeight()); VideoSurfaceView.c(this.qUd); if (VideoSurfaceView.a(this.qUd) == 0 || VideoSurfaceView.b(this.qUd) == 0) { if (VideoSurfaceView.f(this.qUd)) { VideoSurfaceView.g(this.qUd).start(); VideoSurfaceView.h(this.qUd); } } else if (VideoSurfaceView.f(this.qUd)) { VideoSurfaceView.g(this.qUd).start(); VideoSurfaceView.h(this.qUd); } } }
package br.com.tela.cadastro; import javax.swing.JPanel; import java.awt.Frame; import javax.swing.JDialog; import java.awt.Dimension; import java.awt.Color; import javax.swing.JLabel; import java.awt.Rectangle; import javax.swing.SwingConstants; import java.awt.Font; import javax.swing.ImageIcon; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.List; import javax.swing.InputMap; import javax.swing.JButton; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.KeyStroke; import javax.swing.table.DefaultTableModel; import org.apache.commons.lang.StringUtils; import br.com.classes.Cliente; import br.com.entity.Endereco; import br.com.entity.PessoaJuridica; import br.com.entity.ProdutorRural; import br.com.persistencia.EnderecoDao; import br.com.persistencia.PessoaJuridicaDao; import br.com.persistencia.ProdutorRuralDao; import br.com.util.AN; import br.com.util.Constantes; import javax.swing.JTextField; import java.awt.event.KeyAdapter; import java.awt.Toolkit; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class F9Cliente extends JDialog { int[] titsSel = null; // @jve:decl-index=0: static String tituloSel = ""; int totalTit = -1; String titSel = ""; // @jve:decl-index=0: int linhaTit = -1; int colTit = -1; // static String codFor = ""; // @jve:decl-index=0: static String descFor = ""; static DefaultTableModel modelo = new DefaultTableModel(); // private JPanel jContentPane = null; private JLabel jLabel = null; private JButton jButton1 = null; private JScrollPane jScrollPane = null; private static JTable jTable = null; private JLabel jLabel41 = null; private static JTextField jTextField = null; private JLabel jLabel1 = null; private JLabel jLabel2 = null; private JButton jButton = null; JButton btnGravar = null; private JButton btnCarregar; private PessoaJuridicaDao pessoaJuridicaDao; private EnderecoDao enderecoDao; private PessoaJuridica pessoaJuridica; private Endereco endereco; /** * @param owner * @param tela */ String tela = ""; static boolean sohCliente = false; public F9Cliente(Frame owner, String desc, String tela, boolean sohCliente) { super(owner); this.sohCliente = sohCliente; initialize(); if(!desc.equals("")){ jTextField.setText(desc); atualizaTable(); } this.tela = tela; } /** * This method initializes this * * @return void */ private void initialize() { this.setSize(523, 323); this.setTitle("Cadastro - CLIENTES"); this.setModal(true); this.setResizable(false); this.setLocationRelativeTo(null); //this.setUndecorated(true); // RETIRA AS BORDAS DO FRAME this.setContentPane(getJContentPane()); this.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { limparCampos(); } }); atualizaTable(); } public void limparCampos(){ codFor = ""; descFor = ""; jTextField.setText(""); for (int i = (jTable.getRowCount() - 1); i >= 0; --i) { modelo.removeRow(i);//remove todas as linhas selecionadas } modelo.setRowCount(0); } /** * This method initializes jContentPane * * @return javax.swing.JPanel */ private JPanel getJContentPane() { if (jContentPane == null) { jLabel41 = new JLabel(); jLabel41.setBounds(new Rectangle(3, 28, 78, 21)); jLabel41.setHorizontalAlignment(SwingConstants.TRAILING); jLabel41.setText("Nome:"); jLabel41.setPreferredSize(new Dimension(174, 18)); jLabel = new JLabel(); jLabel.setBounds(new Rectangle(3, 1, 511, 28)); jLabel.setHorizontalAlignment(SwingConstants.CENTER); jLabel.setFont(new Font("Dialog", Font.BOLD | Font.ITALIC, 15)); jLabel.setForeground(new Color(51, 0, 102)); jLabel.setText("Consulta de Cliente"); jContentPane = new JPanel(); jContentPane.setLayout(null); jContentPane.setBackground(Color.white); jContentPane.add(jLabel, null); jContentPane.add(getJButton1(), null); jContentPane.add(getJScrollPane(), null); jContentPane.add(jLabel41, null); jContentPane.add(getJTextField(), null); btnCarregar = new JButton(); btnCarregar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { carregar(); } }); btnCarregar.setIcon(new ImageIcon(F9Cliente.class.getResource("/image/icLanc.png"))); btnCarregar.setText("Carregar"); btnCarregar.setPreferredSize(new Dimension(116, 28)); btnCarregar.setMnemonic('F'); btnCarregar.setFont(new Font("Dialog", Font.BOLD, 13)); btnCarregar.setBounds(new Rectangle(205, 238, 116, 28)); btnCarregar.setBounds(129, 241, 125, 28); jContentPane.add(btnCarregar); JButton button = new JButton(""); button.setIcon(new ImageIcon(F9Cliente.class.getResource("/image/icSetar.png"))); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { atualizaTable(); } }); button.setBounds(470, 27, 26, 24); jContentPane.add(button); } return jContentPane; } public void selTudoTitulos(){ jTable.selectAll(); titsSel = jTable.getSelectedRows(); } /** * This method initializes jButton1 * * @return javax.swing.JButton */ private JButton getJButton1() { if (jButton1 == null) {} jButton1 = new JButton(); jButton1.setMnemonic('F'); jButton1.setBounds(new Rectangle(260, 241, 125, 28)); jButton1.setIcon(new ImageIcon(F9Cliente.class.getResource("/image/icSair.png"))); jButton1.setText("Fechar"); jButton1.setPreferredSize(new Dimension(116, 28)); jButton1.setFont(new Font("Dialog", Font.BOLD, 13)); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { fechar(); } }); return jButton1; } /** * This method initializes jScrollPane * * @return javax.swing.JScrollPane */ private JScrollPane getJScrollPane() { if (jScrollPane == null) { jScrollPane = new JScrollPane(); jScrollPane.setBounds(new Rectangle(13, 60, 494, 160)); jScrollPane.setViewportView(getJTable()); } return jScrollPane; } static Cliente c = null; public static void atualizaTable(){ if(c==null){ c=new Cliente(); } String[][] dados = null; String sql1 = ""; String sql2 = ""; limparTable(); String ad = sohCliente==true?" and pr.cliente_contabilidade='S' ":""; String text = jTextField.getText(); int codigo = 0; try{codigo = AN.stringPInt(text);}catch(Exception e){} if(codigo>0){ sql1 = "SELECT count(p.id) as total FROM pessoa p " + "left join pessoa_juridica pj on pj.id_pessoa = p.id " +" left join produtor_rural pr on pr.id_pessoa_juridica=pj.id " + " where p.id is not null and p.id="+text+ad; sql2 = "SELECT p.id, pj.razao_social FROM pessoa p " + "left join pessoa_juridica pj on pj.id_pessoa = p.id " +" left join produtor_rural pr on pr.id_pessoa_juridica=pj.id " + " where p.id is not null and p.id="+text+ad; dados = c.buscarPassandoMatrizCad(sql1, sql2); } if(dados == null){ sql1 = "SELECT count(p.id) as total FROM pessoa p " + "left join pessoa_juridica pj on pj.id_pessoa = p.id " +" left join produtor_rural pr on pr.id_pessoa_juridica=pj.id " + " where pj.razao_social like '%"+text+"%'"+ad; sql2 = "SELECT p.id, pj.razao_social FROM pessoa p " + "left join pessoa_juridica pj on pj.id_pessoa = p.id " +" left join produtor_rural pr on pr.id_pessoa_juridica=pj.id " + " where pj.razao_social like '%"+text+"%'"+ad; dados = c.buscarPassandoMatrizCad(sql1, sql2); } if(dados != null){ for(int i=0; i<dados.length; i++){ modelo.addRow(new Object[] {dados[i][0], dados[i][1]}); } } else{ modelo.addRow(new Object[] {"","Nenhum Cliente Encontrado!!!"}); } } // public static void limparTable(){ try{ int modelos = jTable.getRowCount(); int i = 0; if(modelos > 0){ do{ modelo.removeRow(i); } while(i < modelos && jTable.getRowCount() != 0); i++; } }catch(Exception e){} } /** * This method initializes jTable * * @return javax.swing.JTable */ private JTable getJTable() { if (jTable == null) { modelo.addColumn("CÓDIGO"); modelo.addColumn("CLIENTE"); // modelo.addRow(new Object[] {"","Cadastro de Cliente"}); } jTable = new JTable(modelo){ public boolean isCellEditable(int row, int column) { if (column >= 0) { return false; } else { return true; } } }; jTable.getTableHeader().setReorderingAllowed(false); // Não move as colunas jTable jTable.setFont(new Font("Dialog", Font.PLAIN, 13)); jTable.setColumnSelectionAllowed(false); jTable.setRowHeight(20); jTable.setRowSelectionAllowed(true); //jTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); jTable.setShowGrid(true); jTable.setShowHorizontalLines(true); jTable.setShowVerticalLines(true); jTable.setVisible(true); jTable.setAutoCreateColumnsFromModel(true); jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); jTable.setSelectionForeground(Color.black); jTable.setGridColor(new Color(0, 153, 51)); jTable.setSelectionBackground(new Color(204, 255, 204)); // "CÓDIGO", "CLIENTE", "FANT/SOBRE", "CIDADE", "UF", // "TELEFONE","FAX","CELULAR" jTable.getColumnModel().getColumn(0).setPreferredWidth(95);// Código jTable.getColumnModel().getColumn(1).setPreferredWidth(380);// Cliente // //ENTER KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0); InputMap map = jTable.getInputMap(JTable.WHEN_FOCUSED); map.put(enter, "selectNextColumnCell"); jTable.addKeyListener(new java.awt.event.KeyListener() { public void keyReleased(java.awt.event.KeyEvent e) { totalTit = jTable.getRowCount(); linhaTit = jTable.getSelectedRow(); colTit = jTable.getSelectedColumn(); titSel = ""; try{titSel = jTable.getValueAt(linhaTit, 0).toString();}catch(Exception e2){} titsSel = new int[totalTit]; titsSel = jTable.getSelectedRows(); } public void keyTyped(java.awt.event.KeyEvent e) { } public void keyPressed(java.awt.event.KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_ENTER){ linhaTit = jTable.getSelectedRow(); String a = ""; try{a = jTable.getValueAt(linhaTit, 0).toString();}catch(Exception e2){} if(!a.equals("")){ carregar(); } }if(e.getKeyCode() == KeyEvent.VK_F5){ jTextField.requestFocus(); } } }); jTable.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent e) { totalTit = jTable.getRowCount(); linhaTit = jTable.getSelectedRow(); colTit = jTable.getSelectedColumn(); titSel = ""; try{titSel = jTable.getValueAt(linhaTit, 0).toString();}catch(Exception e2){} titsSel = new int[totalTit]; titsSel = jTable.getSelectedRows(); if(e.getClickCount() == 2){ String a = ""; try{a = jTable.getValueAt(linhaTit, 0).toString();}catch(Exception e2){} try{a = jTable.getValueAt(linhaTit, 0).toString();}catch(Exception e2){} if(!a.equals("")){ carregar(); } } } public void mouseReleased(MouseEvent arg0) { totalTit = jTable.getRowCount(); linhaTit = jTable.getSelectedRow(); colTit = jTable.getSelectedColumn(); titSel = ""; try{titSel = jTable.getValueAt(linhaTit, 0).toString();}catch(Exception e2){} titsSel = new int[totalTit]; titsSel = jTable.getSelectedRows(); } }); return jTable; } /** * This method initializes jTextField * * @return javax.swing.JTextField */ private JTextField getJTextField() { if (jTextField == null) {} jTextField = new JTextField(); jTextField.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_ENTER){ atualizaTable(); String a = ""; try{a = jTable.getValueAt(0, 0).toString();}catch(Exception e2){} if(!a.equals("")){ jTable.requestFocus(); jTable.changeSelection(0, 0, true, false); }else{ jTextField.selectAll(); } } } }); jTextField.setBackground(Color.white); jTextField.setFont(new Font("Dialog", Font.BOLD, 13)); jTextField.setBounds(new Rectangle(83, 28, 382, 22)); return jTextField; } // public void carregar(){ int cod = 0; try{cod = AN.stringPInt(jTable.getValueAt(linhaTit, 0).toString());}catch(Exception e){} if(tela.equals("Inicio")){ try{ String txt = jTable.getValueAt(linhaTit, 0).toString()+" - "+jTable.getValueAt(linhaTit, 1).toString(); if(cod>0){ Inicio.labelCliente.setText(txt); Inicio.setEntrou(true); int id = Integer.parseInt(jTable.getValueAt(linhaTit, 0).toString()); setPessoaJuridica(getPessoaJuridicaDao().getPessoaJuridicaPorPessoa(Integer.toString(id))); if(getPessoaJuridica().getId() != null){ Constantes.pessoaJuridica = getPessoaJuridica(); } setEndereco(getEnderecoDao().getEnderecoPorPessoa(Integer.toString(id))); if(getEndereco().getId() != null){ Constantes.endereco = getEndereco(); } }else{ Inicio.labelCliente.setText(""); Inicio.setEntrou(false); } dispose(); }catch(Exception e){} }else if(tela.equals("LancNotaVend")){ try{ String txt = jTable.getValueAt(linhaTit, 0).toString()+" - "+jTable.getValueAt(linhaTit, 1).toString(); if(cod>0){ LancNota.textVend.setText(txt); }else{ LancNota.textVend.setText(""); } LancNota.textVend.requestFocus(); dispose(); }catch(Exception e){} }else if(tela.equals("LancNotaComp")){ try{ String txt = jTable.getValueAt(linhaTit, 0).toString()+" - "+jTable.getValueAt(linhaTit, 1).toString(); if(cod>0){ LancNota.textComp.setText(txt); }else{ LancNota.textComp.setText(""); } LancNota.textComp.requestFocus(); dispose(); }catch(Exception e){} } } public void fechar(){ if(tela.equals("Inicio")){ try{ dispose(); }catch(Exception e){} }else if(tela.equals("LancNotaVend")){ try{ MovNotaFiscal.lancNota.setSelected(true); LancNota.textVend.requestFocus(); dispose(); }catch(Exception e){} }else if(tela.equals("LancNotaComp")){ try{ MovNotaFiscal.lancNota.setSelected(true); LancNota.textComp.requestFocus(); dispose(); }catch(Exception e){} } sohCliente=false; } public PessoaJuridicaDao getPessoaJuridicaDao() { if(pessoaJuridicaDao == null){ pessoaJuridicaDao = new PessoaJuridicaDao(); } return pessoaJuridicaDao; } public PessoaJuridica getPessoaJuridica() { if(pessoaJuridica == null){ pessoaJuridica = new PessoaJuridica(); } return pessoaJuridica; } public void setPessoaJuridica(PessoaJuridica pessoaJuridica) { this.pessoaJuridica = pessoaJuridica; } public EnderecoDao getEnderecoDao() { if(enderecoDao == null){ enderecoDao = new EnderecoDao(); } return enderecoDao; } public Endereco getEndereco() { if(endereco == null){ endereco = new Endereco(); setEndereco(new Endereco()); } return endereco; } public void setEndereco(Endereco endereco) { this.endereco = endereco; } }
package com.ericlam.mc.minigames.core.gamestats; /** * 可編輯的遊戲玩家資料容器接口 */ public interface GameStatsEditor extends GameStats { /** * 設置殺敵數 * * @param kills 殺數 */ void setKills(int kills); /** * 設置死亡數 * @param deaths 死數 */ void setDeaths(int deaths); /** * 設置遊玩次數 * @param played 遊玩次數 */ void setPlayed(int played); /** * 設置勝利數 * @param wins 勝數 */ void setWins(int wins); }
package LC0_200.LC50_100; import org.junit.Test; public class LC91_Decode_Ways { @Test public void test() { //System.out.println(numDecodings("123123")); //System.out.println(numDecodings("1201234")); //System.out.println(numDecodings("1212")); //System.out.println(numDecodings("256")); System.out.println(numDecodings("12")); System.out.println(numDecodings("226")); System.out.println(numDecodings("2101")); // System.out.println(numDecodings("1123")); System.out.println(numDecodings("2611055971756562")); } public int numDecodings(String s) { int[] dp= new int[s.length() + 1]; dp[0]=1; dp[1]= s.charAt(0)=='0' ? 0 : 1; for(int i = 2; i < dp.length; i++){ int oneDigit= Integer.valueOf(s.substring(i - 1, i)); int twoDig= Integer.valueOf(s.substring(i - 2, i)); if(oneDigit >= 1) dp[i] += dp[i - 1]; if(twoDig >= 10 && twoDig <= 26) dp[i] += dp[i - 2]; } return dp[s.length()]; } }
package com.tdd.model; /** * * @author teyyub Mar 25, 2016 5:17:51 PM */ public class King extends Piece { static final String KING = "k"; private static final String WHITE_COLOR = "WHITE"; private static final String BLACK_COLOR = "BLACK"; public King() { } public static King createKing(String color){ return new King(color); } private King(String color) { if (color == null ? WHITE_COLOR == null : color.equals(WHITE_COLOR)) { setRepresentation(KING); } else { setRepresentation(KING.toUpperCase()); } setColor(color); } }
package com.findbank.c15.validacionForm; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; import com.findbank.c15.model.Usuario; public class UsuarioValidator implements Validator{ @Override public boolean supports(Class<?> arg0) { // TODO Auto-generated method stub return Usuario.class.equals(arg0); } @Override public void validate(Object obj, Errors error) { Usuario user = (Usuario) obj ; ValidationUtils.rejectIfEmptyOrWhitespace(error,"nombre", "user.nombre", "Falto completar el campo Nombre"); ValidationUtils.rejectIfEmptyOrWhitespace(error,"email", "user.email", "Falto completar el campo Email"); ValidationUtils.rejectIfEmptyOrWhitespace(error,"password", "user.password", "Falto completar el campo Password"); String email = user.getEmail(); if (email == null || !email.endsWith("@hotmail.com") || !email.endsWith("@gmail.com")) { error.rejectValue("email", "user.email", "El correo no es valido"); } } }
package com.classcheck.panel; import java.awt.Cursor; import java.awt.FlowLayout; import java.awt.Font; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.BoxLayout; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.table.DefaultTableModel; import org.apache.lucene.search.spell.LevensteinDistance; import com.change_vision.jude.api.inf.model.IClass; import com.classcheck.analyzer.source.CodeVisitor; import com.classcheck.autosource.ClassBuilder; import com.classcheck.autosource.Method; import com.classcheck.autosource.MyClass; import com.classcheck.panel.event.ClassLabelMouseAdapter; import com.classcheck.panel.event.ClickedLabel; import com.classcheck.type.ParamCheck; import com.classcheck.type.ReferenceType; import com.classcheck.window.DebugMessageWindow; import com.github.javaparser.ast.body.ConstructorDeclaration; import com.github.javaparser.ast.body.MethodDeclaration; public class MethodComparePanel extends JPanel { private List<IClass> javaPackage; Map<MyClass, List<JPanel>> mapPanelList; List<CodeVisitor> codeVisitorList; HashMap<MyClass, CodeVisitor> codeMap; private StatusBar mtpSourceStatus; private List<JComboBox<String>> boxList; private DefaultTableModel tableModel; public MethodComparePanel(HashMap<MyClass, CodeVisitor> codeMap) { mapPanelList = new HashMap<MyClass, List<JPanel>>(); this.codeMap = codeMap; mtpSourceStatus = null; setLayout(new BoxLayout(this,BoxLayout.PAGE_AXIS)); setVisible(true); } public MethodComparePanel(List<IClass> javaPackage, ClassBuilder cb, List<CodeVisitor> codeVisitorList, HashMap<MyClass, CodeVisitor> codeMap) { this(codeMap); this.javaPackage = javaPackage; this.codeVisitorList = codeVisitorList; for (MyClass myClass : cb.getClasslist()) { for (CodeVisitor codeVisitor : codeVisitorList) { if(myClass.getName().equals(codeVisitor.getClassName())){ codeMap.put(myClass, codeVisitor); } } mapPanelList.put(myClass, new ArrayList<JPanel>()); } } public List<CodeVisitor> getCodeVisitorList() { return codeVisitorList; } public void setCodeVisitorList(List<CodeVisitor> codeVisitorList) { this.codeVisitorList = codeVisitorList; } public Map<MyClass, CodeVisitor> getCodeMap() { return codeMap; } public Map<MyClass, List<JPanel>> getMapPanelList() { return mapPanelList; } public boolean initComponent(final MyClass myClass,boolean isAllChange){ List<JPanel> panelList = this.mapPanelList.get(myClass); LevensteinDistance levensteinAlgorithm = new LevensteinDistance(); //tmp double distance = 0; //最も大きかった距離 double maxDistance = 0; //最も距離が近かった文字列 String keyStr=null; List<Method> umlMethodList = myClass.getMethods(); List<MethodDeclaration> codeMethodList = null; List<ConstructorDeclaration> codeConstructorList = null; CodeVisitor codeVisitor = this.codeMap.get(myClass); JComboBox<String> methodComboBox = null; //同じシグネチャーが選択されているかどうかを調べる boxList = new ArrayList<JComboBox<String>>(); boolean isSameMethodSelected = false; //ポップアップテキスト StringBuilder popSb = null; //コメントを取り除く String regex = "(?s)/\\*.*\\*/"; Pattern patern = Pattern.compile(regex); Matcher matcher; if (isAllChange) { panelList.clear(); //説明のパネルを加える //(左)astah :(右) ソースコード JPanel explainPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 5)); JLabel explainLabel = new JLabel("(左)クラス図で定義したメソッド : (右)ソースコードのフィールド"); explainLabel.setFont(new Font("SansSerif", Font.BOLD, 12)); explainLabel.setAlignmentX(CENTER_ALIGNMENT); explainPanel.add(explainLabel); panelList.add(explainPanel); if (codeVisitor != null){ codeMethodList = codeVisitor.getMethodList(); codeConstructorList = codeVisitor.getConstructorList(); } for (Method umlMethod : umlMethodList) { boolean isUmlConstructor = false; /* * メソッドの名前がクラスの名前と同じ場合 => メソッドはコンストラクタとする */ if (umlMethod.getName().equals(myClass.getName())) { isUmlConstructor = true; } matcher = patern.matcher(umlMethod.getSignature()); JLabel l = new JLabel(matcher.replaceAll("")); JPanel p = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 5)); String popToolTip_str = popToolTips_UML(umlMethod); l.setAlignmentX(CENTER_ALIGNMENT); l.setToolTipText(popToolTip_str); l.setCursor(new Cursor(Cursor.HAND_CURSOR)); //クラス図を表示 l.addMouseListener(new ClassLabelMouseAdapter(myClass, l, getParent(),ClickedLabel.MethodSig)); //ソースコードが定義されていない場合 if (codeVisitor == null) { //空のボックスを作成 methodComboBox = new JComboBox<String>(); methodComboBox.setToolTipText("<html>"+ "<p>"+ "対応するメソッドがありません<br>"+ "</p>"+ "</html>"); }else{ ArrayList<String> strList = new ArrayList<String>(); String umlMethod_modify_str = umlMethod.getModifiers(); StringBuilder methodError_sb = new StringBuilder(); int itemCount = 0; //最後の空白スペースを取り除く if (umlMethod_modify_str.endsWith(" ")) { umlMethod_modify_str = umlMethod_modify_str.substring(0, umlMethod_modify_str.lastIndexOf(" ")); } //umlMethodがコンストラクタである場合 if (isUmlConstructor) { //ソースコードのコンストラクタを追加 for (ConstructorDeclaration codeConstructor : codeConstructorList) { String codeConstructor_modify_str = Modifier.toString(codeConstructor.getModifiers()); //ソースコードのメソッドのパラメータ数と //スケルトンコードのパラメータ個数の一致 boolean isCorrentLength = codeConstructor.getParameters().size() == umlMethod.getParams().length; //ソースコードのコンストラクタの修飾子と //スケルトンコードの修飾子の一致 //スケルトンコードの修飾子には「public 」のようにスペースが入り込むので削除する boolean isCorrectModifiy = umlMethod_modify_str.equals(codeConstructor_modify_str); //パラメータの型の一致 boolean isCorrectParam = new ParamCheck(isCorrentLength,this.javaPackage, this.tableModel, umlMethod.getParams(), codeConstructor.getParameters()).evaluate(); if (isCorrentLength && isCorrectModifiy && isCorrectParam){ strList.add(codeConstructor.getDeclarationAsString()); itemCount++; }else{ methodError_sb.append(codeConstructor.getDeclarationAsString()+"<br>"); if (isCorrentLength == false) { methodError_sb.append("=>"+"パラメータの個数が合っていません"+"<br>"); } if (isCorrectModifiy == false) { methodError_sb.append("=>"+"修飾子が合っていません"+"<br>"); } if (isCorrectParam == false) { methodError_sb.append("=>"+"パラメータの型が合っていません"+"<br>"); } } } //umlMethodがメソッドである場合 }else{ //ソースコードのメソッドを追加 for (MethodDeclaration codeMethod : codeMethodList) { String codeMethod_modify_str = Modifier.toString(codeMethod.getModifiers()); //ソースコードのメソッドのパラメータ数と //スケルトンコードのパラメータ個数の一致 //パラメータの型も一致させる(型はソースコードに依存する、また基本型の場合も考えるようにする) boolean isCorrentLength = codeMethod.getParameters().size() == umlMethod.getParams().length; //ソースコードのメソッドの修飾子と //スケルトンコードの修飾子の一致 //スケルトンコードの修飾子には「public 」のようにスペースが入り込むので削除する boolean isCorrectModifiy = umlMethod_modify_str.equals(codeMethod_modify_str); //返り値の型一致(型はソースコードに依存する、また基本型の場合も考えるようにする) boolean isCorrectRtnType = new ReferenceType(this.javaPackage,this.tableModel, umlMethod, codeMethod).evaluate(); //パラメータの型の一致 boolean isCorrectParam = new ParamCheck(isCorrentLength,this.javaPackage,this.tableModel,umlMethod.getParams(),codeMethod.getParameters()).evaluate(); if (isCorrentLength && isCorrectModifiy&& isCorrectRtnType && isCorrectParam){ strList.add(codeMethod.getDeclarationAsString()); itemCount++; }else{ methodError_sb.append(codeMethod.getDeclarationAsString()+"<br>"); if (isCorrentLength == false) { methodError_sb.append("=>"+"パラメータの個数が合っていません"+"<br>"); } if (isCorrectModifiy == false) { methodError_sb.append("=>"+"修飾子が合っていません"+"<br>"); } if (isCorrectRtnType == false) { methodError_sb.append("=>"+"返り値の型が合っていません"+"<br>"); } if (isCorrectParam == false) { methodError_sb.append("=>"+"パラメータの型が合っていません"+"<br>"); } } } } methodComboBox = new JComboBox<String>(strList.toArray(new String[strList.size()])); //ボックスに一つも選択するアイテムがない場合はヒントを表示する用意をする if (itemCount == 0) { String tooltipText = ""; tooltipText +="<html>"; tooltipText +="<p>"; tooltipText +=methodError_sb.toString(); tooltipText +="</p>"; tooltipText +="</html>"; methodComboBox.setToolTipText(tooltipText); } methodComboBox.setCursor(new Cursor(Cursor.HAND_CURSOR)); boxList.add(methodComboBox); //レーベンシュタイン距離を初期化 distance = 0; maxDistance = 0; keyStr = null; for (String str : strList) { distance = levensteinAlgorithm.getDistance(umlMethod.toSignature(), str); if(maxDistance < distance){ maxDistance = distance; keyStr = str; } } methodComboBox.setSelectedItem(keyStr); } p.add(l); p.add(methodComboBox); panelList.add(p); } } //描画 for (JPanel panel : panelList) { add(panel); } //ツリーアイテムを押してもうまく表示されないので //常に早く表示させるよう対策 repaint(); //同じメソッドが選択されているかどうかを調べる JComboBox box_1,box_2; String strBox_1,strBox_2; Object obj; for (int i=0; i < boxList.size() ; i++){ box_1 = boxList.get(i); obj = box_1.getSelectedItem(); if (obj == null) { continue ; } strBox_1 = obj.toString(); for(int j=0; j < boxList.size() ; j++){ box_2 = boxList.get(j); obj = box_2.getSelectedItem(); if (obj == null) { continue ; } strBox_2 = obj.toString(); if (i==j) { continue ; } if (strBox_1.equals(strBox_2)) { isSameMethodSelected = true; break; } } if (isSameMethodSelected) { break; } } DebugMessageWindow.msgToTextArea(); return isSameMethodSelected; } private String popToolTips_UML(Method umlMethod){ StringBuilder popSb = new StringBuilder(); //ポップアップテキストを加える popSb.append("<html>"); //popSb.append("<p width=\"500\">"); popSb.append("<p>"); popSb.append("定義:<br>"); if (umlMethod.getOperation().getDefinition().length() == 0) { popSb.append("なし<br>"); }else{ String[] comments = umlMethod.getOperation().getDefinition().split("\\n", 0); for (String comment : comments) { popSb.append(comment + "<br>"); } } popSb.append("本体条件:<br>"); if (umlMethod.getOperation().getBodyCondition().length() == 0) { popSb.append("なし<br>"); }else{ popSb.append("・"+umlMethod.getOperation().getBodyCondition()+"<br>"); } popSb.append("事前条件:<br>"); if (umlMethod.getOperation().getPreConditions().length == 0) { popSb.append("なし<br>"); }else{ for(String text : umlMethod.getOperation().getPreConditions()){ popSb.append("・"+text+"<br>"); } } popSb.append("事後条件:<br>"); if (umlMethod.getOperation().getPostConditions().length == 0) { popSb.append("なし<br>"); }else{ for(String text : umlMethod.getOperation().getPostConditions()){ popSb.append("・"+text+"<br>"); } } popSb.append("</p>"); popSb.append("</html>"); return popSb.toString(); } /** * パネルからもステータスのテキストを変更可能にする * @param text */ public void setStatusText(String text){ mtpSourceStatus.setText(text); } public void setStatus(StatusBar mtpSourceStatus) { this.mtpSourceStatus = mtpSourceStatus; } public void setTableModel(DefaultTableModel tableModel) { this.tableModel = tableModel; } }
/** Ben F Rayfield offers this software opensource GNU GPL 2+ */ package ufnode; import java.util.Arrays; import util.MathUtil; import util.Text; import util.Time; /** Ufnode (unified merkle forest) is for gaming low lag number crunching in blockchains and sidechains. Executable binary forest data structure where every node has a global (100 times faster than sha256) secureHashed int128 name (TODO fork more secure hash algorithms) of a double, float, 0-8 byte string, 15 bytes of a sha256, pair of those, etc. An example global name is uf_d37c$70fd4a944129af73d77d2929b149bf75 which means hash algorithm name (16 bits) d37c then $ then an int128 whose first byte is type (such as 'g' for tiny string, 'd' for double, 'f' for float, 'F' for 2 floats, 'h' for the first 7 concat last 8 bytes of a sha256, 'p' for pair of 2 ufnodes etc). On a 1.6 ghz laptop in Windows 7 I got 10 million hashes per second when allocating an int[4] each time, and 4 million hashes when reusing the arrays. The in-progress hash algorithm uses parts of sha256 but is very different as its designed for a loop of size 16, 128 bit state (other than loop counter), and a constant 256 bit input and 128 bit output. Knowing its constant sizes allows double hashing (of concat of 2 copies of the input) to prevent precomputing until nearly the end of the hash and varying just the last part of the input. It therefore doesnt need the int[64] array of sha256 computed before the main loop. I dont think its a secureHash yet but is close, and I'll keep improving it, with a different hash algorithm name (like d37c) each. https://en.wikipedia.org/wiki/Hash_consing TODO implement ufmaplist (with optional homomorphic dedup requiring secret salt per computer, for global dedup any pair of computers which dont trust eachother will agree on)... Implement the ufmaplist datastruct (see code in the ufnodeOld and ufnodeapi javapackages in (still disorganized to be published soon hopefully) at the binary forest level so an ufmaplist is made of multiple binary forest nodes such as a linkedlist of its fields including min key, max key, long list size, ufnode.ty byte, etc, and different ufnode.ty (small constant set of ufnode types from which complex things are built) are different datastructs. An ufmaplist is an avl treemap or treelist, like in benrayfields wavetree software. TODO create a binary forest (instead of var size maplist) based variation of ufnode.Security class's opcodes where every func is called like [? "someNameOfTheFuncThatDescribesItVeryPrecisely]#prehopfieldname and prehopfieldname can after that in the same code string refer to that node in the immutable forest and will not differ in computing behavior when multiple people locally name the same uf128 different things. TODO lazyEvalHashing for opencl optimized matrixMultiply of RBM neuralnet (as in the paint* rbm experimental code I've been developing which is still too disorganized), which could hook in through sha256 of such arrays before and after opencl ops whose inputs and outputs are much smaller than the number of calculations done, or could reflect pairs of floats or single doubles each as an uf128. Ufnode in those cases would not be the bottleneck but is close to it so be careful to keep it fast, or more practically lazyEvalHashing would avoid hashing within local computer until save to harddrive or send across Internet (any untrusted border) need to compute uf128 recursively and in the process the benefit of dedup. Pure determinism vs allowing roundoff (such as opencl claims strictfp option but its said to work on some computers but not others), order of ops, etc... By default things are slightly nondeterministic but there should be a puredeterministic mode or some types guarantee it per node. TODO linkedhashtable with 256 bit buckets (or 384 if store what they hash to) andOr various other optimized datastructs for lookup and storing and sharing uf128s and bitstrings which 'h' and 'H' (external hash algorithms sha*) point at. Buckets might be int32s pointing into an array used as a heap/hashtablecontents. For faster computing without dedup/sharing (yet or garbcol before that so never for that node), an object in memory using native pointers (java pointers, javascript pointers, C pointers, etc) instead of 128 bit ids use them until trigger lazyEvalHash. TODO use econacyc of com and mem and zapeconacyc, optionally, depending what kinds of sandboxing is needed, such as guaranteeing escape from a function called within a microsecond of it running out of allocated compute cycles and memory allocation, or statistical sharing of memory cost upward along reverse pointers, with a high cost of such zapeconacyc statistics. Allows things like running a virus in debug mode purely statelessly without risk if the ufnode VM correctly sandboxes, similar to how a web browser can safely go to websites without those websites being able to run programs on your computer modifying your private files etc. Javascript's security holes seem to be in the native objects outside the javascript memory space such as Flash and DRM video players. Ufnode has no such state. All nodes are immutable merkle forest. For example, you cant command it to write to stdOut or read from the keyboard. There is no input or output, only the fact of a binary forest with certain types of leafs allowed. A virus may only execute its next computing step to return another virus but may not modify anything, and if you choose to use the new virus it returns, similarly it cant modify itself, only return yet another virus, so there is no such thing as a virus, meaning that which statefully modifies things without permission, since nothing ever modifies anything. An ufnode is a kind of number. It always halts within some guaranteed max time and memory, but its not always turingComplete. It is turingComplete if thats run in a loop, but each execution of the loop body always halts, like a debugger. */ public class HashUtil{ /** 2 uf128s in, 1 uf128 out. All 3 arrays are int[4]. Strange, but this is faster, when allocating arrays, than reusing arrays directly in hashFast(int[],int[]). */ public static int[] hash(int[] left, int[] right){ int[] in = new int[8]; System.arraycopy(left, 0, in, 0, 4); System.arraycopy(right, 0, in, 4, 4); int[] out = new int[4]; hashFast(out,in); return out; } /** 32 minorityBit(a,b,c) ops */ public static int mino(int x, int y, int z){ return ~((x&y)|(x&z)|(y&z)); } /** right rotate aka downshift. Usually gives wrong answer if downshift is negative */ public static int rr(int data, int downshift){ return (data<<(32-downshift))|(data>>>downshift); } /** in is 8 ints (2 uf128s). Writes 1 uf128 to out. */ public static void hashFast(int[] out, int[] in){ //first 4 of "first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19" * int a = 0x6a09e667; int b = 0xbb67ae85; int c = 0x3c6ef372; int d = 0xa54ff53a; for(int doubleHash=0; doubleHash<2; doubleHash++){ //Do the hash on concat(in,in) for(int i=0; i<8; i++){ /*int s1 = (e rightrotate 6) xor (e rightrotate 11) xor (e rightrotate 25); int ch = ch := (e and f) xor ((not e) and g); int temp1 = h + S1 + ch + k[i] + w[i] int S0 = (a rightrotate 2) xor (a rightrotate 13) xor (a rightrotate 22) int maj = (a and b) xor (a and c) xor (b and c) int temp2 = S0 + maj */ int salt = sha256CuberootSalts[i]; int inp = in[i]; int q = (b^salt); //chooser int qChAC = (q&~a)|((~q)&c); //each bit in b chooses a bit in the past vs future int x = rr(a,6)^rr(a,11)^rr(a,25); int y = (rr(b,2)^rr(b,13)^rr(b,22))+inp; int z = ((c+salt+inp)^rr(d+qChAC,19)); int minoXYZ = ~((x&y)|(x&z)|(y&z)); //forest of minorityBit is npcomplete, like forest of nands or nors //int next = salt+qChAC+minoXYZ; //int next = (qChAC+minoXYZ+inp)^salt; int next = qChAC+minoXYZ+inp; //System.out.println("next: "+toString(next)); a = b; b = c+minoXYZ; c = d+salt; d = next; } } out[0] = (('p'&0xff)<<24)|(a&0x00ffffff); //replace first byte with type 'p' meaning its a pair (&0xff is a no-op but may help compilers optimize if they first see the 2 masks complement? But maybe I'm just trying to defend it cuz thats how I first wrote it, not considering that all ASCII are positive signed bytes. And this wouldnt even be a bottleneck since its outside the loop.) out[1] = b; out[2] = c; out[3] = d; } /** first 8 of "first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311" TODO verify these are the bits that last sentence describes, once at boot time using BigDecimal or double, else throw, and the same for the 4 sha256 squareRoot salts for the starting values of a b c d state in the hashFast func. TODO check dotproduct similarity, and audivolv movementScore, to in a basic way verify a near random spread of hashes, and other statistical tests, during development of forks of the hash algorithm (each with 16 bit name). TODO keep a static final var of the smallest sha256 hashcode known and what input hashes to that, among inputs up to 55 bytes (which are 1 sha256 cycle), just to keep track of the security of the few standard leaf types (including sha256 and sha3-256) which ufnode allocates core types (max 256 of them) for. */ private static final int[] sha256CuberootSalts = {0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5}; //static int next(int a, int b, int c, int d, int salt, int in){ //} public static String toString(int... a){ String s = ""; for(int i : a){ String j = Integer.toBinaryString(i); while(j.length() < 32) j = "0"+j; s += j; } return s; } public static String toStringHex(short s){ return Integer.toHexString(s|0xffff0000).substring(4,8); } public static String toStringHex(int... a){ String s = ""; for(int i : a){ String j = Integer.toHexString(i); while(j.length() < 8) j = "0"+j; s += j; } return s; } /** sha256 is type 'h'. sha3-256 is 'H' */ public static int[] wrapFirst7AndLast8BytesOfSha256(byte[] b){ return wrap15BytesWithType((byte)'h',b); } /** sha256 is type 'h'. sha3-256 is 'H' */ public static int[] wrapFirst7AndLast8BytesOfSha3_256(byte[] b){ return wrap15BytesWithType((byte)'H',b); } static int[] wrap15BytesWithType(byte type, byte[] b){ if(b.length != 15) throw new IllegalArgumentException("Wrong size expected 15 bytes: "+b.length); return new int[]{ ((type&0xff)<<24)|((b[1]&0xff)<<16)|((b[2]&0xff)<<8)|(b[3]&0xff), ((b[4]&0xff)<<24)|((b[5]&0xff)<<16)|((b[6]&0xff)<<8)|(b[7]&0xff), ((b[8]&0xff)<<24)|((b[9]&0xff)<<16)|((b[10]&0xff)<<8)|(b[11]&0xff), ((b[12]&0xff)<<24)|((b[13]&0xff)<<16)|((b[14]&0xff)<<8)|(b[15]&0xff) }; } public static int[] wrap(float f){ return wrap((byte)'f',Float.floatToIntBits(f)&0xffffffffL); } public static int[] wrap(float left, float right){ return wrap((byte)'F',(((long)Float.floatToIntBits(left))<<32)|(Float.floatToIntBits(right)&0xffffffffL)); } public static int[] wrap(double d){ return wrap((byte)'d',Double.doubleToLongBits(d)); } public static int[] wrap(long j){ return wrap((byte)'j',j); } public static int[] wrap(int i){ return wrap((byte)'i',i&0xffffffffL); } public static String toUri(int[] uf){ return toUri(hashAlgorithmName, uf); } /** A kind of URI (which URL and URN are subtypes of), the global name of the ufnode */ public static String toUri(short hashAlgorithmName, int[] uf){ return "uf_"+toStringHex(hashAlgorithmName)+"$"+toStringHex(uf); } /** type 'g' (tiny strinG). 0-8 utf8 bytes (using 2 0 bytes for codepoint 0, allowing 2*3 bytes or 4 bytes for high codepoints) FIXME do one of: -- put 4 bits of size (0-8) (reducing hash part from 56 to 52 bits), -- pad prefix or pad suffix with byte0s which practically arent used in strings, but problem will occur in bytestring 0-8 which will also be supported. -- Use 9 type bytes for utf8String and 9 type bytes for byteString (such as chars '0'-'9'). */ public static int[] wrap(String s){ if(s.length() > 8) throw new Error("Too long: "+s); byte[] utf8 = Text.stringToBytes(s); if(utf8.length > 8) throw new Error("Too long ("+utf8.length+" utf8 bytes): "+s); if(utf8.length < 8){ byte[] prefixPadded = new byte[8]; Arrays.fill(prefixPadded, (byte)'_'); System.arraycopy(utf8, 0, prefixPadded, 8-utf8.length, utf8.length); utf8 = prefixPadded; } return wrap((byte)'g',MathUtil.bytesToLong(utf8)); } public static Object unwrap(int[] uf128){ throw new Error("TODO"); } public static String unwrapString(int[] uf128){ throw new Error("TODO"); } public static double unwrapDouble(int[] uf128){ throw new Error("TODO"); } public static float unwrapFloat(int[] uf128){ throw new Error("TODO"); } public static float unwrapLeftFloat(int[] uf128){ throw new Error("TODO"); } public static float unwrapRightFloat(int[] uf128){ throw new Error("TODO"); } public static int[] wrap(byte... zeroTo8Bytes){ throw new Error("TODO"); } /** returns an uf128. 9 bytes are literal data, including 1 type byte. 7 bytes are a hash of that. Those 7 bytes will be a different kind of hash than the pair hasher of 256 to 128 bits. Its a hasher of long to long (ignoring type byte), and 1 byte of that output long is ignored. */ public static int[] wrap(byte type, long literal){ long hash = hashLiteral(literal); long prefix = ((type&0xffL)<<56)|(hash&0x00ffffffffffffffL); return new int[]{ (int)(prefix>>32), (int)prefix, (int)(literal>>32), (int)literal }; } public static long hashLiteral(long literal){ throw new Error("TODO"); } /** Each version of ufnode's hash algorithm is a 16 bit hashcode, whatever are the first 16 bits of hash(pair("pi is",(double)3.14159265358979323846)) hashes to, for example, in text write it as uf_d79b$70fcddd49b05528f5a58bc919ae55191. This allows many opensource forks of ufnode to work together like urls to different networks, given the cooperation of people to not use 2 forks of ufnode intentionally designed to collide on those 16 bits. The 120 bit hashcode (and 8 bit type) is either a secureHash already or will be pursued in such hash variations until find an efficient securehash of pair(128bits,128bits) to 128bits, efficient like 10 million hashes per second on an average computer. */ public static final short hashAlgorithmName = (short)0xd37c; //FIXME TODO (short)(hash(wrap("pi is"),wrap(java.lang.Math.PI))[0]>>>16); public static void main(String[] args){ System.nanoTime(); //dont count booting the clock in the stats int[] left = new int[4]; int[] right = new int[4]; System.out.println(toString(hash(left,right))); right[3] = 1; System.out.println(toString(hash(left,right))); right[3] = 2; System.out.println(toString(hash(left,right))); right[3] = 3; System.out.println(toString(hash(left,right))); for(int i=0; i<100; i++){ left[2] = i; int[] h = hash(left,right); //System.out.println("uf$"+toStringHex(h)+" "+toString(h)); System.out.println(toUri(h)+" "+toString(h)); } //speed test int[] in256 = new int[8]; int[] out = new int[4]; long start = System.nanoTime(); int cycles = 1000000; for(int i=0; i<cycles; i++){ for(int j=0; j<8; j++){ in256[j] = i+j; } hashFast(out, in256); } long end = System.nanoTime(); double seconds = (end-start)*1e-9; double hz = cycles/seconds; System.out.println("hashes per second: "+hz); start = System.nanoTime(); left = new int[4]; right = new int[4]; for(int i=0; i<cycles; i++){ for(int j=0; j<4; j++){ left[j] = i+j; right[j] = j-i; } hash(left, right); } end = System.nanoTime(); seconds = (end-start)*1e-9; hz = cycles/seconds; System.out.println("hashes per second when alloc arrays (strange, why is this faster?): "+hz); /* 2336eb873c9bc65bbe6faa5cb47a455e 00100011001101101110101110000111001111001001101111000110010110111011111001101111101010100101110010110100011110100100010101011110 2e8cb850f61294599f67b8e97a11d2db 00101110100011001011100001010000111101100001001010010100010110011001111101100111101110001110100101111010000100011101001011011011 90db73c064663d8da9b7b49c56275484 10010000110110110111001111000000011001000110011000111101100011011010100110110111101101001001110001010110001001110101010010000100 46f2eef332bea3d91a956d869964a3e0 01000110111100101110111011110011001100101011111010100011110110010001101010010101011011011000011010011001011001001010001111100000 7c0ed34b9a7dac5c493d182ed67c2fe9 01111100000011101101001101001011100110100111110110101100010111000100100100111101000110000010111011010110011111000010111111101001 hashes per second: 4159935.2501086392 */ } }
package com.takshine.wxcrm.domain; import com.takshine.wxcrm.model.PartnerModel; /** * 合作伙伴的domain * @author dengbo * */ public class Partner extends PartnerModel { private String viewtype; private String customername;//合作伙伴名称 private String phoneoffice;//电话号码 private String customerid;//客户ID private String desc;//描述 private String opptyid;//业务机会ID private String rowid; public String getViewtype() { return viewtype; } public void setViewtype(String viewtype) { this.viewtype = viewtype; } public String getPhoneoffice() { return phoneoffice; } public void setPhoneoffice(String phoneoffice) { this.phoneoffice = phoneoffice; } public String getCustomerid() { return customerid; } public void setCustomerid(String customerid) { this.customerid = customerid; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public String getCustomername() { return customername; } public void setCustomername(String customername) { this.customername = customername; } public String getOpptyid() { return opptyid; } public void setOpptyid(String opptyid) { this.opptyid = opptyid; } public String getRowid() { return rowid; } public void setRowid(String rowid) { this.rowid = rowid; } }
package com.myreceiver; import android.content.*; import android.widget.Toast; public class PowerReceiver2 extends BroadcastReceiver { //接收到廣播的訊息 public void onReceive(Context context, Intent intent) { Toast.makeText(context, "電源事件發生", Toast.LENGTH_LONG).show(); //開啟Activity, 以進行通知工作 Intent intent2 = new Intent(); //在新task中啟動Activity intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //設定所欲啟用的Activity intent2.setClass(context, PowerNotification.class); //啟動Activity context.startActivity(intent2); } }
package example.api.v1; import javax.validation.constraints.NotBlank; /** * @author sdelamo * @since 1.0 */ public class HealthStatus { private String status; public HealthStatus(String status) { this.status = status; } protected HealthStatus() { } @NotBlank public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
package com.example.retail.repository.vegetables; import com.example.retail.models.vegetables.Vegetables; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Optional; @Repository public interface VegetablesRepository extends JpaRepository<Vegetables, Long> { @Transactional @Modifying @Query(value = "UPDATE Vegetables v set v.vegetableQuantity= v.vegetableQuantity+ :vegetableQuantity WHERE v.vegetableTableId= :tableId") public Integer updateVegetableQty(@Param("tableId") Long tableId, @Param("vegetableQuantity") Float vegetableQuantity); @Transactional @Modifying @Query(value = "UPDATE Vegetables v set v.vegetableQuantity= v.vegetableQuantity+ :vegetableQuantity, v.vegetableSubId= :subId, v.vegetableSellingPrice= :newSellingPrice WHERE v.vegetableTableId= :tableId") public Integer updateVegetableAsPerInventory(@Param("tableId") Long tableId, @Param("vegetableQuantity") Float vegetableQuantity, @Param("subId") String subId, @Param("newSellingPrice") Float newSellingPrice); @Query(value = "SELECT * FROM vegetables WHERE vegetable_subid = :vegSubId", nativeQuery = true) public Optional<Vegetables> findBySubId(@Param("vegSubId") String vegSubId); @Query(value = "SELECT * FROM vegetables WHERE vegetable_available=true", nativeQuery = true) public List<Vegetables> findAllAvailableVegetables(); @Query(value = "SELECT * FROM vegetables WHERE vegetable_available=false", nativeQuery = true) public List<Vegetables> findAllUnavailableVegetables(); @Query(value = "SELECT * FROM vegetables WHERE item_classification= :itemClassification", nativeQuery = true) public List<Vegetables> findVegetablesByItemCategory(@Param("itemClassification") String itemClassification); }
import java.sql.*; public class ex_8_1s { static String driverClassName = "org.apache.derby.jdbc.ClientDriver" ; static String url = "jdbc:derby://localhost:1527/dblabs" ; static Connection dbConnection = null; static String username = "euclid"; static String passwd = "tbd2017"; static Statement statement = null; public static void main (String[] argv) throws Exception { Class.forName (driverClassName); dbConnection = DriverManager.getConnection (url, username, passwd); statement = dbConnection.createStatement(); statement.executeUpdate("CREATE TABLE SPONSOR("+ "code int not null primary key,"+ "name varchar(10),"+ "about varchar(10))"); statement.executeUpdate("CREATE TABLE SPONSORSHIP("+ "sponsorcode int not null references sponsor(code),"+ "acode int not null, "+ "primary key(sponsorcode,acode))"); statement.close(); dbConnection.close(); } }
package api.longpoll.bots.model.events.messages; import api.longpoll.bots.adapters.deserializers.PayloadDeserializer; import api.longpoll.bots.model.events.EventObject; import com.google.gson.JsonElement; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; /** * Action with message. Used to work with Callback buttons. */ public class MessageEvent implements EventObject { /** * User ID. */ @SerializedName("user_id") private Integer userId; /** * Dialog ID. */ @SerializedName("peer_id") private Integer peerId; /** * Random string. */ @SerializedName("event_id") private String eventId; /** * Additional info. */ @SerializedName("payload") @JsonAdapter(PayloadDeserializer.class) private JsonElement payload; /** * Message ID. */ @SerializedName("conversation_message_id") private String conversationMessageId; public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public Integer getPeerId() { return peerId; } public void setPeerId(Integer peerId) { this.peerId = peerId; } public String getEventId() { return eventId; } public void setEventId(String eventId) { this.eventId = eventId; } public JsonElement getPayload() { return payload; } public void setPayload(JsonElement payload) { this.payload = payload; } public String getConversationMessageId() { return conversationMessageId; } public void setConversationMessageId(String conversationMessageId) { this.conversationMessageId = conversationMessageId; } @Override public String toString() { return "MessageEvent{" + "userId=" + userId + ", peerId=" + peerId + ", eventId='" + eventId + '\'' + ", payload='" + payload + '\'' + ", conversationMessageId='" + conversationMessageId + '\'' + '}'; } }
package LeetCode.ArraysAndStrings; import java.util.ArrayList; import java.util.List; public class KidsWithCandies { public List<Boolean> kidsWithCandies(int[] candies, int extracandies){ int max = Integer.MIN_VALUE; List<Boolean> res = new ArrayList<>(); for(int i : candies) max = Math.max(max, i); for(int i : candies) { if(i+extracandies >= max) res.add(true); else res.add(false); } return res; } public static void main(String[] args){ int[] candies = {2,3,5,1,3}; int extracandies = 3; KidsWithCandies k = new KidsWithCandies(); List<Boolean> res = k.kidsWithCandies(candies, extracandies); for(Boolean b : res){ System.out.print(b); System.out.print('\t'); } } }
package graph; public class GraphUtil { public static int degree(Graph g, int v) { int degree = 0; for(int w : g.adj(v)) degree++; return degree; } public static int maxDegree(Graph g) { int max = 0; int degree = 0; for(int i =0; i < g.V(); i++) { degree = degree(g, i); if(degree > max) max = degree; } return max; } public static double averageDegree(Graph g) { return 2.0 * g.E() / g.V(); } public static int numberOfSelfLoops(Graph g) { int selfLoops = 0; for(int i =0; i < g.V(); i++) { for(int w : g.adj(i)) { if(i == w) selfLoops ++; } } return selfLoops; } }
package org.alienideology.jcord.event.guild.role.update; import org.alienideology.jcord.event.guild.role.GuildRoleUpdateEvent; import org.alienideology.jcord.internal.object.IdentityImpl; import org.alienideology.jcord.internal.object.guild.Guild; import org.alienideology.jcord.internal.object.guild.Role; /** * @author AlienIdeology */ public class GuildRolePositionUpdateEvent extends GuildRoleUpdateEvent { private int oldPosition; public GuildRolePositionUpdateEvent(IdentityImpl identity, Guild guild, int sequence, Role role, int oldPosition) { super(identity, guild, sequence, role); this.oldPosition = oldPosition; } public int getNewPosition() { return role.getPosition(); } public int getOldPosition() { return oldPosition; } public boolean movedUp() { return getNewPosition() < getOldPosition(); } }
package com.tencent.mm.plugin.appbrand.jsapi.bluetooth.ble.sdk.scan; import com.tencent.mm.plugin.appbrand.jsapi.bluetooth.ble.sdk.c.d; import com.tencent.mm.plugin.appbrand.jsapi.bluetooth.ble.sdk.d.a; class a$2 extends e { final /* synthetic */ a fMV; public a$2(a aVar) { this.fMV = aVar; } public final void a(int i, ScanResultCompat scanResultCompat) { int i2 = 0; if (scanResultCompat.getDevice() == null) { a.e("MicroMsg.Ble.BleScanWorker", "[onScanResult]result is null, err", new Object[0]); } else if (!this.fMV.fMR.get()) { a.e("MicroMsg.Ble.BleScanWorker", "[onScanResult]not init, err", new Object[0]); } else if (this.fMV.fMP == null) { a.w("MicroMsg.Ble.BleScanWorker", "[onScanResult]may be close, err", new Object[0]); } else { a.d("MicroMsg.Ble.BleScanWorker", "callbackType:%d, result:%s", new Object[]{Integer.valueOf(i), scanResultCompat}); String address = scanResultCompat.getDevice().getAddress(); if (!this.fMV.fMP.containsKey(address) || com.tencent.mm.plugin.appbrand.jsapi.bluetooth.ble.sdk.a.fLt.fLu) { i2 = 1; } d dVar = new d(scanResultCompat); if (i2 != 0) { if (com.tencent.mm.plugin.appbrand.jsapi.bluetooth.ble.sdk.a.fLt.djl > 0) { if (this.fMV.fMS != null) { this.fMV.fMS.add(dVar); } } else if (this.fMV.fMU != null) { this.fMV.fMU.a(dVar); } } this.fMV.fMP.put(address, dVar); } } public final void onScanFailed(int i) { a.e("MicroMsg.Ble.BleScanWorker", "[onScanResult]onScanFailed, errorCode:%d", new Object[]{Integer.valueOf(i)}); } }
import java.util.*; public class Solution { public static void main(String [] args) { // Declare variables Scanner scan = new Scanner(System.in); int t = 0; ArrayList<AbstractMap.SimpleEntry<Integer, Integer>> pairs = new ArrayList<AbstractMap.SimpleEntry<Integer, Integer>>(); // The previous variable pairs is an arrayList of pairs to store the pairs of n, k from System.in // 1 Scan T t = scan.nextInt(); // 2 Scan N, K pair T times for(int i = 0; i < t; i++) { int n = scan.nextInt(); int k = scan.nextInt(); // Create a pair with the 2 values (n, k) AbstractMap.SimpleEntry<Integer, Integer> tempPair = new AbstractMap.SimpleEntry<Integer, Integer>(n, k); // Push the pair into the ArrayList pairs pairs.add(tempPair); } // 3 Make S (arrayList {1, 2, 3, 4, .. ,N} // For every pair, make an arrayList S, for (AbstractMap.SimpleEntry<Integer, Integer> pair: pairs) { ArrayList<Integer>results = new ArrayList<Integer>(); //System.out.println(pair.toString()); ArrayList<Integer> s = new ArrayList<Integer>(); int n = pair.getKey(); int k = pair.getValue(); for(int i = 1; i <= n; i++) { // making s with this loop s.add(i); } // 4 Double loop logic for(int i = 0; i < n; i++) { for(int j = i + 1; j <= n; j++) { if((i & j) < k) { results.add(i & j); } } } // 5 Print results.max System.out.println(Collections.max(results)); } } }
package ua.project.protester.repository.result; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import ua.project.protester.exception.executable.action.ActionNotFoundException; import ua.project.protester.exception.executable.action.IllegalActionLogicImplementation; import ua.project.protester.exception.result.ResultSubtypeNotFoundException; import ua.project.protester.model.executable.AbstractAction; import ua.project.protester.model.executable.result.ActionResult; import ua.project.protester.model.executable.result.ActionResultDto; import ua.project.protester.model.executable.result.subtype.ActionResultRest; import ua.project.protester.model.executable.result.subtype.ActionResultRestDto; import ua.project.protester.model.executable.result.subtype.ActionResultSql; import ua.project.protester.model.executable.result.subtype.ActionResultSqlDto; import ua.project.protester.model.executable.result.subtype.ActionResultTechnicalDto; import ua.project.protester.model.executable.result.subtype.ActionResultTechnicalExtra; import ua.project.protester.model.executable.result.subtype.ActionResultUi; import ua.project.protester.model.executable.result.subtype.ActionResultUiDto; import ua.project.protester.model.executable.result.subtype.SqlColumn; import ua.project.protester.model.executable.result.subtype.SqlColumnDto; import ua.project.protester.repository.ActionRepository; import ua.project.protester.repository.StatusRepository; import ua.project.protester.utils.PropertyExtractor; import java.util.*; import java.util.stream.Collectors; @PropertySource("classpath:queries/action-result.properties") @Repository @RequiredArgsConstructor @Slf4j @SuppressWarnings("PMD.UnusedPrivateMethod") public class ActionResultRepository { private final NamedParameterJdbcTemplate namedParameterJdbcTemplate; private final Environment env; private final StatusRepository statusRepository; private final ActionRepository actionRepository; @Transactional(propagation = Propagation.MANDATORY) public ActionResultDto save(Integer testCaseResultId, ActionResultDto actionResult) throws IllegalActionLogicImplementation { switch (actionResult.getAction().getType()) { case REST: if (actionResult instanceof ActionResultRestDto) { return saveRest(testCaseResultId, (ActionResultRestDto) actionResult); } break; case TECHNICAL: if (actionResult instanceof ActionResultTechnicalDto) { return saveTechnical(testCaseResultId, (ActionResultTechnicalDto) actionResult); } break; case UI: if (actionResult instanceof ActionResultUiDto) { return saveUi(testCaseResultId, (ActionResultUiDto) actionResult); } break; case SQL: if (actionResult instanceof ActionResultSqlDto) { return saveSql(testCaseResultId, (ActionResultSqlDto) actionResult); } break; default: throw new IllegalActionLogicImplementation( "Action '" + actionResult.getAction().getName() + "' has illegal type: " + actionResult.getAction().getType()); } throw new IllegalActionLogicImplementation( "Action '" + actionResult.getAction().getName() + "' has type " + actionResult.getAction().getType() + ", but actual result type is not instance of appropriate result subtype"); } @Transactional(propagation = Propagation.MANDATORY) public List<ActionResultDto> findByTestCaseResultId(Integer id) { return namedParameterJdbcTemplate.query( PropertyExtractor.extract(env, "findAllActionResultsByTestCaseResultId"), new MapSqlParameterSource().addValue("id", id), new BeanPropertyRowMapper<>(ActionResult.class)) .stream() .map(this::getBaseDto) .map(this::loadSubtypeData) .collect(Collectors.toList()); } private void saveBase(Integer testCaseResultId, ActionResultDto actionResultDto) { KeyHolder keyHolder = new GeneratedKeyHolder(); namedParameterJdbcTemplate.update( PropertyExtractor.extract(env, "saveBaseActionResult"), new BeanPropertySqlParameterSource(getBaseModel(testCaseResultId, actionResultDto)), keyHolder, new String[]{"action_result_id"}); actionResultDto.setId((Integer) keyHolder.getKey()); saveInputParameters(actionResultDto); } private void saveInputParameters(ActionResultDto actionResultDto) { actionResultDto.getInputParameters() .forEach((key, value) -> namedParameterJdbcTemplate.update( PropertyExtractor.extract(env, "saveInputParameter"), new MapSqlParameterSource() .addValue("actionResultId", actionResultDto.getId()) .addValue("key", key) .addValue("value", value))); } private ActionResultRestDto saveRest(Integer testCaseResultId, ActionResultRestDto actionResultRestDto) { saveBase(testCaseResultId, actionResultRestDto); namedParameterJdbcTemplate.update( PropertyExtractor.extract(env, "saveActionResultRest"), new BeanPropertySqlParameterSource(getRestModel(actionResultRestDto))); return actionResultRestDto; } private ActionResultTechnicalDto saveTechnical(Integer testCaseResultId, ActionResultTechnicalDto actionResultTechnicalDto) { saveBase(testCaseResultId, actionResultTechnicalDto); getTechnicalModel(actionResultTechnicalDto) .forEach(actionResultTechnicalExtra -> namedParameterJdbcTemplate.update( PropertyExtractor.extract(env, "saveActionResultTechnicalExtra"), new BeanPropertySqlParameterSource(actionResultTechnicalExtra))); return actionResultTechnicalDto; } private ActionResultUiDto saveUi(Integer testCaseResultId, ActionResultUiDto actionResultUiDto) { saveBase(testCaseResultId, actionResultUiDto); namedParameterJdbcTemplate.update( PropertyExtractor.extract(env, "saveActionResultUi"), new BeanPropertySqlParameterSource(getUiModel(actionResultUiDto))); return actionResultUiDto; } private ActionResultSqlDto saveSql(Integer testCaseResultId, ActionResultSqlDto actionResultSqlDto) { saveBase(testCaseResultId, actionResultSqlDto); KeyHolder keyHolder = new GeneratedKeyHolder(); namedParameterJdbcTemplate.update( PropertyExtractor.extract(env, "saveActionResultSql"), new BeanPropertySqlParameterSource(getSqlModel(actionResultSqlDto)), keyHolder, new String[]{"action_result_sql_id"}); Integer actionResultSqlId = (Integer) keyHolder.getKey(); if (actionResultSqlDto.getColumns() != null) { actionResultSqlDto.getColumns() .forEach(sqlColumnDto -> saveSqlColumn(actionResultSqlId, sqlColumnDto)); } return actionResultSqlDto; } private void saveSqlColumn(Integer actionResultSqlId, SqlColumnDto sqlColumnDto) { KeyHolder keyHolder = new GeneratedKeyHolder(); namedParameterJdbcTemplate.update( PropertyExtractor.extract(env, "saveSqlColumn"), new BeanPropertySqlParameterSource(getSqlColumn(actionResultSqlId, sqlColumnDto)), keyHolder, new String[]{"sql_column_id"}); sqlColumnDto.setId((Integer) keyHolder.getKey()); saveSqlColumnCells(sqlColumnDto); } private void saveSqlColumnCells(SqlColumnDto sqlColumnDto) { ListIterator<String> iterator = sqlColumnDto.getRows().listIterator(); int order = 0; while (iterator.hasNext()) { String value = iterator.next(); namedParameterJdbcTemplate.update( PropertyExtractor.extract(env, "saveSqlColumnCell"), new MapSqlParameterSource() .addValue("sqlColumnId", sqlColumnDto.getId()) .addValue("orderNumber", order++) .addValue("value", value)); } } public ActionResultDto loadSubtypeData(ActionResultDto resultDto) { if (resultDto.getAction() == null) { return resultDto; } try { switch (resultDto.getAction().getType()) { case REST: return findRest(resultDto); case TECHNICAL: return findTechnical(resultDto); case UI: return findUi(resultDto); case SQL: return findSql(resultDto); default: log.warn("Action " + resultDto.getAction().getName() + " has incorrect type: " + resultDto.getAction().getType()); return resultDto; } } catch (ResultSubtypeNotFoundException e) { log.warn(e.getMessage(), e); return resultDto; } } private Map<String, String> findInputParametersByActionResultId(Integer id) { Map<String, String> parameters = new HashMap<>(); namedParameterJdbcTemplate.query( PropertyExtractor.extract(env, "findAllInputParametersByActionResultId"), new MapSqlParameterSource().addValue("id", id), (rs, rowNum) -> parameters.put( rs.getString("key"), rs.getString("value"))); return parameters; } private ActionResultRestDto findRest(ActionResultDto baseDto) throws ResultSubtypeNotFoundException { try { ActionResultRest restModel = namedParameterJdbcTemplate.queryForObject( PropertyExtractor.extract(env, "findRestByActionResultId"), new MapSqlParameterSource().addValue("id", baseDto.getId()), new BeanPropertyRowMapper<>(ActionResultRest.class)); if (restModel == null) { throw new ResultSubtypeNotFoundException(baseDto.getId()); } return getRestDto(baseDto, restModel); } catch (DataAccessException e) { throw new ResultSubtypeNotFoundException(baseDto.getId(), e); } } private ActionResultTechnicalDto findTechnical(ActionResultDto baseDto) throws ResultSubtypeNotFoundException { try { List<ActionResultTechnicalExtra> technicalModel = namedParameterJdbcTemplate.query( PropertyExtractor.extract(env, "findTechnicalExtraByActionResultId"), new MapSqlParameterSource().addValue("id", baseDto.getId()), new BeanPropertyRowMapper<>(ActionResultTechnicalExtra.class)); return getTechnicalDto(baseDto, technicalModel); } catch (DataAccessException e) { throw new ResultSubtypeNotFoundException(baseDto.getId(), e); } } private ActionResultUiDto findUi(ActionResultDto baseDto) throws ResultSubtypeNotFoundException { try { ActionResultUi uiModel = namedParameterJdbcTemplate.queryForObject( PropertyExtractor.extract(env, "findUiByActionResultId"), new MapSqlParameterSource().addValue("id", baseDto.getId()), new BeanPropertyRowMapper<>(ActionResultUi.class)); if (uiModel == null) { throw new ResultSubtypeNotFoundException(baseDto.getId()); } return getUiDto(baseDto, uiModel); } catch (DataAccessException e) { throw new ResultSubtypeNotFoundException(baseDto.getId(), e); } } private ActionResultSqlDto findSql(ActionResultDto baseDto) throws ResultSubtypeNotFoundException { try { ActionResultSql sqlModel = namedParameterJdbcTemplate.queryForObject( PropertyExtractor.extract(env, "findSqlByActionResultId"), new MapSqlParameterSource().addValue("id", baseDto.getId()), new BeanPropertyRowMapper<>(ActionResultSql.class)); if (sqlModel == null) { throw new ResultSubtypeNotFoundException(baseDto.getId()); } return getSqlDto(baseDto, sqlModel); } catch (DataAccessException e) { throw new ResultSubtypeNotFoundException(baseDto.getId(), e); } } private List<SqlColumnDto> findSqlColumns(Integer actionResultSqlId) { return namedParameterJdbcTemplate.query( PropertyExtractor.extract(env, "findSqlColumnsByActionResultSqlId"), new MapSqlParameterSource().addValue("id", actionResultSqlId), new BeanPropertyRowMapper<>(SqlColumn.class)) .stream() .map(this::getSqlColumnDto) .collect(Collectors.toList()); } private List<String> findSqlColumnCells(Integer sqlColumnId) { return namedParameterJdbcTemplate.queryForList( PropertyExtractor.extract(env, "findSqlColumnCellsValueBySqlColumnId"), new MapSqlParameterSource().addValue("id", sqlColumnId), String.class); } private ActionResult getBaseModel(Integer testCaseResultId, ActionResultDto dto) { return new ActionResult( null, testCaseResultId, dto.getAction().getId(), dto.getStartDate(), dto.getEndDate(), statusRepository.getIdByLabel(dto.getStatus()), dto.getMessage()); } private ActionResultRest getRestModel(ActionResultRestDto dto) { return new ActionResultRest( dto.getId(), dto.getRequest(), dto.getResponse(), dto.getStatusCode()); } private List<ActionResultTechnicalExtra> getTechnicalModel(ActionResultTechnicalDto dto) { if (dto.getExtra() == null) { return Collections.emptyList(); } return dto.getExtra().entrySet() .stream() .map(entry -> new ActionResultTechnicalExtra( dto.getId(), entry.getKey(), entry.getValue())) .collect(Collectors.toList()); } private ActionResultUi getUiModel(ActionResultUiDto dto) { return new ActionResultUi( dto.getId(), dto.getPath()); } private ActionResultSql getSqlModel(ActionResultSqlDto dto) { return new ActionResultSql( dto.getId(), dto.getConnectionUrl(), dto.getUsername(), dto.getQuery()); } private SqlColumn getSqlColumn(Integer actionResultSqlId, SqlColumnDto dto) { return new SqlColumn( null, actionResultSqlId, dto.getName()); } private ActionResultDto getBaseDto(ActionResult result) { AbstractAction action; try { action = actionRepository.findActionById(result.getActionId()); } catch (ActionNotFoundException e) { log.warn(e.getMessage()); action = null; } return new ActionResultDto( result.getId(), action, result.getStartDate(), result.getEndDate(), statusRepository.getLabelById(result.getStatusId()), findInputParametersByActionResultId(result.getId()), result.getMessage()); } private ActionResultRestDto getRestDto(ActionResultDto baseDto, ActionResultRest restModel) { return new ActionResultRestDto( baseDto, restModel.getRequest(), restModel.getResponse(), restModel.getStatusCode()); } private ActionResultUiDto getUiDto(ActionResultDto baseDto, ActionResultUi uiModel) { return new ActionResultUiDto( baseDto, uiModel.getPath()); } private ActionResultTechnicalDto getTechnicalDto(ActionResultDto baseDto, List<ActionResultTechnicalExtra> technicalModel) { Map<String, String> extra = new HashMap<>(); technicalModel.forEach(entry -> extra.put(entry.getKey(), entry.getValue())); return new ActionResultTechnicalDto( baseDto, extra); } private ActionResultSqlDto getSqlDto(ActionResultDto baseDto, ActionResultSql sqlModel) { return new ActionResultSqlDto( baseDto, sqlModel.getConnectionUrl(), sqlModel.getUsername(), sqlModel.getQuery(), findSqlColumns(sqlModel.getId())); } private SqlColumnDto getSqlColumnDto(SqlColumn sqlColumnModel) { return new SqlColumnDto( sqlColumnModel.getName(), findSqlColumnCells(sqlColumnModel.getId())); } }
package sessionbean; import entidade.Produto; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; /** * * @author wender */ @Stateless public class ProdutoSBean { @PersistenceContext(unitName = "JavaWebPU") private EntityManager em; public void salvar(Produto produto) throws Exception { try { em.merge(produto); } catch (Exception ex) { throw new Exception("Ouve um erro ao salvar o Produto."); } } public void excluir(Produto produto) throws Exception { try { em.remove(em.find(Produto.class, produto.getId())); } catch (Exception ex) { throw new Exception("Ouve um erro ao apagar o Produto."); } } public Produto pesquisar(Long id) throws Exception { try { return em.find(Produto.class, id); } catch (Exception ex) { throw new Exception("Ouve um erro ao pesquisar o Produto."); } } public List<Produto> pesquisar(String valorPesquisa) throws Exception { try { List<Produto> listaProduto; Query consulta = em.createNamedQuery("Produto.findByNome"); consulta.setParameter("nome", valorPesquisa + "%"); listaProduto = consulta.getResultList(); return listaProduto; } catch (Exception ex) { throw new Exception("Ouve um erro ao pesquisar o Produto."); } } }
package com.zs.util; import javax.servlet.http.HttpServletRequest; /** * @Created by IDEA * @author:LiuYiBo(小博) * @Date:2018/7/29 * @Time:20:24 */ public class CodeUtil { public static boolean checkVerifyCode(HttpServletRequest request) { String verifyCodeExpected = (String)request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY); String verifyCodeActual = HttpServletRequestUtil.getString(request,"verifyCodeActual"); System.out.println("request直接解析---------"+request.getParameter("verifyCodeActual")); System.out.println("--------验证码1"+verifyCodeExpected+"----------"); System.out.println("--------验证码2"+verifyCodeActual+"----------"); if(verifyCodeActual == null || !verifyCodeActual.equals(verifyCodeExpected)) { return false; } return true; } }
class Solution { public String simplifyPath(String path) { String[] components = path.split("/"); Stack<String> stack = new Stack<>(); for (String comp : components) { if (comp.equals(".") || comp.length() == 0) continue; else if (comp.equals("..")) { if (!stack.isEmpty()) { stack.pop(); } } else { stack.push(comp); } } StringBuilder res = new StringBuilder(); for (String folder : stack) { res.append("/"); res.append(folder); } return res.length() > 0 ? res.toString() : "/"; } }
import java.util.*; public class MinimumHeightTrees { //https://leetcode.com/problems/minimum-height-trees/submissions/ public static List<Integer> findMinHeightTrees(int n, int[][] edges) { if (edges.length == 0) { List<Integer> list = new ArrayList<>(); list.add(0); return list; } Map<Integer, List<Node>> degreeMap = new HashMap<>(); Set<Integer> currentNodes = new HashSet<>(); for (int[] edge : edges) { degreeMap.putIfAbsent(edge[0], new ArrayList<>()); degreeMap.get(edge[0]).add(new Node(edge[1])); degreeMap.putIfAbsent(edge[1], new ArrayList<>()); degreeMap.get(edge[1]).add(new Node(edge[0])); currentNodes.add(edge[0]); currentNodes.add(edge[1]); } Set<Integer> visited = new HashSet<>(); Queue<Integer> queue = new ArrayDeque<>(); Queue<Integer> tempQueue = new ArrayDeque<>(); if (currentNodes.size() > 2) for (Map.Entry<Integer, List<Node>> entry : degreeMap.entrySet()) { if (entry.getValue().size() == 1) { tempQueue.add(entry.getKey()); visited.add(entry.getKey()); //currentNodes.remove(entry.getKey()); } } while(currentNodes.size()>3) { queue = tempQueue; tempQueue = new ArrayDeque<>(); while (!queue.isEmpty()) { //TODO here //if(queue.isEmpty()) queue = tempQueue; int node = queue.poll(); currentNodes.remove(node); List<Node> adjacentNodes = degreeMap.get(node); for (Node an : new ArrayList<>(adjacentNodes)) { degreeMap.get(an.id).remove(new Node(node)); if (!visited.contains(an.id) && degreeMap.get(an.id).size() == 1) { tempQueue.add(an.id); visited.add(an.id); } } } } if (currentNodes.size() == 3) { currentNodes.remove(tempQueue.poll()); currentNodes.remove(tempQueue.poll()); } return new ArrayList<>(currentNodes); } static class Node { int id; public Node(int id) { this.id = id; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Node node = (Node) o; return id == node.id; } @Override public int hashCode() { return Objects.hash(id); } } public static void main(String[] args) { findMinHeightTrees(6, new int[][]{{0,1},{0,2}}).forEach(System.out::println); } }
package cn.canlnac.onlinecourse.domain; /** * 回复评论. */ public class Reply { private int id; private long date; private SimpleUser toUser; private SimpleUser author; private String content; public int getId() { return id; } public void setId(int id) { this.id = id; } public long getDate() { return date; } public void setDate(long date) { this.date = date; } public SimpleUser getToUser() { return toUser; } public void setToUser(SimpleUser toUser) { this.toUser = toUser; } public SimpleUser getAuthor() { return author; } public void setAuthor(SimpleUser author) { this.author = author; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
package com.tencent.mm.plugin.brandservice.ui.timeline; import android.content.ClipboardManager; import android.content.Intent; import android.view.MenuItem; import com.tencent.mm.ac.z; import com.tencent.mm.bg.d; import com.tencent.mm.kernel.g; import com.tencent.mm.model.s; import com.tencent.mm.model.u; import com.tencent.mm.plugin.brandservice.b; import com.tencent.mm.plugin.brandservice.ui.timeline.g.a; import com.tencent.mm.plugin.messenger.foundation.a.i; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.ab; import com.tencent.mm.storage.bd; import com.tencent.mm.storage.q; import com.tencent.mm.ui.base.n$d; class a$13 implements n$d { final /* synthetic */ a hqX; a$13(a aVar) { this.hqX = aVar; } public final void onMMMenuItemSelected(MenuItem menuItem, int i) { if (a.i(this.hqX) == null) { x.w("MicroMsg.BizTimeLineAdapter", "onMMMenuItemSelected mInfo == null"); return; } q i2 = a.i(this.hqX); a.a(this.hqX, bi.VE()); a aVar; Intent intent; bd dW; switch (menuItem.getItemId()) { case 1: ab Yg = ((i) g.l(i.class)).FR().Yg(i2.field_talker); if (Yg == null) { x.e("MicroMsg.BizTimeLineAdapter", "changed biz stick status failed, contact is null, talker = " + i2.field_talker); return; } else if (Yg.BG()) { h.mEJ.h(13307, new Object[]{Yg.field_username, Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3)}); s.u(i2.field_talker, true); com.tencent.mm.ui.base.h.bA(a.b(this.hqX), a.b(this.hqX).getString(b.h.biz_time_line_unplacedtop_tips)); a.h(this.hqX).a(a.i(this.hqX), false); return; } else { h.mEJ.h(13307, new Object[]{Yg.field_username, Integer.valueOf(1), Integer.valueOf(1), Integer.valueOf(3)}); s.t(i2.field_talker, true); com.tencent.mm.ui.base.h.bA(a.b(this.hqX), a.b(this.hqX).getString(b.h.biz_time_line_placedtop_tips)); a.h(this.hqX).a(a.i(this.hqX), true); return; } case 2: ab Yg2 = ((i) g.l(i.class)).FR().Yg(i2.field_talker); ((com.tencent.mm.plugin.brandservice.a.a) g.l(com.tencent.mm.plugin.brandservice.a.a.class)).b(z.MY().kA(i2.field_talker), a.b(this.hqX), Yg2); aVar = (a) a.h(this.hqX).hsb.get(Long.valueOf(a.i(this.hqX).field_msgId)); if (aVar != null) { aVar.cancel = 1; return; } return; case 3: intent = new Intent(); intent.putExtra("Contact_User", i2.field_talker); d.b(a.b(this.hqX), "profile", ".ui.ContactInfoUI", intent); aVar = (a) a.h(this.hqX).hsb.get(Long.valueOf(a.i(this.hqX).field_msgId)); if (aVar != null) { aVar.rjw = 1; return; } return; case 4: if (a.j(this.hqX)) { ((com.tencent.mm.plugin.brandservice.a.a) g.l(com.tencent.mm.plugin.brandservice.a.a.class)).a(a.k(this.hqX), a.b(this.hqX), i2.field_content, i2.field_talker, i2.field_msgId, i2.field_msgSvrId); return; } String a = com.tencent.mm.y.i.a(a.b(this.hqX), a.k(this.hqX), i2.field_content, i2.field_talker); if (!bi.oW(a)) { Intent intent2 = new Intent(); intent2.putExtra("Retr_Msg_content", a); intent2.putExtra("Retr_Msg_Type", 2); intent2.putExtra("Retr_Biz_Msg_Selected_Msg_Index", a.k(this.hqX)); intent2.putExtra("Retr_Msg_Id", i2.field_msgId); intent2.putExtra("Retr_MsgFromScene", 1); a = i2.field_talker; String ic = u.ic(i2.field_msgSvrId); intent2.putExtra("reportSessionId", ic); u.b v = u.Hx().v(ic, true); v.p("prePublishId", "msg_" + i2.field_msgSvrId); v.p("preUsername", a); v.p("preChatName", a); v.p("preMsgIndex", Integer.valueOf(a.k(this.hqX))); v.p("sendAppMsgScene", Integer.valueOf(1)); d.e(a.b(this.hqX), ".ui.transmit.MsgRetransmitUI", intent2); return; } return; case 5: bd dW2 = ((i) g.l(i.class)).bcY().dW(i2.field_msgId); if (dW2.field_msgId == 0) { x.w("MicroMsg.BizTimeLineAdapter", "favAppBrandMsg msg is null"); return; } else { ((com.tencent.mm.plugin.brandservice.a.a) g.l(com.tencent.mm.plugin.brandservice.a.a.class)).a(a.l(this.hqX), a.k(this.hqX), a.b(this.hqX), a.b(this.hqX), dW2); return; } case 6: dW = ((i) g.l(i.class)).bcY().dW(i2.field_msgId); if (dW.field_msgId == 0) { x.w("MicroMsg.BizTimeLineAdapter", "favAppBrandMsg msg is null"); return; } else { ((com.tencent.mm.plugin.brandservice.a.a) g.l(com.tencent.mm.plugin.brandservice.a.a.class)).a(dW, a.b(this.hqX)); return; } case 7: dW = ((i) g.l(i.class)).bcY().dW(i2.field_msgId); if (dW.field_msgId == 0) { x.w("MicroMsg.BizTimeLineAdapter", "favAppBrandMsg msg is null"); return; } else { ((com.tencent.mm.plugin.brandservice.a.a) g.l(com.tencent.mm.plugin.brandservice.a.a.class)).a(dW, a.b(this.hqX)); return; } case 8: intent = new Intent(); intent.putExtra("Retr_Msg_content", a.i(this.hqX).field_content); intent.putExtra("Retr_Msg_Type", 4); d.e(a.b(this.hqX), ".ui.transmit.MsgRetransmitUI", intent); return; case 9: try { ((ClipboardManager) a.b(this.hqX).getSystemService("clipboard")).setText(a.i(this.hqX).field_content); } catch (Exception e) { x.e("MicroMsg.BizTimeLineAdapter", "clip.setText error "); } com.tencent.mm.ui.base.h.bA(a.b(this.hqX), a.b(this.hqX).getString(b.h.app_copy_ok)); int i3 = com.tencent.mm.plugin.secinforeport.a.a.mOt; com.tencent.mm.plugin.secinforeport.a.a.f(1, a.i(this.hqX).field_msgSvrId, bi.WK(a.i(this.hqX).field_content)); return; default: return; } } }
package it.cinema.multisala; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.ArrayList; /** * Classe <code>Programmazione</code> contiene informazioni inerenti la * programmazione dei film nei cinema. * * @version 1.00 05 Gen 2018 * @author Matteo Borghese * */ public class Programmazione { /** Id della programmazione. */ private int idProgrammazione; /** Giorno di proiezione del film. */ private LocalDateTime giorno; /** Ora di proiezione del film. */ private LocalTime oraInizio; /** Ora fine proiezione del film. */ private LocalTime oraFine; /** Prenotazioni attive per lo spettacolo. */ private ArrayList<Prenotazione> prenotazioni; /** Sala di proiezione. */ private Sala salaProgrammazione; /** Film proiettato. */ private Film film; /** * Costruttore di programmazione. * * @param idProgrammazione id della programmazione * @param giorno giorno di proiezione del film * @param oraInizio ora di proiezione del film * @param oraFine ora fine proiezione del film * @param salaProgrammazione prenotazioni attive per lo spettacolo * @param film film proiettato */ public Programmazione(int idProgrammazione, LocalDateTime giorno, LocalTime oraInizio, LocalTime oraFine, Sala salaProgrammazione, Film film) { super(); this.idProgrammazione = idProgrammazione; this.giorno = giorno; this.oraInizio = oraInizio; this.oraFine = oraFine; this.prenotazioni = new ArrayList<Prenotazione>(); this.salaProgrammazione = salaProgrammazione; this.film = film; } /** * Get id della programmazione. * * @return id della programmazione */ public int getIdProgrammazione() { return idProgrammazione; } /** * Set id della programmazione. * * @param idProgrammazione id della programmazione */ public void setIdProgrammazione(int idProgrammazione) { this.idProgrammazione = idProgrammazione; } /** * Get giorno di proiezione del film. * * @return giorno di proiezione del film */ public LocalDateTime getGiorno() { return giorno; } /** * Set giorno di proiezione del film. * * @param giorno giorno di proiezione del film */ public void setGiorno(LocalDateTime giorno) { this.giorno = giorno; } /** * ora di proiezione del film. * * @return ora di proiezione del film */ public LocalTime getOraInizio() { return oraInizio; } /** * Set ora di proiezione del film. * * @param oraInizio ora di proiezione del film */ public void setOraInizio(LocalTime oraInizio) { this.oraInizio = oraInizio; } /** * Get ora fine proiezione del film. * * @return ora fine proiezione del film */ public LocalTime getOraFine() { return oraFine; } /** * Set ora fine proiezione del film. * * @param oraFine ora fine proiezione del film */ public void setOraFine(LocalTime oraFine) { this.oraFine = oraFine; } /** * Get prenotazioni attive per lo spettacolo. * * @return prenotazioni attive per lo spettacolo */ public ArrayList<Prenotazione> getPrenotazioni() { return prenotazioni; } /** * Set prenotazioni attive per lo spettacolo. * * @param prenotazioni prenotazioni attive per lo spettacolo */ public void setPrenotazioni(ArrayList<Prenotazione> prenotazioni) { this.prenotazioni = prenotazioni; } /** * Get sala di proiezione. * * @return sala di proiezione */ public Sala getSalaProgrammazione() { return salaProgrammazione; } /** * Set sala di proiezione. * * @param salaProgrammazione sala di proiezione. */ public void setSalaProgrammazione(Sala salaProgrammazione) { this.salaProgrammazione = salaProgrammazione; } /** * Get film proiettato. * * @return film proiettato */ public Film getFilm() { return film; } /** * Set film proiettato. * * @param film film proiettato */ public void setFilm(Film film) { this.film = film; } /** * Aggiunge una prenotazione alla programazione del film. * * @param p prenotazione da aggiungere * @return true posti liberi sufficienti e prenotazione aggiunta, false altrimenti */ public boolean aggiungiPrenotazione(Prenotazione p) { if(salaProgrammazione.prenotaPosti(p.getFilaPosti(), p.getColonnaPosti())) { prenotazioni.add(p); return true; }else{ System.err.println("Impossibile prenotare."); return false; } } /** * Cancella una prenotazione (sequence diagram UC8). * * @param idPrenotazione id della prenotazione da cancellare * @return true prenotazione cancellata, false altrimenti */ public boolean cancellaPrenotazione(int idPrenotazione){ for(Prenotazione p : prenotazioni) { if(p.getIdPrenotazione() == idPrenotazione) { //posso eliminare la prenotazione se la cancellazione avviene con almeno //un'ora di anticipo dall'inizio della proiezione if(verificaOraCancellazione()) { salaProgrammazione.liberaPosti(p.getFilaPosti(), p.getColonnaPosti()); int index = prenotazioni.indexOf(p); this.prenotazioni.remove(index); return true; } } } return false; } /** * Verifica se è possibile eliminare la prenotazione (possibili fino ad * un ora prima dell inizio della proiezione del film). * * @return true prenotazione eliminabile, false altrimenti */ public boolean verificaOraCancellazione() { LocalTime oraAttuale = LocalTime.now(); LocalDateTime giornoAttuale = LocalDateTime.now(); int ore = oraInizio.getHour() - oraAttuale.getHour(); if(giornoAttuale.toLocalDate().equals(giorno.toLocalDate())) { if(ore > 0) { return true; }else{ System.err.println("superata l'ora a disposizione per la " + " cancellazione della prenotazione"); return false; } //giorno della proiezione antecedente alla data della cancellazione // della prenotazione, posso sempre eliminarla. }else if(giornoAttuale.compareTo(giorno) < 0) { return true; }else{ //spettacolo già avvenuto. System.err.println("impossibile rimuovere prenotazione"); return false; } } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object other){ if (other == null) return false; if (other == this) return true; if (!(other instanceof Programmazione))return false; Programmazione p= (Programmazione)other; //id univoco return this.getIdProgrammazione() == p.getIdProgrammazione(); } }
package com.workshops.database; import com.workshops.database.WS_PURCHASE_TRANSACTION; import java.io.Serializable; import java.util.List; public class WS_SHOP implements Serializable { /** * */ private static final long serialVersionUID = 1L; private int ITEM_ID; private String ITEM_NAME; private Double ITEM_PRICE; private int NO_POKEBALL; private int POKEBALL_QTY; private List<WS_PURCHASE_TRANSACTION> list_WS_PURCHASE_TRANSACTION; public List<WS_PURCHASE_TRANSACTION> getList_WS_PURCHASE_TRANSACTION() { return list_WS_PURCHASE_TRANSACTION; } public void setList_WS_PURCHASE_TRANSACTION(List<WS_PURCHASE_TRANSACTION> list_WS_PURCHASE_TRANSACTION) { this.list_WS_PURCHASE_TRANSACTION = list_WS_PURCHASE_TRANSACTION; } public int getITEM_ID() { return ITEM_ID; } public void setITEM_ID(int iTEM_ID) { ITEM_ID = iTEM_ID; } public String getITEM_NAME() { return ITEM_NAME; } public void setITEM_NAME(String iTEM_NAME) { ITEM_NAME = iTEM_NAME; } public Double getITEM_PRICE() { return ITEM_PRICE; } public void setITEM_PRICE(Double iTEM_PRICE) { ITEM_PRICE = iTEM_PRICE; } public int getNO_POKEBALL() { return NO_POKEBALL; } public void setNO_POKEBALL(int nO_POKEBALL) { NO_POKEBALL = nO_POKEBALL; } public int getPOKEBALL_QTY() { return POKEBALL_QTY; } public void setPOKEBALL_QTY(int pOKEBALL_QTY) { POKEBALL_QTY = pOKEBALL_QTY; } }
package zomeapp.com.zomechat.utils; import android.Manifest; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.content.IntentSender; import android.content.pm.PackageManager; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Typeface; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.media.ExifInterface; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.AppBarLayout; import android.support.design.widget.CollapsingToolbarLayout; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v7.widget.Toolbar; import android.text.Spannable; import android.text.SpannableString; import android.text.TextPaint; import android.text.TextUtils; import android.text.method.LinkMovementMethod; import android.text.style.ClickableSpan; import android.util.DisplayMetrics; import android.util.Log; import android.view.Gravity; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.imagepipeline.core.ImagePipeline; import com.facebook.imagepipeline.core.ImagePipelineConfig; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.PendingResult; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.Status; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.LocationSettingsRequest; import com.google.android.gms.location.LocationSettingsResult; import com.google.android.gms.location.LocationSettingsStatusCodes; import java.io.IOException; import java.lang.reflect.Field; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.concurrent.TimeUnit; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; import zomeapp.com.zomechat.application.ZomeApplication; import zomeapp.com.zomechat.fragments.FeedsFragment; /** * Created by tkiet082187 on 29.09.15. */ public class ZomeUtils implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener, ResultCallback<LocationSettingsResult> { private Context mContext; private ZomeApplication application; //public static final String serverUrl = "http://ec2-54-205-59-87.compute-1.amazonaws.com:1442"; //public static final String serverUrl = "http://10.0.2.2:1442"; // default emulator localhost // public static final String serverUrl = "http://10.0.3.2:1442"; // GenyMotion localhost //public static final String serverUrl = "http://192.168.0.142:1442"; // device's localhost (must be connected to same network) public boolean mRequestingLocationUpdates; public int barHeight; public Snackbar mSnackbar; public AppBarLayout mainAppBarLayout; private final String TAG = ZomeUtils.class.getSimpleName(); private Location mLastLocation, mCurrentLocation; private LocationRequest mLocationRequest; private String mLastUpdateTime; private SecretKeyFactory factory; LocationSettingsRequest mLocationSettingsRequest; public boolean isUserAnonymous; private long SECOND_INTERVAL = 1000; public DisplayMetrics metrics; public Fragment feedsInstanceFragment; public ImagePipeline imagePipeline; public ZomeUtils(Context mContext, View view) { this.mContext = mContext; ImagePipelineConfig config = ImagePipelineConfig.newBuilder(this.mContext).setDownsampleEnabled(true).build(); Fresco.initialize(this.mContext, config); imagePipeline = Fresco.getImagePipeline(); application = (ZomeApplication) this.mContext.getApplicationContext(); mSnackbar = Snackbar.make(view, "", Snackbar.LENGTH_SHORT); mRequestingLocationUpdates = false; metrics = Resources.getSystem().getDisplayMetrics(); buildGoogleApiClient(this.mContext); Log.e("context", this.mContext.toString()); createLocationRequest(); buildLocationSettingsRequest(); } public int dpToPx(int dp) { return (int) (dp * Resources.getSystem().getDisplayMetrics().density); } @SuppressLint("SetTextI18n") public void returnApproxTime(Date date, TextView textView) { Date diffDate = GregorianCalendar.getInstance().getTime(); long diffTime = diffDate.getTime() - date.getTime(); long diff = TimeUnit.MILLISECONDS.toSeconds(diffTime); String timeText; Log.e("diff", String.valueOf(diffTime)); Log.e("unit", String.valueOf(diff)); if (diff < 1) { textView.setText("now"); } else if (diff < 60) { textView.setText("less than a minute ago"); } else if (diff < 3600) { int min = (int) (diff / 60); if (min <= 1) { timeText = " minute ago"; } else { timeText = " minutes ago"; } textView.setText(min + timeText); } else if (diff < 86400) { int hour = (int) (diff / 60 / 60); if (hour <= 1) { timeText = " hour ago"; } else { timeText = " hours ago"; } textView.setText(hour + timeText); } else if (diff < 2628000) { int days = (int) (diff / 60 / 60 / 24); if (days <= 1) { timeText = " day ago"; } else { timeText = " days ago"; } textView.setText(days + timeText); } else if (diff < 31536000) { int month = (int) (diff / 60 / 60 / 24 / 30); if (month <= 1) { timeText = " month ago"; } else { timeText = " months ago"; } textView.setText(month + timeText); } else { SimpleDateFormat sdf = new SimpleDateFormat("M/d/y", Locale.getDefault()); textView.setText(sdf.format(date)); } } public void firstStep() throws NoSuchAlgorithmException { factory = SecretKeyFactory.getInstance("DES"); } public final boolean isValidEmail(CharSequence target) { return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches(); } public String whoAmI(byte[] firstBytes, byte[] nextBytes) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, IOException, InvalidKeySpecException { SecretKey key = factory.generateSecret(new DESKeySpec(firstBytes)); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.DECRYPT_MODE, key); byte[] stringBytes = cipher.doFinal(nextBytes); return new String(stringBytes, "UTF-8"); } public void showToastAnonymousUserMessage(String additionalMsg) { Toast.makeText(mContext, "You are in \"Browse Mode\". Please login to " + additionalMsg, Toast.LENGTH_LONG).show(); } public void setAppBarDragging(final boolean newValue) { AppBarLayout appBarLayout = mainAppBarLayout; CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams(); AppBarLayout.Behavior behavior = new AppBarLayout.Behavior(); behavior.setDragCallback(new AppBarLayout.Behavior.DragCallback() { @Override public boolean canDrag(@NonNull AppBarLayout appBarLayout) { return newValue; } }); params.setBehavior(behavior); } public void setTags(TextView pTextView, String pTagString) { SpannableString string = new SpannableString(pTagString); int start = -1; for (int i = 0; i < pTagString.length(); i++) { if (pTagString.charAt(i) == '#') { start = i; } else if (pTagString.charAt(i) == ' ' || (i == pTagString.length() - 1 && start != -1)) { if (start != -1) { if (i == pTagString.length() - 1) { i++; // case for if hash is last word and there is no // space after word } final String tag = pTagString.substring(start, i); string.setSpan(new ClickableSpan() { @Override public void onClick(View widget) { Log.d("Hash", String.format("Clicked %s!", tag)); String hashed = tag.substring(1, tag.length()); if (feedsInstanceFragment instanceof FeedsFragment) { ((FeedsFragment) feedsInstanceFragment).onQueryTextChange(hashed); } } @Override public void updateDrawState(TextPaint ds) { // link color ds.setColor(Color.parseColor("#33b5e5")); ds.setUnderlineText(false); } }, start, i, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); start = -1; } } } pTextView.setMovementMethod(LinkMovementMethod.getInstance()); pTextView.setText(string); } public Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight) { // BEST QUALITY MATCH //First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(path, options); // Calculate inSampleSize, Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; options.inPreferredConfig = Bitmap.Config.RGB_565; int inSampleSize = 1; if (height > reqHeight) { inSampleSize = Math.round((float) height / (float) reqHeight); } int expectedWidth = width / inSampleSize; if (expectedWidth > reqWidth) { //if(Math.round((float)width / (float)reqWidth) > inSampleSize) // If bigger SampSize.. inSampleSize = Math.round((float) width / (float) reqWidth); } options.inSampleSize = inSampleSize; // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; return BitmapFactory.decodeFile(path, options); } public Snackbar getSnackbar(View v, CharSequence commentOrPost, CharSequence snackText, View.OnClickListener clickListener) { mSnackbar = Snackbar.make(v, commentOrPost, Snackbar.LENGTH_INDEFINITE).setActionTextColor(Color.CYAN); if (clickListener != null && !snackText.toString().equals("")) { mSnackbar.setAction(snackText, clickListener); } View view = mSnackbar.getView(); CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) view.getLayoutParams(); params.gravity = Gravity.TOP; params.setMargins(0, barHeight, 0, 0); view.setLayoutParams(params); return mSnackbar; } public Snackbar repositionCustomSnackbarBelowToolbar(Snackbar mSnackbar) { View view = mSnackbar.getView(); CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) view.getLayoutParams(); params.gravity = Gravity.TOP; params.setMargins(0, barHeight, 0, 0); view.setLayoutParams(params); return mSnackbar; } public void delayForDataRetrieval(@Nullable final Long value) { Thread thread = new Thread(new Runnable() { @Override public void run() { try { if (value == null) { Thread.sleep(500); } else { Thread.sleep(value); } } catch (InterruptedException e) { e.printStackTrace(); } } }); thread.run(); } public void changeToolbarTypeface(Toolbar toolbar, Typeface typeface) { TextView titleTextView; try { Field f = toolbar.getClass().getDeclaredField("mTitleTextView"); f.setAccessible(true); titleTextView = (TextView) f.get(toolbar); titleTextView.setTypeface(typeface); } catch (NoSuchFieldException e) { } catch (IllegalAccessException e) { } } public void changeCollapsingToolbarTypeface(CollapsingToolbarLayout collapsingToolbarLayout, Typeface typeface) { try { // Retrieve the CollapsingTextHelper Field final Field cthf = collapsingToolbarLayout.getClass().getDeclaredField("mCollapsingTextHelper"); cthf.setAccessible(true); // Retrieve an instance of CollapsingTextHelper and its TextPaint final Object cth = cthf.get(collapsingToolbarLayout); final Field tpf = cth.getClass().getDeclaredField("mTextPaint"); tpf.setAccessible(true); // Apply your Typeface to the CollapsingTextHelper TextPaint ((TextPaint) tpf.get(cth)).setTypeface(typeface); } catch (Exception ignored) { ignored.printStackTrace(); // Nothing to do } } public Location getLegacyLocation() { Location location = null; // Acquire a reference to the system Location Manager LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE); // Define a listener that responds to location updates LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { // Called when a new location is found by the network location provider. //makeUseOfNewLocation(location); if (location != null) { Log.e("loc from network", location.toString()); //mLocation = location; } } public void onStatusChanged(String provider, int status, Bundle extras) { } public void onProviderEnabled(String provider) { } public void onProviderDisabled(String provider) { } }; // Register the listener with the Location Manager to receive location updates if (Build.VERSION.SDK_INT >= 23) if (mContext.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && mContext.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // public void requestPermissions(@NonNull String[] permissions, int requestCode) // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for Activity#requestPermissions for more details. //return; } try { locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location == null) { boolean enabled = locationManager .isProviderEnabled(LocationManager.GPS_PROVIDER); if (!enabled) { new Utils().displayPromptForEnablingGPS((Activity) mContext); //Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); //startActivity(intent); } locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); Log.e("called", "success"); } locationManager.removeUpdates(locationListener); if (location != null) { Log.e("mLoc", location.toString()); } } catch (IllegalArgumentException e) { e.printStackTrace(); } return location; } public Location getLocation() { if (mCurrentLocation != null) { return mCurrentLocation; } else { return mLastLocation; } } public synchronized void buildGoogleApiClient(Context context) { application.mGoogleApiClient = new GoogleApiClient.Builder(context) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } protected void createLocationRequest() { mLocationRequest = new LocationRequest(); // Sets the desired interval for active location updates. This interval is // inexact. You may not receive updates at all if no location sources are available, or // you may receive them slower than requested. You may also receive updates faster than // requested if other applications are requesting location at a faster interval. mLocationRequest.setInterval(SECOND_INTERVAL); // Sets the fastest rate for active location updates. This interval is exact, and your // application will never receive updates faster than this value. mLocationRequest.setFastestInterval(SECOND_INTERVAL); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); } public void startLocationUpdates() { Log.e("startUpd", "called"); LocationServices.FusedLocationApi.requestLocationUpdates( application.mGoogleApiClient, mLocationRequest, this ).setResultCallback(new ResultCallback<Status>() { @Override public void onResult(Status status) { mRequestingLocationUpdates = true; } }); } @Override public void onConnected(Bundle bundle) { if(application.mGoogleApiClient.isConnected()){ Log.e("client", "Google_Api_Client: It was connected on (onConnected) function, working as it should."); } else{ Log.e("client", "Google_Api_Client: It was NOT connected on (onConnected) function, It is definetly bugged."); } mLastLocation = LocationServices.FusedLocationApi.getLastLocation( application.mGoogleApiClient); Log.e("client", application.mGoogleApiClient.toString()); if (mLastLocation != null) { Log.e("gLoc", mLastLocation.toString()); application.lat = mLastLocation.getLatitude(); application.lng = mLastLocation.getLongitude(); } //buildLocationSettingsRequest(); checkLocationSettings(); startLocationUpdates(); //stopLocationUpdates(); } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(ConnectionResult connectionResult) { } @Override public void onLocationChanged(Location location) { mCurrentLocation = location; mLastUpdateTime = DateFormat.getTimeInstance().format(new Date()); Log.e("gCurLoc", mCurrentLocation.toString()); application.lat = mCurrentLocation.getLatitude(); application.lng = mCurrentLocation.getLongitude(); /*if (mCurrentLocation != null) { stopLocationUpdates(); }*/ //stopLocationUpdates(); } public Bitmap rotateBitmap(Bitmap bitmap, int orientation) { Matrix matrix = new Matrix(); switch (orientation) { case ExifInterface.ORIENTATION_NORMAL: return bitmap; case ExifInterface.ORIENTATION_FLIP_HORIZONTAL: matrix.setScale(-1, 1); break; case ExifInterface.ORIENTATION_ROTATE_180: matrix.setRotate(180); break; case ExifInterface.ORIENTATION_FLIP_VERTICAL: matrix.setRotate(180); matrix.postScale(-1, 1); break; case ExifInterface.ORIENTATION_TRANSPOSE: matrix.setRotate(90); matrix.postScale(-1, 1); break; case ExifInterface.ORIENTATION_ROTATE_90: matrix.setRotate(90); break; case ExifInterface.ORIENTATION_TRANSVERSE: matrix.setRotate(-90); matrix.postScale(-1, 1); break; case ExifInterface.ORIENTATION_ROTATE_270: matrix.setRotate(-90); break; default: return bitmap; } try { Bitmap bmRotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); bitmap.recycle(); return bmRotated; } catch (OutOfMemoryError e) { e.printStackTrace(); return null; } } public void stopLocationUpdates() { LocationServices.FusedLocationApi.removeLocationUpdates( application.mGoogleApiClient, this ).setResultCallback(new ResultCallback<Status>() { @Override public void onResult(Status status) { mRequestingLocationUpdates = false; } }); } public void buildLocationSettingsRequest() { LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder(); builder.addLocationRequest(mLocationRequest); mLocationSettingsRequest = builder.build(); } protected void checkLocationSettings() { PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings( application.mGoogleApiClient, mLocationSettingsRequest ); result.setResultCallback(this); } @Override public void onResult(LocationSettingsResult locationSettingsResult) { final Status status = locationSettingsResult.getStatus(); Log.e("status", status.getStatusCode() + ""); switch (status.getStatusCode()) { case LocationSettingsStatusCodes.SUCCESS: Log.i(TAG, "All location settings are satisfied."); startLocationUpdates(); //stopLocationUpdates(); break; case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: Log.i(TAG, "Location settings are not satisfied. Show the user a dialog to" + "upgrade location settings "); try { // Show the dialog by calling startResolutionForResult(), and check the result // in onActivityResult(). status.startResolutionForResult((Activity) this.mContext, application.REQUEST_CHECK_SETTINGS); } catch (IntentSender.SendIntentException e) { Log.i(TAG, "PendingIntent unable to execute request."); } break; case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: Log.i(TAG, "Location settings are inadequate, and cannot be fixed here. Dialog " + "not created."); break; } } }
package TriangleUtilitiesPkg; public class TriangleUtilities { public static String getRow(int width) { String s = ""; for(int i = 0; i < width; i++ ){ s += "*"; } return s; } public static String getTriangle(int numberOfRows) { String s =""; for(int i = 1; i < numberOfRows; i++){ for(int x = 1; x <= i; x++){ s += "*"; } s += "\n"; } return s; } public static String getSmallTriangle() { String s = ""; for(int x = 1; x < 5 ; x++ ){ for(int y = 1 ; y <= x ; y++ ){ s += "* "; } s += " \n"; } return s; } public static String getLargeTriangle() { String s = ""; for(int x = 1; x < 9; x++){ for(int y = 1 ; y <= x ; y++ ){ s += "* "; } s+= " \n"; } return s; } }
package gr.athena.innovation.fagi.core.function.property; import gr.athena.innovation.fagi.core.function.IFunction; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.Property; import org.apache.jena.rdf.model.RDFNode; import org.apache.jena.rdf.model.ResourceFactory; import org.apache.jena.rdf.model.Statement; import org.apache.jena.rdf.model.StmtIterator; import gr.athena.innovation.fagi.core.function.IFunctionTwoModelStringParameters; import gr.athena.innovation.fagi.model.CustomRDFProperty; import gr.athena.innovation.fagi.repository.SparqlRepository; import gr.athena.innovation.fagi.utils.RDFUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /** * Checks if the provided property is absent from the RDF model of a resource. * * @author nkarag */ public class NotExists implements IFunction, IFunctionTwoModelStringParameters{ private static final Logger LOG = LogManager.getLogger(NotExists.class); /** * Evaluates the absence of the property in the model. * * @param model the RDF model. * @param propertyString the property string. * @return true if the property exists in the model, false otherwise. */ @Override public boolean evaluate(Model model, String propertyString) { Property property = ResourceFactory.createProperty(propertyString); return !propertyExistsInModel(model, property); } /** * Evaluates the absence of the property in the model. * * @param model the RDF jena model. * @param property the customRDFProperty object. * @return true if the property exists in the model, false otherwise. */ public boolean evaluate(Model model, CustomRDFProperty property) { return propertyExistsInModel(model, property); } private static boolean propertyExistsInModel(Model model, CustomRDFProperty property){ int c; if(property.isSingleLevel()){ c = SparqlRepository.countProperty(model, RDFUtils.addBrackets(property.getValueProperty().toString())); } else { c = SparqlRepository.countPropertyChain(model, RDFUtils.addBrackets(property.getParent().toString()), RDFUtils.addBrackets(property.getValueProperty().toString())); } return c > 0; } private static boolean propertyExistsInModel(Model model, Property property){ for (StmtIterator i = model.listStatements( null, null, (RDFNode) null ); i.hasNext(); ) { Statement originalStatement = i.nextStatement(); Property p = originalStatement.getPredicate(); if(p.equals(property)){ return true; } } return false; } @Override public String getName(){ String className = this.getClass().getSimpleName().toLowerCase(); return className; } }
package com.hcl.service; import com.hcl.entity.Category; import com.hcl.entity.Products; import com.hcl.entity.Users; import java.util.List; import java.util.Set; import com.hcl.dao.UserDAO; public class UserService { public boolean validateUser(String email,String password) { UserDAO edao=new UserDAO(); return edao.validateUser(email, password); } public boolean addUser(String firstName, String lastName, String email, String password, String mobileNo) { UserDAO edao=new UserDAO(); return edao.addUser(firstName,lastName,email,password,mobileNo); } }
package ProjectPersonal.Thethreecarddealer; import javafx.util.Pair; import java.util.Scanner; public class CardGuess { String[] card = {"A","1","2","3","4","5","6","7","8","9","10","J","Q","K"}; //constructor CardGuess(){} //find a card value. int FindCard(int lowerbound, int upperbound, int currentValue) { Scanner x = new Scanner(System.in);// used to get the user respond. String temp = ""; //this while loop will ask the same question over and over again tell the dealer finds the correct number. while (lowerbound != currentValue) { System.out.print( "Is your card value greater then or less then/equal to " + currentValue + "?\n"); System.out.print( "1) Type 1 for greater then.\n"+ "2) Type 2 for less then/ equal to.\n"); temp = x.nextLine();//stores the users respond. x.close(); //Depending on the player(s) selection determines the alterations for the upperbound and lowerbound. if (temp.equals("1")) { lowerbound = currentValue; currentValue = ((upperbound - currentValue) / 2) + lowerbound; } else if (temp.equals("2")) { upperbound = currentValue; currentValue = ((currentValue - lowerbound) / 2) + lowerbound; } } return upperbound; } //Main function for the game play. public void GamerStarter(){ Pair<String, String> red = new Pair<>("Hearts","Spades"); Pair<String, String> black = new Pair<>("Diamond","Clubs"); //The welcoming screen. System.out.println( "Ok let me explain the game so a novice like you can under stand it easily."); System.out.println("I have a regular deck of 52 cards."); System.out.println("Your job is to picture one card, together not seperate, and I will try to guess your card."); System.out.println("To make things intresting, I have converted each card with a special value."); System.out.println("The values are:\n"); System.out.println("2 through 10 will be the value shown on the card."); System.out.println( " While A = 1, J = 11, Q = 12 and K = 13."); System.out.println("These values ar none negotiable."); System.out.println("So, choose your card and lets begin the game."); int CardFound = FindCard(1, 13, 7); CardFound -=1; Scanner o = new Scanner(System.in); //Requesting the color of the card will help find the suites. System.out.print( "I believe I got some idea what the card value is.\n"); System.out.print( "But before I can give you my guess I need you to tell me the color of the card.\n"); System.out.print( "Type 1 for red.\n Type 2 for black.\n"); String y = o.nextLine(); o.close(); //Figuring out the suite Pair<String, String> suites; if (y.equals("1")) { suites = red; } else { suites = black; } //Taking a guess. System.out.print( "I am ready to give you my answer.\n "); System.out.print("Your card is...\n"); System.out.print(card[CardFound]+" "+ suites.getKey()+ ".\n"); System.out.print("If this is not your card allow me a second chance.\n"); System.out.print("To allow the dealer a second chance, type 1.\n" + " If the dealer was correct type 0.\n"); Scanner p = new Scanner(System.in); String z = p.nextLine(); p.close(); //depending on the player(s) respond will determine the ending cout statements. if (z.equals("1")) { System.out.print( "I am ready to try again.\n "); System.out.print( "Your card is...\n"); System.out.print(card[CardFound] + " " + suites.getValue() + ".\n"); System.out.print( "If it is not your card then you must of made a mistake.\n"); System.out.print( "Therefore, I win this round.\n" + "See I knew you where all a bunch of looser(s).\n"); } else if (z == "0") { System.out.print("So, let me see if I got this straight.\n"); System.out.print("You are pathetic to allow a dealer like myslef to beat you so easily.\n"); System.out.print( "I do not associate with loosers.\n"+"So, get lost looser!!!"); } else { System.out.print("So, you beat me, big deal.\n" + "Your still a looser and I do not associate with losers.\n"+ "Get lost you bunch of looser(s).\n"); } } }
package com.heartmarket.model.dto.response; import lombok.AllArgsConstructor; import lombok.Getter; // 검색 결과 표시를 위한 response @Getter @AllArgsConstructor public class OtherTrade { int tradeNo; String tTitle; String tArea; int pPrice; String uImg; }
package com.bucares.barcode.model; import java.util.Date; public class PeriodoDTO { private String name; private Date dateInicio; private Date dateFinal; public PeriodoDTO(){} public String getName() { return name; } public Date getDateFinal() { return dateFinal; } public void setDateFinal(Date dateFinal) { this.dateFinal = dateFinal; } public Date getDateInicio() { return dateInicio; } public void setDateInicio(Date dateInicio) { this.dateInicio = dateInicio; } public void setName(String name) { this.name = name; } public PeriodoDTO(String name, Date dateInicio, Date dateFinal) { this.name = name; this.dateInicio = dateInicio; this.dateFinal = dateFinal; } }
package com.ehootu.park.dao; import java.util.List; import com.ehootu.park.model.PublicInformationEntity; import org.springframework.stereotype.Repository; @Repository public interface PublicInformationDao { int save(PublicInformationEntity publicInformation); List<PublicInformationEntity> selectOne(String dizhibianma); PublicInformationEntity select(String dizhibianma); List<PublicInformationEntity> selectAddress(String enterprise_address); void update(PublicInformationEntity PublicInformation); void updateSign(PublicInformationEntity PublicInformation); }
package com.meihf.mjoyblog.service.error; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import com.meihf.mjoyblog.bean.ErrorCode; import com.meihf.mjoyblog.dao.ErrorCodeDao; import com.meihf.mjoyblog.util.GlobalConstraints; /** * @desc:错误编码服务层实现 * @author 梅海风 */ public class ErrorCodeSvcImpl implements IErrorCodeSvc { @Autowired private ErrorCodeDao errorCodeDao; private static Log log = LogFactory.getLog(ErrorCodeSvcImpl.class); @Override public String getMessage(int code) { ErrorCode bean = errorCodeDao.queryById(code); if(bean != null){ return bean.getMessage(); } log.error("根据ID:["+code+"]"+"找不到对应的错误信息"); return GlobalConstraints.ErrorCode.UNKNOW_ERROR_MESSAGE; } }
class Coinchange{ private static int findNumberOfWays(int[] arr, int m, int n){ if(n==0){ return 1; } if(n<0){ return 0; } if(m<=0 && n>=1){ return 0; } return findNumberOfWays(arr,m-1,n)+findNumberOfWays(arr,m,n-arr[m-1]); } public static void main(String args[]){ int[] arr = {1,2,3}; int n = 10; System.out.println(findNumberOfWays(arr,arr.length,n)); } }
/* * Copyright 2008 University of California at Berkeley * * 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.rebioma.server.util; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Helper class for getting, setting, and resetting {@link HttpServletRequest} * and {@link HttpServletResponse} {@link Cookie}s. * * @author eighty * */ public class CookieUtil { /** * Returns the cookie value for a specific cookie in the a request. * * @param request the request * @param cookieName the name of the cookie * @return the cookie value */ public static String getRequestCookieValue(HttpServletRequest request, String cookieName) { if (request == null || request.getCookies() == null) { return null; } for (Cookie c : request.getCookies()) { if (c == null) { continue; } if (c.getName().equalsIgnoreCase(cookieName)) { return c.getValue(); } } return null; } /** * Resets cookie values in the request and response. * * @param request the request * @param response the response * @param cookieName the name of the cookie to reset */ public static void resetCookieValue(HttpServletRequest request, HttpServletResponse response, String cookieName) { if (request.getCookies() == null) { response.addCookie(new Cookie(cookieName, null)); return; } for (Cookie c : request.getCookies()) { if (c.getName().equalsIgnoreCase(cookieName)) { c.setValue(null); response.addCookie(c); } } } public static void setCookie(HttpServletRequest request, HttpServletResponse response, String uniqueIdCookieName, String uuid) { if (request.getCookies() == null) { response.addCookie(new Cookie(uniqueIdCookieName, uuid)); return; } for (Cookie c : request.getCookies()) { if (c.getName().equalsIgnoreCase(uniqueIdCookieName)) { c.setValue(uuid); response.addCookie(c); return; } } Cookie c = new Cookie(uniqueIdCookieName, uuid); response.addCookie(c); } }
package com.notet.activity; import android.app.ActionBar; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.GridView; import com.adapter.NotesArrayAdapter; import com.note.databasehandler.DabaseHandler; import com.note.model.Notes; import com.permissions.Permissions; import java.util.ArrayList; public class MainActivity extends Activity { Activity mActivity; DabaseHandler myDabaseHandler; ArrayList<Notes> mNotesArrayList = null; NotesArrayAdapter mAdapter = null; //NotesAdapter adapterNote=null; GridView mGvNotes; Notes mNote; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); BitmapDrawable background=new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.drawable.bg_actionbar)); //actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3399FF"))); ActionBar actionBar = getActionBar(); actionBar.setBackgroundDrawable(background);// set background for action bar loadMain(); // set on item click listener of gridview // setting permission Permissions.requestRWPermission(this); } // laoding data (use when call onCreate and onResume) public void loadMain() { myDabaseHandler = new DabaseHandler(this); //myDabaseHandler.deleteNotes(); //myDabaseHandler.dropTable(); //myDabaseHandler.CreateTable(); //myDabaseHandler.deleteAllNotes(); mNotesArrayList = myDabaseHandler.getAllNotesDESC(); if (mNotesArrayList.size() > 0) { setContentView(R.layout.activity_main); mGvNotes = (GridView) findViewById(R.id.gvNote); Log.d("Main Notes size :", mNotesArrayList.size() + ""); mAdapter = new NotesArrayAdapter(this, R.layout.custom_item_notes, mNotesArrayList); mGvNotes.setAdapter(mAdapter); // set on item click listener of gridview mGvNotes.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent it = new Intent(MainActivity.this, EditNoteActivity.class); Log.d("Move mActivity", "editor"); // pust extra Notes iNote = mNotesArrayList.get(position); // get id mNote and put to edit mActivity it.putExtra("id", iNote.getID()); startActivity(it); //Toast.makeText(getBaseContext(), "vi tri"+position, Toast.LENGTH_LONG).show(); } }); // set on item clong click listener TODO THIS : handler long clck listener mGvNotes.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle("Confirm Delete"); builder.setMessage("Are you sure want to delete this ?"); builder.setPositiveButton("Yes",new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialogInterface, int i) { Notes iNote = mNotesArrayList.get(position); myDabaseHandler.deleteNotes(iNote.getID()); onResume(); } }); builder.setNegativeButton("No",new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.cancel(); } }); Log.d("delete photo", "ok"); builder.create().show(); return true; } }); } else { setContentView(R.layout.activity_main_no_notes); } } @Override protected void onResume() { super.onResume(); loadMain(); Log.d("MainActivity", "Call event OnResume()"); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent mActivity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_addNote) { Intent i = new Intent(MainActivity.this, AddNoteActivity.class); startActivity(i); Log.d("MainActivity", "Call AddNoteActivity class"); return true; } return super.onOptionsItemSelected(item); } /*@Override TODO create function delete item when long click item public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.setQwertyMode(true); MenuItem itemdelete = menu.add(0, 0, 0, "Delete"); { itemdelete.setAlphabeticShortcut('a'); itemdelete.setIcon(R.drawable.ic_action_discard); } } @Override public boolean onContextItemSelected(MenuItem item) { switch (item.getItemId()){ case 0: Toast.makeText(getBaseContext(),"delete item",Toast.LENGTH_LONG).show(); break; default: Toast.makeText(getBaseContext(),"no choise item",Toast.LENGTH_LONG).show(); break; } return super.onContextItemSelected(item); }*/ }
package com.flute.atp.core; public interface Visitor { }
package pl.norbgrusz.ui.di; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.Singleton; import pl.norbgrusz.keyfinder.KeyFinder; import pl.norbgrusz.keyfinder.StructureProperties; import pl.norbgrusz.keyfinder.analyzer.AnalyzerResults; import pl.norbgrusz.keyfinder.model.Structure; import pl.norbgrusz.ui.controller.StructureController; import pl.norbgrusz.ui.data.Graph; import pl.norbgrusz.ui.data.GraphFactory; import javax.sound.midi.InvalidMidiDataException; import javax.sound.midi.MidiSystem; import javax.sound.midi.Sequence; import java.io.*; import java.util.Properties; public class StructureControllerModule extends AbstractModule { private File midiFile; public StructureControllerModule(File midiFile) { this.midiFile = midiFile; } @Override protected void configure() { bind(StructureController.class); } @Provides @Singleton public Graph getGraph(Structure structure) { return new GraphFactory().createGraph(midiFile.getName(), structure, StructureController.GRAPH_RADIUS); } @Provides @Singleton public Structure getStructrue(Sequence sequence, StructureProperties properties) { return KeyFinder.createStructure(sequence, properties); } @Provides @Singleton public Sequence getSequence() throws InvalidMidiDataException, IOException { return MidiSystem.getSequence(midiFile); } @Provides @Singleton public StructureProperties getStructureProperties() throws IOException { Properties properties = new Properties(); InputStream propertiesFile = new FileInputStream(StructureControllerModule.class.getResource("/structure.properties").getFile()); properties.load(propertiesFile); return StructureProperties.create(properties); } @Provides @Singleton public AnalyzerResults getAnalyzerResults(Structure structure) { return KeyFinder.getAnalyz(structure); } }
/* * Copyright (C) 2001 - 2015 Marko Salmela, http://fuusio.org * * 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.fuusio.api.rest.volley; import com.android.volley.VolleyError; import org.fuusio.api.rest.HttpHeaders; import org.fuusio.api.rest.RequestError; public class VolleyRequestError extends RequestError { private final HttpHeaders mHeaders; public VolleyRequestError(final VolleyError error) { mException = error.getCause(); mMessage = error.getMessage(); mNetworkTime = error.getNetworkTimeMs(); mStatusCode = error.networkResponse.statusCode; mHeaders = new HttpHeaders(error.networkResponse.headers); } public final HttpHeaders getHeaders() { return mHeaders; } }
package com.tencent.mm.ui.chatting.viewitems; import com.tencent.mm.pluginsdk.ui.applet.e.a; import com.tencent.mm.storage.bd; import com.tencent.mm.ui.chatting.viewitems.p.c; import com.tencent.mm.ui.chatting.viewitems.p.j; import com.tencent.mm.y.m; class p$j$1 implements a { final /* synthetic */ bd dAs; final /* synthetic */ m hrc; final /* synthetic */ int hrd; final /* synthetic */ c ubU; final /* synthetic */ p.a ubV; final /* synthetic */ j ubW; p$j$1(j jVar, c cVar, p.a aVar, m mVar, bd bdVar, int i) { this.ubW = jVar; this.ubU = cVar; this.ubV = aVar; this.hrc = mVar; this.dAs = bdVar; this.hrd = i; } public final void onFinish() { j.a(this.ubW, this.ubU, this.ubV, this.hrc, this.dAs, this.hrd); } }
package com.tencent.mm.plugin.account.ui; import android.view.View; import android.view.View.OnClickListener; import com.tencent.mm.kernel.a; import com.tencent.mm.kernel.g; import com.tencent.mm.plugin.account.a.j; import com.tencent.mm.ui.base.h; class EmailVerifyUI$3 implements OnClickListener { final /* synthetic */ EmailVerifyUI ePX; EmailVerifyUI$3(EmailVerifyUI emailVerifyUI) { this.ePX = emailVerifyUI; } public final void onClick(View view) { StringBuilder stringBuilder = new StringBuilder(); g.Eg(); stringBuilder = stringBuilder.append(a.DA()).append(",").append(getClass().getName()).append(",R500_250,"); g.Eg(); com.tencent.mm.plugin.c.a.pV(stringBuilder.append(a.gd("R500_250")).append(",3").toString()); h.a(this.ePX, j.regby_email_resend_verify_code, j.regby_email_err_tip_title, j.app_ok, j.app_cancel, new 1(this), null); } }
// // Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7 generiert // Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren. // Generiert: 2016.05.11 um 01:33:35 PM CEST // package com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java-Klasse für BRGW01PlanungType complex type. * * <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist. * * <pre> * &lt;complexType name="BRGW01PlanungType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="STRANG" type="{http://www-fls.thyssen.com/xml/schema/qcs}STRANGPlanungType" minOccurs="0"/> * &lt;element name="ERHITZEN" type="{http://www-fls.thyssen.com/xml/schema/qcs}ERHITZENPlanungType" minOccurs="0"/> * &lt;element name="WARMWALZ" type="{http://www-fls.thyssen.com/xml/schema/qcs}WARMWALZPlanungType" minOccurs="0"/> * &lt;element name="ABKUEHL" type="{http://www-fls.thyssen.com/xml/schema/qcs}ABKUEHLPlanungType" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "BRGW01PlanungType", propOrder = { "strang", "erhitzen", "warmwalz", "abkuehl" }) public class BRGW01PlanungType { @XmlElement(name = "STRANG") protected STRANGPlanungType strang; @XmlElement(name = "ERHITZEN") protected ERHITZENPlanungType erhitzen; @XmlElement(name = "WARMWALZ") protected WARMWALZPlanungType warmwalz; @XmlElement(name = "ABKUEHL") protected ABKUEHLPlanungType abkuehl; /** * Ruft den Wert der strang-Eigenschaft ab. * * @return * possible object is * {@link STRANGPlanungType } * */ public STRANGPlanungType getSTRANG() { return strang; } /** * Legt den Wert der strang-Eigenschaft fest. * * @param value * allowed object is * {@link STRANGPlanungType } * */ public void setSTRANG(STRANGPlanungType value) { this.strang = value; } /** * Ruft den Wert der erhitzen-Eigenschaft ab. * * @return * possible object is * {@link ERHITZENPlanungType } * */ public ERHITZENPlanungType getERHITZEN() { return erhitzen; } /** * Legt den Wert der erhitzen-Eigenschaft fest. * * @param value * allowed object is * {@link ERHITZENPlanungType } * */ public void setERHITZEN(ERHITZENPlanungType value) { this.erhitzen = value; } /** * Ruft den Wert der warmwalz-Eigenschaft ab. * * @return * possible object is * {@link WARMWALZPlanungType } * */ public WARMWALZPlanungType getWARMWALZ() { return warmwalz; } /** * Legt den Wert der warmwalz-Eigenschaft fest. * * @param value * allowed object is * {@link WARMWALZPlanungType } * */ public void setWARMWALZ(WARMWALZPlanungType value) { this.warmwalz = value; } /** * Ruft den Wert der abkuehl-Eigenschaft ab. * * @return * possible object is * {@link ABKUEHLPlanungType } * */ public ABKUEHLPlanungType getABKUEHL() { return abkuehl; } /** * Legt den Wert der abkuehl-Eigenschaft fest. * * @param value * allowed object is * {@link ABKUEHLPlanungType } * */ public void setABKUEHL(ABKUEHLPlanungType value) { this.abkuehl = value; } }
package models; import java.io.Serializable; public abstract class SportsClub implements Serializable { private String clubName; private Address clubLocation; private int numOfWins; private int numOfDraws; private int numOfDefeats; private int points; private int numOfMatchPlayed; private static int numOfClubs; /*default constructor*/ public SportsClub(){ this.clubName = null; this.clubLocation = null; this.numOfWins = 0; this.numOfDraws = 0; this.numOfDefeats = 0; this.points = 0; this.numOfMatchPlayed = 0; numOfClubs++; } public SportsClub(String clubName, Address clubLocation){ this.clubName = clubName; this.clubLocation = clubLocation; } public String getClubName(){ return this.clubName; } public void setClubName(String clubName){ this.clubName = clubName; } public Address getClubLocation(){ return this.clubLocation; } public void setClubLocation(Address clubLocation){ this.clubLocation = clubLocation; } public int getNumOfWins(){ return this.numOfWins; } public void setNumOfWins(){ this.numOfWins++; } public int getNumOfDraws(){ return this.numOfDraws; } public void setNumOfDraws(){ this.numOfDraws++; } public int getNumOfDefeats(){ return this.numOfDefeats; } public void setNumOfDefeats(){ this.numOfDefeats++; } public int getNumOfMatchPlayed(){ return this.numOfMatchPlayed; } public void setNumOfMatchPlayed(){ this.numOfMatchPlayed++; } public int getPoints(){ return this.points; } public void setPoints(int points){ this.points += points; } public static int getNumOfClubs(){ return numOfClubs; } @Override public String toString(){ return "Club Name: "+this.getClubName()+"\n" +this.getClubLocation()+"\n" +"Num of Wins: "+this.getNumOfWins()+"\n" +"Num of Draws: "+this.getNumOfDraws()+"\n" +"Num of Defeats: "+this.getNumOfDefeats()+"\n" +"Num of Played: "+this.getNumOfMatchPlayed()+"\n" +"Points: "+this.getPoints()+"\n"; } }
package com.figureshop.springmvc.dataAccess.dao.impl; import com.figureshop.springmvc.dataAccess.dao.PurchaseDAO; import com.figureshop.springmvc.dataAccess.repository.PurchaseRepository; import com.figureshop.springmvc.dataAccess.util.EntityMapper; import com.figureshop.springmvc.model.Purchase; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.transaction.Transactional; @Service @Transactional public class PurchaseDAOImpl implements PurchaseDAO { @Autowired private PurchaseRepository purchaseRepository; @Autowired private EntityMapper entityMapper; public void savePurchase(Purchase purchase) { purchaseRepository.save(entityMapper.convertPurchaseModelToEntity(purchase)); } }
package com.uinsk.mobileppkapps.ui.binaan; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.navigation.NavController; import androidx.navigation.Navigation; import androidx.navigation.ui.NavigationUI; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.uinsk.mobileppkapps.R; public class BinaanFragment extends Fragment { private BinaanViewModel binaanViewModel; BottomNavigationView bottomNavigationView; NavController navController; FloatingActionButton floatingActionButton; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View root = inflater.inflate(R.layout.fragment_binaan, container, false); bottomNavigationView = root.findViewById(R.id.nav_bottom); navController = Navigation.findNavController(root.findViewById(R.id.nav_host_fragment)); NavigationUI.setupWithNavController(bottomNavigationView, navController); return root; } }
package in.conceptarchitect.collections; import java.util.Iterator; public class LinkedList<X> implements IndexedList<X>, Iterable<X>{ public static <E> LinkedList<E> create(E ... values){ LinkedList<E> newList=new LinkedList<>(); for(E value :values) newList.add(value); return newList; } class Node { X value; Node next; Node previous; } private Node first; //optional but useful elements private Node last; private int count; private Node current; public Container<X> add(X value) { Node newNode=new Node(); newNode.value=value; newNode.next=null; //this is the last node newNode.previous=last; //current last will be its previous. if(count==0) //list is currently empty first=newNode; //this is also the first else last.next=newNode; last=newNode; count++; return this; } int currentIndex; private Node locate_v2(int pos) { if(pos==-1) return last; if(pos<0 || pos>=count) throw new IndexOutOfBoundsException("Invalid Index "+pos+" Should be in range [0-"+(count-1)+"]"); if(pos==0) return first; if(pos==count-1) return last; //The 80% use case ---> one by one access if (current!=null && currentIndex+1==pos) { current=current.next; currentIndex++; return current; } //Direct access to nth index int deltaFirst= pos; int deltaLast= count-pos-1; int deltaCurrent=Math.abs(currentIndex-pos); int direction=1; int delta=0; Node node=null; if(current!=null && deltaCurrent<=deltaFirst && deltaCurrent<=deltaLast) { delta=deltaCurrent; direction = pos > currentIndex? 1 : -1; node=current; //System.out.print("+"); } if(deltaFirst<=deltaLast && deltaFirst<=deltaCurrent) { //start from begining delta=deltaFirst; direction=1; node=first; //System.out.print("|<"); } else if(deltaLast<=deltaFirst && deltaLast<=deltaCurrent) { //start from end delta=deltaLast; direction=-1; node=last; //System.out.print("|>"); } for(int i=0;i<delta;i++) { if(direction==1) node=node.next; else node=node.previous; } current=node; currentIndex=pos; return node; } private Node locate(int pos) { if(pos==-1) return last; if(pos<0 || pos>=count) throw new IndexOutOfBoundsException("Invalid Index "+pos+" Should be in range [0-"+(count-1)+"]"); if(pos==0) return first; if(pos==count-1) return last; Node node=first; for(int i=0;i<pos;i++) node=node.next; return node; } public X get(int pos) { return locate(pos).value; } public IndexedList<X> set(int pos, X value) { locate(pos).value=value; return this; } public <O> O each(ReturnableAction<X,O> action) { //System.out.println("using specialized each for LinkedList"); for(Node n=first; n!=null; n=n.next) { action.actOn(n.value); } return action.result(); } public X remove(int pos) { Node delNode= locate(pos); if(delNode.previous!=null) delNode.previous.next=delNode.next; else first=delNode.next; if(delNode.next!=null) delNode.next.previous=delNode.previous; else last=delNode.previous; count--; current=delNode.next; return delNode.value; } public int size() { return count; } public String toString() { String str="LinkedList[\t"; for(Node n=first;n!=null;n=n.next) str+=(n.value+"\t"); str+="]"; return str; } @Override public Iterator<X> iterator() { // TODO Auto-generated method stub return new MySimplerIterator(); } class MySimplerIterator implements Iterator<X>{ Node current=first; @Override public boolean hasNext() { // TODO Auto-generated method stub return current!=null; } @Override public X next() { // TODO Auto-generated method stub X value= current.value; current=current.next; return value; } } //static class E{} }
//package java.lang; // //// Error:(1, 1) java: 程序包已存在于另一个模块中: java.base //public class String { // @Override // public String toString() { // return "String{}"; // } // // public static void main(String[] args) { // String str = new String(); // System.out.println(str.getClass().getClassLoader().toString()); // AppClassLoader // } // //}
package ledcontrol.serialcomm.processor; import ledcontrol.serialcomm.model.*; import org.apache.camel.EndpointInject; import org.apache.camel.ProducerTemplate; import java.util.ArrayList; import java.util.List; public class SerialDataSender { @EndpointInject(uri = "direct:sendSerialData") private ProducerTemplate sendSerial; public void sendStatusRequest() { ArduinoMessage jsonMessage = new ArduinoMessageImpl(ArduinoMessageType.STATUS); sendSerial.sendBody(jsonMessage); } public void sendDebugState(boolean debugState) { ArduinoMessage jsonMessage = new ArduinoMessageImpl(ArduinoMessageType.DEBUG); jsonMessage.setDebug(new Debug(debugState)); sendSerial.sendBody(jsonMessage); } public void sendReset() { sendSerial.sendBody("RESET"); } public void sendEffect(String effect) { ArduinoMessage jsonMessage = new ArduinoMessageImpl(ArduinoMessageType.CMD); Command command = new Command(); command.setName("effect"); command.setParam(new ArrayList<String>()); command.getParam().add(effect); jsonMessage.setCommand(command); sendSerial.sendBody(jsonMessage); } public void sendCommand(String commandName, List<String> parameters) { ArduinoMessage jsonMessage = new ArduinoMessageImpl(ArduinoMessageType.CMD); Command command = new Command(); command.setName(commandName); command.setParam(parameters); //command.setParam(new ArrayList<String>()); //command.getParam().add("255"); //command.getParam().add("dummy"); jsonMessage.setCommand(command); sendSerial.sendBody(jsonMessage); } public void sendCommand(String commandName, String parameter) { if (parameter == null) { sendCommand(commandName); } else { List<String> parameters = new ArrayList<>(); parameters.add(parameter); sendCommand(commandName, parameters); } } public void sendCommand(String commandName) { sendCommand(commandName, (List<String>)null); } }
import com.itextpdf.text.Document; import com.itextpdf.text.Element; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; import java.awt.event.WindowEvent; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import javax.swing.JOptionPane; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartFrame; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import java.io.*; import java.awt.*; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * decision_making_dashboard_JFrame.java * * Created on Jan 23, 2012, 3:33:40 PM */ /** * * @author 9589693153 */ public class decision_making_dashboard_JFrame extends javax.swing.JFrame { Connection conn=null; ResultSet rs = null; PreparedStatement pst=null; /** Creates new form decision_making_dashboard_JFrame */ public decision_making_dashboard_JFrame() { initComponents(); } public void close() { WindowEvent winClosingEvent = new WindowEvent( this, WindowEvent.WINDOW_CLOSING ); Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent( winClosingEvent ); } /** 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() { jToolBar1 = new javax.swing.JToolBar(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jMenu2 = new javax.swing.JMenu(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); jToolBar1.setRollover(true); jButton1.setText("jButton1"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("jButton2"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jMenu1.setText("File"); jMenuBar1.add(jMenu1); jMenu2.setText("Edit"); jMenuBar1.add(jMenu2); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 747, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(339, Short.MAX_VALUE) .addComponent(jButton2) .addGap(135, 135, 135) .addComponent(jButton1) .addGap(127, 127, 127)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(80, 80, 80) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton1) .addComponent(jButton2)) .addContainerGap(212, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed Chart_JFrame s=new Chart_JFrame(); s.setVisible(true); close(); double divide_torque=0,divide_rotationalspeed=0,divide_Temperature=0,divide_volumeflow=0,divide_pr1=0,divide_pr2=0,divide_pr3=0; try{ String sql1=" SELECT Count(idpump) FROM pump "; pst =conn.prepareStatement(sql1); rs=pst.executeQuery(); // pst.setString(1, jTextField1.getText()); String count_pr1=rs.getString("Count(idpump)"); count_p1_intform =Integer.parseInt(count_pr1); }catch(Exception e) { JOptionPane.showMessageDialog(null, e); } finally { try{ rs.close(); } catch(Exception e) { } } try{ // pst.setString(1, jTextField1.getText()); XYSeries series =new XYSeries("Graph"); for(int i=1;i<=count_p1_intform;i++){ /* String sql1=" SELECT pressure1 FROM pump where idpump ='"+i+"' "; pst =conn.prepareStatement(sql1); rs=pst.executeQuery(); String value_pr1 = rs.getString("pressure1"); int value_pr1_intform =Integer.parseInt(value_pr1); if( value_pr1_intform<=10.0 && value_pr1_intform>=0.0){ series.add(i, value_pr1_intform); counter1++; }*/ int counter1 = 0,counter2 = 0,counter3 = 0,counter4 = 0,counter5 = 0,counter6 = 0,counter7 = 0; String sql1=" SELECT * FROM pump where idpump ='"+i+"' "; pst =conn.prepareStatement(sql1); rs=pst.executeQuery(); while(rs.next()){ double pressure11 = rs.getDouble("pressure1"); //System.out.println(pressure11); if(pressure11<=5 && pressure11>=0.0){ counter1++; } double pressure22 = rs.getDouble("pressure2"); //System.out.println(pressure22); if(pressure22<=10.0 && pressure22>=0.0){ counter2++; } double pressure33 = rs.getDouble("pressure3"); //System.out.println(pressure33); if(pressure33<=500 && pressure33>=0){ counter3++; } double volumeflow = rs.getDouble("VolumeFlow"); //System.out.println(volumeflow); if(volumeflow<=500 && volumeflow>=0){ counter4++; } double Temperature1 = rs.getDouble("Temperature"); //System.out.println(Temperature1); if(Temperature1<=60 && Temperature1>=0){ counter5++; } double rotationalspeed1 = rs.getDouble("RotationalSpeed"); //System.out.println(rotationalspeed1); if(rotationalspeed1<=6000){ counter6++; } double torque1 = rs.getDouble("Torque"); // System.out.println(torque1); if(torque1 <=200 && torque1>=0){ counter7++; } } sum_availability =counter1+counter2+counter3+counter4+counter5+counter6+counter7; total_availability =((sum_availability/7)*100); int total_hello=(int)total_availability; // jProgressBar_availability_total.setValue(total_hello); String avail1 = Double.toString(total_availability); String sql="update pump set Remarks='"+total_availability+"'where idpump ='"+i+"' "; pst =conn.prepareStatement(sql); pst.execute(); // JOptionPane.showMessageDialog(null, "Updated"); series.add(i, total_availability); //System.out.println(total_availability); } XYSeriesCollection dataset =new XYSeriesCollection(); dataset.addSeries(series); JFreeChart chart =ChartFactory.createXYLineChart("Availability Percentage Per Day", "Day", "Percentage(%)", dataset, PlotOrientation.VERTICAL, true,true,false); ChartFrame frame = new ChartFrame("Availability Percentage Per Day",chart); frame.pack(); frame.setVisible(true); }catch(Exception e) { JOptionPane.showMessageDialog(null, e); } finally { try{ rs.close(); } catch(Exception e) { } } }//GEN-LAST:event_jButton2ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed try //try statement { String a ="namaste ji kaise ho"; Document document=new Document(); PdfWriter.getInstance(document,new FileOutputStream("tableTilePDF.pdf")); document.open(); PdfPTable table=new PdfPTable(2); PdfPCell cell = new PdfPCell (new Paragraph ("Rose India")); cell.setColspan (8); cell.setHorizontalAlignment (Element.ALIGN_CENTER); //cell.setBackgroundColor(Color.BLUE); cell.setPadding (10.0f); table.addCell (cell); cell = new PdfPCell (new Paragraph ("Name")); cell.setHorizontalAlignment (Element.ALIGN_CENTER); //cell.setBackgroundColor (new Color (255, 200, 0)); cell.setPadding (10.0f); table.addCell (cell); cell = new PdfPCell (new Paragraph ("Place")); cell.setHorizontalAlignment (Element.ALIGN_CENTER); //cell.setBackgroundColor (new Color (255, 200, 0)); cell.setPadding (10.0f); table.addCell (cell); table.addCell("NewsTrack"); table.addCell("Delhi"); table.addCell(a); table.addCell("Delhi"); document.add(table); document.close(); } catch (Exception e) //catch any exceptions here { JOptionPane.showMessageDialog(null,"Error"); //print the error } }//GEN-LAST:event_jButton1ActionPerformed /** * @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(decision_making_dashboard_JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(decision_making_dashboard_JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(decision_making_dashboard_JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(decision_making_dashboard_JFrame.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 decision_making_dashboard_JFrame().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JMenu jMenu1; private javax.swing.JMenu jMenu2; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JToolBar jToolBar1; // End of variables declaration//GEN-END:variables private int count_p1_intform; private double divide1,divide2,divide3,divide4,divide5,divide6,divide7,total_availability,sum_availability; }
package ru.android.messenger.model.utils; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import java.util.concurrent.TimeUnit; public class DateUtils { private static final int USER_ONLINE_DELAY_SECONDS = 180; private DateUtils() { } @SuppressWarnings("SimpleDateFormat") public static String[] getFormattedDateAndTime(Date lastOnlineUTCDate) { Date convertedToLocalDate = convertUTCToLocalDate(lastOnlineUTCDate); String date = new SimpleDateFormat("dd.MM.yyyy").format(convertedToLocalDate); String time = new SimpleDateFormat("HH:mm").format(convertedToLocalDate); return new String[]{date, time}; } public static boolean isOnline(Date date) { Date currentDateOnDevice = new Date(); Date userLastOnlineDate = convertUTCToLocalDate(date); long currentTimeOnDevice = currentDateOnDevice.getTime(); long userLastOnlineTime = userLastOnlineDate.getTime(); long userOnlineDelayMillis = TimeUnit.SECONDS.toMillis(USER_ONLINE_DELAY_SECONDS); return currentTimeOnDevice - userLastOnlineTime < userOnlineDelayMillis; } static Date convertUTCToLocalDate(Date date) { long time = date.getTime(); TimeZone currentTimeZone = TimeZone.getDefault(); int offset = currentTimeZone.getRawOffset(); return new Date(time + offset); } }
package org.lvzr.fast.java.patten.create.singleton; /** * 3、单例模式(Singleton) 单例对象(Singleton)是一种常用的设计模式。在Java应用中,单例对象能保证在一个JVM中, 该对象只有一个实例存在。这样的模式有几个好处: a、某些类创建比较频繁,对于一些大型的对象,这是一笔很大的系统开销。 b、省去了new操作符,降低了系统内存的使用频率,减轻GC压力。 c、有些类如交易所的核心交易引擎,控制着交易流程,如果该类可以创建多个的话,系统完全乱了。 (比如一个军队出现了多个司令员同时指挥,肯定会乱成一团),所以只有使用单例模式, 才能保证核心交易服务器独立控制整个流程。 * */ public class Singleton { /* 持有私有静态实例,防止被引用,此处赋值为null,目的是实现延迟加载 */ private static Singleton instance = null; /* 私有构造方法,防止被实例化 */ private Singleton() { } /* 静态工程方法,创建实例 */ public static synchronized Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } /* 如果该对象被用于序列化,可以保证对象在序列化前后保持一致 */ public Object readResolve() { return instance; } }
package com.tencent.mm.plugin.webview.model; import android.os.Parcel; import android.os.Parcelable.Creator; import com.tencent.mm.modelvoice.q; public class WebViewJSSDKVoiceItem extends WebViewJSSDKFileItem { public static final Creator<WebViewJSSDKVoiceItem> CREATOR = new Creator<WebViewJSSDKVoiceItem>() { public final /* synthetic */ Object createFromParcel(Parcel parcel) { return new WebViewJSSDKVoiceItem(parcel); } public final /* bridge */ /* synthetic */ Object[] newArray(int i) { return new WebViewJSSDKVoiceItem[i]; } }; public WebViewJSSDKVoiceItem() { this.bMT = 2; } public final WebViewJSSDKFileItem bUh() { this.fnM = q.getFullPath(this.fileName); this.bNH = aj.Qt(this.fnM); return this; } public final String bUi() { return "speex"; } public final String bUj() { return "voice"; } public int describeContents() { return 0; } public void writeToParcel(Parcel parcel, int i) { super.writeToParcel(parcel, i); } protected WebViewJSSDKVoiceItem(Parcel parcel) { super(parcel); } }
package five; /** * static: * 修饰成员变量的时候,表示静态成员表变量或者叫类变量 * 普通变量在使用的时候,必须通过对象名进行调用;: * 类变量或者静态变量可以使用对象名调用,也可以使用类名进行调用 * 修饰方法的时候,表示静态方法或者叫类方法 * 注意: * 1、 静态变量,在创建对象之前被初始化,或者说类在载入之前进行初始化 * 2、 静态变量被所有的对象所共享,属于公共变量 ,对象和类都可以直接调用 * 3、 成员变量放在堆中,而静态变量放在方法区中静态区; * 4、静态变量不能定义在静态方法中 * 5、静态方法可以在非静态方法中进行调用 * 6、静态方法中不能调用非静态方法 * 7、静态方法中不允许this调用般 * 8、一般工具类中的方法定义为static * * * */ public class StaticDemo { String name="zhangsan"; static int age=10; public static void test(){ System.out.println("static"); } public void test2(){ test(); } public static void main(String[] args){ StaticDemo staticDemo=new StaticDemo(); //使用对象进行调用 System.out.println(staticDemo.name); System.out.println(staticDemo.age); //使用类名进行调用 //System.out.println(StaticDemo.name); //System.out.println(StaticDemo.age); staticDemo.age=20; System.out.println(staticDemo.age); System.out.println(StaticDemo.age); staticDemo.age=30; System.out.println(staticDemo.age); System.out.println(StaticDemo.age); StaticDemo staticDemo1=new StaticDemo(); System.out.println(staticDemo1.age); } }
package fi.jjc.graphics.vertex; /** * Enumeration of all vertex types. * * @author Jens ┼kerblom */ public enum VertexMetaData { /** * 2D position. */ V2(2, 0, false, false), /** * 2D position and 1D texture coordinate. */ V2_T1(2, 1, false, false), /** * 2D position and 2D texture coordinate. */ V2_T2(2, 2, false, false), /** * 2D position and 3D texture coordinate. */ V2_T3(2, 3, false, false), /** * 2D position and 4D texture coordinate. */ V2_T4(2, 4, false, false), /** * 2D position and color. */ V2_C(2, 0, true, false), /** * 2D position, 1D texture coordinate and color. */ V2_T1_C(2, 1, true, false), /** * 2D position, 2D texture coordinate and color. */ V2_T2_C(2, 2, true, false), /** * 2D position, 3D texture coordinate and color. */ V2_T3_C(2, 3, true, false), /** * 2D position, 4D texture coordinate and color. */ V2_T4_C(2, 4, true, false), /** * 2D position and normal. */ V2_N(2, 0, false, true), /** * 2D position, 1D texture coordinate and normal. */ V2_T1_N(2, 1, false, true), /** * 2D position, 2D texture coordinate and normal. */ V2_T2_N(2, 2, false, true), /** * 2D position, 3D texture coordinate and normal. */ V2_T3_N(2, 3, false, true), /** * 2D position, 4D texture coordinate and normal. */ V2_T4_N(2, 4, false, true), /** * 2D position, color and normal. */ V2_C_N(2, 0, true, true), /** * 2D position, 1D texture coordinate, color and normal. */ V2_T1_C_N(2, 1, true, true), /** * 2D position, 2D texture coordinate, color and normal. */ V2_T2_C_N(2, 2, true, true), /** * 2D position, 3D texture coordinate, color and normal. */ V2_T3_C_N(2, 3, true, true), /** * 2D position, 4D texture coordinate, color and normal. */ V2_T4_C_N(2, 4, true, true), /** * 3D position. */ V3(3, 0, false, false), /** * 3D position and 1D texture coordinate. */ V3_T1(3, 1, false, false), /** * 3D position and 2D texture coordinate. */ V3_T2(3, 2, false, false), /** * 3D position and 3D texture coordinate. */ V3_T3(3, 3, false, false), /** * 3D position and 4D texture coordinate. */ V3_T4(3, 4, false, false), /** * 3D position and color. */ V3_C(3, 0, true, false), /** * 3D position, 1D texture coordinate and color. */ V3_T1_C(3, 1, true, false), /** * 3D position, 2D texture coordinate and color. */ V3_T2_C(3, 2, true, false), /** * 3D position, 3D texture coordinate and color. */ V3_T3_C(3, 3, true, false), /** * 3D position, 4D texture coordinate and color. */ V3_T4_C(3, 4, true, false), /** * 3D position and normal. */ V3_N(3, 0, false, true), /** * 3D position, 1D texture coordinate and normal. */ V3_T1_N(3, 1, false, true), /** * 3D position, 2D texture coordinate and normal. */ V3_T2_N(3, 2, false, true), /** * 3D position, 3D texture coordinate and normal. */ V3_T3_N(3, 3, false, true), /** * 3D position, 4D texture coordinate and normal. */ V3_T4_N(3, 4, false, true), /** * 3D position, color and normal. */ V3_C_N(3, 0, true, true), /** * 3D position, 1D texture coordinate, color and normal. */ V3_T1_C_N(3, 1, true, true), /** * 3D position, 2D texture coordinate, color and normal. */ V3_T2_C_N(3, 2, true, true), /** * 3D position, 3D texture coordinate, color and normal. */ V3_T3_C_N(3, 3, true, true), /** * 3D position, 4D texture coordinate, color and normal. */ V3_T4_C_N(3, 4, true, true), /** * 4D position. */ V4(4, 0, false, false), /** * 4D position and 1D texture coordinate. */ V4_T1(4, 1, false, false), /** * 4D position and 2D texture coordinate. */ V4_T2(4, 2, false, false), /** * 4D position and 3D texture coordinate. */ V4_T3(4, 3, false, false), /** * 4D position and 4D texture coordinate. */ V4_T4(4, 4, false, false), /** * 4D position and color. */ V4_C(4, 0, true, false), /** * 4D position, 1D texture coordinate and color. */ V4_T1_C(4, 1, true, false), /** * 4D position, 2D texture coordinate and color. */ V4_T2_C(4, 2, true, false), /** * 4D position, 3D texture coordinate and color. */ V4_T3_C(4, 3, true, false), /** * 4D position, 4D texture coordinate and color. */ V4_T4_C(4, 4, true, false), /** * 4D position and normal. */ V4_N(4, 0, false, true), /** * 4D position, 1D texture coordinate and normal. */ V4_T1_N(4, 1, false, true), /** * 4D position, 2D texture coordinate and normal. */ V4_T2_N(4, 2, false, true), /** * 4D position, 3D texture coordinate and normal. */ V4_T3_N(4, 3, false, true), /** * 4D position, 4D texture coordinate and normal. */ V4_T4_N(4, 4, false, true), /** * 4D position, color and normal. */ V4_C_N(4, 0, true, true), /** * 4D position, 1D texture coordinate, color and normal. */ V4_T1_C_N(4, 1, true, true), /** * 4D position, 2D texture coordinate, color and normal. */ V4_T2_C_N(4, 2, true, true), /** * 4D position, 3D texture coordinate, color and normal. */ V4_T3_C_N(4, 3, true, true), /** * 4D position, 4D texture coordinate, color and normal. */ V4_T4_C_N(4, 4, true, true); /** * Dimension of position. */ private final int vDim; /** * Dimension of texture coordinate, or 0 if no texture coordinate is associated. */ private final int tDim; /** * Has color flag. */ private final boolean colors; /** * Has normal flag. */ private final boolean normals; /** * @param vDim * dimension of position. * @param tDim * dimension of texture coordinate, or zero if vertex has no coordinates. * @param colors * true if vertex has color. * @param normals * true if vertex has normal. */ private VertexMetaData(int vDim, int tDim, boolean colors, boolean normals) { this.vDim = vDim; this.tDim = tDim; this.colors = colors; this.normals = normals; } /** * @return dimension of position. */ public final int getPosDim() { return this.vDim; } /** * @return dimension of position, or 0 if vertex has no texture coordinate. */ public final int getTexDim() { return this.tDim; } /** * @return true if vertex has color. */ public final boolean hasColors() { return this.colors; } /** * @return true if vertex has normal. */ public final boolean hasNormals() { return this.normals; } }
package com.hiwes.cores.thread.thread3.Thread0218; /** * 假死。线程进入Waitting等待状态,如果所有线程都进入等待状态,程序就不再执行任何业务功能。 * 出现假死的主要原因:有可能是因为连续唤醒同类。 */ public class MyThread14 extends Thread { private P14 p; public MyThread14(P14 p) { super(); this.p = p; } @Override public void run() { while (true) { p.setValue(); } } } class MyThread14_2 extends Thread { private C14 c; public MyThread14_2(C14 c) { super(); this.c = c; } @Override public void run() { c.getValue(); } } class P14 { private String lock; public P14(String lock) { super(); this.lock = lock; } public void setValue() { try { synchronized (lock) { while (!ValueObject14.value.equals("")) { System.out.println("生产者 " + Thread.currentThread().getName() + " waiting了。※"); lock.wait(); } System.out.println("生产者 " + Thread.currentThread().getName() + " Runnable了。"); String value = System.currentTimeMillis() + "_" + System.nanoTime(); ValueObject14.value = value; // lock.notify(); lock.notifyAll(); // 不止唤醒同类,异类也会唤醒。 } } catch (InterruptedException e) { e.printStackTrace(); } } } class C14 { private String lock; public C14(String lock) { super(); this.lock = lock; } public void getValue() { try { synchronized (lock) { while (ValueObject14.value.equals("")) { System.out.println("消费者 " + Thread.currentThread().getName() + " wating了.✨"); lock.wait(); } System.out.println("消费者 " + Thread.currentThread().getName() + " Runnable了."); ValueObject14.value = ""; // lock.notify(); lock.notifyAll(); } } catch (InterruptedException e) { e.printStackTrace(); } } } class ValueObject14 { public static String value = ""; } class Run14 { public static void main(String[] args) throws InterruptedException { String lock = new String(""); P14 p = new P14(lock); C14 c = new C14(lock); MyThread14[] pThread = new MyThread14[2]; MyThread14_2[] cThread = new MyThread14_2[2]; for (int i = 0; i < 2; i++) { pThread[i] = new MyThread14(p); pThread[i].setName("生产者 " + (i + 1)); cThread[i] = new MyThread14_2(c); cThread[i].setName("消费者 " + (i + 1)); pThread[i].start(); cThread[i].start(); } Thread.sleep(5000); Thread[] threadArray = new Thread[Thread.currentThread().getThreadGroup().activeCount()]; Thread.currentThread().getThreadGroup().enumerate(threadArray); for (int i = 0; i < threadArray.length; i++) { System.out.println(threadArray[i].getName() + " " + threadArray[i].getState()); } } }
package com.fleet.restdocs.controller; import com.fleet.restdocs.entity.User; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/user") public class UserController { @CrossOrigin @RequestMapping(value = "/insert") public boolean insert(@RequestBody User user) { return true; } @RequestMapping(value = "/delete") public boolean delete(@RequestParam Long id) { return true; } @CrossOrigin @RequestMapping(value = "/update") public boolean update(@RequestBody User user) { return true; } @CrossOrigin @RequestMapping(value = "/get") public User get(@RequestParam Long id) { User user = new User(); user.setId(1L); user.setName("fleet"); return user; } }
package com.vilio.fms.fileLoad.controller; import com.vilio.fms.fileLoad.service.FileUploadService; import com.vilio.fms.util.CommonUtil; import com.vilio.fms.util.ReturnCode; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.context.ServletContextAware; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by zhuxu on 2017/1/13. */ @Controller("fileUploadController") public class FileUploadController implements ServletContextAware { private static Logger logger = Logger.getLogger(FileUploadController.class); @Resource FileUploadService fileUploadService; //Spring这里是通过实现ServletContextAware接口来注入ServletContext对象 private ServletContext servletContext; public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; } @RequestMapping(value = "/api/fileLoad/uploadFile",method = RequestMethod.POST) @ResponseBody public Map uploadFile(HttpServletResponse rsp,HttpServletRequest rqs,@RequestParam("file") MultipartFile[] files) throws Exception{ Integer length = null == files ? -1 : files.length; String filePath = rqs.getParameter("filePath"); logger.info("文件上传(FileUploadController.uploadFile)被调用开始,入参:length = " + length + ",filePath = " + filePath); Map param = new HashMap(); param.put("files",files); param.put("filePath",filePath); Map result = null; try { CommonUtil.dealEmpty2Null(param); result = fileUploadService.uploadFile(param); }catch (Exception e){ logger.error("系统异常:",e); result.put("returnCode", ReturnCode.SYSTEM_EXCEPTION); } logger.info("文件上传(FileUploadController.uploadFile),输出结果:" + result); return result; } @RequestMapping(value = "/api/fileLoad/zipAndUploadFile",method = RequestMethod.POST) @ResponseBody public Map zipAndUploadFile(HttpServletResponse rsp,HttpServletRequest rqs,@RequestParam("file") MultipartFile[] files) throws Exception{ logger.info("文件压缩并上传(FileUploadController.zipAndUploadFile)被调用开始,入参:" + "" ); Map param = new HashMap(); String filePath = rqs.getParameter("filePath"); param.put("files",files); param.put("filePath",filePath); Map result = null; try { CommonUtil.dealEmpty2Null(param); result = fileUploadService.zipAndUploadFile(param); }catch (Exception e){ logger.error("系统异常:",e); result.put("returnCode", ReturnCode.SYSTEM_EXCEPTION); } logger.info("文件压缩并上传(FileUploadController.zipAndUploadFile),输出结果:" + result); return result; } }
/* * Copyright 2013 Cloudera Inc. * * 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.kitesdk.morphline.useragent; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.kitesdk.morphline.api.Command; import org.kitesdk.morphline.api.CommandBuilder; import org.kitesdk.morphline.api.MorphlineCompilationException; import org.kitesdk.morphline.api.MorphlineContext; import org.kitesdk.morphline.api.Record; import org.kitesdk.morphline.base.AbstractCommand; import org.kitesdk.morphline.base.Configs; import org.kitesdk.morphline.base.Metrics; import org.kitesdk.morphline.base.Validator; import ua_parser.Client; import ua_parser.Parser; import com.codahale.metrics.Meter; import com.google.common.base.Preconditions; import com.google.common.io.Closeables; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; /** * Command that parses user agent strings and returns structured higher level data like user agent * family, operating system, version, and device type, using the underlying API and regexes.yaml * BrowserScope database from https://github.com/tobie/ua-parser. */ public final class UserAgentBuilder implements CommandBuilder { @Override public Collection<String> getNames() { return Collections.singletonList("userAgent"); } @Override public Command build(Config config, Command parent, Command child, MorphlineContext context) { return new UserAgent(this, config, parent, child, context); } /////////////////////////////////////////////////////////////////////////////// // Nested classes: /////////////////////////////////////////////////////////////////////////////// private static final class UserAgent extends AbstractCommand { private final String inputFieldName; private final List<Mapping> mappings = new ArrayList(); public UserAgent(CommandBuilder builder, Config config, Command parent, Command child, MorphlineContext context) { super(builder, config, parent, child, context); this.inputFieldName = getConfigs().getString(config, "inputField"); String databaseFile = getConfigs().getString(config, "database", null); int cacheCapacity = getConfigs().getInt(config, "cacheCapacity", 1000); String nullReplacement = getConfigs().getString(config, "nullReplacement", ""); Parser parser; try { if (databaseFile == null) { parser = new Parser(); } else { InputStream in = new BufferedInputStream(new FileInputStream(databaseFile)); try { parser = new Parser(in); } finally { Closeables.closeQuietly(in); } } } catch (IOException e) { throw new MorphlineCompilationException("Cannot parse UserAgent database: " + databaseFile, config, e); } Meter numCacheHitsMeter = isMeasuringMetrics() ? getMeter(Metrics.NUM_CACHE_HITS) : null; Meter numCacheMissesMeter = isMeasuringMetrics() ? getMeter(Metrics.NUM_CACHE_MISSES) : null; Config outputFields = getConfigs().getConfig(config, "outputFields", ConfigFactory.empty()); for (Map.Entry<String, Object> entry : new Configs().getEntrySet(outputFields)) { mappings.add( new Mapping( entry.getKey(), entry.getValue().toString().trim(), parser, new BoundedLRUHashMap(cacheCapacity), nullReplacement, config, numCacheHitsMeter, numCacheMissesMeter )); } validateArguments(); } @Override protected boolean doProcess(Record record) { for (Object value : record.get(inputFieldName)) { Preconditions.checkNotNull(value); String stringValue = value.toString().trim(); for (Mapping mapping : mappings) { mapping.apply(record, stringValue); } } // pass record to next command in chain: return super.doProcess(record); } } /////////////////////////////////////////////////////////////////////////////// // Nested classes: /////////////////////////////////////////////////////////////////////////////// private static final class Mapping { private final String fieldName; private final List components = new ArrayList(); private final Parser parser; private final Map<String, String> cache; private final String nullReplacement; private final Meter numCacheHitsMeter; private final Meter numCacheMissesMeter; private static final String START_TOKEN = "@{"; private static final char END_TOKEN = '}'; public Mapping(String fieldName, String expression, Parser parser, Map<String, String> cache, String nullReplacement, Config config, Meter numCacheHitsMeter, Meter numCacheMissesMeter) { this.fieldName = fieldName; this.parser = parser; this.cache = cache; Preconditions.checkNotNull(nullReplacement); this.nullReplacement = nullReplacement; this.numCacheHitsMeter = numCacheHitsMeter; this.numCacheMissesMeter = numCacheMissesMeter; int from = 0; while (from < expression.length()) { int start = expression.indexOf(START_TOKEN, from); if (start < 0) { // START_TOKEN not found components.add(expression.substring(from, expression.length())); return; } else { // START_TOKEN found if (start > from) { components.add(expression.substring(from, start)); } int end = expression.indexOf(END_TOKEN, start + START_TOKEN.length()); if (end < 0) { throw new IllegalArgumentException("Missing closing token: " + END_TOKEN); } String ref = expression.substring(start + START_TOKEN.length(), end); components.add(new Validator<Component>().validateEnum( config, ref, Component.class)); from = end + 1; } } } public void apply(Record record, String userAgent) { String result = cache.get(userAgent); if (result == null) { // cache miss if (numCacheMissesMeter != null) { numCacheMissesMeter.mark(); } result = extract(userAgent); cache.put(userAgent, result); } else if (numCacheHitsMeter != null) { numCacheHitsMeter.mark(); } record.put(fieldName, result); } private String extract(String userAgent) { Client client = parser.parse(userAgent); StringBuilder buf = new StringBuilder(); String lastString = null; for (Object component : components) { assert component != null; if (component instanceof Component) { String result = resolve((Component)component, client); if (result == null) { result = nullReplacement; } // suppress preceding string separator if component resolves to empty string: if (result.length() > 0 && lastString != null) { buf.append(lastString); } buf.append(result); lastString = null; } else { lastString = (String)component; } } if (lastString != null) { buf.append(lastString); } return buf.toString(); } private String resolve(Component component, Client client) { switch (component) { case ua_family : { return client.userAgent.family; } case ua_major : { return client.userAgent.major; } case ua_minor : { return client.userAgent.minor; } case ua_patch : { return client.userAgent.patch; } case os_family : { return client.os.family; } case os_major : { return client.os.major; } case os_minor : { return client.os.minor; } case os_patch : { return client.os.patch; } case os_patch_minor : { return client.os.patchMinor; } case device_family : { return client.device.family; } default : { throw new IllegalArgumentException(); } } } } /////////////////////////////////////////////////////////////////////////////// // Nested classes: /////////////////////////////////////////////////////////////////////////////// private static enum Component { ua_family, ua_major, ua_minor, ua_patch, os_family, os_major, os_minor, os_patch, os_patch_minor, device_family } /////////////////////////////////////////////////////////////////////////////// // Nested classes: /////////////////////////////////////////////////////////////////////////////// private static final class BoundedLRUHashMap<K,V> extends LinkedHashMap<K,V> { private final int capacity; private BoundedLRUHashMap(int capacity) { super(16, 0.5f, true); this.capacity = capacity; } @Override protected boolean removeEldestEntry(Map.Entry eldest) { return size() > capacity; } } }
package model.cursor; import java.awt.AWTException; import java.awt.Point; import java.awt.Robot; import java.awt.event.InputEvent; import model.Calibration; import model.platform.Blob; import model.platform.PlatformReader; public class MouseCursor extends Cursor { private boolean seen = false; private Robot robot; public MouseCursor(PlatformReader reader, Blob blob, Calibration calibration) { super(reader, blob, calibration); try { this.robot = new Robot(); } catch (AWTException e) { e.printStackTrace(); System.exit(0); } } @Override protected void handleMouseUpdate(Point mouse) { if (!validPoint(mouse)) { if (seen) { this.releaseMouse(); seen = false; } return; } this.moveMouse(mouse); if (!seen) { this.pressMouse(); seen = true; } } protected boolean validPoint(Point mouse) { return (int) mouse.getX() != 1023 && (int) mouse.getY() != 1023; } protected void moveMouse(Point mouse) { if (this.getCalibration() != null) { mouse = this.getCalibration().translatePoint(mouse); } int x = (int) mouse.getX(); int y = (int) mouse.getY(); this.robot.mouseMove(x, y); } protected void pressMouse() { this.getRobot().mousePress(InputEvent.BUTTON1_MASK); } protected void releaseMouse() { this.getRobot().mouseRelease(InputEvent.BUTTON1_MASK); } protected Robot getRobot() { return this.robot; } }
package com.rx.rxmvvmlib.ui.base; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.view.Window; import com.rx.rxmvvmlib.R; public class RxBaseLoadingDialog extends Dialog { public Context context; private int layoutId; public RxBaseLoadingDialog(Context context) { this(context, R.layout.loading_dialog, false); } public RxBaseLoadingDialog(Context context, int layoutId, boolean cancelable) { super(context, R.style.loading_dialog); this.context = context; if (layoutId == 0) { layoutId = R.layout.loading_dialog; } this.layoutId = layoutId; setCancelable(cancelable); setCanceledOnTouchOutside(cancelable); Window window = getWindow(); window.setWindowAnimations(R.style.LoadingDialogWindowStyle); } protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(layoutId); } }
package com.akhil.todo.controllers; import com.akhil.todo.models.ToDo; import com.akhil.todo.services.NotificationService; import com.akhil.todo.services.ToDoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import java.security.Principal; import java.util.Map; import java.util.Set; @RestController @RequestMapping("/todo/v1/") public class TodoController { @Autowired private ToDoService toDoService; @Autowired private NotificationService notificationService; @PostMapping("/create") public ResponseEntity<ToDo> createNewToDo(@Validated @RequestBody ToDo toDo) throws NoSuchFieldException { return ResponseEntity.ok(toDoService.createNewEntry(toDo)); } @GetMapping("/all") public ResponseEntity<Map> createNewToDo(Principal principal){ return ResponseEntity.ok(toDoService.getAll(principal.getName())); } @PutMapping("/update") public ResponseEntity<ToDo> updateToDo(@Validated @RequestBody ToDo toDo) throws NoSuchFieldException { return ResponseEntity.ok(toDoService.updateNewEntry(toDo)); } @GetMapping("/{id}") public ResponseEntity<ToDo> getById(@PathVariable("id") int id, Principal principal){ return ResponseEntity.ok(toDoService.getById(id, principal.getName())); } @GetMapping("/alerts") public ResponseEntity<Set<ToDo>> getAlerts(Principal principal){ return ResponseEntity.ok(notificationService.getToDoList(principal.getName())); } }
package org.alienideology.jcord.event.message.dm; import org.jetbrains.annotations.NotNull; import org.alienideology.jcord.handle.channel.IPrivateChannel; import org.alienideology.jcord.internal.object.channel.PrivateChannel; /** * @author AlienIdeology */ public interface IPrivateMessageEvent { @NotNull IPrivateChannel getPrivateChannel(); }
package com.xxzp.xxzp.service.yearofholiday; import com.xxzp.xxzp.common.utils.DateUtils; import com.xxzp.xxzp.entities.YearOfHolidayEntity; import com.xxzp.xxzp.model.HolidayBO; import com.xxzp.xxzp.repositories.YearOfHolidayRepository; import com.xxzp.xxzp.rpc.GetHolidayRpc; import java.sql.Timestamp; import java.time.DayOfWeek; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.Month; import java.time.temporal.ChronoUnit; import java.util.EnumSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; @Service public class HolidayProcessImpl implements HolidayProcess { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Resource private YearOfHolidayRepository yearOfHolidayRepository; @Resource private GetHolidayRpc getHolidayRpc; private static final int YEARS_COUNT = 2; @Override public void getHolidayTask() { final LocalDate localDate = LocalDate.now(); for (int i = 0; i < YEARS_COUNT; i++) { LocalDate newLocalDate = localDate.plusYears(i); holidayHandle(newLocalDate); } } private void holidayHandle(LocalDate localDate) { List<HolidayBO> holidays = getHolidays(localDate); List<LocalDate> allDays = getAllDayOfYear(localDate); if (CollectionUtils.isEmpty(allDays)) { logger.error("生成节假日失败"); } Set<String> holidaySet = holidays.stream().filter(h -> h.getStatus().equals(HOLIDAY)) .map(HolidayBO::getDate).collect(Collectors.toSet()); Set<String> workdaySet = holidays.stream().filter(h -> h.getStatus().equals(WORKDAY)) .map(HolidayBO::getDate).collect(Collectors.toSet()); List<YearOfHolidayEntity> entities = allDays.stream() .map(d -> setHolidayEntity(d, isHoliday(d, holidaySet, workdaySet))) .collect(Collectors.toList()); entities.forEach(entity -> yearOfHolidayRepository .saveByUpdate(entity.getHolidayStatus(), entity.getYearOfDate())); } private boolean isHoliday(LocalDate localDate, Set<String> holidays, Set<String> workday) { String date = DateUtils.YEAR_MONTH_DAY_DATE_FORMATTER.format(localDate); if (holidays.contains(date)) { return true; } else if (workday.contains(date)) { return false; } else { Set<DayOfWeek> weekendSet = EnumSet.of(DayOfWeek.SATURDAY, DayOfWeek.SUNDAY); return weekendSet.contains(localDate.getDayOfWeek()); } } private YearOfHolidayEntity setHolidayEntity(LocalDate localDate, boolean isHoliday) { YearOfHolidayEntity entity = new YearOfHolidayEntity(); entity.setHolidayStatus(isHoliday ? HOLIDAY : WORKDAY); entity.setYearOfDate(Timestamp.valueOf(LocalDateTime.of(localDate, LocalTime.MIN))); return entity; } private List<HolidayBO> getHolidays(LocalDate localDate) { List<String> months = getAllMonthOfYear(localDate); return months.stream() .flatMap(m -> getHolidayRpc.getDates(m).stream()) .collect(Collectors.toList()); } private List<String> getAllMonthOfYear(LocalDate localDate) { LocalDate beginMonth = LocalDate .of(localDate.getYear(), Month.JANUARY, LocalDate.MIN.getMonthValue()); LocalDate endMonth = LocalDate .of(localDate.getYear(), Month.DECEMBER, LocalDate.MAX.getMonthValue()); return Stream.iterate(beginMonth, date -> date.plusMonths(1)) .limit(ChronoUnit.MONTHS.between(beginMonth, endMonth) + 1) .map(DateUtils.YEAR_MONTH_DATE_FORMATTER::format) .collect(Collectors.toList()); } private List<LocalDate> getAllDayOfYear(LocalDate localDate) { LocalDate beginDate = LocalDate .of(localDate.getYear(), Month.JANUARY, LocalDate.MIN.getDayOfMonth()); LocalDate endDate = LocalDate .of(localDate.getYear(), Month.DECEMBER, LocalDate.MAX.getDayOfMonth()); return Stream.iterate(beginDate, date -> date.plusDays(1)) .limit(ChronoUnit.DAYS.between(beginDate, endDate) + 1) .collect(Collectors.toList()); } }
package com.saven.batch.domain.util; import com.saven.batch.domain.Column; import java.math.BigDecimal; import java.math.RoundingMode; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; /** * Created by nrege on 1/30/2017. */ public class ColumnUtils { public static double getDoubleValue(Column column) { if(column.getClazz().isAssignableFrom(Instant.class)) { Instant instant = (Instant) column.getVal(); LocalDateTime time = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); return time.getMinute(); } else if(column.getClazz().isAssignableFrom(Integer.class)) { Integer integer = (Integer) column.getVal(); return integer; } else if(column.getClazz().isAssignableFrom(Double.class)) { Double duble = (Double) column.getVal(); return round(duble, 2); } else if(column.getClazz().isAssignableFrom(String.class)) { String string = (String) column.getVal(); return Double.valueOf(string); } else { return 0; } } public static double round(double value, int places) { if (places < 0) throw new IllegalArgumentException(); BigDecimal bd = new BigDecimal(value); bd = bd.setScale(places, RoundingMode.HALF_UP); return bd.doubleValue(); } }
package cn.tedu.search.controller; import cn.tedu.search.service.IndexService; import com.jt.common.pojo.MyOrder; import com.jt.common.vo.SysResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping("search/manage") public class IndexController { @Autowired private IndexService is; //访问该接口,创建一次索引文件 @RequestMapping("create/{indexName}") public SysResult createIndex(@PathVariable String indexName){ try{ is.createIndex(indexName); return SysResult.ok(); }catch(Exception e){ e.printStackTrace(); return SysResult.build(201,"",null); } } //实现match_query搜索功能 @RequestMapping("query") public List<MyOrder> query(String text){ System.out.println("controller"); return is.query(text); } }
package pages; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.How; import org.openqa.selenium.support.PageFactory; import wdMethods.ProjectMethods; public class MyLeadpage extends ProjectMethods { public MyLeadpage() { PageFactory.initElements(driver, this); } @FindBy(how = How.LINK_TEXT, using = "Create Lead") private WebElement createleads; public Createleadpage clickCreateleadbutton() { click(createleads); return new Createleadpage(); } @FindBy(how = How.LINK_TEXT, using = "Find Leads") private WebElement eleFindleads; public Findpage clickFindleadbutton() { click(eleFindleads); return new Findpage(); } @FindBy(how = How.LINK_TEXT, using = "Merge Leads") private WebElement elemerge; public MergeLeadpage clickmerge() { click(elemerge); return new MergeLeadpage(); } }
import java.util.ArrayList; /** * Used by requirements to store the framework for a Literal. * For checking against a WorldLiteral requires pairing up the * placeholder actors with actual actors. * @author cdgira * */ public class RequirementLiteral { /** * The id should match the WorldLiteral Id it is mirroring. */ int m_id; ArrayList<Actor> m_actors = new ArrayList<Actor>(); }
package com.tencent.xweb.x5; import android.webkit.JavascriptInterface; import java.util.HashMap; import java.util.concurrent.atomic.AtomicInteger; public class h$a { private static final AtomicInteger vDJ = new AtomicInteger(1); HashMap<Integer, byte[]> geu = new HashMap(); @JavascriptInterface public final int getNativeBufferId() { int i; int i2; do { i = vDJ.get(); i2 = i + 1; if (i2 > 16777215) { i2 = 1; } } while (!vDJ.compareAndSet(i, i2)); return i; } @JavascriptInterface public final void setNativeBuffer(int i, byte[] bArr) { this.geu.put(Integer.valueOf(i), bArr); } @JavascriptInterface public final byte[] getNativeBuffer(int i) { return (byte[]) this.geu.remove(Integer.valueOf(i)); } }
package com.ioc.annotations; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @author Ashutosh Bane * */ public class SpringMainApp { /** * @param args */ public static void main(String[] args) { // load the spring configuration file ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); /** * Bean id defined */ // retrieve bean from spring container ICountry myCountry = context.getBean("theIndia", ICountry.class); // call methods on the bean System.out.println("The one with bean id mentioned"); System.out.println(myCountry.getCapital()); /** * Deafult bean id */ // retrieve bean from spring container ICountry theKiwis = context.getBean("newZealand", ICountry.class); // call methods on the bean System.out.println("\nThe one with default bean id"); System.out.println(theKiwis.getCapital()); // close the context context.close(); } }
package com.example.john.proxie.LoginActivities; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.example.john.proxie.R; import com.example.john.proxie.SettingsActivities.SettingsActivity; public class LoginActivity extends Activity { private boolean newUser; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); PreferenceManager.setDefaultValues(this, R.xml.preferences, false); SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this); String savedUsername = sharedPref.getString("usernameKey", "none"); if(savedUsername.equalsIgnoreCase("none")){ Toast.makeText(getApplicationContext(), "New user", Toast.LENGTH_LONG).show(); newUser = true; } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_login, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. switch (item.getItemId()) { case R.id.mssgaction_bar_settings_button: Intent intent = new Intent(this, SettingsActivity.class); this.startActivity(intent); break; default: return super.onOptionsItemSelected(item); } return true; } public void exitActivity(View view) { EditText usernameView = (EditText)findViewById(R.id.userNameloginfieldid); usernameView.requestFocus(); SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this); sharedPref.edit().putString("usernameKey", usernameView.getText().toString()).apply(); Intent intent = new Intent(this, StartActivity.class); startActivity(intent); finish(); } }
package com.example.fireapp; import android.annotation.SuppressLint; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.HashMap; public class Profile extends AppCompatActivity { private Button updateProfile; private EditText name, surname, emailAddress, gender, age; private DatabaseProfile userdata; @SuppressLint("ResourceType") @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); name = findViewById(R.id.profileName); surname = findViewById(R.id.profileSurname); emailAddress = findViewById(R.id.profileEmail); gender = findViewById(R.id.profileGender); age = findViewById(R.id.profileAge); updateProfile = findViewById(R.id.updateProfile); Toolbar toolbar = findViewById(R.id.toolbar2); setSupportActionBar(toolbar); getSupportActionBar().setTitle("Calorie Count"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); setData(); } private void setData() { final DatabaseReference rootref; final String userid = getIntent().getStringExtra("loginUser"); rootref = FirebaseDatabase.getInstance().getReferenceFromUrl("https://fireapp-dc6ac.firebaseio.com/"); rootref.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { userdata = snapshot.child("profile").child(userid).getValue(DatabaseProfile.class); if(userdata == null) { Toast.makeText(Profile.this, "Profile Empty", Toast.LENGTH_SHORT).show(); } else { //sets data name.setText(userdata.getName()); surname.setText(userdata.getSurname()); emailAddress.setText(userdata.getGender()); gender.setText(userdata.getGender()); age.setText(userdata.getAge()); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); updateProfile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final String nameText = name.getText().toString(); final String surnameText = surname.getText().toString(); final String emailAddressText = emailAddress.getText().toString(); final String genderText = gender.getText().toString(); final String ageText = age.getText().toString(); rootref.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { if (!(snapshot.child("profile").child(userid).exists())) { //updates profile using hashmap HashMap<String, Object> profileDataMap = new HashMap<>(); profileDataMap.put("userid", userid); profileDataMap.put("name", nameText); profileDataMap.put("surname", surnameText); profileDataMap.put("email_address", emailAddressText); profileDataMap.put("gender", genderText); profileDataMap.put("age", ageText); rootref.child("profile").child(userid).updateChildren(profileDataMap).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Toast.makeText(Profile.this, R.string.profileUpdated, Toast.LENGTH_LONG).show(); } else { Toast.makeText(Profile.this, R.string.profileNotUpdated, Toast.LENGTH_LONG).show(); } } }); } else { HashMap<String, Object> profileDataMap = new HashMap<>(); profileDataMap.put("userid", userid); profileDataMap.put("name", nameText); profileDataMap.put("surname", surnameText); profileDataMap.put("email_address", emailAddressText); profileDataMap.put("gender", genderText); profileDataMap.put("age", ageText); rootref.child("profile").child(userid).updateChildren(profileDataMap).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Toast.makeText(Profile.this, R.string.profileUpdated, Toast.LENGTH_LONG).show(); } else { Toast.makeText(Profile.this, R.string.profileNotUpdated, Toast.LENGTH_LONG).show(); } } }); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); } }); } }
package test.main; public class MainClass04 { public static void main(String[] args) { // new int[5] 가 뭐지요? => {0,0,0,0,0} int[] nums=new int[5]; // new String[3] ? => {null, null, null} String[] names=new String[3]; //미리 만들어진 배열에 item 저장하기 nums[0]=10; nums[1]=20; nums[2]=30; names[0]="김구라"; names[1]="해골"; names[2]="원숭이"; } }
package RetailStore; public class Goods { public String goodsId; public String goodsName; public int goodsQuantity; public double goodsPrice; public void addGoods() { } public void removeGoods() { } public void orderGoods() { } public void updateGoods() { } }
import java.util.List; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Stream; import java.util.*; public class Assignment4Q3 { static void modifyValue(String name){ System.out.println(name+" is applying functional interface."); } static Integer Sum(List<Integer> l1){ return l1.stream() .mapToInt(Integer::intValue) .sum(); } static boolean display(int age) { if(age>=25) return true; else return false; } public static void main(String[] args) { Consumer<String> c1=Assignment4Q3::modifyValue; c1.accept("Raj"); Predicate<Integer> p1=Assignment4Q3::display; boolean b1=p1.test(24); System.out.println(b1); List<Integer> l1=new ArrayList<Integer>(); l1.add(1); l1.add(2); l1.add(4); Function<List<Integer>,Integer> fun=Assignment4Q3::Sum; int productvalue=fun.apply(l1); System.out.println(productvalue); Supplier<Integer> random=() -> new Random().nextInt(10); Stream.generate(random) .limit(5) .forEach(System.out::println); } }
package de.zarncke.lib.progress; /** * Indicates progress, both relative and absolute. */ public interface Progress { /** * @return number of items processed so far, always <= {@link #getTotal()} */ int getCount(); /** * @return total number of items to process */ int getTotal(); /** * @return already processed data volume in bytes */ long getVolume(); /** * @return total data volume to process in bytes */ long getTotalVolume(); /** * @return current duration in millis */ long getDuration(); /** * @return total duration in millis (known or expected) */ long getTotalDuration(); }
package com.awsec2; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests; @ContextConfiguration(locations={"/config/spring/applicationContext.xml"}) public class BaseJunitTest extends AbstractTransactionalJUnit4SpringContextTests{ }
import java.util.ArrayList; import javafx.application.Platform; import javafx.event.EventHandler; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.layout.Pane; import javafx.scene.shape.Rectangle; public class GameController implements Runnable{ Scene mS; Pane gB; ArrayList<Entity> es; Bot chr; double tls = System.currentTimeMillis(); Controller c; double cjv; double cdv; double yjv; double ydv; boolean running = true; public GameController(Pane p, Scene scene, Controller c) { mS = scene; gB = p; this.c = c; es = new ArrayList<Entity>(); chr = new Bot(this); aE(chr.root); mS.setOnKeyPressed(new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent event) { if(event.getCode() == KeyCode.SPACE) { chr.jump(); yjv = 1; new Thread() { @Override public void run() { try { Thread.sleep(10); } catch (InterruptedException e1) { e1.printStackTrace(); } while(chr.y < chr.ground) { try { Thread.sleep(10); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } yjv = 0; } }.start(); return; } else if(event.getCode() == KeyCode.DOWN) { ydv = 1; chr.duck(); new Thread() { @Override public void run() { try { Thread.sleep(10); } catch (InterruptedException e1) { e1.printStackTrace(); } while(chr.height < 30) { try { Thread.sleep(10); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } ydv = 0; } }.start(); } else if(event.getCode() == KeyCode.UP) { } } }); mS.setOnKeyReleased(new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent event) { } }); } @Override public void run() { startGameLoop(); } public Entity createObstacle(boolean isRock) { Entity e = new Entity(new Rectangle(20, 20)); e.setX(500); e.setY(isRock ? 290.0 : 265.0); e.bird = !isRock; e.setXSpeed(-2); e.setYSpeed(0); aE(e.root); es.add(e); return e; } public void startGameLoop() { while(true) { checkEntities(); if(System.currentTimeMillis() - tls > 1500) { if(Math.random() < .5) { createObstacle(false); }else if(Math.random() < .5) { createObstacle(true); } tls = System.currentTimeMillis(); } chr.doPhysics(); for(Entity e : es) { e.doPhysics(); } try { Thread.sleep(8); } catch (InterruptedException e1) { e1.printStackTrace(); } } } private void checkEntities() { for(int i = 0; i < es.size(); i++ ) { if(es.get(i).x - chr.x < 85) { if(!es.get(i).seen) { if(es.get(i).bird) { cdv = 1; } else { cjv = 1; } System.out.println(c.w[0][0] + " " + c.w[0][1] + " " + c.w[1][0] + " " + c.w[1][1] + " " + c.w[2][0] + " " + c.w[2][1] + " " + c.w[3][0] + " " + c.w[3][1]); double[] res = c.think(new double[] {cjv, cdv, yjv, ydv }); if(res[0] > 0) { chr.jump(); } if(res[1] > 0) { chr.duck(); } es.get(i).seen = true; } } else { cjv = 0; cdv = 0; } if(chr.checkCollision(es.get(i))) { System.out.println("COLLISION"); rE(es.get(i).root); es.remove(i); } else if(es.get(i).x < -100) { rE(es.get(i).root); es.remove(i); } } } /* * Removes an entity and discards it */ public void rE(Node e) { Platform.runLater(new Runnable() { @Override public void run() { gB.getChildren().remove(e); } }); } public void aE(Node e) { Platform.runLater(new Runnable() { @Override public void run() { gB.getChildren().add(e); } }); } }
package seng301.convert; import android.test.ActivityInstrumentationTestCase2; import android.widget.EditText; import android.widget.TextView; import com.robotium.solo.Solo; import java.text.DecimalFormat; public class ExtensiveTest extends ActivityInstrumentationTestCase2 { private Solo solo; public ExtensiveTest() { super(Conversion.class); } @Override public void setUp() throws Exception { solo = new Solo(getInstrumentation(), getActivity()); } @Override public void tearDown() throws Exception { solo.finishOpenedActivities(); } public void testFull() throws Exception{ solo.unlockScreen(); int vInputNumber = randomWithRange(0,999999); int vMulNumber = 88; Double vMulNumber2 = 0.0166666667; String vResult = Double.toString(roundDecimals(Double.valueOf(vInputNumber)*Double.valueOf(vMulNumber))); String vResult2 = Double.toString(roundDecimals(Double.valueOf(vInputNumber)*vMulNumber2)); solo.clickOnActionBarHomeButton(); solo.clickInList(2); EditText vEditTextInput2 = (EditText) solo.getView(R.id.radiusIn); String vInputNumber2 = String.valueOf(randomWithRange(0,999999)); String vResult3 = Double.toString(roundDecimals2(Double.valueOf(vInputNumber2)*Double.valueOf(vInputNumber2)*Math.PI)); solo.enterText(vEditTextInput2, String.valueOf(vInputNumber2)); solo.clickOnButton(1); assertTrue(solo.waitForText(vResult3)); solo.clickOnActionBarHomeButton(); solo.clickInList(4); int randomButton = randomWithRange(0,5); solo.clickOnButton(randomButton); buttonTest(randomButton); solo.clickOnActionBarHomeButton(); solo.clickInList(1); solo.setActivityOrientation(Solo.LANDSCAPE); solo.pressSpinnerItem(0, 4); solo.pressSpinnerItem(1, 4); EditText vEditTextInput = (EditText) solo.getView(R.id.inputText); solo.enterText(vEditTextInput, String.valueOf(vInputNumber)); solo.clickOnButton("Convert"); assertTrue(solo.searchText(vResult)); TextView result = (TextView) solo.getView(R.id.fourthValue); assertEquals(vResult2, result.getText().toString()); solo.clickOnActionBarHomeButton(); solo.clickInList(4); int randomButton2 = randomWithRange(0,5); solo.clickOnButton(randomButton2); buttonTest(randomButton2); solo.setActivityOrientation(Solo.PORTRAIT); solo.clickOnActionBarHomeButton(); solo.clickInList(2); EditText vEditTextInput3 = (EditText) solo.getView(R.id.lengthIn); EditText vEditTextInput4 = (EditText) solo.getView(R.id.widthIn); String vInputNumber3 = String.valueOf(randomWithRange(0,999999)); String vInputNumber4 = String.valueOf(randomWithRange(0,999999)); String vResult4 = Double.toString(roundDecimals2(Double.valueOf(vInputNumber3)*Double.valueOf(vInputNumber4))); solo.enterText(vEditTextInput3, String.valueOf(vInputNumber3)); solo.enterText(vEditTextInput4, String.valueOf(vInputNumber4)); solo.clickOnButton(0); assertTrue(solo.waitForText(vResult4)); } public double roundDecimals(double d) { DecimalFormat twoDForm = new DecimalFormat("#.##########E0"); return Double.valueOf(twoDForm.format(d)); } int randomWithRange(int min, int max) { int range = Math.abs(max - min) + 1; return (int)(Math.random() * range) + (min <= max ? min : max); } public double roundDecimals2(double d) { DecimalFormat twoDForm = new DecimalFormat("#.######E0"); return Double.valueOf(twoDForm.format(d)); } void buttonTest(int button){ switch (button){ case 0: solo.waitForFragmentByTag("Options",2000); assertEquals("#eeeeee", Conversion.bgColor); break; case 1: solo.waitForFragmentByTag("Options",2000); assertEquals("#ff9955", Conversion.bgColor); break; case 2: solo.waitForFragmentByTag("Options",2000); assertEquals("#a3cfff", Conversion.bgColor); break; case 3: solo.waitForFragmentByTag("Options",2000); assertEquals("#b7fec5", Conversion.bgColor); break; case 4: solo.waitForFragmentByTag("Options",2000); assertEquals("#ff7373", Conversion.bgColor); break; case 5: solo.waitForFragmentByTag("Options",2000); assertEquals("#ffffff", Conversion.bgColor); break; } } }
package dev.federicocapece.jdaze; import javax.swing.event.MouseInputListener; import java.awt.event.*; import java.util.HashSet; /** * <pre> * Input manager for the game engine * </pre> */ public final class Input { //#region Private status data /** * The set of keys that are currently pressed, * do not touch this directly */ private static HashSet<Integer> keysDown = new HashSet<>(); /** * The set of mouse buttons that are currently pressed, * do not touch this directly */ private static HashSet<Integer> mouseButtonsDown = new HashSet<>(); /** * The float representing the mouse wheel rotation in the last frame. */ private static float mouseWheelRotation = 0f; private static final Vector mousePosition = new Vector(0,0); //#endregion //#region Engine methods/listener /** * Internal method for resetting the mouse wheel status, called after each update */ protected static void mouseWheelReset() { mouseWheelRotation = 0; } //#endregion //#region Listeners /** * The KeyListener that will send the Key data to the Input manager. * It is automatically registered on the renderer canvas */ protected static final KeyListener keyListener = new KeyListener() { @Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { keysDown.add((int)e.getKeyCode()); } @Override public void keyReleased(KeyEvent e) { keysDown.remove((int)e.getKeyCode()); } }; /** * The MouseWheelListener that will send the mouse move and click data to the Input manager. * It is automatically registered on the renderer canvas */ protected static final MouseInputListener mouseInputListener = new MouseInputListener() { @Override public void mouseClicked(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { mouseButtonsDown.add(e.getButton()); } @Override public void mouseReleased(MouseEvent e) { mouseButtonsDown.remove(e.getButton()); } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } @Override public void mouseDragged(MouseEvent e) { mousePosition.set(e.getX(), e.getY()); } @Override public void mouseMoved(MouseEvent e) { mousePosition.set(e.getX(), e.getY()); } }; /** * The MouseWheelListener that will send the mouse wheel data to the Input manager. * It is automatically registered on the renderer canvas */ protected static final MouseWheelListener mouseWheelListener = new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { mouseWheelRotation -= e.getPreciseWheelRotation(); } }; //#endregion //#region static methods for external use /** * Use this method inside the update() to check if a key is pressed and react to it. * @param keyCode The keycode as integer, use the constants in: java.awt.KeyEvent * @return true/false */ public static boolean isKeyDown(int keyCode){ return keysDown.contains(keyCode); } /** * Use this method inside the update() to check if a key is NOT pressed and react to it. * NOTE: this actually does !isKeyDown, so it is not recommended, just use !isKeyDown * @param keyCode The keycode as integer, use the constants in: java.awt.KeyEvent * @return true/false */ public static boolean isKeyUp(int keyCode){ return !isKeyDown(keyCode); } /** * Use this method inside the update() to check if the mouse wheel was rotated. * This method will return a float: * <pre> * positive = up * negative = down * zero = no rotation * </pre> * NOTE: the rotation of the mouse wheel get reset after the update, * so you shouldn't use it in combination with deltaTime. * @return a float representing the mouseWheel rotation */ public static float getMouseWheelRotation(){ return mouseWheelRotation; } /** * Use this method inside the update() to check if a mouse button is pressed and react to it. * @param buttonCode the MouseButton code as integer, use constants in: java.awt.MouseEvent * @return true/false according to the mouse button status */ public static boolean isMouseDown(int buttonCode) { return mouseButtonsDown.contains(buttonCode); } /** * Get the mouse position as a Vector. * The mouse position is referred to the canvas, not to the world position. * NOTE: You could theoretically store it inside your class * and reuse it as it's directly updated by the Input Manager. * @return the Vector representing the mouse position */ public static Vector getMousePosition(){ return mousePosition; } /** * Get the mouse position inside the world coordinate system as a Vector. * This is calculated every time you call it by using the Camera position, * so it's recommended to store it and not to call this multiple time for every update. * @return the Vector representing the mouse position */ public static Vector getMouseWorldPosition(){ return Engine.camera.canvasToWorldPoint(mousePosition); } public static Vector getWASDVector(){ Vector movement = Vector.ZERO(); if(isKeyDown(KeyEvent.VK_S)){ movement.sumUpdate(Vector.DOWN()); }else if(isKeyDown(KeyEvent.VK_W)) { movement.sumUpdate(Vector.UP()); } if(isKeyDown(KeyEvent.VK_A)){ movement.sumUpdate(Vector.LEFT()); }else if(isKeyDown(KeyEvent.VK_D)) { movement.sumUpdate(Vector.RIGHT()); } return movement.normalize(); } public static Vector getArrowsVector(){ Vector movement = Vector.ZERO(); if(isKeyDown(KeyEvent.VK_UP)){ movement.sumUpdate(Vector.DOWN()); }else if(isKeyDown(KeyEvent.VK_DOWN)) { movement.sumUpdate(Vector.UP()); } if(isKeyDown(KeyEvent.VK_LEFT)){ movement.sumUpdate(Vector.LEFT()); }else if(isKeyDown(KeyEvent.VK_RIGHT)) { movement.sumUpdate(Vector.RIGHT()); } return movement.normalize(); } //#endregion }
package com.example.demo.reviewimage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class ReviewimageService { private ReviewimageRepository reviewimageRepository; @Autowired public ReviewimageService(ReviewimageRepository repository) { this.reviewimageRepository = repository; } public List<Reviewimage> retrieveReviewimage() { return (List<Reviewimage>) reviewimageRepository.findAll(); } public Optional<Reviewimage> retrieveReviewimage(Long id) { return reviewimageRepository.findById(id); } public List<Reviewimage> retrieveReviewimage(String FullName) { return null; } public Reviewimage createReviewimage(Reviewimage reviewimage) { return reviewimageRepository.save(reviewimage); } public Optional<Reviewimage> updateReviewimage(Long id, Reviewimage reviewimage) { Optional<Reviewimage> reviewimageOptional = reviewimageRepository.findById(id); if(!reviewimageOptional.isPresent()) { return reviewimageOptional; } return Optional.of(reviewimageRepository.save(reviewimage)); } public boolean deleteReviewimage(Long id) { try { reviewimageRepository.deleteById(id); return true; } catch (EmptyResultDataAccessException e) { return false; } } }