text
stringlengths
10
2.72M
package com.pangpang6.hadoop.kafka; import org.apache.kafka.clients.admin.AdminClient; import org.apache.kafka.clients.admin.AdminClientConfig; import org.apache.kafka.clients.admin.KafkaAdminClient; import java.util.Properties; public class Test { public static void main(String[] args) { Properties properties = new Properties(); properties.setProperty(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.0.106:9092"); AdminClient adminClient = KafkaAdminClient.create(properties); System.out.println(); } }
/** * original(c) zhuoyan company * projectName: java-design-pattern * fileName: ObserverTest.java * packageName: cn.zy.pattern.observer * date: 2018-12-27 20:34 * history: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ package cn.zy.pattern.observer; import org.junit.Test; /** * @version: V1.0 * @author: ending * @className: ObserverTest * @packageName: cn.zy.pattern.observer * @description: 观察者测试类 * @data: 2018-12-27 20:34 **/ public class ObserverTest { @Test public void simpleTest(){ Play play = new Play("小红"); Play play1 = new Play("小黑"); Play play2 = new Play("小黄"); Play play3 = new Play("小蓝"); AllControl allControl = new AllControl(); allControl.add(play); allControl.add(play1); allControl.add(play2); allControl.add(play3); play3.beattacket(allControl); } }
package com.google.android.gms.common.data; public interface c<T> { T freeze(); }
package com.teamdev.calculator.parser; import com.teamdev.calculator.*; public class BlockStartParser implements ExpressionParser { @Override public EvaluationCommand accept(MathExpressionReader reader) { if(!reader.hasMoreElements() || reader.geCurrentCharacter() != '('){ return null; } reader.movePosition(1); return new EvaluationCommand() { @Override public void execute(EvaluationStack outputContext) { StackNode currentNode = outputContext.getStackNode(); outputContext.setStackNode(new StackNode(currentNode)); } }; } }
package com.ai.slp.order.service.atom.interfaces; import java.util.List; import com.ai.slp.order.dao.mapper.bo.OrdOdLogistics; import com.ai.slp.order.dao.mapper.bo.OrdOdLogisticsCriteria; public interface IOrdOdLogisticsAtomSV { int insertSelective(OrdOdLogistics record); List<OrdOdLogistics> selectByExample(OrdOdLogisticsCriteria example); OrdOdLogistics selectByOrd(String tenantId,long orderId); int updateByPrimaryKey(OrdOdLogistics record); }
package io.zipcoder.controller; import io.zipcoder.domain.Student; import io.zipcoder.repository.StudentRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import java.net.URI; @RestController public class StudentController { @Autowired private StudentRepository studentRepository; @RequestMapping(value="/students", method= RequestMethod.GET) public ResponseEntity<?> getAllStudents(){ Iterable<Student> allStudents = studentRepository.findAll(); return new ResponseEntity<>(allStudents, HttpStatus.OK); } @RequestMapping(value="/student", method = RequestMethod.POST) public ResponseEntity<?> createStudent(){ Student student = new Student(); student.setFirstName("Chuck"); student.setId(22l); student = studentRepository.save(student); // Set the location header for the newly created resource HttpHeaders responseHeaders = new HttpHeaders(); URI newPollUri = ServletUriComponentsBuilder.fromCurrentRequest().path("/students").buildAndExpand(student.getId()).toUri(); responseHeaders.setLocation(newPollUri); return new ResponseEntity<>(null, responseHeaders, HttpStatus.CREATED); } }
package com.xvr.serviceBook.controller.restapi.assemblers; import com.xvr.serviceBook.controller.restapi.dtorepresentation.StatusTicketModelRepresentation; import com.xvr.serviceBook.entity.StatusTicket; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.CollectionModel; import org.springframework.hateoas.server.RepresentationModelAssembler; import org.springframework.stereotype.Component; @Component public class StatusTicketPaginationModelAssembler implements RepresentationModelAssembler<StatusTicket, StatusTicketModelRepresentation> { private final TicketPaginationModelAssembler ticketPaginationModelAssembler; @Autowired public StatusTicketPaginationModelAssembler(TicketPaginationModelAssembler ticketPaginationModelAssembler) { this.ticketPaginationModelAssembler = ticketPaginationModelAssembler; } @Override public StatusTicketModelRepresentation toModel(StatusTicket entity) { return StatusTicketModelRepresentation.builder() .id(entity.getId()) .statusName(entity.getStatusName()) .statusTickets(ticketPaginationModelAssembler.toCollectionModel(entity.getTickets())) .build(); } @Override public CollectionModel<StatusTicketModelRepresentation> toCollectionModel(Iterable<? extends StatusTicket> entities) { return RepresentationModelAssembler.super.toCollectionModel(entities); } }
package com.ttcnpm.g36.sharexe.payload; import lombok.Getter; import lombok.Setter; import java.util.Date; @Getter @Setter public class TripResponse { private String from; private String to; private Date begin; private Long duration; private Integer numOfPeople; }
/** * Created by Oscar on 2015-10-15. */ public class MVCBoarder { public static void main(String[] args) { System.out.println("Houston we have lift-off!"); BoardingView theView = new BoardingView(); BoardingModel theModel = new BoardingModel(); BoardingController theController = new BoardingController(theView, theModel); theView.setVisible(true); System.out.println("What is going on?"); } }
package com.example.lg.retroex; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import java.util.ArrayList; import java.util.List; /** * Created by LG on 2016-02-02. */ public class ImageAdapter extends BaseAdapter { List<ImageItem> items = new ArrayList<ImageItem>(); String keyword; int totalCount; public void setKeyword(String keyword){ this.keyword = keyword; } public String getKeyword(){ return this.keyword; } public void setTotalCount(int totalCount){ this.totalCount = totalCount; } public int getTotalCount(){ return this.totalCount; } public int getStartIndex(){ if(items.size() < totalCount){ return items.size()+1; } return -1; } public void add(ImageItem item){ items.add(item); notifyDataSetChanged(); } public void clear(){ items.clear(); notifyDataSetChanged(); } @Override public int getCount() { return items.size(); } @Override public Object getItem(int position) { return items.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ImageItemView view; if(convertView ==null){ view = new ImageItemView(parent.getContext()); }else{ view = (ImageItemView)convertView; } view.setSearchResult(items.get(position)); return view; } }
package com.google.android.gms.common.api; import com.google.android.gms.common.internal.ResolveAccountResponse; import com.google.android.gms.common.internal.t.a; import java.lang.ref.WeakReference; class m$b extends a { private final WeakReference<m> aLb; m$b(m mVar) { this.aLb = new WeakReference(mVar); } public final void a(ResolveAccountResponse resolveAccountResponse) { m mVar = (m) this.aLb.get(); if (mVar != null) { mVar.aKG.a(new 1(this, mVar, mVar, resolveAccountResponse)); } } }
package com.nbc.controller; import com.nbc.model.LogItem; import com.nbc.services.LogItemServiceImpl; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.http.HttpServletRequest; /** * LogItemController * * @author <a href="mailto:nbccong@inetcloud.vn">Chi Cong Nguyen</a> * @version $Id: LogItemController.java Dec 29, 2016 00:19:59 nbccong $ * @since 1.0 */ @Controller @Transactional public class LogItemController extends AbstractController { private static final Logger logger = Logger.getLogger(LogItemController.class); @Autowired private LogItemServiceImpl service; @RequestMapping(value = "/add/item", method = RequestMethod.GET) public String addItem(HttpServletRequest request) { logger.debug("Adding new item"); service.add(new LogItem(getString(request, "message"))); return "test"; } }
public class Demo { public static void main(String[] args) { List<Integer> ns = new ArrayList<>(); ns.add(0); ns.add(9); ns.add(4); System.out.println(GenericMax.max(ns)); List<String> ss = new ArrayList<>(); ss.add("alma"); ss.add("körte"); ss.add("almafa"); System.out.println(GenericMax.max(ss)); UniqueList<String> uints = new ArrayList<>(); try { uints.uniqueAdd(2); uints.uniqueAdd(4); uints.uniqueAdd(2); } catch (AlreadyContainsException e) { // első: legspecifikusabb kivétel System.out.println("Oops. " + e.getMessage()); } catch (Exception e) { // majd: általánosabb kivétel System.out.println("Nagy baj van."); } } }
package com.cyl.util; public class PageMsg { /** * 页面数据条数 */ public final static int msgSize = 10; }
package com.example.gheorghe.notificationservice2; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class UpdateActivity extends AppCompatActivity { SQLiteDatabase sqLiteDatabase; myHelper MyHelper; String updateString; EditText editText_update; Button btn_update,btn_delete; ContentValues content; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_update); editText_update = findViewById(R.id.editText_Update); btn_update = findViewById(R.id.btn_update); btn_delete = findViewById(R.id.btn_delete); MyHelper = new myHelper(getApplicationContext(),"database",null,1); sqLiteDatabase = MyHelper.getWritableDatabase(); updateString = getIntent().getStringExtra("updateString"); Log.d("UpdateString",updateString); content = new ContentValues(); btn_update.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (editText_update.getText().toString().trim().length() == 0) { editText_update.setError("Field is empty"); } else { content.put("task",editText_update.getText().toString()); Log.d("UpdateString",editText_update.getText().toString()); sqLiteDatabase.update("mytable",content,"task = '"+updateString+"'",null); } Intent intent = new Intent(UpdateActivity.this,MainActivity.class); Toast.makeText(getApplicationContext(),"The item Has beed updated",Toast.LENGTH_SHORT).show(); startActivity(intent); finish(); } }); btn_delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { sqLiteDatabase.delete("mytable","task = '"+updateString+"'",null); Toast.makeText(getApplicationContext(),"The item Has beed removed",Toast.LENGTH_SHORT).show(); Intent intent = new Intent(UpdateActivity.this,MainActivity.class); startActivity(intent); finish(); } }); } @Override public void onBackPressed() { Intent intent = new Intent(UpdateActivity.this,MainActivity.class); startActivity(intent); finish(); return; } }
package com.smxknife.java2.classloader.different_classloader_with_supperclass; import java.net.URL; import java.net.URLClassLoader; /** * @author smxknife * 2020/8/21 */ public class SubClassLoader extends URLClassLoader { public SubClassLoader(URL[] urls, ClassLoader classLoader) { super(urls, classLoader); } }
/* Order the input string by ASC (a -> z, 0 -> 9) with any string S?p x?p chu?i theo d?ng ASC */ package btl1; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; /** * * @author Nguyen Thu Thuy */ public class bai7 { public static void main(String[] args) { Scanner in = new Scanner(System.in); String s; System.out.println("Moi ban nhap chuoi: "); s=in.nextLine(); Map<Integer, String> chuoi = new HashMap(); for (int i = 0; i <s.length(); i++) { chuoi.put(i,s.substring(i,i+1));//substring la ham cat chuoi tu vi tri a den b } List<Map.Entry<Integer, String>> chuoimoi = new ArrayList<Map.Entry<Integer, String>>(); chuoimoi.addAll(chuoi.entrySet()); Collections.sort(chuoimoi, new Comparator<Map.Entry<Integer, String>>() { @Override public int compare(Map.Entry<Integer, String> o1, Map.Entry<Integer, String> o2) { return o1.getValue().compareTo(o2.getValue()); } }); for (int i = 0; i < chuoimoi.size(); i++) { System.out.println(chuoimoi.get(i)); } System.out.println(chuoimoi); } }
package Actions; import java.io.IOException; import javax.swing.SwingWorker; import InterfacesGUI.ClientGUI; public class ActionLogout extends SwingWorker<Object, Object> { private ClientGUI fenetre = null; public ActionLogout(ClientGUI fenetre) { this.fenetre = fenetre; } @Override protected Object doInBackground() throws Exception { try { // Commande logout fenetre.getOut().writeObject("logout"); fenetre.getOut().flush(); // Envoie du login déconnecté fenetre.getOut().writeObject(fenetre.getCurrentUser().getEmail()); fenetre.getOut().flush(); return true; } catch (IOException e) { e.printStackTrace(); } return false; } }
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package eu.intrasoft.cordova.filesdownloader; import android.app.DownloadManager; import android.database.Cursor; import android.net.Uri; import android.os.Environment; import org.apache.cordova.CallbackContext; import org.apache.cordova.PluginResult; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.IOException; import java.util.Timer; import java.util.TimerTask; /** * Download item */ class DownloadItem { private long id; private String remoteUrl; private String destinationFileUrl; private String title; private boolean extract; private CallbackContext callback; private Timer timer; DownloadItem(String remoteUrl, String destinationFileUrl, CallbackContext callback) { this.remoteUrl = remoteUrl; this.destinationFileUrl = destinationFileUrl; this.callback = callback; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getRemoteUrl() { return remoteUrl; } public String getDestinationFileUrl() { return destinationFileUrl; } /** * Get temporary file url (in the downloads folder) * * @return String * @throws IOException IO Error */ public String getTemporaryFileUrl() throws IOException { File downloadDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); String filename = this.getDestinationFileUrl().substring(this.getDestinationFileUrl().lastIndexOf("/") + 1); File outputFile = new File(downloadDir, filename.concat(".download"));// File.createTempFile(filename, "download", outputDir); return Uri.fromFile(outputFile).toString(); } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public boolean isExtract() { return extract; } public void setExtract(boolean extract) { this.extract = extract; } public CallbackContext setCallback(CallbackContext callback) { return this.callback = callback; } public CallbackContext getCallback() { return callback; } /** * Get new request for this item * * @return DownloadManager.Request */ public DownloadManager.Request getNewRequest() throws IOException { DownloadManager.Request request = new DownloadManager.Request(Uri.parse(this.getRemoteUrl())); request.setTitle(this.getTitle()); request.setVisibleInDownloadsUi(false); request.setDestinationUri(Uri.parse(this.getTemporaryFileUrl())); return request; } public void stopMonitoring() { if (null != this.timer) { this.timer.cancel(); this.timer = null; } } public void startMonitoring(TimerTask timerTask, long interval) { final long id = this.getId(); this.timer = new Timer(); timer.schedule(timerTask, 0, interval); } /** * Send result to UI * * @param status Current status * @param progress Current progress */ public void sendResult(String status, int progress) { try { JSONObject info = Utils.getResultJSON(this, status, progress); PluginResult progressUpdate = new PluginResult(PluginResult.Status.OK, info); progressUpdate.setKeepCallback(true); this.getCallback().sendPluginResult(progressUpdate); } catch (JSONException e) { e.printStackTrace(); this.getCallback().sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); } } /** * Send result to UI * * @param status Current status */ public void sendResult(String status) { this.sendResult(status, 0); } /** * Send error to UI * * @param message Message for UI * @param code Internal error code * @param error Inner exception */ public void sendError(String message, int code, Exception error) { try { this.getCallback().error(Utils.getErrorJSON(message, code, error.getMessage())); } catch (JSONException e) { e.printStackTrace(); this.getCallback().sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); } } /** * Send error to UI * * @param message Message for UI * @param error Inner exception */ public void sendError(String message, Exception error) { sendError(message, 0, error); } }
/********************************************************************************************************************************* * Copyright (c) 2017. martin.doody@gmail.com All rights reserved. * * This software is put together for investigation purposes. Use at your own risk. ********************************************************************************************************************************/ package com.jjProj.common; /** * ATM Directory Action Enum. */ public enum AtmDirectoryActionType { CREATE_DIRECTORY("create"), DELETE_DIRECTORY("delete"), UNKNOWN(""); private String action; AtmDirectoryActionType(String action) { this.action = action; } public String action() { return action; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Service.Impl; import DbConnection.MSSQLDbConnection; import Service.BillTypeManager; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Vector; import javax.swing.JOptionPane; /** * * @author THU */ public class BillTypeManagerImpl implements BillTypeManager { private final MSSQLDbConnection msssqlConnection; public BillTypeManagerImpl() { msssqlConnection = new MSSQLDbConnection(); } @Override public Vector getAll() { Vector listLoanType = new Vector(); try { msssqlConnection.registerDriver(); Connection cn = msssqlConnection.createConnection(); CallableStatement cs = cn.prepareCall("{call sp_BillType_SelectAll()}"); ResultSet rs = cs.executeQuery(); if (rs != null) { while (rs.next()) { Vector LoanType = new Vector(); LoanType.add(rs.getInt("TypeID")); LoanType.add(rs.getString("TypeName")); listLoanType.add(LoanType); } } else { JOptionPane.showMessageDialog(null, "Data null"); } } catch (SQLException ex) { JOptionPane.showMessageDialog(null, "Error occurs :"+ex.getMessage()); } return listLoanType; } @Override public Vector search(String key) { Vector listBillType = new Vector(); try { msssqlConnection.registerDriver(); Connection cn = msssqlConnection.createConnection(); String sql = "select * from [BillType] where "; sql += "[TypeID] like '%" + key + "%' "; sql += "or [TypeName] like '%" + key + "%' "; PreparedStatement ps = cn.prepareStatement(sql); ResultSet rs = ps.executeQuery(); if (rs != null) { while (rs.next()) { Vector billType = new Vector(); billType.addElement(rs.getInt("TypeID")); billType.addElement(rs.getString("TypeName")); listBillType.addElement(billType); } } else { JOptionPane.showMessageDialog(null, "Could not found any results!"); } } catch (SQLException ex) { JOptionPane.showMessageDialog(null, "Error occurs :"+ex.getMessage()); } return listBillType; } }
package strategy.design.pattern.example2; public class Designation { private String designation; PayAlgorithm payAlgorithm; private double basicSalary; Designation(String designation,PayAlgorithm payAlgorithm,double basicSalary){ this.designation=designation; this.payAlgorithm=payAlgorithm; this.basicSalary=basicSalary; } public String getDesignation() { return designation; } public PayAlgorithm getPayAlgorithm() { return payAlgorithm; } public double getBasicSalary() { return basicSalary; } }
package jp.co.logacy.validator.user; import jp.co.logacy.dto.user.UserDto; /** * ユーザ登録名前チェッククラス * @author User * */ public class CheckUserRegistName { /** * 名前が入力サイズを超えているかどうか * @param {@link UserDto} * @return true:超えている<br> * false:超えていない */ public static boolean isOverNameSize(final String name) { final int MAX_NAME_SIZE = 30; if (name == null || name.length() > MAX_NAME_SIZE) { return true; } return false; } }
package com.javakc.ssm.modules.chapters.dao; /** * @InterfaceName ChaptersDao * @Description TODO * @Author Administrator * @Date 2020/3/21 11:59 * @Version 1.0 **/ public interface ChaptersDao { }
package emp.application.service; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import emp.application.model.Role; import emp.application.repository.RoleRepository; @Service @Transactional public class RoleService { @Autowired private RoleRepository roleRepository; @PersistenceContext private EntityManager em; // @Cacheable(value="roleList") // @Transactional(readOnly = true) public List<Role> findAll() { return roleRepository.findAll(); } public Role save(Role role) { roleRepository.save(role); return role; } public Role findById(int Id) { return roleRepository.findById(Id); } }
package com.fleet.redisson.delayqueue.controller; import com.fleet.redisson.delayqueue.entity.Order; import com.fleet.redisson.delayqueue.enums.DelayQueueEnum; import com.fleet.redisson.delayqueue.sevice.OrderService; import com.fleet.redisson.delayqueue.util.DelayQueueUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import java.util.concurrent.TimeUnit; /** * @author April Han */ @RestController @RequestMapping("/order") public class OrderController { private static final Logger logger = LoggerFactory.getLogger(OrderController.class); @Resource private OrderService orderService; @Resource private DelayQueueUtil delayQueueUtil; /** * 新增订单 */ @RequestMapping("/insert") public Order insert(@RequestBody Order order) { order.setPaid("支付中"); if (orderService.insert(order)) { delayQueueUtil.add(DelayQueueEnum.ORDER_PAY_TIMEOUT.getKey(), order.getId(), 10, TimeUnit.SECONDS); delayQueueUtil.add(DelayQueueEnum.ORDER_EVALUATE_TIMEOUT.getKey(), order.getId(), 20, TimeUnit.SECONDS); } return order; } @RequestMapping("/get") public Order get(@RequestParam String id) { return orderService.get(id); } /** * 订单支付 */ @RequestMapping("/pay") public Order pay(@RequestParam("id") String id) { Order order = orderService.get(id); if (order != null) { order.setPaid("支付完成"); orderService.paid(id, "支付完成"); } return order; } /** * 订单评价 */ @RequestMapping("/evaluate") public Order evaluate(@RequestParam("id") String id, @RequestParam("evaluate") String evaluate) { Order order = orderService.get(id); if (order != null) { order.setEvaluate(evaluate); orderService.evaluate(id, evaluate); } return order; } }
package merge_sort; import java.util.Arrays; public class MergeSort { public static void main(String[] args) { int[] arr = new int[]{38, 5, 8, 3, 45, 140, 77, 127, 65, 102, 91, 73, 66, 100, 80, 69, 0, 23, 4, 654, 3, 2}; mergeSort(arr); System.out.println(Arrays.toString(arr)); } public static void mergeSort(int[] array) { int n = array.length; if (n < 2) { return; } int middle = n / 2; int[] leftArray = new int[middle]; int[] rightArray = new int[n - middle]; for (int i = 0; i < middle; i++) { leftArray[i] = array[i]; } for (int i = middle; i < n; i++) { rightArray[i - middle] = array[i]; } mergeSort(leftArray); mergeSort(rightArray); merge(array, leftArray, rightArray); } private static void merge(int[] array, int[] left, int[] right) { int lPos = 0; int rPos = 0; int index = 0; while (lPos < left.length && rPos < right.length) { if (left[lPos] <= (right[rPos])) { array[index++] = left[lPos++]; } else { array[index++] = right[rPos++]; } } while (lPos < left.length) { array[index++] = left[lPos++]; } while (rPos < right.length) { array[index++] = right[rPos++]; } } }
package java_Thread; public class producerconsmerThread { public static void main(String[] args) { Rers r = new Rers(); producer1 pro = new producer1(r); consmer1 con = new consmer1(r) ; new Thread(pro).start(); new Thread(pro).start(); new Thread(con).start(); new Thread(con).start(); } } class Rers { private String name; private int count ; private boolean flag; Rers(){ } public synchronized void set(String name){ while(flag){ try{ this.wait(); } catch(Exception e){} } this.name = name+" "+count++; System.out.println("生产了"+name+"number:"+count); flag = true; this.notifyAll(); } public synchronized void out(){ while (!flag) { try { this.wait(); }catch (Exception e) { } } System.out.println("消费了"+this.name+"编号:"+count); flag = false; this.notifyAll(); } } class producer1 implements Runnable { private Rers r; producer1(Rers r){ this.r = r; } @Override public void run() { while(true){ r.set("肥皂"); } } } class consmer1 implements Runnable{ private Rers r; consmer1(Rers r ){ this.r = r; } @Override public void run() { while(true){ r.out(); } } }
package com.utils.tools.wechat.sendsubmsg.data; import lombok.AllArgsConstructor; import lombok.Data; /** * 这是其中一个模板 这些参数字段一定要对应微信那边申请的字段 要不然会发送失败 */ @Data public class StateTemplateData { private CharacterString1 character_string1; private Phrase2 phrase2; private Name3 name3; private Phone4 phone_number4; private Thing6 thing6; @Data @AllArgsConstructor public static class CharacterString1{ private String value; } @Data @AllArgsConstructor public static class Phrase2{ private String value; } @Data @AllArgsConstructor public static class Name3{ private String value; } @Data @AllArgsConstructor public static class Phone4{ private Long value; } @Data @AllArgsConstructor public static class Thing6{ private String value; } }
package com.spring.demo.controller; import java.util.HashMap; import java.util.Map; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import com.spring.demo.bean.UserBean; @RestController public class RestTemplateTest { @RequestMapping("/xml") public String getXMLResponse() { String cinemaURL = "http://planetakino.ua/lvov2/showtimes/xml/"; RestTemplate restTemplate = new RestTemplate(); String result = restTemplate.getForObject(cinemaURL, String.class); System.out.println(result); return result; } @RequestMapping("/json") public String getJSONResponse() { String jsonURL = "http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20yahoo.finance.quotes%20WHERE%20symbol%3D%27WRC%27&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback"; RestTemplate restTemplate = new RestTemplate(); String result = restTemplate.getForObject(jsonURL, String.class); System.out.println(result); return result; } @RequestMapping("/userdata") public UserBean getUSERResponse() { String userURL = "http://localhost:8081/user/jdbc/{login}"; Map<String, String> params = new HashMap<String, String>(); params.put("login", "admin"); RestTemplate restTemplate = new RestTemplate(); UserBean user = restTemplate.getForObject(userURL, UserBean.class, params); return user; } }
/** * Helios, OpenSource Monitoring * Brought to you by the Helios Development Group * * Copyright 2007, Helios Development Group and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. * */ package com.heliosapm.opentsdb; import java.math.BigDecimal; import java.net.URLEncoder; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import javax.management.MBeanAttributeInfo; import javax.management.MBeanServerConnection; import javax.management.ObjectName; import javax.management.openmbean.CompositeData; import javax.management.openmbean.CompositeType; import org.cliffc.high_scale_lib.NonBlockingHashMap; import org.cliffc.high_scale_lib.NonBlockingHashSet; import org.jboss.netty.buffer.ChannelBuffer; import org.json.JSONArray; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.heliosapm.jmx.util.helpers.JMXHelper; import com.heliosapm.opentsdb.AnnotationBuilder.TSDBAnnotation; import com.heliosapm.opentsdb.TSDBSubmitterConnection.SubmitterFlush; import com.ning.http.client.AsyncHandler; import com.ning.http.client.HttpResponseBodyPart; import com.ning.http.client.HttpResponseHeaders; import com.ning.http.client.HttpResponseStatus; /** * <p>Title: TSDBSubmitterImpl</p> * <p>Description: The default {@link TSDBSubmitter} implementation</p> * <p>Company: Helios Development Group LLC</p> * @author Whitehead (nwhitehead AT heliosdev DOT org) * <p><code>com.heliosapm.opentsdb.TSDBSubmitterImpl</code></p> */ public class TSDBSubmitterImpl implements TSDBSubmitter { /** The underlying TSDBSubmitterConnection */ final TSDBSubmitterConnection tsdbConnection; /** This submitter's tracing buffer */ final ChannelBuffer dataBuffer; /** Indicates if times are traced in seconds (true) or milliseconds (false) */ protected boolean traceInSeconds = true; /** Indicates if traces should be logged */ protected boolean logTraces = false; /** Indicates if dup checking should be enabled */ protected boolean dupChecking = false; /** Indicates if traces are disabled */ protected boolean disableTraces = false; /** The sequential root tags applied to all traced metrics */ protected final Set<String> rootTags = new LinkedHashSet<String>(); /** The root tags map applied to all traced metrics */ protected final Map<String, String> rootTagsMap = new LinkedHashMap<String, String>(); /** Filter in map defs */ protected final NonBlockingHashMap<String, Map<String, String>> filterIns = new NonBlockingHashMap<String, Map<String, String>>(); /** Instance logger */ protected final Logger log = LoggerFactory.getLogger(getClass()); /** The default character set */ public static final Charset CHARSET = Charset.forName("UTF-8"); /** The query template to get TSUIDs from a metric name and tags. Tokens are: http server, http port, metric, comma separated key value pairs */ public static final String QUERY_TEMPLATE = "http://%s:%s/api/query?start=1s-ago&show_tsuids=true&m=avg:%s%s"; /** End of line separator */ public static final String EOL = System.getProperty("line.separator", "\n"); /** Fast string builder */ private static final ThreadLocal<StringBuilder> SB = new ThreadLocal<StringBuilder>() { @Override protected StringBuilder initialValue() { final StringBuilder b = new StringBuilder(1024); return b; } }; /** * Cleans the passed stringy * @param cs The stringy to clean * @return the cleaned stringy */ public static String clean(final CharSequence cs) { if(cs==null || cs.toString().trim().isEmpty()) return ""; String s = cs.toString().trim(); final int index = s.indexOf('/'); if(index!=-1) { s = s.substring(index+1); } return s.replace(" ", "_"); } /** * Cleans the object name property identified by the passed key * @param on The ObjectName to extract the value from * @param key The key property name * @return the cleaned key property value */ public static String clean(final ObjectName on, final String key) { if(on==null) throw new IllegalArgumentException("The passed ObjectName was null"); if(key==null || key.trim().isEmpty()) throw new IllegalArgumentException("The passed key was null or empty"); return clean(on.getKeyProperty(key.trim())); } /** * Cleans a simple name * @param s The simple name stringy * @return the cleaned name */ public static String simpleName(final CharSequence s) { if(s==null) return null; String str = clean(s); final int index = str.lastIndexOf('.'); return index==-1 ? str : str.substring(index+1); } /** * Creates a new TSDBSubmitterImpl * @param tsdbConnection The underlying TSDBSubmitterConnection */ TSDBSubmitterImpl(final TSDBSubmitterConnection tsdbConnection) { if(tsdbConnection==null) throw new IllegalArgumentException("The passed TSDBSubmitterConnection was null"); this.tsdbConnection = tsdbConnection; this.dataBuffer = this.tsdbConnection.newChannelBuffer(); } /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#newExpressionResult() */ @Override public ExpressionResult newExpressionResult() { final ChannelBuffer _buffer = tsdbConnection.newChannelBuffer(); return new ExpressionResult(true, rootTagsMap, _buffer, tsdbConnection.newSubmitterFlush(_buffer, isLogTraces())); } /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#newExpressionResult(java.util.Map) */ @Override public ExpressionResult newExpressionResult(final Map<String, String> rootTagsMapOverride) { final ChannelBuffer _buffer = tsdbConnection.newChannelBuffer(); return new ExpressionResult(true, rootTagsMapOverride, _buffer, tsdbConnection.newSubmitterFlush(_buffer, isLogTraces())); } /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#isConnected() */ @Override public boolean isConnected() { return tsdbConnection.isConnected(); } /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#getSB() */ @Override public StringBuilder getSB() { return tsdbConnection.getSB(); } // ========================================================================================================================= // Filter Ins // ========================================================================================================================= /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#addFilterIn(java.util.Map) */ @Override public void addFilterIn(final Map<String, String> in) { if(in!=null) filterIns.put("*", in); } /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#addFilterIn(java.lang.String, java.util.Map) */ @Override public void addFilterIn(final String metric, final Map<String, String> in) { final String _metric = metric==null ? "*" : metric.trim().isEmpty() ? "*" : metric.trim(); if(in!=null) filterIns.put(_metric, in); } // ========================================================================================================================= // Filter Ins Matching // ========================================================================================================================= public boolean matches(final String metric, final Map<String, String> tags) { if(metric==null || metric.trim().isEmpty() || tags==null || tags.isEmpty()) return false; final String _metric = metric.trim(); if(filterIns.isEmpty()) return true; for(final Map.Entry<String, Map<String, String>> entry: filterIns.entrySet()) { final String fmet = entry.getKey(); if("*".equals(fmet) || _metric.equals(fmet)) { for(Map.Entry<String, String> f: entry.getValue().entrySet()) { if(!matches(f.getKey(), f.getValue(), tags)) return false; } } } return true; } /** * Checks a filter entry item against the passed tags * @param key The defined filter key * @param value The defined filter value * @param tags The tag map to verify * @return true for a match, false otherwise */ protected boolean matches(final String key, final String value, final Map<String, String> tags) { final String _value = tags.get(key); if(_value==null) return false; if("*".equals(value)) return true; return _value.equals(value); } // ========================================================================================================================= // Time Gathering // ========================================================================================================================= /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#time() */ @Override public long time() { return traceInSeconds ? System.currentTimeMillis()/1000 : System.currentTimeMillis(); } /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#time(long) */ @Override public long time(final long time) { return traceInSeconds ? TimeUnit.SECONDS.convert(time, TimeUnit.MILLISECONDS) : time; } // ========================================================================================================================= // OpenType Mapping // ========================================================================================================================= /** * Decomposes a composite data type so it can be traced * @param objectName The ObjectName of the MBean the composite data came from * @param cd The composite data instance * @return A map of values keyed by synthesized ObjectNames that represent the structure down to the numeric composite data items */ protected Map<ObjectName, Number> fromOpenType(final ObjectName objectName, final CompositeData cd) { if(objectName==null) throw new IllegalArgumentException("The passed ObjectName was null"); if(cd==null) throw new IllegalArgumentException("The passed CompositeData was null"); final Map<ObjectName, Number> map = new HashMap<ObjectName, Number>(); final CompositeType ct = cd.getCompositeType(); for(final String key: ct.keySet()) { final Object value = cd.get(key); if(value==null || !(value instanceof Number)) continue; StringBuilder b = new StringBuilder(objectName.toString()); b.append(",ctype=").append(simpleName(ct.getTypeName())); b.append(",metric=").append(key); ObjectName on = JMXHelper.objectName(clean(b)); map.put(on, (Number)value); } return map; } /** * Decoposes the passed composite data instance to a map of numeric values keyed by the composite type key * @param cd The composite data instance * @return a map of numeric values keyed by the composite type key */ protected Map<String, Number> fromOpenType(final CompositeData cd) { if(cd==null) return Collections.emptyMap(); final Map<String, Number> map = new LinkedHashMap<String, Number>(); final CompositeType ct = cd.getCompositeType(); for(final String key: ct.keySet()) { final Object value = cd.get(key); if(value!=null && (value instanceof Number)) { map.put(key, (Number)value); } } return map; } // ========================================================================================================================= // Tracing Formats // ========================================================================================================================= /** * Appends the root tags to the passed buffer * @param b The buffer to append to * @return the same buffer */ protected StringBuilder appendRootTags(final StringBuilder b) { if(b==null) throw new IllegalArgumentException("The passed string builder was null"); if(!rootTags.isEmpty()) { for(String tag: rootTags) { b.append(tag).append(" "); } } return b; } /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#formatTags(java.lang.String, java.lang.String[]) */ @Override public String formatTags(final String metric, final String...tags) { if(metric==null || metric.trim().isEmpty()) throw new IllegalArgumentException("The passed metric was null or empty"); if(tags==null || tags.length < 2) throw new IllegalArgumentException("Insufficient number of tags. Must have at least 1 tag, which would be 2 values"); if(tags.length%2!=0) throw new IllegalArgumentException("Odd number of tag values [" + tags.length + "]. Tag values come in pairs"); StringBuilder b = new StringBuilder("{"); final Map<String, String> tagMap = new LinkedHashMap<String, String>(rootTagsMap); for(int i = 0; i < tags.length; i++) { String k = tags[i].trim(); i++; String v = tags[i].trim(); tagMap.put(k, v); } for(Map.Entry<String, String> entry: tagMap.entrySet()) { b.append(entry.getKey()).append("=").append(entry.getValue()).append(","); } try { final String formattedTags = URLEncoder.encode(b.deleteCharAt(b.length()-1).append("}").toString(), "UTF-8"); return String.format(QUERY_TEMPLATE, tsdbConnection.host, tsdbConnection.port, metric.trim(), formattedTags); } catch (Exception ex) { throw new RuntimeException("Failed to format " + Arrays.toString(tags), ex); } } // ========================================================================================================================= // Tracing // ========================================================================================================================= /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#trace(java.lang.String, double, java.util.Map) */ @Override public void trace(final String metric, final double value, final Map<String, String> tags) { trace(time(), metric, value, tags); } /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#trace(long, java.lang.String, double, java.util.Map) */ @Override public void trace(final long timestamp, final String metric, final double value, final Map<String, String> tags) { if(!matches(metric, tags)) return; StringBuilder b = getSB(); b.append("put ").append(clean(metric)).append(" ").append(time()).append(" ").append(value).append(" "); appendRootTags(b); for(Map.Entry<String, String> entry: tags.entrySet()) { b.append(clean(entry.getKey())).append("=").append(clean(entry.getValue())).append(" "); } final byte[] trace = b.deleteCharAt(b.length()-1).append("\n").toString().getBytes(CHARSET); synchronized(dataBuffer) { dataBuffer.writeBytes(trace); } tsdbConnection.traceCount.incrementAndGet(); } /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#trace(java.lang.String, long, java.util.Map) */ @Override public void trace(final String metric, final long value, final Map<String, String> tags) { trace(time(), metric, value, tags); } /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#trace(long, java.lang.String, long, java.util.Map) */ @Override public void trace(final long timestamp, final String metric, final long value, final Map<String, String> tags) { if(!matches(metric, tags)) return; StringBuilder b = getSB(); b.append("put ").append(clean(metric)).append(" ").append(timestamp).append(" ").append(value).append(" "); appendRootTags(b); for(Map.Entry<String, String> entry: tags.entrySet()) { b.append(clean(entry.getKey())).append("=").append(clean(entry.getValue())).append(" "); } final byte[] trace = b.deleteCharAt(b.length()-1).append("\n").toString().getBytes(CHARSET); synchronized(dataBuffer) { dataBuffer.writeBytes(trace); } tsdbConnection.traceCount.incrementAndGet(); } /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#trace(javax.management.ObjectName, double) */ @Override public void trace(final ObjectName metric, final double value) { if(metric==null || metric.isPattern()) return; trace(time(), metric.getDomain(), value, metric.getKeyPropertyList()); } /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#trace(javax.management.ObjectName, long) */ @Override public void trace(final ObjectName metric, final long value) { if(metric==null || metric.isPattern()) return; trace(time(), metric.getDomain(), value, metric.getKeyPropertyList()); } /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#trace(java.lang.String, double, java.lang.String[]) */ @Override public void trace(final String metric, final double value, final String... tags) { if(tags==null) return; if(tags.length%2!=0) throw new IllegalArgumentException("The tags varg " + Arrays.toString(tags) + "] has an odd number of values"); final int pairs = tags.length/2; final Map<String, String> map = new LinkedHashMap<String, String>(pairs); for(int i = 0; i < tags.length; i++) { map.put(tags[i], tags[++i]); } if(!matches(metric, map)) return; trace(metric, value, map); } /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#trace(java.lang.String, long, java.lang.String[]) */ @Override public void trace(final String metric, final long value, final String... tags) { if(tags==null) return; if(tags.length%2!=0) throw new IllegalArgumentException("The tags varg " + Arrays.toString(tags) + "] has an odd number of values"); final int pairs = tags.length/2; final Map<String, String> map = new LinkedHashMap<String, String>(pairs); for(int i = 0; i < tags.length; i++) { map.put(tags[i], tags[++i]); } if(!matches(metric, map)) return; trace(metric, value, map); } /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#trace(javax.management.ObjectName, java.lang.String, java.util.Map, java.lang.String[]) */ @Override public void trace(final ObjectName target, final String metricName, final Map<String, Object> attributeValues, final String...objectNameKeys) { if(target==null) throw new IllegalArgumentException("The passed target ObjectName was null"); if(objectNameKeys==null || objectNameKeys.length==0) throw new IllegalArgumentException("At least one ObjectName Key is required"); if(attributeValues==null || attributeValues.isEmpty()) return; final String m = (metricName==null || metricName.trim().isEmpty()) ? target.getDomain() : metricName.trim(); final Map<String, String> tags = new LinkedHashMap<String, String>(rootTagsMap); int keyCount = 0; boolean all = (objectNameKeys.length==1 && "*".equals(objectNameKeys[0])); if(all) { for(Map.Entry<String, String> entry: target.getKeyPropertyList().entrySet()) { tags.put(clean(entry.getKey()), clean(entry.getValue())); keyCount++; } } else { for(String key: objectNameKeys) { if(key==null || key.trim().isEmpty()) continue; String v = clean(target, key.trim()); if(v==null || v.isEmpty()) continue; tags.put(clean(key), clean(v)); keyCount++; } } if(keyCount==0) throw new IllegalArgumentException("No ObjectName Keys Usable as Tags. Keys: " + Arrays.toString(objectNameKeys) + ", ObjectName: [" + target.toString() + "]"); for(Map.Entry<String, Object> attr: attributeValues.entrySet()) { final String attributeName = clean(attr.getKey()); try { tags.put("metric", attributeName); final Object v = attr.getValue(); if(v==null) continue; if(v instanceof Number) { if(v instanceof Double) { trace(m, (Double)v, tags); } else { trace(m, ((Number)v).longValue(), tags); } } else if(v instanceof CompositeData) { final CompositeData cd = (CompositeData)v; tags.put("ctype", attributeName); try { Map<String, Number> cmap = fromOpenType(cd); for(Map.Entry<String, Number> ce: cmap.entrySet()) { final String key = clean(ce.getKey()); tags.put("metric", key); try { final Number cv = ce.getValue(); if(v instanceof Double) { trace(m, cv.doubleValue(), tags); } else { trace(m, cv.longValue(), tags); } } finally { tags.put("metric", attributeName); } } } finally { tags.remove("ctype"); } } } finally { tags.remove("metric"); } } } /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#trace(com.heliosapm.opentsdb.AnnotationBuilder.TSDBAnnotation) */ @Override public void trace(final TSDBAnnotation annotation) { if(annotation==null) throw new IllegalArgumentException("The passed annotation was null"); try { final long start = System.currentTimeMillis(); tsdbConnection.httpPost("api/annotation", annotation.toJSON(), new AsyncHandler<Object>(){ protected HttpResponseStatus responseStatus = null; @Override public void onThrowable(final Throwable t) { log.error("Async failure on annotation send for [{}]", annotation, t); } @Override public STATE onBodyPartReceived(final HttpResponseBodyPart bodyPart) throws Exception { return null; } @Override public STATE onStatusReceived(final HttpResponseStatus responseStatus) throws Exception { this.responseStatus = responseStatus; return null; } @Override public STATE onHeadersReceived(final HttpResponseHeaders headers) throws Exception { return null; } @Override public Object onCompleted() throws Exception { long elapsed = System.currentTimeMillis() - start; log.info("Annotation Send Complete in [{}] ms. Response: [{}], URI: [{}]", elapsed, responseStatus.getStatusText(), responseStatus.getUrl()); return null; } }); } catch (Exception ex) { log.error("Failed to send annotation [{}]", annotation, ex); } } /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#trace(java.util.Map) */ @Override public void trace(final Map<ObjectName, Map<String, Object>> batchResults) { if(batchResults==null || batchResults.isEmpty()) return; for(Map.Entry<ObjectName, Map<String, Object>> entry: batchResults.entrySet()) { final ObjectName on = entry.getKey(); final Map<String, Object> keyValuePairs = entry.getValue(); TSDBJMXResultTransformer transformer = tsdbConnection.transformCache.getTransformer(on); if(transformer!=null) { Map<ObjectName, Number> transformed = transformer.transform(on, keyValuePairs); for(Map.Entry<ObjectName, Number> t: transformed.entrySet()) { final Number v = t.getValue(); if(v==null) continue; if(v instanceof Double) { trace(t.getKey(), v.doubleValue()); } else { trace(t.getKey(), v.longValue()); } } } else { for(Map.Entry<String, Object> attr: entry.getValue().entrySet()) { final Object v = attr.getValue(); if(v==null) continue; if(v instanceof Number) { if(v instanceof Double) { trace(JMXHelper.objectName(clean(new StringBuilder(on.toString()).append(",metric=").append(attr.getKey()))), ((Number)v).doubleValue()); } else { trace(JMXHelper.objectName(clean(new StringBuilder(on.toString()).append(",metric=").append(attr.getKey()))), ((Number)v).longValue()); } } else if(v instanceof CompositeData) { Map<ObjectName, Number> cmap = fromOpenType(on, (CompositeData)v); for(Map.Entry<ObjectName, Number> ce: cmap.entrySet()) { final Number cv = ce.getValue(); if(v instanceof Double) { trace(ce.getKey(), cv.doubleValue()); } else { trace(ce.getKey(), cv.longValue()); } } } } } } } // ========================================================================================================================= // OpenTSDB Queries // ========================================================================================================================= /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#query(java.lang.String, java.lang.String[]) */ @Override public JSONArray query(final String metric, final String... tags) { return query(formatTags(metric, tags)); } /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#query(java.lang.String) */ @Override public JSONArray query(final String url) { try { return tsdbConnection.query(url); } catch (Exception ex) { log.error("Failed to retrieve content for [{}]", url, ex); throw new RuntimeException(String.format("Failed to retrieve content for [%s] - %s", url, ex), ex); } } /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#tsuid(java.lang.String, java.lang.String[]) */ @Override public String tsuid(final String metric, final String... tags) { return tsdbConnection.tsuid(formatTags(metric, tags)); } // ========================================================================================================================= // JMX Ops and Queries // ========================================================================================================================= /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#getAttributeNames(javax.management.MBeanServerConnection, javax.management.ObjectName) */ @Override public String[] getAttributeNames(final MBeanServerConnection conn, final ObjectName target) { try { MBeanAttributeInfo[] attrInfos = conn.getMBeanInfo(target).getAttributes(); String[] attrNames = new String[attrInfos.length]; for(int i = 0; i < attrInfos.length; i++) { attrNames[i] = attrInfos[i].getName(); } return attrNames; } catch (Exception ex) { throw new RuntimeException(ex); } } // ========================================================================================================================= // Delta Ops // ========================================================================================================================= /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#doubleDelta(double, java.lang.String[]) */ @Override public Double doubleDelta(final double value, final String... id) { return tsdbConnection.doubleDelta(value, id); } /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#longDelta(long, java.lang.String[]) */ @Override public Long longDelta(final long value, final String... id) { return tsdbConnection.longDelta(value, id); } /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#longInteger(int, java.lang.String[]) */ @Override public Integer longInteger(final int value, final String... id) { return tsdbConnection.longInteger(value, id); } /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#flushDeltas() */ @Override public void flushDeltas() { tsdbConnection.flushDeltas(); } // ========================================================================================================================= // Flush Ops // ========================================================================================================================= /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#flush() */ @Override public void flush() { synchronized(dataBuffer) { tsdbConnection.acceptFlush(dataBuffer); } } /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#deepFlush() */ @Override public void deepFlush() { flush(); tsdbConnection.flush(logTraces); } // ========================================================================================================================= // Misc Ops // ========================================================================================================================= /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#tagMap() */ @Override public FluentMap tagMap() { return new FluentMap(); } /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#getVersion() */ @Override public String getVersion() { return tsdbConnection.getVersion(); } // ========================================================================================================================= // Submitter Configs // ========================================================================================================================= /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#setTraceInSeconds(boolean) */ @Override public TSDBSubmitter setTraceInSeconds(final boolean traceInSeconds) { this.traceInSeconds = traceInSeconds; return this; } /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#isTraceInSeconds() */ @Override public boolean isTraceInSeconds() { return this.traceInSeconds; } /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#addRootTag(java.lang.String, java.lang.String) */ @Override public TSDBSubmitter addRootTag(final String key, final String value) { if(key==null || key.trim().isEmpty()) throw new IllegalArgumentException("The passed key was null or empty"); if(value==null || value.trim().isEmpty()) throw new IllegalArgumentException("The passed value was null or empty"); rootTags.add(clean(key) + "=" + clean(value)); rootTagsMap.put(clean(key), clean(value)); return this; } public TSDBSubmitter addRootTags(final Map<String, String> tags) { if(tags!=null && !tags.isEmpty()) { for(Map.Entry<String, String> entry: tags.entrySet()) { addRootTag(entry.getKey(), entry.getValue()); } } return this; } /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#setLogTraces(boolean) */ @Override public TSDBSubmitter setLogTraces(final boolean logTraces) { this.logTraces = logTraces; return this; } /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#isLogTraces() */ @Override public boolean isLogTraces() { return logTraces; } /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#isDupChecking() */ @Override public boolean isDupChecking() { return dupChecking; } /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#setDupChecking(boolean) */ @Override public TSDBSubmitter setDupChecking(final boolean enabled) { this.dupChecking = enabled; return this; } /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#isTracingDisabled() */ @Override public boolean isTracingDisabled() { return this.disableTraces; } /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#setTracingDisabled(boolean) */ @Override public TSDBSubmitter setTracingDisabled(final boolean disableTraces) { this.disableTraces = disableTraces; return this; } /** * {@inheritDoc} * @see com.heliosapm.opentsdb.TSDBSubmitter#close() */ @Override public void close() { tsdbConnection.close(); } public class ExpressionResult { /** The OpenTSDB metric name */ protected String metricName = null; /** The OpenTSDB tags */ protected Map<String, String> tags = new LinkedHashMap<String, String>(8); /** The OpenTSDB root tags that do not get reset */ protected Map<String, String> rootTags = new LinkedHashMap<String, String>(2); /** Indicates if the ER is loaded (true) or reset (false) */ protected final AtomicBoolean loaded = new AtomicBoolean(false); /** The dup check filter */ protected final NonBlockingHashSet<String> dupCheck; /** The metric value if a double type */ protected double dValue = 0D; /** The metric value if a long type */ protected long lValue = 0L; /** Indicates if the metric value is a double type */ protected boolean doubleValue = true; /** Indicates if the ER should track and filter dups. */ protected final boolean filterDups; /** The submitted metric buffer */ protected final ChannelBuffer buffer; /** The flush target where this buffer will flush to */ protected final SubmitterFlush flushTarget; /** * Creates a new ExpressionResult * @param filterDups Indicates if the ER should track and filter dups * @param rootTags An optional map of root tags * @param buffer The submitted metric buffer * @param flushTarget The target the buffer will be flushed to */ ExpressionResult(final boolean filterDups, final Map<String, String> rootTags, final ChannelBuffer buffer, final SubmitterFlush flushTarget) { this.buffer = buffer; this.filterDups = filterDups; this.flushTarget = flushTarget; dupCheck = this.filterDups ? new NonBlockingHashSet<String>() : null; if(rootTags!=null && !rootTags.isEmpty()) { for(final Map.Entry<String, String> tag: rootTags.entrySet()) { this.rootTags.put(clean(tag.getKey()), clean(tag.getValue())); } } } /** * Indicates if this ER is loaded * @return true if this ER is loaded, false otherwise */ public boolean isLoaded() { return loaded.get(); } /** * Flushes the current ER value to the buffer * @return This expression result */ public ExpressionResult flush() { return flush(null); } /** * Flushes the current ER value to the buffer * @param result Appends the rendered expression result into the passed buffer * @return This expression result */ public ExpressionResult flush(final StringBuilder result) { if(result!=null && loaded.get()) result.append(toString()); appendPut(); return this; } /** * Flushes the current ER value to the buffer * @param timestamp The timestamp to attach to the flushed ER * @param result Appends the rendered expression result into the passed buffer * @return This expression result */ public ExpressionResult flush(final long timestamp, final StringBuilder result) { if(result!=null && loaded.get()) result.append(toString()); appendPut(timestamp); return this; } /** * Flushes the current ER value to the buffer and then flushes to the endpoint */ public void deepFlush() { flush(); if(filterDups) { dupCheck.clear(); } if(buffer.readableBytes()>0) { flushTarget.deepFlush(); } } private StringBuilder getSB() { StringBuilder b = SB.get(); b.setLength(0); return b; } /** * Resets this result * @return this result in a reset state */ public ExpressionResult reset() { metricName = null; tags.clear(); return this; } /** * Sets the metric name for this result * @param name The metric name to set * @return this result */ public ExpressionResult metric(final String name) { if(name==null || name.trim().isEmpty()) throw new IllegalArgumentException("The passed meric name was null or empty"); metricName = clean(name); return this; } /** * Sets the result value as a long * @param value The long value * @return this result */ public ExpressionResult value(final long value) { lValue = value; doubleValue = false; loaded.set(true); return this; } /** * Sets the result value as a double * @param value The double value * @return this result */ public ExpressionResult value(final double value) { dValue = value; doubleValue = true; loaded.set(true); return this; } /** * Accepts an opaque object and attempts to convert the string value of it to a double or a long and applies it * @param value The opaque value whose {@link #toString()} should render the intended number * @return this result */ public ExpressionResult value(final Object value) { if(value==null) throw new IllegalArgumentException("The passed value was null"); if(value instanceof Number) { if(value instanceof Double || value instanceof Float || value instanceof BigDecimal) { value(((Number)value).doubleValue()); } else { value(((Number)value).longValue()); } } else { String valStr = value.toString().trim(); if(valStr.isEmpty()) throw new IllegalArgumentException("The passed value [" + value + "] evaluated to an empty string"); if("null".equals(valStr)) throw new IllegalArgumentException("The passed value [" + value + "] evaluated to a null"); final int index = valStr.indexOf('.'); if(index != -1) { if(valStr.substring(index+1).replace("0", "").isEmpty()) { value(Long.parseLong(valStr.substring(0, index))); } else { value(Double.parseDouble(valStr)); } } else { value(Long.parseLong(valStr)); } } return this; } /** * Populates this ExpressionResult from the passed ObjectName stringy. * @param cs The ObjectName stringy * @return this result */ public ExpressionResult objectName(final CharSequence cs) { if(cs==null) throw new IllegalArgumentException("The passed CharSequence was null"); return objectName(JMXHelper.objectName(cs)); } /** * Populates this ExpressionResult from the passed ObjectName. * @param on The ObjectName * @return this result */ public ExpressionResult objectName(final ObjectName on) { if(on==null) throw new IllegalArgumentException("The passed ObjectName was null"); metric(on.getDomain()); tags(on.getKeyPropertyList()); loaded.set(true); return this; } /** * Appends a tag to this result * @param key The tag key * @param value The tag value * @return this result */ public ExpressionResult tag(final String key, final String value) { if(key==null || key.trim().isEmpty()) throw new IllegalArgumentException("The passed key was null or empty"); if(value==null || value.trim().isEmpty()) throw new IllegalArgumentException("The passed value was null or empty"); tags.put(clean(key), clean(value)); return this; } /** * Appends a map of tags to this result * @param tags The map of tags to add * @return this result */ public ExpressionResult tags(final Map<String, String> tags) { if(tags==null) throw new IllegalArgumentException("The passed tag map was null"); for(final Map.Entry<String, String> tag: tags.entrySet()) { this.tags.put(clean(tag.getKey()), clean(tag.getValue())); } return this; } /** * Appends an OpenTSDB telnet put text line to submit this result to the passed buffer. * @param timestamp The timestamp in ms. * @return this expression result */ public ExpressionResult appendPut(final long timestamp) { if(loaded.compareAndSet(true, false)) { if(filterDups) { final String key = rootTags.toString() + tags.toString() + metricName.toString() + timestamp; if(dupCheck.add(key)) { buffer.writeBytes(renderPut(timestamp).getBytes()); } } else { buffer.writeBytes(renderPut(timestamp).getBytes()); } reset(); } return this; } /** * Appends an OpenTSDB telnet put text line to submit this result for the current timestamp to the passed buffer. * @return this expression result */ public ExpressionResult appendPut() { appendPut(time()); return this; } /** * Renders an OpenTSDB telnet put text line to submit this result for the current timestamp * @return the rendered metric put command */ public String renderPut() { return renderPut(time()); } /** * Renders an OpenTSDB telnet put text line to submit this result * @param timestamp The timestamp of the metric in ms. * @return the rendered metric put command */ public String renderPut(final long timestamp) { // put $metric $now $value host=$HOST StringBuilder b = getSB() .append("put ") .append(clean(metricName)).append(" ") .append(timestamp).append(" "); if(doubleValue) { b.append(dValue); } else { b.append(lValue); } b.append(" "); for(final Map.Entry<String, String> tag: rootTags.entrySet()) { b.append(clean(tag.getKey())).append("=").append(clean(tag.getValue())).append(" "); } for(final Map.Entry<String, String> tag: tags.entrySet()) { b.append(clean(tag.getKey())).append("=").append(clean(tag.getValue())).append(" "); } return b.deleteCharAt(b.length()-1).append(EOL).toString(); } public String toString() { StringBuilder b = new StringBuilder(clean(metricName)).append(":"); for(final Map.Entry<String, String> tag: rootTags.entrySet()) { b.append(clean(tag.getKey())).append("=").append(clean(tag.getValue())).append(","); } for(final Map.Entry<String, String> tag: tags.entrySet()) { b.append(clean(tag.getKey())).append("=").append(clean(tag.getValue())).append(","); } b.deleteCharAt(b.length()-1); b.append("/").append(doubleValue ? dValue : lValue); return b.toString(); } /** * Indicates if the ER is tracking and filter dups. * @return true if the ER is tracking and filter dups, false otherwise */ public boolean isFilterDups() { return filterDups; } } }
package com.yiki.blog; import com.yiki.blog.SecurityLearn.JwtUtil; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @SpringBootApplication public class YikiBlogApplication { public static void main(String[] args) { SpringApplication.run(YikiBlogApplication.class, args); //jwt 相关 //JwtUtil.createJwt(); } @Bean public BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(); } }
package com.tt.miniapp.shortcut; import com.tt.miniapp.event.Event; import com.tt.miniapphost.AppBrandLogger; public class ShortcutEventReporter { public static void reportClick(String paramString) { AppBrandLogger.d("ShortcutEventReporter", new Object[] { "mp_add_desktop_icon_click", "params", paramString }); Event.builder("mp_add_desktop_icon_click").kv("trigger_by", paramString).flush(); } public static void reportDialogOption(String paramString) { AppBrandLogger.d("ShortcutEventReporter", new Object[] { "mp_add_desktop_icon_select_option" }); Event.builder("mp_add_desktop_icon_select_option").kv("select_option", paramString).flush(); } public static void reportDialogShow() { AppBrandLogger.d("ShortcutEventReporter", new Object[] { "mp_add_desktop_icon_pop_up" }); Event.builder("mp_add_desktop_icon_pop_up").flush(); } public static void reportLearnMore() { AppBrandLogger.d("ShortcutEventReporter", new Object[] { "mp_add_desktop_icon_learn_more_show" }); Event.builder("mp_add_desktop_icon_learn_more_show").flush(); } public static void reportResult(String paramString1, String paramString2) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(paramString1); stringBuilder.append(":"); AppBrandLogger.d("ShortcutEventReporter", new Object[] { "mp_add_desktop_icon_click_result", "params", stringBuilder.toString(), paramString2 }); Event.builder("mp_add_desktop_icon_click_result").kv("add_icon_success", paramString1).kv("error_msg", paramString2).flush(); } } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\shortcut\ShortcutEventReporter.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package leetcode.tree; import java.util.LinkedList; import java.util.Queue; /** * Created by apple on 2019/7/2. * 给定一个二叉树,找出其最大深度。 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。 说明: 叶子节点是指没有子节点的节点。 示例: 给定二叉树 [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 返回它的最大深度 3 。 * * */ public class MaxDepth { /** * @param root * @return */ public int maxDepth(TreeNode root){ int maxdepth=0; while (root.left!=null||root.right!=null){ maxdepth+=1; root=root.left; root=root.right; } return maxdepth; } /** * 递归(自顶向下) */ private int maxDepth; public int maxDepth1(TreeNode root) { topDown(root, 0); return maxDepth; } private void topDown(TreeNode node, int depth) { if (node == null) { maxDepth = depth > maxDepth ? depth : maxDepth; return; } topDown(node.left, depth + 1); topDown(node.right, depth + 1); } /** * 递归(自底向上) */ public int maxDepth2(TreeNode root) { return root == null ? 0 : Math.max(maxDepth2(root.left), maxDepth2(root.right)) + 1; } /** * 迭代 */ public int maxDepth3(TreeNode root) { if (root == null) return 0; Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); int level = 0; while (!queue.isEmpty()) { level++; int size = queue.size(); while (size-- > 0) { TreeNode n = queue.remove(); if (n.left != null) queue.add(n.left); if (n.right != null) queue.add(n.right); } } return level; } }
/* * @name Tanvir Ahmed * @course CSCI 231 * @instructor Hieu Vu * @date 08/20/19 * @description This is the first project for CSCI 231, where it will print out "Hello World". */ public class TanAhmedProject01 { public static void main(String [] args) { System.out.println("Hello, World!"); System.out.println("This is my first Java Program"); } /*For Question 6, when I change System to system, I receive errors telling me that the package system does not exist. Because methods are case sensitive, the lower case 's' will cause errors. */ /*For Question 7, I get an "unclosed string literal" if I break the line * of code. This happens because string statements such as this must be * on the same line. */ /*For Question 8, 'print' will run the program successfully, but will not separate * the statements into two lines. 'println' will also run the program and will * separate the statements into two lines. */ }
package com.didiglobal.thriftmock.server; import com.google.common.collect.Maps; import org.apache.thrift.ProcessFunction; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocolFactory; import java.util.Map; public class ServerConfig implements Config<ProcessFunction>{ private static final int DEFAULT_THREAD_SIZE = 2; private int port; private int minWorkerThread; private int maxWorkerThread; private TProtocolFactory tProtocolFactory; private Map<String, ProcessFunction> processMap = Maps.newConcurrentMap(); public ServerConfig(int port) { this(port, new TBinaryProtocol.Factory()); } public ServerConfig(int port, TProtocolFactory tProtocolFactory) { this(port, tProtocolFactory, DEFAULT_THREAD_SIZE, DEFAULT_THREAD_SIZE); } public ServerConfig(int port, TProtocolFactory tProtocolFactory, int minWorkerThread, int maxWorkerThread) { this.port = port; this.tProtocolFactory = tProtocolFactory; this.minWorkerThread = minWorkerThread; this.maxWorkerThread = maxWorkerThread; } @Override public int getPort() { return port; } @Override public Map<String, ProcessFunction> getProcessMap() { return processMap; } @Override public TProtocolFactory getTProtocolFactory() { return tProtocolFactory; } public ServerConfig setPort(int port) { this.port = port; return this; } public ServerConfig settServerProtocolFactory(TProtocolFactory tServerProtocolFactory) { this.tProtocolFactory = tServerProtocolFactory; return this; } public int getMinWorkerThread() { return minWorkerThread; } public void setMinWorkerThread(int minWorkerThread) { this.minWorkerThread = minWorkerThread; } public int getMaxWorkerThread() { return maxWorkerThread; } public void setMaxWorkerThread(int maxWorkerThread) { this.maxWorkerThread = maxWorkerThread; } }
package br.com.thiagoGomes.domain; import java.io.Serializable; import java.time.LocalDate; import java.util.Date; import javax.persistence.Entity; import com.fasterxml.jackson.annotation.JsonFormat; import br.com.thiagoGomes.domain.enums.EstadoPagamento; @Entity //Comentei a linha abaixo, pois configurei com a anotação @JsonSubTypes na classe Pai //@JsonTypeName("pagamentoComBoleto") //Serve pra mapear o @JsonTypeInfo da classe Pagamento public class PagamentoComBoleto extends Pagamento implements Serializable { private static final long serialVersionUID = 7297328117652387761L; @JsonFormat(pattern = "dd/MM/yyyy") private LocalDate dataVencimento; @JsonFormat(pattern = "dd/MM/yyyy") private Date dataPagamento; public PagamentoComBoleto() { } public PagamentoComBoleto(Integer id, EstadoPagamento estado, Pedido pedido, LocalDate dataVencimento, Date dataPagamento) { super(id, estado, pedido); this.dataVencimento = dataVencimento; this.dataPagamento = dataPagamento; } public LocalDate getDataVencimento() { return dataVencimento; } public void setDataVencimento(LocalDate dataVencimento) { this.dataVencimento = dataVencimento; } public Date getDataPagamento() { return dataPagamento; } public void setDataPagamento(Date dataPagamento) { this.dataPagamento = dataPagamento; } }
package com.deltastuido.payment.port.alipay.api.util; import com.google.common.collect.Maps; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; public class FormBuilder { private FormBuilder() { } String signType; String method; String partner; String key; String charset; String getaway; Map parameters; String service; public FormBuilder withParameters(Map parameters) { this.parameters = parameters; return this; } public FormBuilder withService(String service) { this.service = service; return this; } public FormBuilder withGetaway(String getaway) { this.getaway = getaway; return this; } public FormBuilder withSignType(String signType) { this.signType = signType; return this; } public FormBuilder withKey(String key) { this.key = key; return this; } public FormBuilder withMethod(String method) { this.method = method; return this; } public FormBuilder withCharset(String charset) { this.charset = charset; return this; } public FormBuilder withPartner(String partner) { this.partner = partner; return this; } public static FormBuilder custom() { return new FormBuilder(); } private static final SimpleDateFormat fomart = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public Form build() { // 基本参数 parameters.put("service", service); parameters.put("payment_type", "1"); // {必传} 支付类型,商品购买。写死1 parameters.put("partner", partner); // 签约的支付宝账号对应的支付宝唯一用户号。以2088开头的16位纯数字组成。 // 除去数组中的空值和签名参数 Map sPara = Utils.filter(parameters); String queryString = Utils.getQueryString(sPara); // 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串 String sign = MD5.sign(queryString, key, charset); // 生成签名结果 sPara.put("sign", sign); sPara.put("sign_type", signType); // 签名方式 List<String> keys = new ArrayList(sPara.keySet()); String action = getaway + "?_input_charset=" + charset; Map<String, String> inputs = Maps.newHashMap(); for (int i = 0; i < keys.size(); i++) { String name = keys.get(i); Object value = sPara.get(name); // 处理数据 if (value == null) value = ""; // double if (value instanceof BigDecimal) { value = String.format("%1$.2f", ((BigDecimal) value).doubleValue()); } // date else if (value instanceof Date) { value = fomart.format(value); } // int else if (value instanceof Integer) { value = String.valueOf(value); } // else else value = value.toString(); inputs.put(name, (String) value); } Form form = new Form(); form.action = action; form.method = method; form.inputs = inputs; return form; } }
package com.advance.academy.homework.bank.system.controller; import com.advance.academy.homework.bank.system.services.AccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/account") public class AccountController { private final AccountService accountService; @Autowired public AccountController(AccountService accountService) { this.accountService = accountService; } @PostMapping("/add") public void addAccount(){ } }
package com.wipe.zc.journey.db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * 本地信息存储数据库 */ public class IMSQliteOpenHelper extends SQLiteOpenHelper { public IMSQliteOpenHelper(Context context) { super(context, "IM.db", null, 1); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { String sql_invite = "CREATE TABLE invite(" + "id integer primary key autoincrement," + "inviter varchar(20) not null,"+ "reason varchar (20) not null)"; sqLiteDatabase.execSQL(sql_invite); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { } }
package pe.gob.trabajo.web.rest; import com.codahale.metrics.annotation.Timed; import pe.gob.trabajo.domain.Motivpase; import pe.gob.trabajo.repository.MotivpaseRepository; import pe.gob.trabajo.repository.search.MotivpaseSearchRepository; import pe.gob.trabajo.web.rest.util.HeaderUtil; import io.github.jhipster.web.util.ResponseUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import static org.elasticsearch.index.query.QueryBuilders.*; /** * REST controller for managing Motivpase. */ @RestController @RequestMapping("/api") public class MotivpaseResource { private final Logger log = LoggerFactory.getLogger(MotivpaseResource.class); private static final String ENTITY_NAME = "motivpase"; private final MotivpaseRepository motivpaseRepository; private final MotivpaseSearchRepository motivpaseSearchRepository; public MotivpaseResource(MotivpaseRepository motivpaseRepository, MotivpaseSearchRepository motivpaseSearchRepository) { this.motivpaseRepository = motivpaseRepository; this.motivpaseSearchRepository = motivpaseSearchRepository; } /** * POST /motivpases : Create a new motivpase. * * @param motivpase the motivpase to create * @return the ResponseEntity with status 201 (Created) and with body the new motivpase, or with status 400 (Bad Request) if the motivpase has already an ID * @throws URISyntaxException if the Location URI syntax is incorrect */ @PostMapping("/motivpases") @Timed public ResponseEntity<Motivpase> createMotivpase(@Valid @RequestBody Motivpase motivpase) throws URISyntaxException { log.debug("REST request to save Motivpase : {}", motivpase); if (motivpase.getId() != null) { return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new motivpase cannot already have an ID")).body(null); } Motivpase result = motivpaseRepository.save(motivpase); motivpaseSearchRepository.save(result); return ResponseEntity.created(new URI("/api/motivpases/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString())) .body(result); } /** * PUT /motivpases : Updates an existing motivpase. * * @param motivpase the motivpase to update * @return the ResponseEntity with status 200 (OK) and with body the updated motivpase, * or with status 400 (Bad Request) if the motivpase is not valid, * or with status 500 (Internal Server Error) if the motivpase couldn't be updated * @throws URISyntaxException if the Location URI syntax is incorrect */ @PutMapping("/motivpases") @Timed public ResponseEntity<Motivpase> updateMotivpase(@Valid @RequestBody Motivpase motivpase) throws URISyntaxException { log.debug("REST request to update Motivpase : {}", motivpase); if (motivpase.getId() == null) { return createMotivpase(motivpase); } Motivpase result = motivpaseRepository.save(motivpase); motivpaseSearchRepository.save(result); return ResponseEntity.ok() .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, motivpase.getId().toString())) .body(result); } /** * GET /motivpases : get all the motivpases. * * @return the ResponseEntity with status 200 (OK) and the list of motivpases in body */ @GetMapping("/motivpases") @Timed public List<Motivpase> getAllMotivpases() { log.debug("REST request to get all Motivpases"); return motivpaseRepository.findAll(); } /** * GET /motivpases/:id : get the "id" motivpase. * * @param id the id of the motivpase to retrieve * @return the ResponseEntity with status 200 (OK) and with body the motivpase, or with status 404 (Not Found) */ @GetMapping("/motivpases/{id}") @Timed public ResponseEntity<Motivpase> getMotivpase(@PathVariable Long id) { log.debug("REST request to get Motivpase : {}", id); Motivpase motivpase = motivpaseRepository.findOne(id); return ResponseUtil.wrapOrNotFound(Optional.ofNullable(motivpase)); } /** JH * GET /motivpases : get all the motivpases. * * @return the ResponseEntity with status 200 (OK) and the list of motivpases in body */ @GetMapping("/motivpases/activos") @Timed public List<Motivpase> getAll_Activos() { log.debug("REST request to get all motivpases"); return motivpaseRepository.findAll_Activos(); } /** JH * GET motiv-pases/pasegl/id/:id_pase : * @param id_pase es el id del Pasegl * @return the ResponseEntity with status 200 (OK) and with body the MotivPase, or with status 404 (Not Found) */ @GetMapping("/motivpases/pasegl/id/{id_pase}") @Timed public List<Motivpase> getListMotivPaseById_Pasegl(@PathVariable Long id_pase) { log.debug("REST request to get MotivPase : id_pase {}", id_pase); return motivpaseRepository.findListMotivPaseById_Pasegl(id_pase); } /** JH * GET /motiv-pases/idoficina/:id_ofi/idpase/:id_pase : * @param id_ofi es el id de la Oficina * @return the ResponseEntity with status 200 (OK) and with body the Motivpase, or with status 404 (Not Found) */ @GetMapping("/motivpases/idoficina/{id_ofi}/idpase/{id_pase}") @Timed public List<Motivpase> getListMotivPaseByIdOfic_IdPase(@PathVariable Long id_ofi, @PathVariable Long id_pase) { log.debug("REST request to get Motivpase : id_ofi {} id_pase {}", id_ofi,id_pase); return motivpaseRepository.findListMotivPaseByIdOfic_IdPase(id_ofi,id_pase); } /** * DELETE /motivpases/:id : delete the "id" motivpase. * * @param id the id of the motivpase to delete * @return the ResponseEntity with status 200 (OK) */ @DeleteMapping("/motivpases/{id}") @Timed public ResponseEntity<Void> deleteMotivpase(@PathVariable Long id) { log.debug("REST request to delete Motivpase : {}", id); motivpaseRepository.delete(id); motivpaseSearchRepository.delete(id); return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build(); } /** * SEARCH /_search/motivpases?query=:query : search for the motivpase corresponding * to the query. * * @param query the query of the motivpase search * @return the result of the search */ @GetMapping("/_search/motivpases") @Timed public List<Motivpase> searchMotivpases(@RequestParam String query) { log.debug("REST request to search Motivpases for query {}", query); return StreamSupport .stream(motivpaseSearchRepository.search(queryStringQuery(query)).spliterator(), false) .collect(Collectors.toList()); } }
package com.tencent.mm.pluginsdk.model; import android.content.Context; import android.webkit.ValueCallback; import com.tencent.mm.sdk.platformtools.x; import com.tencent.xweb.x5.sdk.d; class u$1 implements ValueCallback<Boolean> { final /* synthetic */ Context ePr; final /* synthetic */ String ewx; final /* synthetic */ String qzx; u$1(String str, String str2, Context context) { this.ewx = str; this.qzx = str2; this.ePr = context; } public final /* synthetic */ void onReceiveValue(Object obj) { if (!((Boolean) obj).booleanValue()) { u.fz(this.ewx, this.qzx); } else if (d.isTbsCoreInited()) { u.fA(this.ewx, this.qzx); } else { x.i("MicroMsg.TBSHelper", "tbs preInit"); d.a(this.ePr, new 1(this)); } } }
package application; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import formats.Format; import formats.FormatReader; import formats.FormatWriter; import formats.KV; import map.MapReduce; import ordo.Job; import ordo.SynchronizedList; public class WordStandardDeviation implements MapReduce { private static final long serialVersionUID = 1L; private static final String LETTERS = new String("letters"); private static final String SQUARES = new String("squares"); private static final String WORDS = new String("words"); public boolean requiresReader() { return true; } // MapReduce program that computes word-lengths mean public void map(FormatReader reader, SynchronizedList<KV> channel, int id) { KV pair; Long letters = 0L; Long squares = 0L; Long words = 0L; while ((pair = reader.read()) != null) { StringTokenizer separator = new StringTokenizer(pair.v); while (separator.hasMoreTokens()) { int length = separator.nextToken().length(); letters += length; squares += (long)Math.pow(length, 2); words++; } } channel.add(new KV(LETTERS, letters.toString())); channel.add(new KV(SQUARES, squares.toString())); channel.add(new KV(WORDS, words.toString())); } public void reduce(SynchronizedList<KV> channel, FormatWriter writer) { List<KV> input = new ArrayList<>(); long words = 0; long squares = 0; long letters = 0; while (channel.waitUntilIsNotEmpty()) { channel.removeAllInto(100, input); for (KV pair : input) { if (pair.k.equals(LETTERS)) letters += Long.parseLong(pair.v); else if (pair.k.equals(SQUARES)) squares += Long.parseLong(pair.v); else if (pair.k.equals(WORDS)) words += Long.parseLong(pair.v); } input.clear(); } double mean = (((double) letters) / ((double) words)); mean = Math.pow(mean, 2.0); double term = (((double) squares / ((double) words))); Double standardDeviation = Math.sqrt((term - mean)); //System.out.print("Ecart-type des mots : " + standardDeviation); writer.write(new KV("Ecart-type des mots", standardDeviation.toString())); } public static void main(String args[]) { Job job = new Job(); job.setInputFormat(Format.Type.LINE); job.setInputFile(MapReduce.getFile(args[0])); //System.out.println("Execution de l'instance de Job"); long begin = System.currentTimeMillis(); job.startJob(new WordStandardDeviation()); long end = System.currentTimeMillis(); //System.out.println("Fin de l'éxecution de l'instance de Job"); //System.out.println("Durée de l'éxecution : " + (end - begin) + "ms"); System.out.print((end - begin)); System.exit(0); } }
package com.example.calculator; import androidx.databinding.DataBindingUtil; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import com.example.calculator.databinding.ActivityMainBinding; import java.text.DecimalFormat; public class MainActivity extends AppCompatActivity { private ActivityMainBinding binding; private static final char ADDITION = '+'; private static final char SUBTRACTION = '-'; private static final char MULTIPLICATION = '*'; private static final char PERCENTAGE = '%'; private static final char DIVISION = '/'; private char CURRENT_ACTION; private double valueOne = Double.NaN; private double valueTwo; private DecimalFormat decimalFormat; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); decimalFormat = new DecimalFormat("#.#####"); binding = DataBindingUtil.setContentView(this, R.layout.activity_main); binding.btnDot.setOnClickListener(view -> binding.editText.setText(String.format("%s.", binding.editText.getText()))); binding.btn0.setOnClickListener(view -> binding.editText.setText(String.format("%s0", binding.editText.getText()))); binding.btn1.setOnClickListener(view -> binding.editText.setText(String.format("%s1", binding.editText.getText()))); binding.btn2.setOnClickListener(view -> binding.editText.setText(String.format("%s2", binding.editText.getText()))); binding.btn3.setOnClickListener(view -> binding.editText.setText(String.format("%s3", binding.editText.getText()))); binding.btn4.setOnClickListener(view -> binding.editText.setText(String.format("%s4", binding.editText.getText()))); binding.btn5.setOnClickListener(view -> binding.editText.setText(String.format("%s5", binding.editText.getText()))); binding.btn6.setOnClickListener(view -> binding.editText.setText(String.format("%s6", binding.editText.getText()))); binding.btn7.setOnClickListener(view -> binding.editText.setText(String.format("%s7", binding.editText.getText()))); binding.btn8.setOnClickListener(view -> binding.editText.setText(String.format("%s8", binding.editText.getText()))); binding.btn9.setOnClickListener(view -> binding.editText.setText(String.format("%s9", binding.editText.getText()))); binding.btnPlus.setOnClickListener(view -> { computeCalculation(); CURRENT_ACTION = ADDITION; binding.infoTextView.setText(String.format("%s+", decimalFormat.format(valueOne))); binding.editText.setText(null); }); binding.btnMinus.setOnClickListener(view -> { computeCalculation(); CURRENT_ACTION = SUBTRACTION; binding.infoTextView.setText(String.format("%s-", decimalFormat.format(valueOne))); binding.editText.setText(null); }); binding.btnMultiply.setOnClickListener(view -> { computeCalculation(); CURRENT_ACTION = MULTIPLICATION; binding.infoTextView.setText(String.format("%s*", decimalFormat.format(valueOne))); binding.editText.setText(null); }); binding.btnDivision.setOnClickListener(view -> { computeCalculation(); CURRENT_ACTION = DIVISION; binding.infoTextView.setText(String.format("%s/", decimalFormat.format(valueOne))); binding.editText.setText(null); }); binding.btnPercent.setOnClickListener(view -> { computeCalculation(); CURRENT_ACTION = PERCENTAGE; binding.infoTextView.setText(String.format("%s%%", decimalFormat.format(valueOne))); binding.editText.setText(null); }); binding.btnEqual.setOnClickListener(view -> { computeCalculation(); binding.infoTextView.setText(String.format("%s%s = %s", binding.infoTextView.getText().toString(), decimalFormat.format(valueTwo), decimalFormat.format(valueOne))); valueOne = Double.NaN; CURRENT_ACTION = '0'; }); binding.btnClear.setOnClickListener(view -> { if(binding.editText.getText().length() > 0) { CharSequence currentText = binding.editText.getText(); binding.editText.setText(currentText.subSequence(0, currentText.length()-1)); } else { valueOne = Double.NaN; valueTwo = Double.NaN; binding.editText.setText(""); binding.infoTextView.setText(""); } }); } private void computeCalculation() { if(!Double.isNaN(valueOne)) { valueTwo = Double.parseDouble(binding.editText.getText().toString()); binding.editText.setText(null); if(CURRENT_ACTION == ADDITION) valueOne = this.valueOne + valueTwo; else if(CURRENT_ACTION == SUBTRACTION) valueOne = this.valueOne - valueTwo; else if(CURRENT_ACTION == MULTIPLICATION) valueOne = this.valueOne * valueTwo; else if(CURRENT_ACTION == DIVISION) valueOne = this.valueOne / valueTwo; else if(CURRENT_ACTION == PERCENTAGE) valueOne = this.valueOne % valueTwo; } else { try { valueOne = Double.parseDouble(binding.editText.getText().toString()); } catch (Exception e){ /* Catch what you want */ } } } }
package Gui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import javax.swing.*; public class MainGui { // metodo per inserire una pausa static void pausa(int secondi) { try { Thread.sleep(1000*secondi); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) { //Cornice o perimetro della nostra finestra JFrame finestra = new JFrame("Prima finestra Swing"); finestra.setBounds(500, 500, 600, 300); Container contenuto = finestra.getContentPane(); contenuto.setLayout(new BoxLayout(contenuto,BoxLayout.X_AXIS)); // Una JLabel è un'etichetta JLabel label1 =new JLabel("Primo applicati"); JLabel label2 =new JLabel("Secondo applicati"); JLabel label3 =new JLabel("Terzo applicati"); JLabel label4 =new JLabel("Quarto applicativo"); JLabel label5 =new JLabel("Quinto applicativo"); JLabel label6 =new JLabel("Sesto applicativo"); //Pannelli o contenitori JPanel sx = new JPanel(); JPanel dx = new JPanel(); JPanel sep = new JPanel(); sx.setLayout(new BoxLayout(sx, BoxLayout.Y_AXIS)); dx.setLayout(new BoxLayout(dx, BoxLayout.Y_AXIS)); sep.setLayout(new BoxLayout(sep, BoxLayout.Y_AXIS)); contenuto.add(sx); contenuto.add(sep); contenuto.add(dx); sep.add(new JButton("Bottone 1")); sep.add(new JButton("Bottone 2")); sep.add(new JButton("Bottone 3")); finestra.add(label1); finestra.add(label2); finestra.setVisible(true); //Con setOpaque rendiamo lo sfondo da trasparente(default) a opaco ,e quindi modificabile. label1.setOpaque(true); label1.setForeground(Color.white); label1.setBackground(Color.BLUE); sx.add(label1); //Secondo appli label2.setOpaque(true); label2.setForeground(Color.BLUE); label2.setBackground(Color.pink); sx.add(label2); //Terzo appli label3.setOpaque(true); label3.setForeground(Color.BLUE); label3.setBackground(Color.GREEN); sx.add(label3); //Quarto applicativo label4.setOpaque(true); label4.setForeground(Color.BLACK); label4.setBackground(Color.LIGHT_GRAY); dx.add(label4); //Quinto applicativo label5.setOpaque(true); label5.setForeground(Color.cyan); label5.setBackground(Color.MAGENTA); dx.add(label5); //Sesto applicativo label6.setOpaque(true); label6.setForeground(Color.ORANGE); label6.setBackground(Color.BLACK); dx.add(label6); // superficie visibile contenuto.setBackground(Color.cyan); finestra.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
/** * Created by pober on 28.11.2016. */ public class NotEnoughMoneyException extends Exception{ NotEnoughMoneyException(){ super ("Недостаточно средств на карте"); } NotEnoughMoneyException(String s){ super(s); } }
package app.com.blogapi; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Collections; import java.util.List; import app.com.blogapi.adaptadores.AdaptadorEntrada; import app.com.blogapi.entidades.Entradas; import app.com.blogapi.entidades.Login; import app.com.blogapi.entidades.User; import app.com.blogapi.servicio.BlogApiServices; import app.com.blogapi.servicio.PostService; import app.com.blogapi.servicio.SecurityService; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class MainMenu extends AppCompatActivity { public String authToken, email, pass; private RecyclerView rvEntradasLista; private List<Entradas> entradasLista; private AdaptadorEntrada adaptadorEntrada; public static final String EXTRA_ID ="app.com.blogapi.EXTRA_ID"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_menu); final PostService postService = BlogApiServices .getInstance().getPostService(); final SecurityService securityService = BlogApiServices .getInstance().getSecurityService(); rvEntradasLista = findViewById(R.id.rvListaPost); /* Obteniendo las variables almacenadas en el shared preferences */ SharedPreferences pref = getApplicationContext().getSharedPreferences("BlogApiPref", MODE_PRIVATE); authToken = pref.getString("token", null); email = pref.getString("email", null); pass = pref.getString("password", null); rvEntradasLista.setLayoutManager(new LinearLayoutManager(this)); Call<List<Entradas>> call = postService.getEstrada("Bearer "+authToken); call.enqueue(new Callback<List<Entradas>>() { @Override public void onResponse(Call<List<Entradas>> call, final Response<List<Entradas>> response) { if (response.isSuccessful()) { entradasLista = response.body(); Collections.reverse(entradasLista); adaptadorEntrada = new AdaptadorEntrada(entradasLista); adaptadorEntrada.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int id = entradasLista.get(rvEntradasLista.getChildAdapterPosition(v)).getId(); viewPost(id); } }); rvEntradasLista.setAdapter(adaptadorEntrada); }else{ Toast.makeText(MainMenu.this, "Error: "+response.code(), Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Call<List<Entradas>> call, Throwable t) { Toast.makeText(MainMenu.this, "Error: "+t.getMessage(), Toast.LENGTH_SHORT).show(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()){ case R.id.item2: FormularioCrearNuevoPost(); return true; case R.id.item3: SharedPreferences pref = getApplicationContext().getSharedPreferences("BlogApiPref", MODE_PRIVATE); SharedPreferences.Editor editor = pref.edit(); /* Guardar mi token el en shared preference */ editor.putString("token", null); editor.apply(); salir(); return true; default: return super.onOptionsItemSelected(item); } } public void FormularioCrearNuevoPost(){ Intent intent = new Intent(this, FormPost.class); startActivity(intent); } public void salir(){ Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } public void viewPost(int id){ Intent intent = new Intent(this,VistaPost.class); intent.putExtra(EXTRA_ID,String.valueOf(id)); startActivity(intent); } }
package com.jim.mpviews.utils; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import com.jim.mpviews.R; /** * A simple dialog containing month and year picker and also provides callback on positive * selection. */ public class SimpleDatePickerDialog extends Dialog implements DialogInterface .OnClickListener, SimpleDatePickerDelegate.OnDateChangedListener { private static final String YEAR = "year"; private static final String MONTH = "month"; private View dialogView; private SimpleDatePickerDelegate mSimpleDatePickerDelegate; private OnDateSetListener mDateSetListener; /** * @param context The context the dialog is to run in. */ public SimpleDatePickerDialog(Context context, OnDateSetListener listener, int year, int monthOfYear) { this(context, 0, listener, year, monthOfYear); } /** * @param context The context the dialog is to run in. * @param theme the theme to apply to this dialog */ @SuppressLint("InflateParams") public SimpleDatePickerDialog(Context context, int theme, OnDateSetListener listener, int year, int monthOfYear) { super(context, theme); mDateSetListener = listener; dialogView = getLayoutInflater().inflate(R.layout.month_year_picker, null); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(dialogView); View v = getWindow().getDecorView(); v.setBackgroundResource(android.R.color.transparent); findViewById(R.id.cancel_btn).setOnClickListener(view -> { cancel(); }); findViewById(R.id.btnOk).setOnClickListener(view -> { if (mDateSetListener != null) { mDateSetListener.onDateSet( mSimpleDatePickerDelegate.getYear(), mSimpleDatePickerDelegate.getMonth()); } cancel(); }); findViewById(R.id.btnBack).setOnClickListener(view -> { cancel(); }); mSimpleDatePickerDelegate = new SimpleDatePickerDelegate(dialogView); mSimpleDatePickerDelegate.init(year, monthOfYear, this); } @Override public void onDateChanged(int year, int month) { // Stub - do nothing } @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case BUTTON_POSITIVE: if (mDateSetListener != null) { mDateSetListener.onDateSet( mSimpleDatePickerDelegate.getYear(), mSimpleDatePickerDelegate.getMonth()); } break; case BUTTON_NEGATIVE: cancel(); break; } } @Override public Bundle onSaveInstanceState() { Bundle state = super.onSaveInstanceState(); state.putInt(YEAR, mSimpleDatePickerDelegate.getYear()); state.putInt(MONTH, mSimpleDatePickerDelegate.getMonth()); return state; } @Override public void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); int year = savedInstanceState.getInt(YEAR); int month = savedInstanceState.getInt(MONTH); mSimpleDatePickerDelegate.init(year, month, this); } public void setMinDate(long minDate) { mSimpleDatePickerDelegate.setMinDate(minDate); } public void setMaxDate(long maxDate) { mSimpleDatePickerDelegate.setMaxDate(maxDate); } /** * The callback used to indicate the user is done filling in the date. */ public interface OnDateSetListener { /** * @param year The year that was set. * @param monthOfYear The month that was set (0-11) for compatibility with {@link * java.util.Calendar}. */ void onDateSet(int year, int monthOfYear); } }
package solution; import java.util.HashMap; import java.util.Map; /** * User: jieyu * Date: 9/11/16. */ public class FindTheDifference389 { public char findTheDifference(String s, String t) { Map<Character, Integer> charMap = new HashMap<>(); for(int i = 0; i < s.length(); i++) { if (charMap.get(s.charAt(i)) == null) { charMap.put(s.charAt(i),1); } else { charMap.put(s.charAt(i),charMap.get(s.charAt(i))+1); } } for(int i = 0; i < t.length(); i++) { if(charMap.get(t.charAt(i)) == null) { return t.charAt(i); } else { charMap.put(t.charAt(i), charMap.get(t.charAt(i)) - 1); } } for(Map.Entry<Character, Integer> entry:charMap.entrySet()) { if (entry.getValue() == -1) return entry.getKey(); } return t.charAt(0); } public char findTheDifference2(String s, String t) { char result = 0; for (int i = 0; i < s.length(); i++) { result -= s.charAt(i); } for (int i = 0; i < t.length(); i++) { result += t.charAt(i); } return result; } public static void main(String[] args) { FindTheDifference389 ftd = new FindTheDifference389(); System.out.println(ftd.findTheDifference("abcd", "dbcaf")); System.out.println(ftd.findTheDifference2("abcd", "dbcaf")); } }
package persistencia; import dominio.Contacto; import java.sql.*; public class ContactoDAO { private static ContactoDAO contactDAO; private static Agente agenteBD; private ContactoDAO()throws Exception{ agenteBD= Agente.getAgente(); } public static ContactoDAO getContactoDAO() throws Exception{ if(contactDAO==null) contactDAO = new ContactoDAO(); return contactDAO; } public void deleteContacto(long telefono) throws Exception{ agenteBD.delete("DELETE FROM Contactos WHERE telefono='"+telefono+"';"); } public void updateContacto(Contacto contacto) throws Exception{ agenteBD.update("UPDATE contactos SET nombre='"+contacto.getNombre()+"', apellido1='" +contacto.getApellido1()+"', apellido2='"+contacto.getApellido2()+"'" +" WHERE telefono='"+contacto.getTelefono()+"';"); } public Contacto readContacto(long telefono) throws Exception{ ResultSet resultado = agenteBD.read("SELECT * FROM contactos WHERE telefono='" +telefono+"';"); resultado.next(); Contacto resulContacto = new Contacto(resultado.getLong(1), resultado.getString(2), resultado.getString(3), resultado.getString(4)); return resulContacto; } public void createContacto(Contacto contacto)throws Exception{ agenteBD.create("INSERT INTO contactos VALUES('"+contacto.getTelefono()+"','"+contacto.getNombre()+"','"+contacto.getApellido1()+"','" +contacto.getApellido2()+"');"); } }
package fl.sabal.source.interfacePC.Windows; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.border.EmptyBorder; import fl.sabal.source.interfacePC.Codes.ControllerCourseAssignment; import fl.sabal.source.interfacePC.Codes.DataBases.MySQL; import fl.sabal.source.interfacePC.Codes.Event.lettersToUppsercase; import fl.sabal.source.interfacePC.Codes.Event.notDigit; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.JComboBox; import java.awt.Font; import javax.swing.JButton; import javax.swing.DefaultComboBoxModel; import javax.swing.JTable; @SuppressWarnings({"serial", "rawtypes"}) public class WindowCourseAssignment extends JFrame { private JPanel contentPane; public JTextField userField; public JComboBox carrerBox; public JComboBox semesterBox; public JTable tableData; private JButton btnAccept; private JButton btnCancel; public MySQL mysql; private JScrollPane scrollPane; /** * Create the frame. */ @SuppressWarnings("unchecked") public WindowCourseAssignment(MySQL mysql) { this.mysql = mysql; setResizable(false); setBounds(100, 100, 728, 334); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JLabel lblUser = new JLabel("User :"); lblUser.setFont(new Font("Arial", Font.BOLD, 14)); lblUser.setBounds(7, 12, 57, 14); contentPane.add(lblUser); userField = new JTextField(); userField.setFont(new Font("Arial", Font.BOLD, 14)); userField.setBounds(65, 8, 151, 23); contentPane.add(userField); userField.setColumns(10); JLabel lblCarrera = new JLabel("Carrera :"); lblCarrera.setFont(new Font("Arial", Font.BOLD, 14)); lblCarrera.setBounds(7, 46, 69, 14); contentPane.add(lblCarrera); carrerBox = new JComboBox(); carrerBox.setModel(new DefaultComboBoxModel(new String[] {"-- SELECCIONAR --"})); carrerBox.setFont(new Font("Arial", Font.BOLD, 14)); carrerBox.setBounds(75, 42, 326, 23); contentPane.add(carrerBox); btnAccept = new JButton("Aceptar"); btnAccept.setFont(new Font("Arial", Font.BOLD, 14)); btnAccept.setBounds(414, 12, 95, 23); contentPane.add(btnAccept); btnCancel = new JButton("Cancelar"); btnCancel.setFont(new Font("Arial", Font.BOLD, 14)); btnCancel.setBounds(519, 12, 95, 23); contentPane.add(btnCancel); JLabel lblSemestre = new JLabel("Semestre:"); lblSemestre.setFont(new Font("Arial", Font.BOLD, 14)); lblSemestre.setBounds(424, 46, 76, 14); contentPane.add(lblSemestre); semesterBox = new JComboBox(); semesterBox.setModel(new DefaultComboBoxModel(new String[] {"-- SELECCIONAR --", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"})); semesterBox.setFont(new Font("Arial", Font.BOLD, 14)); semesterBox.setBounds(506, 42, 175, 23); contentPane.add(semesterBox); tableData = new JTable(); tableData.setFont(new Font("Gotham Book", Font.PLAIN, 10)); contentPane.add(tableData); scrollPane = new JScrollPane(tableData); scrollPane.setAutoscrolls(true); scrollPane.setBounds(7, 71, 705, 223); contentPane.add(scrollPane); } /** * @param event */ public void controller(ControllerCourseAssignment event) { btnCancel.addActionListener(event); btnCancel.setActionCommand("DISPOSE"); btnAccept.addActionListener(event); btnAccept.setActionCommand("ACCEPT"); userField.addKeyListener(new lettersToUppsercase()); userField.addKeyListener(new notDigit()); semesterBox.addItemListener(event); carrerBox.addItemListener(event); } }
package pseudoinverse; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JTextField; import javax.swing.JButton; import javax.swing.JComboBox; import java.awt.event.ActionListener; import java.util.regex.Pattern; import java.awt.event.ActionEvent; public class MatrisGir extends JFrame { private JPanel contentPane; public static HataEkrani hata; public JTextField [][]matrisDegerleri; private JTextField textField; public static Hata tmp33; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { MatrisGir frame = new MatrisGir(0,0); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public MatrisGir(int satir,int sutun) { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 561, 400); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); matrisDegerleri = new JTextField[satir][sutun]; for (int i = 0; i < matrisDegerleri.length; i++) { for (int j = 0; j < matrisDegerleri[0].length; j++) { matrisDegerleri[i][j] = new JTextField(); SecimEkrani.toplamSayisi++; } SecimEkrani.toplamSayisi++; } //setBounds(100, 100, 500, 400); for (int i = 0; i < matrisDegerleri.length; i++) { for (int j = 0; j < matrisDegerleri[0].length; j++) { matrisDegerleri[i][j].setBounds(10+(100+4)*j, 10+(60+4)*i, 70,22); SecimEkrani.toplamSayisi+=5; SecimEkrani.carpmaSayisi+=2; contentPane.add(matrisDegerleri[i][j]); } SecimEkrani.toplamSayisi++; } JButton btnDevam = new JButton("Devam"); btnDevam.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { boolean flag = true; boolean bayrak =true; double [][] matris = new double[satir][sutun]; for (int i = 0; i < matrisDegerleri.length; i++) { for (int j = 0; j < matrisDegerleri[0].length; j++) { if(Pattern.compile("[A-Za-z]").matcher(matrisDegerleri[i][j].getText()).find() || matrisDegerleri[i][j].getText().equals("")) { bayrak=false; } } } if(bayrak == true) { for (int i = 0; i < matrisDegerleri.length; i++) { for (int j = 0; j < matrisDegerleri[0].length; j++) { matris[i][j] = Double.valueOf(matrisDegerleri[i][j].getText().toString()); matris[i][j]*=10; matris[i][j]=Math.round(matris[i][j]); matris[i][j]/=10; SecimEkrani.toplamSayisi++; SecimEkrani.carpmaSayisi+=2; } SecimEkrani.toplamSayisi++; } if(matris.length<matris[0].length) if(SecimEkrani.determinant(SecimEkrani.matrisCarpimi(matris,SecimEkrani.transpoze(matris)))==0) flag = false; else if(matris.length<matris[0].length) if(SecimEkrani.determinant(SecimEkrani.matrisCarpimi(SecimEkrani.transpoze(matris),matris))==0) flag=false; if(flag==true) { SecimEkrani.islemSayfasiFrame = new IslemSayfasi(matris); SecimEkrani.islemSayfasiFrame.setVisible(true); SecimEkrani.matrisGirFrame.dispose(); } else { hata = new HataEkrani(); hata.show(); } } else { tmp33 = new Hata(); tmp33.show(); } } }); btnDevam.setBounds(434, 315, 97, 25); contentPane.add(btnDevam); JButton btnBack = new JButton("Back"); btnBack.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { SecimEkrani.matrisGirFrame.dispose(); SecimEkrani.frame.setVisible(true); } }); btnBack.setBounds(325, 315, 97, 25); contentPane.add(btnBack); } }
package com.company; public class User { public User(){ } private int id; private String UserId; private String UserName; private String lastName; private String firstName; private String mail; public User(int id, String userId, String userName, String lastName, String firstName, String mail) { this.setId(id); setUserId(userId); setUserName(userName); this.setLastName(lastName); this.setFirstName(firstName); this.setMail(mail); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserId() { return UserId; } public void setUserId(String userId) { UserId = userId; } public String getUserName() { return UserName; } public void setUserName(String userName) { UserName = userName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getMail() { return mail; } public void setMail(String mail) { this.mail = mail; } }
package TangramCore; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; public interface ObrazecListener { void mouseDown(MouseEvent e); void keyDown(KeyEvent e); void changed(); }
package sbe.reader; import org.junit.Test; import sbe.builder.TradingSessionBuilder; import sbe.msg.marketData.TradingSessionEnum; import uk.co.real_logic.agrona.DirectBuffer; import static org.junit.Assert.assertEquals; /** * Created by dharmeshsing on 26/08/15. */ public class TradingSessionReaderTest { @Test public void testRead() throws Exception { TradingSessionReader tradingSessionReader = new TradingSessionReader(); DirectBuffer buffer = build(); StringBuilder sb = tradingSessionReader.read(buffer); assertEquals("TradingSession=StartOfTradingsecurityId=1",sb.toString()); } private DirectBuffer build(){ TradingSessionBuilder tradingSessionBuilder = new TradingSessionBuilder(); tradingSessionBuilder.tradingSessionEnum(TradingSessionEnum.StartOfTrading); tradingSessionBuilder.securityId(1); return tradingSessionBuilder.build(); } }
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.niubimq.dao; import java.io.IOException; import java.io.InputStream; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; /** * @Description: mysql数据库连接基础类 * @author junjin4838 * @version 1.0 */ public class BaseDao { protected static SqlSessionFactory sqlSessionFactory; protected SqlSession sqlSession; public SqlSession getSqlSession(){ return sqlSession; } public void setSqlSession(SqlSession sqlSession){ this.sqlSession = sqlSession; } static{ String resource = "mybatis-config.xml"; InputStream reader = null; try { reader = Resources.getResourceAsStream(resource); } catch (IOException e) { e.printStackTrace(); } sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } }
package com.samyotech.laundry.model; import java.io.Serializable; import java.util.ArrayList; public class BookingDTO implements Serializable { ArrayList<OrderListDTO> order_list = new ArrayList<>(); public ArrayList<OrderListDTO> getOrder_list() { return order_list; } public void setOrder_list(ArrayList<OrderListDTO> order_list) { this.order_list = order_list; } }
package chatroom.server.listener; import chatroom.model.message.Message; import chatroom.model.UserConnectionInfo; import chatroom.model.message.PublicTextMessage; import chatroom.model.message.RoomChangeRequestMessage; import chatroom.serializer.Serializer; import chatroom.server.Server; import java.io.IOException; import java.util.logging.Level; /** * This Thread's purpose is listening from a stream of a Client and putting them * into the MessageQueue of an <code>MessageListener</code> after serialization. */ public class UserListeningThread extends Thread { private final UserConnectionInfo userConnectionInfo; // Contains information about Sockets and Streams private final Server server; private final Serializer serializer; public UserListeningThread(UserConnectionInfo userConnectionInfo, Server server) { this.server = server; this.userConnectionInfo = userConnectionInfo; serializer = new Serializer(); // userConnectionInfo.setActiveRoom(server.getRoomHandler().getPublicRoom("lobby")); // userConnectionInfo.getActiveRoom().addUser(userConnectionInfo); } @Override public void run() { listen(); } /** * This method first reads a byte from the stream of the Client, and sends * it through the <code>Serializer</code>, putting it into an MessageQueue * afterwards. */ private void listen() { boolean isRunning = true; while (isRunning) { try { //ready byte to decide which type of message is sent byte type = (byte) userConnectionInfo.getIn().read(); if(type == (byte)-1){ throw new IOException("Socket closed"); } //deserialize message, create new Message Object Message m = serializer.deserialize(userConnectionInfo.getIn(), type); //put UserConnectionInfo into the message m.setUserConnectionInfo(userConnectionInfo); //log the message if it's a Text message log(m); //put message into queue server.getMessageListener().getMessageQueue().put(m); } catch (IOException e) { server.log(Level.WARNING,"UserListeningThread: Lost Connection to " + userConnectionInfo.getSocket().getInetAddress()); isRunning = false; //Stop the Thread if connection is lost server.getNetworkListener().removeClient(this); server.getBridge().updateUserListView(server.getUserListWithRooms()); } catch (InterruptedException e) { server.log(Level.WARNING,"UserListeningThread: Exception has been thrown for user " + userConnectionInfo.getSocket().getInetAddress(),e); isRunning = false; server.getNetworkListener().removeClient(this); server.getBridge().updateUserListView(server.getUserListWithRooms()); } } } /** * Logs messages depending on their types * @param m The message to be logged */ private void log(Message m) { String logmsg = "Receiving: [" + server.getMessageTypeDictionary().getType(m.getType()).toString() + "] "; switch (server.getMessageTypeDictionary().getType(m.getType())){ case PUBLICTEXTMSG: String message = ((PublicTextMessage)m).getMessage(); logmsg = logmsg.concat(userConnectionInfo.getUserAccountInfo().getLoginName() + "@" + userConnectionInfo.getActiveRoom().getName() + ": " + message); server.log(Level.INFO,logmsg); break; case ROOMCHANGEREQMSG: logmsg = logmsg.concat(userConnectionInfo.getUserAccountInfo().getLoginName() + "@" + userConnectionInfo.getActiveRoom().getName() + " requests room change to " + ((RoomChangeRequestMessage)m).getRoomName()); server.log(Level.INFO,logmsg); break; } } /** * Returns the <code>UserConnectionInfo</code> of the client * @return ConnectionInfo of the client */ public UserConnectionInfo getUserConnectionInfo() { return userConnectionInfo; } /** * Closes the Sockets of this Client */ public void close() { try { userConnectionInfo.getSocket().close(); userConnectionInfo.getOut().close(); userConnectionInfo.getIn().close(); } catch (IOException e) { //We are closing anyways } } }
package employee; import java.io.Serializable; import java.util.List; public class Employee implements Serializable{ public static int serial=0; private String eid; // 사원번호 private String name; // 사원이름 private int salary; private List<String> license; public Employee() { } public Employee(String name, int salary, List<String> license) { super(); serial++; this.eid = serial+""; this.name = name; this.salary = salary; this.license = license; } public String getEid() { return eid; } public void setEid(String eid) { this.eid = eid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } public List<String> getLicense() { return license; } public void setLicense(List<String> license) { this.license = license; } @Override public String toString() { String temp = ""; for(String s : license) { temp += "," + s; } return eid + "," + name + "," + salary + temp; } }
package de.raidcraft.skillsandeffects.pve.skills; import com.sk89q.minecraft.util.commands.CommandContext; import de.raidcraft.skills.api.exceptions.CombatException; import de.raidcraft.skills.api.hero.Hero; import de.raidcraft.skills.api.persistance.SkillProperties; import de.raidcraft.skills.api.profession.Profession; import de.raidcraft.skills.api.skill.AbstractSkill; import de.raidcraft.skills.api.skill.SkillInformation; import de.raidcraft.skills.api.trigger.CommandTriggered; import de.raidcraft.skills.tables.THeroSkill; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; /** * @author Silthus */ @SkillInformation( name = "Transform Splash Potion", description = "Verwandelt einen normalen Trank in einen Wurftrank." ) public class TransformSplashPotion extends AbstractSkill implements CommandTriggered { public TransformSplashPotion(Hero hero, SkillProperties data, Profession profession, THeroSkill database) { super(hero, data, profession, database); } @Override public void runCommand(CommandContext args) throws CombatException { if (getHolder().getItemTypeInHand() != Material.POTION) { throw new CombatException("Du musst für diesen Skill den Trank den du anritzen willst in der Hand haben."); } ItemStack itemInHand = getHolder().getEntity().getEquipment().getItemInHand(); if (itemInHand == null) { throw new CombatException("Bitte nehme den Trank den du anritzten willst in die Hand."); } byte data = (byte) itemInHand.getDurability(); // lets check if the splash potion bit is already set // here we shift the 14 position (the splash potion bit) so // that it is a written byte and check if the bit is set if ((data & (1L << 14)) != 0) { throw new CombatException("Dieser Trank ist bereits ein Wurftrank."); } // so now lets set the bit // remember that the 14 bit is the bit for splash potions // http://www.minecraftwiki.net/wiki/Potion#Data_value_table data |= 1 << 14; itemInHand.setDurability(data); ItemMeta itemMeta = itemInHand.getItemMeta(); itemMeta.setDisplayName("Angeritzter Wurftrank"); itemInHand.setItemMeta(itemMeta); } }
package com.tencent.mm.plugin.emoji.model; import com.tencent.mm.bt.h.d; import com.tencent.mm.storage.emotion.h; class i$12 implements d { i$12() { } public final String[] xb() { return h.diD; } }
package com.example.hardwaremart; import java.util.List; import okhttp3.MultipartBody; import okhttp3.RequestBody; import retrofit2.Call; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.http.GET; import retrofit2.http.Multipart; import retrofit2.http.POST; import retrofit2.http.Part; import retrofit2.http.Path; public class ProductService { public static ProductApi productApi = null; public static ProductApi getProductApiInstance(){ Retrofit retrofit = new Retrofit.Builder() .baseUrl(ServerAddress.baseUrl) .addConverterFactory(GsonConverterFactory.create()) .build(); if(productApi == null) productApi = retrofit.create(ProductApi.class); return productApi; } public interface ProductApi{ @Multipart @POST("/product/") public Call<Product> saveProduct(@Part MultipartBody.Part file, @Part("categoryId")RequestBody categoryId, @Part("shopKeeperId") RequestBody shopKeeperId, @Part("name") RequestBody name, @Part("price") RequestBody price, @Part("brand") RequestBody brand, @Part("qtyInStock") RequestBody qtyInStock, @Part("description") RequestBody description, @Part("discount") RequestBody discount); @GET("/product/productlist/{categoryId}/{shopkeerperId}") public Call<List<Product>> getProductByCategoryAndShopKeeper(@Path("categoryId") String categoryId, @Path("shopkeerperId")String shopkeerperId); } }
package com.waltonbd.WebTests; import org.testng.Assert; import org.testng.annotations.Test; import com.waltonbd.WebPages.FramesPage; public class FramesTest extends BaseTest { public FramesTest(String url) { super("https://www.hyrtutorials.com/p/frames-practice.html"); } @Test(priority = 1, enabled = true) public void openFramesPage() { Assert.assertEquals(page.getPageTitle(), "Frames Practice - H Y R Tutorials"); System.out.println("Page Title: " + page.getPageTitle()); } @Test(priority = 2) public void openAndInputFrames() { FramesPage fPage = page.getInstance(FramesPage.class); fPage.inputText(); fPage.selectCourse(); fPage.selectNestedCourse(); // Assert.assertEquals(page.getPageTitle(), "Frames Practice - H Y R Tutorials"); // System.out.println("Page Title: "+page.getPageTitle()); } }
package _base.global_steps.api_steps; import base.BaseSteps; import cucumber.api.java.en.And; import global.Global; import helper.RandomHelper; import member.desktop.pages.account.*; public class MemberApiSteps extends BaseSteps { private static String commonEmail = Global.getConfig().getString("member.account.mail"); private static String commonPhone = Global.getConfig().getString("member.registered_phone"); private static String commonPass = Global.getConfig().getString("member.account.pass"); private static String checkoutEmail = Global.getConfig().getString("checkout.checkoutAccount.mail"); private static String checkoutPass = Global.getConfig().getString("checkout.checkoutAccount.pass"); @And("^I login by api with email$") public void loginApiByEmail(){ visit(Login_Page.class); on(Login_Page.class).loginApi(commonEmail,commonPass); Global.getMap().put("current_mail",commonEmail); Global.getMap().put("current_pass",commonPass); Global.getBrowser().refresh(); } @And ("^I login by api with email for checkout$") public void loginApiByEmailForCheckout(){ visit(Login_Page.class); on(Login_Page.class).loginApi(checkoutEmail,checkoutPass); Global.getMap().put("current_mail",checkoutEmail); Global.getMap().put("current_pass",checkoutPass); Global.getBrowser().refresh(); } @And("^I login by api with phone$") public void loginApiByPhone(){ visit(Login_Page.class); on(Login_Page.class).loginApi(commonPhone,commonPass); Global.getBrowser().refresh(); } @And("^I sign up by api with email") public void signUpEmailByApi(){ visit(SignUp_Page.class); String signupEmail = RandomHelper.randomTestMail(); on(SignUp_Page.class).signUpApi(signupEmail,commonPass); Global.getMap().put("current_mail",signupEmail); Global.getMap().put("current_pass",commonPass); Global.getBrowser().refresh(); } @And("^I create a new member address by api") public void createAddressByApi(){ visit(Account_Page.class); String mobilephoneTemplate = Global.getConfig().getString("member.phone_number_template"); String addressPhone = RandomHelper.randomPhoneNumber(mobilephoneTemplate); String addressName = Global.getConfig().getString("member.account.name"); on(Account_Page.class).createAddressByApi(Global.getConfig().getConfig("member.address"),addressPhone,addressName); Global.getBrowser().refresh(); } @And("^I delete address by api") public void deleteAddressByApi() { String addressId = on(Account_Page.class).getSecondAddressID(); on(Account_Page.class).deleteAddressByApi(addressId); } }
package com.cse308.sbuify.artist; import com.cse308.sbuify.common.CatalogItem; import com.cse308.sbuify.common.Followable; import com.cse308.sbuify.common.api.Decorable; import com.cse308.sbuify.image.Image; import com.cse308.sbuify.user.User; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import org.hibernate.search.annotations.Indexed; import org.hibernate.search.annotations.IndexedEmbedded; import javax.persistence.*; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; @Entity @Indexed public class Artist extends CatalogItem implements Followable, Decorable, Cloneable { @NotNull @Column(unique = true) private String mbid; @ElementCollection(fetch = FetchType.EAGER) @Column(name = "alias") @IndexedEmbedded private Set<String> aliases = new HashSet<>(); @NotNull private Integer monthlyListeners = 0; @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "artist", fetch = FetchType.EAGER) @JsonIgnore private Set<Product> merchandise = new HashSet<>(); @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true) @PrimaryKeyJoinColumn private Biography bio; // todo: include in search index? @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true) private Image coverImage; @Transient private Map<String, Object> properties = new HashMap<>(); public Artist() { } public Artist(@NotEmpty String name, User owner, Image image, @NotNull String mbid) { super(name, owner, image); this.mbid = mbid; } public String getMBID() { return mbid; } public Integer getMonthlyListeners() { return monthlyListeners; } public Set<Product> getMerchandise() { return merchandise; } public void setMerchandise(Set<Product> merchandise) { if (merchandise != null) { this.merchandise.clear(); this.merchandise.addAll(merchandise); } } public Biography getBio() { return bio; } public void setBio(Biography bio) { this.bio = bio; } public Image getCoverImage() { return coverImage; } public void setCoverImage(Image coverImage) { this.coverImage = coverImage; } public Set<String> getAliases() { return aliases; } public Boolean addProduct(Product product){ return this.getMerchandise().add(product); } public Boolean removeProduct(Product product){ return this.getMerchandise().remove(product); } public void setMonthlyListeners(Integer monthlyListeners) { this.monthlyListeners = monthlyListeners; } public void setAliases(Set<String> aliases) { if(aliases != null){ this.aliases.clear(); this.aliases.addAll(aliases); } } /** * Get all transient properties of the artist. */ @JsonAnyGetter public Map<String, Object> getProperties() { return properties; } /** * Get a specific transient property of the artist. */ public Object get(String key) { return properties.get(key); } /** * Set a transient property of the artist. */ @JsonAnySetter public void set(String key, Object value) { properties.put(key, value); } @Override protected Object clone() throws CloneNotSupportedException { Artist clone = (Artist) super.clone(); clone.properties = new HashMap<>(); return clone; } }
package animatronics.api.energy; public interface ITERequiresEntropy extends ITEHasEntropy { }
package com.mes.old.meta; // Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final import java.math.BigDecimal; import java.util.Date; /** * CRtCostObject generated by hbm2java */ public class CRtCostObject implements java.io.Serializable { private String uniqueid; private CAccountantPeriod CAccountantPeriod; private CCostCenter CCostCenter; private String batchnum; private String costObjectId; private Long costObjectType; private BigDecimal costObjectQuantity; private String leaderid; private Date completeDate; private BigDecimal actualCost; private BigDecimal operationAddUpCost; private String notes; private String costObjectName; private BigDecimal allocateCost; private BigDecimal unallocateCost; private BigDecimal planCost; private String partNumber; private String deptid; private String costObjectAccountId4; private String model; private String parentuid; private Long wasterQty; private Long wasterCost; private Long relationResourceType; private String relationResourceId; private Long isAllocated; private String costDriverId; private Long operationId; public CRtCostObject() { } public CRtCostObject(String uniqueid) { this.uniqueid = uniqueid; } public CRtCostObject(String uniqueid, CAccountantPeriod CAccountantPeriod, CCostCenter CCostCenter, String batchnum, String costObjectId, Long costObjectType, BigDecimal costObjectQuantity, String leaderid, Date completeDate, BigDecimal actualCost, BigDecimal operationAddUpCost, String notes, String costObjectName, BigDecimal allocateCost, BigDecimal unallocateCost, BigDecimal planCost, String partNumber, String deptid, String costObjectAccountId4, String model, String parentuid, Long wasterQty, Long wasterCost, Long relationResourceType, String relationResourceId, Long isAllocated, String costDriverId, Long operationId) { this.uniqueid = uniqueid; this.CAccountantPeriod = CAccountantPeriod; this.CCostCenter = CCostCenter; this.batchnum = batchnum; this.costObjectId = costObjectId; this.costObjectType = costObjectType; this.costObjectQuantity = costObjectQuantity; this.leaderid = leaderid; this.completeDate = completeDate; this.actualCost = actualCost; this.operationAddUpCost = operationAddUpCost; this.notes = notes; this.costObjectName = costObjectName; this.allocateCost = allocateCost; this.unallocateCost = unallocateCost; this.planCost = planCost; this.partNumber = partNumber; this.deptid = deptid; this.costObjectAccountId4 = costObjectAccountId4; this.model = model; this.parentuid = parentuid; this.wasterQty = wasterQty; this.wasterCost = wasterCost; this.relationResourceType = relationResourceType; this.relationResourceId = relationResourceId; this.isAllocated = isAllocated; this.costDriverId = costDriverId; this.operationId = operationId; } public String getUniqueid() { return this.uniqueid; } public void setUniqueid(String uniqueid) { this.uniqueid = uniqueid; } public CAccountantPeriod getCAccountantPeriod() { return this.CAccountantPeriod; } public void setCAccountantPeriod(CAccountantPeriod CAccountantPeriod) { this.CAccountantPeriod = CAccountantPeriod; } public CCostCenter getCCostCenter() { return this.CCostCenter; } public void setCCostCenter(CCostCenter CCostCenter) { this.CCostCenter = CCostCenter; } public String getBatchnum() { return this.batchnum; } public void setBatchnum(String batchnum) { this.batchnum = batchnum; } public String getCostObjectId() { return this.costObjectId; } public void setCostObjectId(String costObjectId) { this.costObjectId = costObjectId; } public Long getCostObjectType() { return this.costObjectType; } public void setCostObjectType(Long costObjectType) { this.costObjectType = costObjectType; } public BigDecimal getCostObjectQuantity() { return this.costObjectQuantity; } public void setCostObjectQuantity(BigDecimal costObjectQuantity) { this.costObjectQuantity = costObjectQuantity; } public String getLeaderid() { return this.leaderid; } public void setLeaderid(String leaderid) { this.leaderid = leaderid; } public Date getCompleteDate() { return this.completeDate; } public void setCompleteDate(Date completeDate) { this.completeDate = completeDate; } public BigDecimal getActualCost() { return this.actualCost; } public void setActualCost(BigDecimal actualCost) { this.actualCost = actualCost; } public BigDecimal getOperationAddUpCost() { return this.operationAddUpCost; } public void setOperationAddUpCost(BigDecimal operationAddUpCost) { this.operationAddUpCost = operationAddUpCost; } public String getNotes() { return this.notes; } public void setNotes(String notes) { this.notes = notes; } public String getCostObjectName() { return this.costObjectName; } public void setCostObjectName(String costObjectName) { this.costObjectName = costObjectName; } public BigDecimal getAllocateCost() { return this.allocateCost; } public void setAllocateCost(BigDecimal allocateCost) { this.allocateCost = allocateCost; } public BigDecimal getUnallocateCost() { return this.unallocateCost; } public void setUnallocateCost(BigDecimal unallocateCost) { this.unallocateCost = unallocateCost; } public BigDecimal getPlanCost() { return this.planCost; } public void setPlanCost(BigDecimal planCost) { this.planCost = planCost; } public String getPartNumber() { return this.partNumber; } public void setPartNumber(String partNumber) { this.partNumber = partNumber; } public String getDeptid() { return this.deptid; } public void setDeptid(String deptid) { this.deptid = deptid; } public String getCostObjectAccountId4() { return this.costObjectAccountId4; } public void setCostObjectAccountId4(String costObjectAccountId4) { this.costObjectAccountId4 = costObjectAccountId4; } public String getModel() { return this.model; } public void setModel(String model) { this.model = model; } public String getParentuid() { return this.parentuid; } public void setParentuid(String parentuid) { this.parentuid = parentuid; } public Long getWasterQty() { return this.wasterQty; } public void setWasterQty(Long wasterQty) { this.wasterQty = wasterQty; } public Long getWasterCost() { return this.wasterCost; } public void setWasterCost(Long wasterCost) { this.wasterCost = wasterCost; } public Long getRelationResourceType() { return this.relationResourceType; } public void setRelationResourceType(Long relationResourceType) { this.relationResourceType = relationResourceType; } public String getRelationResourceId() { return this.relationResourceId; } public void setRelationResourceId(String relationResourceId) { this.relationResourceId = relationResourceId; } public Long getIsAllocated() { return this.isAllocated; } public void setIsAllocated(Long isAllocated) { this.isAllocated = isAllocated; } public String getCostDriverId() { return this.costDriverId; } public void setCostDriverId(String costDriverId) { this.costDriverId = costDriverId; } public Long getOperationId() { return this.operationId; } public void setOperationId(Long operationId) { this.operationId = operationId; } }
package jcode18.community.mapper; import jcode18.community.model.Comment; import jcode18.community.model.CommentExample; import jcode18.community.model.Question; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.session.RowBounds; import java.util.List; public interface CommentExtMapper { int incCommentCount(Comment comment); }
package com.company; import java.util.*; /** * * @author Alex Barbuzza * */ public class WareHouse { protected String invFileName; protected String inventory; /** * @param * @return * @return */ public void getInventory(){ //needs to use the ReadWrite; method needs to be redone } public String readInventory(String invFileName){ //needs to use the ReadWrite; method needs to be redone return inventory; } public void RemoveFromWareHouse(ArrayList<BikePart> currentInventory, ArrayList<String> wareHouseInventory){//needs to use the ReadWrite; method needs to be redone for(int i = 0; i < wareHouseInventory.size(); ++i){ if(currentInventory.get(i).equals(wareHouseInventory.get(i))){ int j = Integer.parseInt(wareHouseInventory.get(i)); String newNum = Integer.toString(j); wareHouseInventory.set(i, newNum); } } } public void AddtoWareHouse(ArrayList<BikePart> currentInventory, ArrayList<String> wareHouseInventory){//needs to use the ReadWrite; method needs to be redone for(int i = 0; i < wareHouseInventory.size(); ++i){ if(currentInventory.get(i).equals(wareHouseInventory.get(i))){ int j = Integer.parseInt(wareHouseInventory.get(i)); String newNum = Integer.toString(j); wareHouseInventory.set(i, newNum); } } } }
package com.takshine.wxcrm.domain; import java.io.Serializable; import com.takshine.wxcrm.base.model.BaseModel; /** * 登录用户 所拥有的功能菜单 * @author liulin * */ public class UserFunc extends BaseModel implements Serializable { /** * */ private static final long serialVersionUID = 1L; private String opId = null; private String crmId = null; private String opName = null; private String entId = null; private String roleId = null; private String funId = null; private String funName = null; private String funLevel = null; private String funParentId = null; private String funIdx = null; private String funMem = null; private String funModel = null; private String funUri = null; private String funImg = null; public String getOpId() { return opId; } public void setOpId(String opId) { this.opId = opId; } public String getCrmId() { return crmId; } public void setCrmId(String crmId) { this.crmId = crmId; } public String getOpName() { return opName; } public void setOpName(String opName) { this.opName = opName; } public String getEntId() { return entId; } public void setEntId(String entId) { this.entId = entId; } public String getRoleId() { return roleId; } public void setRoleId(String roleId) { this.roleId = roleId; } public String getFunId() { return funId; } public void setFunId(String funId) { this.funId = funId; } public String getFunName() { return funName; } public void setFunName(String funName) { this.funName = funName; } public String getFunLevel() { return funLevel; } public void setFunLevel(String funLevel) { this.funLevel = funLevel; } public String getFunParentId() { return funParentId; } public void setFunParentId(String funParentId) { this.funParentId = funParentId; } public String getFunIdx() { return funIdx; } public void setFunIdx(String funIdx) { this.funIdx = funIdx; } public String getFunMem() { return funMem; } public void setFunMem(String funMem) { this.funMem = funMem; } public String getFunUri() { return funUri; } public void setFunUri(String funUri) { this.funUri = funUri; } public String getFunImg() { return funImg; } public void setFunImg(String funImg) { this.funImg = funImg; } public String getFunModel() { return funModel; } public void setFunModel(String funModel) { this.funModel = funModel; } }
/* * Copyright 2009 Kjetil Valstadsve * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package vanadis.modules.httpprovider; import vanadis.core.lang.Proxies; import vanadis.remoting.AbstractRemoteClientFactory; import vanadis.services.remoting.TargetHandle; public class HttpRemoteClientFactory extends AbstractRemoteClientFactory { @Override public <T> T createClient(ClassLoader classLoader, TargetHandle<T> targetHandle) { return Proxies.genericProxy(classLoader, targetHandle.getReference().getTargetInterface(), new Handler<T>(targetHandle, classLoader)); } }
package org.gtap; import java.awt.Color; import java.awt.Point; import java.awt.geom.Ellipse2D; import java.util.ArrayList; import java.awt.Graphics2D; /** * Drawable Node Object. */ public class Node { ArrayList<Node> neighbors; // list of adjacent nodes ArrayList<Edge> edges; // list of adjacent edges private int xPos, yPos; // center of the node private int radius = 15, diameter = radius * 2; // size private String value = ""; /** * Constructor. * * @param x x position of the node. * @param y y position of the node. */ public Node(int x, int y) { neighbors = new ArrayList<Node>(); edges = new ArrayList<Edge>(); xPos = x; yPos = y; } /** * Set the x position of the node. * * @param x new x position */ public void setX(int x) { xPos = x; } /** * Set the y position of the node. * * @param y: new y position. */ public void setY(int y) { yPos = y; } /** * Get the x position of the node. * * @return x position of node. */ public int getX() { return xPos; } /** * Get the y position of the node. * * @return y position of node. */ public int getY() { return yPos; } /** * Get the position at the center of the node. * * @return position at the center of the node. */ public Point getCenter() { return new Point(xPos, yPos); } /** * Get the width of the node. * * @return width of the node. */ public int getWidth() { return diameter; } /** * Get the height of the node. * * @return height of the node. */ public int getHeight() { return diameter; } /** * Get the value/label of the node. */ public void setValue(String s) { value = s; } /** * Check whether the node contains the point (x, y). * * @param x the x value of the point we are checking. * @param y the y value of the point we are checking. * @return true if (x, y) is contained in the node. */ public boolean contains(int x, int y) { return new Ellipse2D.Double(xPos - radius, yPos - radius, diameter, diameter).contains(new Point(x, y)); } public void moveTo(int x, int y) { this.setX(x); this.setY(y); } public void addNeighbor(Node n) { neighbors.add(n); } public void removeNeighbor(Node n) { neighbors.remove(n); } public boolean hasNeighbor(Node n) { for (Node node : neighbors) { if (node == n) { return true; } } return false; } public ArrayList<Node> getNeighbors() { return neighbors; } public void addEdge(Edge e) { edges.add(e); } public ArrayList<Edge> getEdges() { return edges; } public void paint(Graphics2D g) { g.setColor(Color.WHITE); g.fillOval(xPos - radius, yPos - radius, diameter, diameter); g.setColor(Color.GRAY); g.drawOval(xPos - radius, yPos - radius, diameter, diameter); g.drawString(value, xPos, yPos); } public String toString() { return "Node"; } }
package ja; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class JA_1175_주사위_던지기2 { public static void main(String[] args) throws IOException{ // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int N = Integer.parseInt(st.nextToken()); int M = Integer.parseInt(st.nextToken()); DicePermutaion(N,0,new int[N],M); } public static void DicePermutaion(int r, int d,int[] tmp, int count) { if(d == r && count == 0) { for (int i = 0; i < r; i++) { System.out.print(tmp[i] + " "); } System.out.println(); return; }else if(d == r ){ return; } for (int i = 0; i <6 ; i++) { tmp[d] = i+1; count-=(i+1); DicePermutaion(r, d+1,tmp,count); count+=(i+1); } } }
package com.manage.salary.employee; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Optional; @Service public class EmployeeServiceImpl implements EmployeeService { private EmployeeRepository employeeRepository; @Autowired public EmployeeServiceImpl(EmployeeRepository employeeRepository) { this.employeeRepository = employeeRepository; } @Override @Transactional public List<Employee> getEmployees() { return employeeRepository.findAll(orderByLastName()); } @Override @Transactional public void saveOrUpdateEmployee(Employee theEmployee) { if (theEmployee.getId() != null){ Employee emp = employeeRepository.getOne(theEmployee.getId()); emp.setFirstName(theEmployee.getFirstName()); emp.setLastName(theEmployee.getLastName()); emp.setPosition(theEmployee.getPosition()); employeeRepository.save(emp); } else employeeRepository.save(theEmployee); } @Override @Transactional public Employee getEmployeeById(Long employeeId){ return employeeRepository.findById(employeeId).orElse(null); } @Override @Transactional public void deleteEmployee(Long employeeId) { employeeRepository.deleteById(employeeId); } private Sort orderByLastName(){ return new Sort(Sort.Direction.ASC, "lastName"); } }
package controllers; import battleships.Player; import battleships.Utilities; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Label; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; public class ScorePage implements Initializable { @FXML private Label name; @FXML private Label score; @Override public void initialize(URL url, ResourceBundle resourceBundle) { name.setText("Congratulations, " + Utilities.getWinner() + "!"); score.setText(Utilities.getScore()); try { FileWriter fileWriter = new FileWriter("src/gameHistory.txt", true); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); Utilities.setScore(" &#10;"); bufferedWriter.write(score.getText().replace("You", Utilities.getWinner())); bufferedWriter.newLine(); bufferedWriter.close(); } catch (IOException ignored) { } } @FXML private void exit() { System.exit(1); } @FXML private void continueGame(ActionEvent event) throws IOException { Utilities.setPlayer1(new Player()); Utilities.setPlayer2(new Player()); Utilities.cleanScore(); Utilities.changeScene(event, "../FXML/begin.fxml"); } }
package com.tencent.mm.plugin.fav.ui; import android.graphics.Bitmap.CompressFormat; import com.tencent.mm.model.q; import com.tencent.mm.plugin.fav.a.ae; import com.tencent.mm.plugin.fav.a.b; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.protocal.c.vx; import com.tencent.mm.protocal.c.wr; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.c; import com.tencent.mm.sdk.platformtools.x; import java.util.LinkedList; import java.util.List; public final class g { public static boolean a(String str, LinkedList<vx> linkedList, long j) { if (str.length() == 0) { x.e("MicroMsg.FavPostLogic", "postNote null"); return false; } com.tencent.mm.plugin.fav.a.g a; if (-1 == j) { a = a(linkedList, j); } else { a = ((ae) com.tencent.mm.kernel.g.n(ae.class)).getFavItemInfoStorage().dy(j); } b.B(a); return true; } public static com.tencent.mm.plugin.fav.a.g a(LinkedList<vx> linkedList, long j) { com.tencent.mm.plugin.fav.a.g gVar = null; if (j != -1) { gVar = ((ae) com.tencent.mm.kernel.g.n(ae.class)).getFavItemInfoStorage().dy(j); if (gVar == null) { com.tencent.mm.plugin.fav.a.g gVar2 = new com.tencent.mm.plugin.fav.a.g(); gVar2.field_type = 18; gVar2.field_sourceType = 6; String GF = q.GF(); wr wrVar = new wr(); wrVar.Vw(GF); wrVar.Vx(GF); wrVar.CO(gVar2.field_sourceType); wrVar.fU(bi.VF()); gVar2.field_favProto.a(wrVar); gVar2.field_fromUser = wrVar.bSS; gVar2.field_toUser = wrVar.toUser; gVar2.field_favProto.CN(1); gVar2.field_favProto.CM(127); gVar2.field_edittime = bi.VE(); gVar2.field_updateTime = bi.VF(); gVar2.field_favProto.fT(gVar2.field_edittime); gVar2.field_favProto.rBG.fU(bi.VF()); gVar2.field_itemStatus = 9; gVar2.field_localId = j; ((ae) com.tencent.mm.kernel.g.n(ae.class)).getFavItemInfoStorage().y(gVar2); gVar = gVar2; } gVar.field_favProto.rBI.clear(); } if (gVar == null) { gVar = new com.tencent.mm.plugin.fav.a.g(); gVar.field_type = 18; gVar.field_sourceType = 6; E(gVar); gVar.field_favProto.CN(1); gVar.field_favProto.CM(127); } gVar.field_edittime = bi.VE(); gVar.field_updateTime = bi.VF(); gVar.field_favProto.fT(gVar.field_edittime); gVar.field_favProto.rBG.fU(bi.VF()); gVar.field_favProto.ar(linkedList); return gVar; } /* JADX WARNING: inconsistent code. */ /* Code decompiled incorrectly, please refer to instructions dump. */ private static java.util.List<java.lang.String> bd(java.util.List<java.lang.String> r7) { /* if (r7 == 0) goto L_0x0008; L_0x0002: r0 = r7.size(); if (r0 != 0) goto L_0x0009; L_0x0008: return r7; L_0x0009: r1 = new java.util.ArrayList; r1.<init>(); r3 = new com.tencent.mm.sdk.platformtools.MMBitmapFactory$DecodeResultLogger; r3.<init>(); r4 = r7.iterator(); L_0x0017: r0 = r4.hasNext(); if (r0 == 0) goto L_0x005b; L_0x001d: r0 = r4.next(); r0 = (java.lang.String) r0; r2 = 0; r2 = com.tencent.mm.vfs.d.openRead(r0); Catch:{ Exception -> 0x005d, all -> 0x0056 } if (r2 != 0) goto L_0x002e; L_0x002a: com.tencent.mm.sdk.platformtools.bi.d(r2); goto L_0x0017; L_0x002e: r5 = com.tencent.mm.sdk.platformtools.MMBitmapFactory.checkIsImageLegal(r2, r3); Catch:{ Exception -> 0x0050, all -> 0x0056 } if (r5 == 0) goto L_0x003b; L_0x0034: r1.add(r0); Catch:{ Exception -> 0x0050, all -> 0x0056 } L_0x0037: com.tencent.mm.sdk.platformtools.bi.d(r2); goto L_0x0017; L_0x003b: r0 = r3.getDecodeResult(); Catch:{ Exception -> 0x0050, all -> 0x0056 } r5 = 2000; // 0x7d0 float:2.803E-42 double:9.88E-321; if (r0 < r5) goto L_0x0037; L_0x0043: r0 = 5; r0 = com.tencent.mm.sdk.platformtools.MMBitmapFactory.KVStatHelper.getKVStatString(r2, r0, r3); Catch:{ Exception -> 0x0050, all -> 0x0056 } r5 = com.tencent.mm.plugin.report.service.h.mEJ; Catch:{ Exception -> 0x0050, all -> 0x0056 } r6 = 12712; // 0x31a8 float:1.7813E-41 double:6.2806E-320; r5.k(r6, r0); Catch:{ Exception -> 0x0050, all -> 0x0056 } goto L_0x0037; L_0x0050: r0 = move-exception; r0 = r2; L_0x0052: com.tencent.mm.sdk.platformtools.bi.d(r0); goto L_0x0017; L_0x0056: r0 = move-exception; com.tencent.mm.sdk.platformtools.bi.d(r2); throw r0; L_0x005b: r7 = r1; goto L_0x0008; L_0x005d: r0 = move-exception; r0 = r2; goto L_0x0052; */ throw new UnsupportedOperationException("Method not decompiled: com.tencent.mm.plugin.fav.ui.g.bd(java.util.List):java.util.List<java.lang.String>"); } public static boolean be(List<String> list) { List<String> bd = bd(list); if (bd == null || bd.size() == 0) { x.e("MicroMsg.FavPostLogic", "postImgs path null"); return false; } com.tencent.mm.plugin.fav.a.g gVar = new com.tencent.mm.plugin.fav.a.g(); gVar.field_type = 2; gVar.field_sourceType = 6; E(gVar); for (String str : bd) { vx vxVar = new vx(); vxVar.UP(str); vxVar.UO(b.bm(vxVar.toString(), 2)); c.c(str, 150, 150, CompressFormat.JPEG, 90, b.c(vxVar)); vxVar.UQ(b.c(vxVar)); vxVar.CF(2); gVar.field_favProto.rBI.add(vxVar); } b.B(gVar); h.mEJ.h(10648, new Object[]{Integer.valueOf(2), Integer.valueOf(bd.size())}); return true; } static void E(com.tencent.mm.plugin.fav.a.g gVar) { String GF = q.GF(); wr wrVar = new wr(); wrVar.Vw(GF); wrVar.Vx(GF); wrVar.CO(gVar.field_sourceType); wrVar.fU(bi.VF()); gVar.field_favProto.a(wrVar); gVar.field_fromUser = wrVar.bSS; gVar.field_toUser = wrVar.toUser; } }
package wx.realware.grp.pt.pb.entry.job; import wx.realware.grp.pt.pb.interconfig.Column; import wx.realware.grp.pt.pb.interconfig.Table; import java.io.Serializable; @Table(value = "wx_auto_task") public class QuartJobEntity implements Serializable { /** * uuid * 主键 */ @Column(value = "job_id") private String job_id; /** * 自动任务名称 */ @Column(value = "job_name") private String job_name; /** * 自动任务类型 */ @Column(value = "job_type") private int job_type; /** * 自动任务类路径 */ @Column(value = "class_name") private String class_name; /** * 是否启用 * 0不启用 * 1启用 */ @Column(value = "job_enabled") private int job_enabled; /** * quart时间表达式 */ @Column(value = "job_time") private String job_time; /** *间隔执行时间(ms) */ @Column(value = "job_interval") private int job_interval; /** *重复执行次数 */ @Column(value = "repearcount") private int repearcount; /** *延迟时间 */ @Column(value = "delaytime") private int delaytime; /** *注解 */ @Column(value = "remark") private String remark; /** * 执行类型 同一个库的时候 1: 只有一台机器能执行 2:多台机器执行 */ @Column(value = "exe_type") private int exe_type; /** * 最后一次操作的时间 */ @Column(value = "last_op_date") private String last_op_date; /** * 是否当前正在执行(针对于只有一个机器能执行的任务) */ @Column(value = "is_cur_exe") private int is_cur_exe; /** * 最大超时时间(单位: 分钟) */ @Column(value = "max_exe_time") private int max_exe_time; public String getJob_id() { return job_id; } public void setJob_id(String job_id) { this.job_id = job_id; } public String getJob_name() { return job_name; } public void setJob_name(String job_name) { this.job_name = job_name; } public int getJob_type() { return job_type; } public void setJob_type(int job_type) { this.job_type = job_type; } public String getClass_name() { return class_name; } public void setClass_name(String class_name) { this.class_name = class_name; } public int getJob_enabled() { return job_enabled; } public void setJob_enabled(int job_enabled) { this.job_enabled = job_enabled; } public String getJob_time() { return job_time; } public void setJob_time(String job_time) { this.job_time = job_time; } public int getJob_interval() { return job_interval; } public void setJob_interval(int job_interval) { this.job_interval = job_interval; } public int getRepearcount() { return repearcount; } public void setRepearcount(int repearcount) { this.repearcount = repearcount; } public int getDelaytime() { return delaytime; } public void setDelaytime(int delaytime) { this.delaytime = delaytime; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public int getExe_type() { return exe_type; } public void setExe_type(int exe_type) { this.exe_type = exe_type; } public String getLast_op_date() { return last_op_date; } public void setLast_op_date(String last_op_date) { this.last_op_date = last_op_date; } public int getIs_cur_exe() { return is_cur_exe; } public void setIs_cur_exe(int is_cur_exe) { this.is_cur_exe = is_cur_exe; } public int getMax_exe_time() { return max_exe_time; } public void setMax_exe_time(int max_exe_time) { this.max_exe_time = max_exe_time; } }
package com.tencent.xweb.extension.video; import java.util.TimerTask; class c$17 extends TimerTask { final /* synthetic */ c vCb; c$17(c cVar) { this.vCb = cVar; } public final void run() { this.vCb.cIC(); } }
package com.kkd.aadharverificationservice; import java.io.IOException; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.context.annotation.Bean; import org.xmlpull.v1.XmlPullParserException; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @SpringBootApplication @EnableDiscoveryClient //@EnableSwagger2 //@EnableFeignClients("com.kkd.authenticationauthorisationserver") public class AadharVerificationServiceApplication{ public static void main(String[] args) { SpringApplication.run(AadharVerificationServiceApplication.class, args); } // For swagger to document the Service /*@Bean public Docket api() throws IOException,XmlPullParserException{ return new Docket(DocumentationType.SWAGGER_2); }*/ }
package com.mes.old.meta; // Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final import java.math.BigDecimal; /** * CCostCorrect generated by hbm2java */ public class CCostCorrect implements java.io.Serializable { private String uniqueid; private String allocateFrom; private Long relationResourceType; private String relationResourceId; private BigDecimal correctCoefficient; public CCostCorrect() { } public CCostCorrect(String uniqueid) { this.uniqueid = uniqueid; } public CCostCorrect(String uniqueid, String allocateFrom, Long relationResourceType, String relationResourceId, BigDecimal correctCoefficient) { this.uniqueid = uniqueid; this.allocateFrom = allocateFrom; this.relationResourceType = relationResourceType; this.relationResourceId = relationResourceId; this.correctCoefficient = correctCoefficient; } public String getUniqueid() { return this.uniqueid; } public void setUniqueid(String uniqueid) { this.uniqueid = uniqueid; } public String getAllocateFrom() { return this.allocateFrom; } public void setAllocateFrom(String allocateFrom) { this.allocateFrom = allocateFrom; } public Long getRelationResourceType() { return this.relationResourceType; } public void setRelationResourceType(Long relationResourceType) { this.relationResourceType = relationResourceType; } public String getRelationResourceId() { return this.relationResourceId; } public void setRelationResourceId(String relationResourceId) { this.relationResourceId = relationResourceId; } public BigDecimal getCorrectCoefficient() { return this.correctCoefficient; } public void setCorrectCoefficient(BigDecimal correctCoefficient) { this.correctCoefficient = correctCoefficient; } }
package com.techlab.basic; public class RectangleRefTest { }
package com.khaale.bigdatarampup.mapreduce.hw4.part1.writables; import org.apache.hadoop.io.WritableComparable; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; /** * Created by Aleksander_Khanteev on 3/30/2016. */ public class ImpressionKeyWritable implements WritableComparable<ImpressionKeyWritable> { private String iPinYouId; private long timestamp; public ImpressionKeyWritable() { set("", 0L); } public ImpressionKeyWritable(String iPinYouId, long timestamp) { set(iPinYouId, timestamp); } public void set(String iPinYouId, Long timestamp) { this.iPinYouId = iPinYouId; this.timestamp = timestamp; } @Override public void write(DataOutput dataOutput) throws IOException { dataOutput.writeUTF(iPinYouId); dataOutput.writeLong(timestamp); } @Override public void readFields(DataInput dataInput) throws IOException { iPinYouId = dataInput.readUTF(); timestamp = dataInput.readLong(); } @Override public String toString() { return "IpStatsWritable{" + "iPinYouId=" + iPinYouId + ", timestamp=" + timestamp + '}'; } public long getTimestamp() { return timestamp; } public String getiPinYouId() { return iPinYouId; } @Override public int compareTo(ImpressionKeyWritable that) { if (this == that) return 0; int comp = iPinYouId.compareTo(that.iPinYouId); if (comp == 0) { comp = Long.compare(timestamp, that.timestamp); } return comp; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ImpressionKeyWritable that = (ImpressionKeyWritable) o; if (timestamp != that.timestamp) return false; return iPinYouId != null ? iPinYouId.equals(that.iPinYouId) : that.iPinYouId == null; } @Override public int hashCode() { int result = iPinYouId != null ? iPinYouId.hashCode() : 0; result = 31 * result + (int) (timestamp ^ (timestamp >>> 32)); return result; } }
/* CMPT 225 - EXTRA WORK: CHALLENGE 1 (June 19th) * Detect a corrupted single-linked list. */ /** * Some testing of isCorrupt() method and fixCorrupt() method. * * * @author Riku Kenju (301067011). E-mail: rkenju@sfu.ca * */ public class Main { public static void main(String[] args) { int max_prints = 20; CorruptableLinkedList corrupted_list = new CorruptableLinkedList(); if (corrupted_list.isCorrupt())//check if the list is not already corrupted System.out.println("Corrupted!(even before corruption!?)"); corrupted_list.corrupt();//intentioanlly corrupt the list for testing if (corrupted_list.isCorrupt()){ System.out.println("Corrupted!(isCorrupt method is working!)"); System.out.println("Printing corrupted list"); for(int elt : corrupted_list) {//print the corrupted list System.out.println(elt); max_prints--; if(max_prints == 0) break; } } corrupted_list.fixCorruption();//attempt a fix if (corrupted_list.isCorrupt())//print notice if list still corrupted System.out.println("Corrupted!(fixCorruption() not working!)"); else{ System.out.println("fixCorruption() is working! Printing fixed list"); for(int elt : corrupted_list) {//print the fixed list (partial) System.out.println(elt); max_prints--; if(max_prints == 0) break; } } } }
/* * Copyright 2017 University of Michigan * * 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 edu.umich.verdict.query; import edu.umich.verdict.VerdictContext; import edu.umich.verdict.dbms.DbmsJDBC; //import edu.umich.verdict.dbms.DbmsSpark; import edu.umich.verdict.dbms.DbmsSpark2; import edu.umich.verdict.exceptions.VerdictException; import edu.umich.verdict.parser.VerdictSQLBaseVisitor; import edu.umich.verdict.parser.VerdictSQLParser; import edu.umich.verdict.util.StringManipulations; import edu.umich.verdict.util.VerdictLogger; public class ShowTablesQuery extends SelectQuery { public ShowTablesQuery(VerdictContext vc, String q) { super(vc, q); } @Override public void compute() throws VerdictException { VerdictSQLParser p = StringManipulations.parserOf(queryString); VerdictSQLBaseVisitor<String> visitor = new VerdictSQLBaseVisitor<String>() { private String schemaName = null; protected String defaultResult() { return schemaName; } @Override public String visitShow_tables_statement(VerdictSQLParser.Show_tables_statementContext ctx) { if (ctx.schema != null) { schemaName = ctx.schema.getText(); } return schemaName; } }; String schema = visitor.visit(p.show_tables_statement()); schema = (schema != null) ? schema : ((vc.getCurrentSchema().isPresent()) ? vc.getCurrentSchema().get() : null); if (schema == null) { VerdictLogger.info("No schema specified; cannot show tables."); return; } else { if (vc.getDbms().isJDBC()) { rs = ((DbmsJDBC) vc.getDbms()).getTablesInResultSet(schema); // } else if (vc.getDbms().isSpark()) { // df = ((DbmsSpark) vc.getDbms()).getTablesInDataFrame(schema); } else if (vc.getDbms().isSpark2()) { ds = ((DbmsSpark2) vc.getDbms()).getTablesInDataset(schema); } } } }
package com.he.loader; import android.content.Context; import android.content.ContextWrapper; import com.he.SettingsProvider; public class TTAppCompiler implements Runnable { private static volatile boolean libs_loaded; private long _ptr; private int cacheMinSize = 32768; private Callback callback; public TTAppCompiler() { if (!libs_loaded) loadLibs(); } public TTAppCompiler(Callback paramCallback) { if (!libs_loaded) loadLibs(); this.callback = paramCallback; } private static native void cleanupCompiler(long paramLong); private static native void clearTasks(long paramLong); private static void loadLibs() { // Byte code: // 0: ldc com/he/loader/TTAppCompiler // 2: monitorenter // 3: getstatic com/he/loader/TTAppCompiler.libs_loaded : Z // 6: istore_0 // 7: iload_0 // 8: ifeq -> 15 // 11: ldc com/he/loader/TTAppCompiler // 13: monitorexit // 14: return // 15: ldc 'c++_shared' // 17: invokestatic load : (Ljava/lang/String;)V // 20: goto -> 32 // 23: astore_1 // 24: ldc 'TTAppCompiler' // 26: ldc 'library for c++_shared not loaded' // 28: aload_1 // 29: invokestatic eWithThrowable : (Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)V // 32: ldc 'v8_libbase.cr' // 34: invokestatic load : (Ljava/lang/String;)V // 37: ldc 'v8_libplatform.cr' // 39: invokestatic load : (Ljava/lang/String;)V // 42: ldc 'v8.cr' // 44: invokestatic load : (Ljava/lang/String;)V // 47: ldc 'skialite' // 49: invokestatic load : (Ljava/lang/String;)V // 52: goto -> 64 // 55: astore_1 // 56: ldc 'TTAppCompiler' // 58: ldc 'load skialite failed' // 60: aload_1 // 61: invokestatic eWithThrowable : (Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)V // 64: ldc 'helium' // 66: invokestatic load : (Ljava/lang/String;)V // 69: goto -> 81 // 72: astore_1 // 73: ldc 'TTAppCompiler' // 75: ldc 'library for v8xxx not loaded' // 77: aload_1 // 78: invokestatic eWithThrowable : (Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)V // 81: iconst_1 // 82: putstatic com/he/loader/TTAppCompiler.libs_loaded : Z // 85: ldc com/he/loader/TTAppCompiler // 87: monitorexit // 88: return // 89: astore_1 // 90: ldc com/he/loader/TTAppCompiler // 92: monitorexit // 93: aload_1 // 94: athrow // Exception table: // from to target type // 3 7 89 finally // 15 20 23 finally // 24 32 89 finally // 32 47 72 finally // 47 52 55 finally // 56 64 72 finally // 64 69 72 finally // 73 81 89 finally // 81 85 89 finally } private static native void pauseCompiler(long paramLong); private static native int queueTask(long paramLong, byte[] paramArrayOfbyte, String paramString, boolean paramBoolean, int paramInt); private void reflectedOnAsyncCompile(int paramInt1, int paramInt2, int paramInt3) { StringBuilder stringBuilder = new StringBuilder("compiled, id: "); stringBuilder.append(paramInt1); stringBuilder.append(", duration: "); stringBuilder.append(paramInt2); stringBuilder.append(", cache_size: "); stringBuilder.append(paramInt3); Log.i("TTAppCompiler", new Object[] { stringBuilder.toString() }); Callback callback = this.callback; if (callback != null) callback.onCompiled(paramInt1, paramInt2, paramInt3); } private static native boolean removeTask(long paramLong, int paramInt); private static native void resumeCompiler(long paramLong); private native long setupCompiler(String paramString); private static native void startCompiler(long paramLong); private static native void stopCompiler(long paramLong); public void cleanup() { cleanupCompiler(this._ptr); this._ptr = 0L; } public void clearTasks() { long l = this._ptr; if (l != 0L) { clearTasks(l); return; } throw new RuntimeException("TTAppCompilerPtr is null"); } public void pause() { long l = this._ptr; if (l != 0L) { pauseCompiler(l); return; } throw new RuntimeException("TTAppCompilerPtr is null"); } public int queueTask(byte[] paramArrayOfbyte, String paramString, boolean paramBoolean, int paramInt) { long l = this._ptr; if (l != 0L) return queueTask(l, paramArrayOfbyte, paramString, paramBoolean, paramInt); throw new RuntimeException("TTAppCompilerPtr is null"); } public boolean removeTask(int paramInt) { long l = this._ptr; if (l != 0L) return removeTask(l, paramInt); throw new RuntimeException("TTAppCompilerPtr is null"); } public void resume() { long l = this._ptr; if (l != 0L) { resumeCompiler(l); return; } throw new RuntimeException("TTAppCompilerPtr is null"); } public void run() { long l = this._ptr; if (l != 0L) { startCompiler(l); return; } throw new RuntimeException("TTAppCompilerPtr is null"); } public void setup(ContextWrapper paramContextWrapper, SettingsProvider paramSettingsProvider) { String str = "com.he.loader.js_cache"; if (paramSettingsProvider != null) { str = paramSettingsProvider.getSetting((Context)paramContextWrapper, TTAppLoader.Settings.CODECACHE_DIR, "com.he.loader.js_cache"); this.cacheMinSize = paramSettingsProvider.getSetting((Context)paramContextWrapper, TTAppLoader.Settings.CODECACHE_MINSIZE, this.cacheMinSize); } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(paramContextWrapper.getCacheDir()); stringBuilder.append("/"); stringBuilder.append(str); stringBuilder.append("/"); this._ptr = setupCompiler(stringBuilder.toString()); } public boolean shouldCache(int paramInt) { return (paramInt >= this.cacheMinSize); } public void stop() { long l = this._ptr; if (l != 0L) { stopCompiler(l); return; } throw new RuntimeException("TTAppCompilerPtr is null"); } public static interface Callback { void onCompiled(int param1Int1, int param1Int2, int param1Int3); } } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\he\loader\TTAppCompiler.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package com.example.galdino.filmespopulares.telas.detalhesDoFilme; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.support.v7.widget.LinearLayoutManager; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.example.galdino.filmespopulares.R; import com.example.galdino.filmespopulares.adapter.AdapterListComentario; import com.example.galdino.filmespopulares.adapter.AdapterListTrailers; import com.example.galdino.filmespopulares.dataBase.AppDataBase; import com.example.galdino.filmespopulares.databinding.FragmentFilmeDetalheBinding; import com.example.galdino.filmespopulares.databinding.IncludeCapaFilmeBinding; import com.example.galdino.filmespopulares.dominio.AnimationControler; import com.example.galdino.filmespopulares.dominio.Filme; import com.example.galdino.filmespopulares.dominio.filmeDetalhe.Comentarios; import com.example.galdino.filmespopulares.dominio.filmeDetalhe.Result; import com.example.galdino.filmespopulares.dominio.filmeDetalhe.Videos; import com.example.galdino.filmespopulares.mvp.di.AppComponent; import com.example.galdino.filmespopulares.mvp.di.DaggerAppComponent; import com.example.galdino.filmespopulares.mvp.di.modules.ModelModule; import com.squareup.picasso.Picasso; import java.util.List; import javax.inject.Inject; public class FilmeDetalheFragment extends Fragment implements FilmeDetalheMvpView, View.OnClickListener { private FragmentFilmeDetalheBinding mBinding; private FilmeDetalheMvpPresenter mPresenter; private Integer mIdFilme; private Filme mFilme; private boolean mFgListaTrailerAberta; // private Filme filme; private AppDataBase db; private Videos mVideos; private AdapterListTrailers.ListenerAdapter mListener = new AdapterListTrailers.ListenerAdapter() { @Override public void onItenClickListener(Result result) { // Toast.makeText(getContext().getApplicationContext(),"teste",Toast.LENGTH_SHORT).show(); String urlVideo = "vnd.youtube:"+result.getKey(); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(urlVideo)); intent.putExtra("VIDEO_ID",result.getKey()); startActivity(intent); } }; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment mBinding = FragmentFilmeDetalheBinding.inflate(inflater,container, false); mFgListaTrailerAberta = false; // Habilita o menu no fragment setHasOptionsMenu(true); // Dagger AppComponent appComponent = DaggerAppComponent.builder() .modelModule(new ModelModule(getContext().getApplicationContext())) .build(); appComponent.inject(this); if (mIdFilme != null) { onFilmeDetalheBuscarInformacoes(mIdFilme); } return mBinding.getRoot(); } @Inject public void setPresenter(FilmeDetalheMvpPresenter presenter) { mPresenter = presenter; // Vincula a view ao presenter presenter.attach(this); } @Override public void onFilmeDetalheBuscarInformacoes(int idFilme) { mIdFilme = idFilme; if (mBinding != null) { mBinding.pbLoading.setVisibility(View.VISIBLE); mPresenter.getFilmeDetalhe(idFilme); } } @Override public void onFilmeDetalheFalhaAoBuscarInformacoes() { Toast.makeText(getContext(),getString(R.string.erro_buscar_detalhe_filme),Toast.LENGTH_SHORT).show(); mBinding.pbLoading.setVisibility(View.INVISIBLE); } @Override public void onFilmeDetalhePreparado(Filme filme) { if(filme != null && mBinding != null) { mBinding.labelTrailer.setOnClickListener(this); mBinding.labelComentarios.setOnClickListener(this); mBinding.includeListTrailers.tvFecharListaTrailers.setOnClickListener(this); mBinding.labelTrailer.setVisibility(View.VISIBLE); mBinding.labelComentarios.setVisibility(View.VISIBLE); mFilme = filme; db = AppDataBase.getInstance(getContext().getApplicationContext()); mBinding.inclCapaFilme.getRoot().setVisibility(View.VISIBLE); String urlCapa = getResources().getString(R.string.url_images_500) + filme.getPosterPath(); IncludeCapaFilmeBinding includeCapaFilmeBinding = mBinding.inclCapaFilme; Picasso.with(mBinding.getRoot().getContext()).load(urlCapa).into(includeCapaFilmeBinding.ivCapaFilme); mBinding.tvNomeFilme.setText(filme.getTitle()); if(filme.getReleaseDate()!= null) { String ano = filme.getReleaseDate().substring(0, filme.getReleaseDate().indexOf("-")); mBinding.tvAno.setText(ano); } if(filme.getRuntime() != null) { String tempo = Integer.toString(filme.getRuntime()); tempo += "min"; mBinding.tvTempoFilme.setText(tempo); } if(filme.getVoteAverage() != null) { String nota = Double.toString(filme.getVoteAverage()) + "/10"; mBinding.tvNotaFilme.setText(nota); } mBinding.tvDescricaoFilme.setText(filme.getOverview()); if(filme.getVideos() != null) { mVideos = filme.getVideos(); openTrailers(filme.getVideos()); } } mBinding.pbLoading.setVisibility(View.INVISIBLE); } @Override public void onComentariosPreparado(List<Result> comentarios) { openComentarios(comentarios); mFgListaTrailerAberta = true; AnimationControler.upShowView(mBinding.includeListTrailers.constraintTrailer,getContext().getApplicationContext()); mBinding.includeListTrailers.tvFecharListaTrailers.setFocusable(true); mBinding.pbLoading.setVisibility(View.INVISIBLE); } @Override public void onComentarioFalhaAoBuscarInformacoes() { Toast.makeText(getContext().getApplicationContext(),getString(R.string.erro_busca_comentario), Toast.LENGTH_SHORT).show(); fecharListaTrailer(); mBinding.pbLoading.setVisibility(View.INVISIBLE); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if(id == R.id.im_filmes_detalhe_favorito) { if(mFilme != null) { if (mFilme.getFgFavorito() == 1) { item.setIcon(ContextCompat.getDrawable(getContext().getApplicationContext(), R.drawable.ic_favorito_vazio_azul)); mFilme.setFgFavorito(0); db.filmeDAO().deleteAll(mFilme); if (mFilme.getVideos() != null && mFilme.getVideos().getResults() != null && mFilme.getVideos().getResults().size() > 0) { db.resultDAO().deleteById(mFilme.getVideos().getResults()); } } else { item.setIcon(ContextCompat.getDrawable(getContext().getApplicationContext(), R.drawable.ic_favorito_preenchido_azul)); mFilme.setFgFavorito(1); if (mFilme.getUid() == 0) { db.filmeDAO().insertAll(mFilme); if (mFilme.getVideos() != null && mFilme.getVideos().getResults() != null && mFilme.getVideos().getResults().size() > 0) { db.resultDAO().insertAll(mFilme.getVideos().getResults()); } } } } } else { if(mFgListaTrailerAberta) { fecharListaTrailer(); } else { getActivity().finish(); } } return true; } @Override public void onClick(View v) { if(v == mBinding.includeListTrailers.tvFecharListaTrailers) { fecharListaTrailer(); } else if(v == mBinding.labelComentarios) { mBinding.pbLoading.setVisibility(View.VISIBLE); mPresenter.getComentarios(mFilme.getId()); } else if (v == mBinding.labelTrailer) { if(mVideos != null) { openTrailers(mVideos); mFgListaTrailerAberta = true; // AnimationControler.translateShow(mBinding.ivSombra,getContext().getApplicationContext()); AnimationControler.upShowView(mBinding.includeListTrailers.constraintTrailer, getContext().getApplicationContext()); mBinding.includeListTrailers.tvFecharListaTrailers.setFocusable(true); } } } public boolean listaTrailerAberta() { return mFgListaTrailerAberta; } public void fecharListaTrailer() { mFgListaTrailerAberta = false; // AnimationControler.translateHide(mBinding.ivSombra,getContext().getApplicationContext()); AnimationControler.downHideView(mBinding.includeListTrailers.constraintTrailer,getContext().getApplicationContext()); } @Override public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) { MenuInflater menuInflater = getActivity().getMenuInflater(); menuInflater.inflate(R.menu.menu_activity_filmes_detalhe,menu); if(mFilme != null && mFilme.getUid() > 0) { mFilme.setFgFavorito(0); // Passa false pra ficar true onOptionsItemSelected(menu.findItem(R.id.im_filmes_detalhe_favorito)); } } private void openComentarios(List<Result> comentarios) { AdapterListComentario adapterListComentarios = new AdapterListComentario(comentarios); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext().getApplicationContext()); mBinding.includeListTrailers.rvTrailers.setAdapter(adapterListComentarios); mBinding.includeListTrailers.rvTrailers.setLayoutManager(linearLayoutManager); mBinding.includeListTrailers.rvTrailers.setNestedScrollingEnabled(false); } private void openTrailers(Videos videos) { AdapterListTrailers adapterListTrailers = new AdapterListTrailers(videos.getResults()); if(mListener != null) { adapterListTrailers.setListener(mListener); } LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext().getApplicationContext()); mBinding.includeListTrailers.rvTrailers.setAdapter(adapterListTrailers); mBinding.includeListTrailers.rvTrailers.setLayoutManager(linearLayoutManager); mBinding.includeListTrailers.rvTrailers.setNestedScrollingEnabled(false); } }
package com.xj.library.utils.file; import android.database.Cursor; import android.util.Log; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.math.BigInteger; import java.security.MessageDigest; import java.text.SimpleDateFormat; import java.util.List; import java.util.Locale; import java.util.Set; /** * 博客地址:http://blog.csdn.net/gdutxiaoxu * * @author xujun * 2016/12/27 23:50. * <p> * 文件工具类 */ public class FileUtil { public static final String UTF_8 = "UTF-8"; public static final String GBK = "GBK"; public static boolean isImage(String fileName) { return fileName.endsWith(".jpg") || fileName.endsWith(".png") || fileName.endsWith("" + ".jpeg") || fileName.endsWith(".gif") || fileName.endsWith(".bmp") || fileName.endsWith(".webp"); } public static void exportToCSV(Cursor c, File saveFile) { int rowCount = 0; int colCount = 0; BufferedWriter bfw; try { rowCount = c.getCount(); colCount = c.getColumnCount(); bfw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(saveFile), GBK)); if (rowCount > 0) { c.moveToFirst(); // 写入表头 for (int i = 0; i < colCount; i++) { if (i != colCount - 1) bfw.write(c.getColumnName(i) + ','); else bfw.write(c.getColumnName(i)); } // 写好表头后换行 bfw.newLine(); // 写入数据 for (int i = 0; i < rowCount; i++) { c.moveToPosition(i); // Toast.makeText(mContext, "正在导出第"+(i+1)+"条", // Toast.LENGTH_SHORT).show(); // Log.v("导出数据", "正在导出第" + (i + 1) + "条"); for (int j = 0; j < colCount; j++) { if (j != colCount - 1) bfw.write(c.getString(j) + ','); else bfw.write(c.getString(j)); } // 写好每条记录后换行 bfw.newLine(); } } // 将缓存数据写入文件 bfw.flush(); // 释放缓存 bfw.close(); // Toast.makeText(mContext, "导出完毕!", Toast.LENGTH_SHORT).show(); Log.v("导出数据", "导出完毕!"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { c.close(); } } /** * if exit, rename file * * @param file * @return */ public static File ifExitRenameFile(File file) { int i = 1; String path = file.getPath(); path = path + "(" + i + ")"; while (new File(path).exists()) { ++i; path = path + "(" + i + ")"; } return new File(path); } /** * byte(字节)根据长度转成kb(千字节)和mb(兆字节) * * @param bytes * @return */ public static String bytes2kb(long bytes) { BigDecimal filesize = new BigDecimal(bytes); BigDecimal megabyte = new BigDecimal(1024 * 1024); float returnValue = filesize.divide(megabyte, 2, BigDecimal.ROUND_UP) .floatValue(); if (returnValue > 1) return (returnValue + "MB"); BigDecimal kilobyte = new BigDecimal(1024); returnValue = filesize.divide(kilobyte, 2, BigDecimal.ROUND_UP) .floatValue(); return (returnValue + "KB"); } public static String dateFormat(long date) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()); return sdf.format(date * 1000); } public static void saveToFile(List<String> list, String path) { File file = new File(path); StringBuilder stringBuilder = new StringBuilder(); for (String line : list) { stringBuilder.append(line).append("\n"); } BufferedWriter bufferedWriter = null; try { bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), UTF_8)); bufferedWriter.write(stringBuilder.toString()); bufferedWriter.flush(); bufferedWriter.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.close(bufferedWriter); } /* FileWriter filerWriter = null; BufferedWriter bufWriter = null; try { filerWriter = new FileWriter(file, true); bufWriter = new BufferedWriter(filerWriter); bufWriter.write(stringBuilder.toString()); // bufWriter.newLine(); bufWriter.flush(); bufWriter.close(); filerWriter.close(); } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.close(bufWriter); IOUtils.close(filerWriter); }*/ } public static String readFile(Set<String> list, String path) { File file = new File(path); BufferedReader bufferedReader = null; try { StringBuilder stringBuilder = new StringBuilder(); bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), UTF_8)); String line = bufferedReader.readLine(); while (line != null) { list.add(line); line = bufferedReader.readLine(); stringBuilder.append(line); } return stringBuilder.toString(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.close(bufferedReader); } return ""; } public static String readFile(List<String> list, String path) { File file = new File(path); BufferedReader bufferedReader = null; try { StringBuilder stringBuilder = new StringBuilder(); bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), UTF_8)); String line = bufferedReader.readLine(); while (line != null) { list.add(line); line = bufferedReader.readLine(); stringBuilder.append(line); } return stringBuilder.toString(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.close(bufferedReader); } return ""; } public static long fileSize(String pathAndFile) { File file = new File(pathAndFile); return file.length(); } public static boolean fileExist(String pathAndFile) { File file = new File(pathAndFile); if (file.exists()) return true; else return false; } public static void fileRename(String fName, String nName) { File file = new File(fName); file.renameTo(new File(nName)); file.delete(); } public static String getMd5ByFile(File file) { String value = null; FileInputStream in = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); in = new FileInputStream(file); byte[] buffer = new byte[4096]; int length = -1; while ((length = in.read(buffer)) != -1) { md5.update(buffer, 0, length); } BigInteger bi = new BigInteger(1, md5.digest()); value = bi.toString(16); } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (in != null) { in.close(); } } catch (IOException ex) { } } return value; } }
package com.tencent.tencentmap.mapsdk.a; import android.graphics.Bitmap; import com.tencent.map.lib.basemap.data.GeoPoint; public class iz { protected String a; private GeoPoint b; private Bitmap[] c; private float d = 0.5f; private float e = 0.5f; private float f = 1.0f; private boolean g = false; private int h; private boolean i; private int j; private int k; private int l; private boolean m; private boolean n = false; private boolean o; private boolean p = true; public iz a(GeoPoint geoPoint) { this.b = geoPoint; return this; } public GeoPoint a() { return this.b; } public iz a(String str, Bitmap... bitmapArr) { this.a = str; this.c = bitmapArr; return this; } public iz a(boolean z) { this.n = z; return this; } public Bitmap[] b() { return this.c; } public String c() { return this.a; } public iz b(boolean z) { this.g = z; return this; } public boolean d() { return this.g; } public iz a(float f) { this.f = f; return this; } public float e() { return this.f; } public iz a(float f, float f2) { this.d = f; this.e = f2; return this; } public float f() { return this.d; } public float g() { return this.e; } public iz a(int i) { this.h = i; return this; } public int h() { return this.h; } public boolean i() { return this.i; } public iz c(boolean z) { this.o = z; return this; } public boolean j() { return this.o; } public int k() { return this.j; } public int l() { return this.k; } public iz b(int i) { this.l = i; return this; } public int m() { return this.l; } public iz d(boolean z) { this.m = z; return this; } public boolean n() { return this.m; } public boolean o() { return this.n; } public iz e(boolean z) { this.p = z; return this; } public boolean p() { return this.p; } }
package test; import hidden.HiddenBody; import javax.persistence.Persistence; import jpamock.instance.JPAMock; import junit.framework.TestCase; public class TestHidden extends TestCase { JPAMock jpaMock; @Override protected void setUp() throws Exception { jpaMock = new JPAMock(Persistence.createEntityManagerFactory("jpamock_mysql")); } public void test() { //jpaMock.clearAll(); jpaMock.mock(HiddenBody.class); } }
package com.hxzy.mapper; import com.hxzy.common.vo.PageSearch; import com.hxzy.entity.Major; import java.util.List; public interface MajorMapper { /** * 新增 * @param record * @return */ int insert(Major record); /** * 根据主键查询 * @param id * @return */ Major selectByPrimaryKey(Integer id); /** * 根据主键,只更新不为null的列 * @param record * @return */ int updateByPrimaryKeySelective(Major record); /** * 根据主键全部更新 * @param record * @return */ int updateByPrimaryKey(Major record); /** * 分页查询 * @param pageSearch * @return */ List<Major> search(PageSearch pageSearch); /** * 加载所有的数据 * @return */ List<Major> searchAll(); }
package sample; public class Responsability { private int OwnerID; private int ChildID; public Responsability(int Owner,int Child){ this.OwnerID = Owner; this.ChildID = Child; } public void setOwner(int newowner) { OwnerID = newowner; } public void setChild(int newchild) { ChildID = newchild; } public int getOwner() { return this.OwnerID; } public int getChild() { return this.ChildID; } @Override public String toString() { return "OwnerId = " + this.OwnerID + " ChildId = " + this.ChildID; } }
package it.univpm.Progetto_Programmazione.Service; import java.util.List; import java.util.Map; import org.springframework.stereotype.Service; import com.lindatato.Progetto.Model.Erasmus; import com.lindatato.Progetto.Service.Filter; import com.lindatato.Progetto.Service.Metadata; import com.lindatato.Progetto.Service.Stats; import com.lindatato.Progetto.Utilities.DownloadAndParsing; /** * Classe concepita per rispondere alle richieste effettuate tramite postman, utilizzando le classi precedentemente create */ @Service public class Service { private String url= "https://data.europa.eu/euodp/data/api/3/action/package_show?id=vrjbNpJPeAOWLuNRhT6Tg"; private DownloadandParsing dp; private Metadata Mdata; private Statistic stats; private Filter filtri; private List<Energy> lista; /* * Costruttore che, all'avvio dell'applicazione, effettua Download e Parsing dei dati del tsv * e vengono estratti i relativi dati */ public Service() { this.dp = new DownloadAndParsing(); this.Mdata = new Metadata(); this.stats = new Statistic(); this.filtri = new Filter(); String link=""; link = dp.download(url); lista = dp.parsing(link); } /** * Metodo che restituisce i metadati del file TSV * @return la lista dei metadati */ public List<Map> getMetadata() { return Mdata.getMetadata(); } /** * Metodo che restituisce i dati del file * @return lista dei dati */ public List<Energy> getData() { return this.lista; } /** * Metodo che restituisce le statistiche di un dato attributo * @param nomeCampo contiene il valore dell'attributo del quale si vogliono calcolare le statistiche * @return map delle statistiche desiderate */ }
package kodlamaIo; public class Trainers { public Trainers(){ } public Trainers(int id, String userid, String name, String lastname) { this.id = id; this.userid = userid; this.name = name; this.lastname = lastname; } int id; String userid; String name; String lastname; }
package edu.tacoma.uw.myang12.pocketdungeon.authenticate; import androidx.appcompat.app.AppCompatActivity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import edu.tacoma.uw.myang12.pocketdungeon.MainMenuActivity; import edu.tacoma.uw.myang12.pocketdungeon.R; /** * SignIn activity checks if a user was previously logged in. */ public class SignInActivity extends AppCompatActivity implements LoginFragment.LoginFragmentListener, RegisterFragment.RegisterFragmentListener { private SharedPreferences mSharedPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign_in); /** Use SharedPreferences to check if the user was previously logged in. */ mSharedPreferences = getSharedPreferences(getString(R.string.LOGIN_PREFS), Context.MODE_PRIVATE); /** if not logged in, open login screen */ if (!mSharedPreferences.getBoolean(getString(R.string.LOGGEDIN), false)) { getSupportFragmentManager().beginTransaction() .add(R.id.sign_in_fragment_id, new LoginFragment()) .commit(); /** if previously logged in, open main screen */ } else { Intent intent = new Intent(this, MainMenuActivity.class); startActivity(intent); finish(); } } /** After user logs in, change SharedPreferences to true. */ @Override public void login(String email, String pwd) { mSharedPreferences .edit() .putBoolean(getString(R.string.LOGGEDIN), true) .commit(); } @Override public void register(String email, String pwd) { } }
package edu.pdx.cs410J.hueb; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.widget.Button; import android.widget.Toast; import com.google.android.material.textfield.TextInputEditText; import java.io.File; public class ListAllApptsActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list_all_appts); Button viewAppts = findViewById(R.id.viewAllApptsButtonViewAppts); viewAppts.setOnClickListener(view -> viewAppts()); } private void toast(String message) { Toast.makeText(ListAllApptsActivity.this, message, Toast.LENGTH_LONG).show(); } private void viewAppts() { TextInputEditText owner = findViewById(R.id.text_input_owner2_view_appt); String ownerString = owner.getText().toString(); if(ownerString.isEmpty()) { toast("Owner Name Is Required"); return; } File contextDir = getApplicationContext().getDataDir(); File file = new File(contextDir, ownerString+".txt"); if (file.exists()) { // toast("EXISTS!"); Intent intent = new Intent(this, ListViewActivity.class); intent.putExtra("OWNER", ownerString); startActivity(intent); } else { toast("Could Not Find Appointment Book For "+ownerString); } } }
package VFlyweight.Flyweight; import java.awt.*; import java.util.Iterator; import java.util.Map; public class FlyweightTest { static int CANVAS_SIZE = 500; static int TREES_TO_DRAW = 1000000; static int TREE_TYPES = 3; public static void main(String[] args) { //Creating additional class instance Forest forest = new Forest(); //Creating trees for (int i = 0; i < Math.floor(TREES_TO_DRAW / TREE_TYPES); i++) { forest.createTree(random(0, CANVAS_SIZE), random(0, CANVAS_SIZE), "Summer Oak", Color.GREEN, "Oak texture stub"); if (i % 5 == 0) { forest.createTree(random(0, CANVAS_SIZE), random(0, CANVAS_SIZE), "Autumn Oak", Color.ORANGE, "Autumn Oak texture stub"); forest.createTree(random(0, CANVAS_SIZE), random(0, CANVAS_SIZE), "Deep autumn Oak", Color.RED, "Deep autumn Oak texture stub"); } } forest.setSize(CANVAS_SIZE, CANVAS_SIZE); forest.setVisible(true); System.out.println("Number of Flyweights in Cache:"); Iterator<Map.Entry<String, TreeFlyweight>> mapIterator = TreeFlyweightFactory.treeFlyweightsCache.entrySet().iterator(); int i = 1; while (mapIterator.hasNext()) { System.out.print(i + ". "); System.out.println(mapIterator.next()); i++; } System.out.println(); System.out.println(TREES_TO_DRAW * 11 / 15 + " trees drawn"); System.out.println("---------------------"); System.out.println("Memory usage:"); System.out.println("TreeContext memory size - 8 bytes"); System.out.println("TreeFlyweight memory size ~30 bytes"); System.out.println("---------------------"); System.out.println("Total: " + ((TREES_TO_DRAW * 11 / 15 * 8 + TREE_TYPES * 30) / 1024 / 1024) + "MB"); } private static int random(int min, int max) { return min + (int) (Math.random() * ((max - min) + 1)); } }
package com.box.androidsdk.content.requests; import com.box.androidsdk.content.BoxConfig; import com.box.androidsdk.content.listeners.ProgressListener; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import javax.net.ssl.HttpsURLConnection; /** * Class that represents an HTTP request. */ class BoxHttpRequest { protected final HttpURLConnection mUrlConnection; protected final ProgressListener mListener; /** * Constructs an HTTP request with the default parameters. * * @param url URL to connect to. * @param method method type for the HTTP request. * @param listener progress listener for a long-running API call. * @throws IOException */ public BoxHttpRequest(URL url, BoxRequest.Methods method, ProgressListener listener) throws IOException { mUrlConnection = (HttpURLConnection) url.openConnection(); mUrlConnection.setRequestMethod(method.toString()); mListener = listener; // enables TLS 1.1 and 1.2 which is disabled by default on kitkat and below if (BoxConfig.ENABLE_TLS_FOR_PRE_20 && mUrlConnection instanceof HttpsURLConnection) { ((HttpsURLConnection) mUrlConnection).setSSLSocketFactory(new BoxRequest.TLSSSLSocketFactory()); } } /** * Adds an HTTP header to the request. * * @param key the header key. * @param value the header value. * @return request with the updated header. */ public BoxHttpRequest addHeader(String key, String value) { mUrlConnection.addRequestProperty(key, value); return this; } /** * Sets the body for the HTTP request to the contents of an InputStream. * * @param body InputStream to use for the contents of the body. * @return request with the updated body input stream. * @throws IOException */ public BoxHttpRequest setBody(InputStream body) throws IOException { mUrlConnection.setDoOutput(true); OutputStream output = mUrlConnection.getOutputStream(); int b = body.read(); while (b != -1) { output.write(b); b = body.read(); } output.close(); return this; } /** * Returns the URL connection for the request. * * @return URL connection for the request. */ public HttpURLConnection getUrlConnection() { return mUrlConnection; } }
package com.xtw.accc; import client.CRClient; import client.PeerUnit; import android.app.Application; public class AcccApp extends Application { public static CRClient sClient; public static PeerUnit sPeerUnit; @Override public void onCreate() { super.onCreate(); } }
package com.coupons.me.couponsme; import android.provider.BaseColumns; /** * Created by user on 6/17/2016. */ public class CouponsMeDbContract { public CouponsMeDbContract() {} /* Inner class that defines the table contents */ public static abstract class Coupons implements BaseColumns { public static final String TABLE_NAME = "Coupons"; //public static final String COLUMN_NAME_ID = "Id"; public static final String COLUMN_NAME_STORE = "StoreName"; public static final String COLUMN_NAME_DATE = "ExpiryDt"; public static final String COLUMN_NAME_DESC = "Description"; public static final String COLUMN_NAME_IS_USED = "IsUsed"; public static final String COLUMN_NAME_PRICE = "Price"; public static final String COLUMN_NAME_UPDATE_TMSTMP="UpdateTimestamp"; public static final String COLUMN_NAME_CREATE_TMSTMP = "CreatedTimestamp"; } }
package com.example.strongM.mycalendarview.calendar.formatter; import android.support.annotation.NonNull; import com.example.strongM.mycalendarview.calendar.CalendarDayData; public interface DayFormatter { String format(@NonNull CalendarDayData day); }