text
stringlengths 10
2.72M
|
|---|
package com.bonc.dxbrgrmp.pojo.po;
import org.springframework.stereotype.Component;
/**
* @Auther: lgf
* @Date: 2019/12/23
* @Description: com.bonc.dxbrgrmp.pojo.po
* @version: 1.0
*/
@Component
public class Testdb {
private int testId;
private float testFloat;
private double testDouble;
private int testBigInt;
private String name;
private String name3;
@Override
public String toString() {
return "Testdb{" +
"testId=" + testId +
", testFloat=" + testFloat +
", testDouble=" + testDouble +
", testBigInt=" + testBigInt +
", name='" + name + '\'' +
", name3='" + name3 + '\'' +
'}';
}
public int getTestId() {
return testId;
}
public void setTestId(int testId) {
this.testId = testId;
}
public float getTestFloat() {
return testFloat;
}
public void setTestFloat(float testFloat) {
this.testFloat = testFloat;
}
public double getTestDouble() {
return testDouble;
}
public void setTestDouble(double testDouble) {
this.testDouble = testDouble;
}
public int getTestBigInt() {
return testBigInt;
}
public void setTestBigInt(int testBigInt) {
this.testBigInt = testBigInt;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getName3() {
return name3;
}
public void setName3(String name3) {
this.name3 = name3;
}
}
|
package com.tencent.mm.ui.contact.a;
import android.view.View;
import android.widget.TextView;
import com.tencent.mm.ui.contact.a.a.a;
public class f$a extends a {
public TextView eCn;
public View umJ;
final /* synthetic */ f umK;
public f$a(f fVar) {
this.umK = fVar;
super(fVar);
}
}
|
package com.brady.euler;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.TreeSet;
public class Problem124 extends Problem {
public long solve() {
int n = 100000, sqrtN = (int) Math.sqrt(n);
int k = 10000;
int[] primes = EulerUtils.sieve(n);
TreeMap<Integer, TreeSet<Integer>> tree = new TreeMap<>();
TreeSet<Integer> one = new TreeSet<Integer>(Arrays.asList(1));
tree.put(1, one);
for (int p : primes) {
TreeSet<Integer> powersOfP = new TreeSet<>();
int pExp = p;
do {
powersOfP.add(pExp);
} while (p <= sqrtN && (pExp *= p) < n);
ArrayDeque<TreeSet<Integer>> toAdd = new ArrayDeque<>();
for (Entry<Integer, TreeSet<Integer>> prevPowers : tree.entrySet()) {
if ((p * prevPowers.getKey()) > n) {
break;
} else {
TreeSet<Integer> powersOfNewBase = new TreeSet<>();
for (int powerOfP : powersOfP) {
for (int prevPower : prevPowers.getValue()) {
int product;
if ((product = powerOfP*prevPower) <= n){
powersOfNewBase.add(product);
} else {
break;
}
}
}
toAdd.add(powersOfNewBase);
}
}
tree.put(p, powersOfP);
for (TreeSet<Integer> powersOfNewBase : toAdd) {
tree.put(powersOfNewBase.first(), powersOfNewBase);
}
}
//Find first radical that brings us over k
int count = 0;
TreeSet<Integer> nextRadical;
while (count + (nextRadical = tree.pollFirstEntry().getValue()).size() < k) {
count += nextRadical.size();
}
//Increment through the radical until we find the k'th number
int num = 0;
for (; count < k; count++) {
num = nextRadical.pollFirst();
}
return num;
}
}
|
/*
* 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.extrt;
import org.osgi.framework.Bundle;
import vanadis.blueprints.BundleSpecification;
import vanadis.blueprints.ModuleSpecification;
interface ModuleSystemListener {
/**
* <P>Notify that a bundle has been added. Will install the bundle from the URI. Later,
* {@link org.osgi.framework.BundleListener#bundleChanged(org.osgi.framework.BundleEvent)} is invoked.
* When this happens, it is either because we installed the bundle, or someone else did. Either way,
* that will force us to look through the bundle for
* {@link vanadis.objectmanagers.ObjectManagerFactory object manager factories}.</P>
*
* <p>Properties respected:</p>
*
* <ul>
* <li><dt><code>start-level</code></dt> <dd>start level for bundle</dd></li>
* </ul>
*
* @param bundleSpecification Bundle specification
*/
void bundleSpecificationAdded(BundleSpecification bundleSpecification);
/**
* Bundle was removed.
*
* @param bundleSpecification URI for bundle
*/
void bundleSpecificationRemoved(BundleSpecification bundleSpecification);
/**
* <P>Notify that a launch has been added. This launch will refer to an existing (or future)
* {@link vanadis.objectmanagers.ObjectManagerFactory object manager factory},
* and specify the creation of an actual, named
* {@link vanadis.ext.ObjectManager object manager}.
*
* @param moduleSpecification Actual launch specification
*/
void moduleSpecificationAdded(ModuleSpecification moduleSpecification);
/**
* A launch has been removed. Take down the {@link vanadis.ext.ObjectManager object manager}
* that was specified by it.
*
* @param moduleSpecification Actual launch specification
*/
void moduleSpecificationRemoved(ModuleSpecification moduleSpecification);
/**
* Notify that these bundles existed prior to the startup.
*
* @param bundles The bundles
*/
void spool(Iterable<Bundle> bundles);
}
|
package com.tencent.tencentmap.mapsdk.a;
public class at {
public static final at a = new at();
private ThreadLocal<b> b = new 1(this);
private at() {
}
public b a() {
return (b) this.b.get();
}
}
|
package com.jim.multipos.ui.admin_main_page.fragments.establishment.model;
public class Establishment {
String name;
String address;
String phone;
String stocks;
String mainStock;
String description;
String posCount;
public Establishment(String name, String address, String phone, String stocks, String mainStock, String description, String posCount) {
this.name = name;
this.address = address;
this.phone = phone;
this.stocks = stocks;
this.mainStock = mainStock;
this.description = description;
this.posCount = posCount;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public String getPhone() {
return phone;
}
public String getStocks() {
return stocks;
}
public String getMainStock() {
return mainStock;
}
public String getDescription() {
return description;
}
public String getPosCount() {
return posCount;
}
}
|
package com.example.provider8001;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author CBeann
* @create 2019-07-26 12:35
*/
@RestController
public class GatewayController{
@RequestMapping("/mypath/get/method1")
public String method1(){
return "/mypath/get/metoid1";
}
}
|
package com.example.victor.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
public class DisplayLyrics extends AppCompatActivity {
public static final String LYRICS_BODY = "com.example.victor.myapplication.LYRICS_BODY";
public static final String TRACK_NAME = "com.example.victor.myapplication.TRACK_NAME";
public static final String ARTIST_NAME = "com.example.victor.myapplication.ARTIST_NAME";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_lyrics);
Bundle bundle = getIntent().getExtras();
((TextView)findViewById(R.id.lyricsBody)).setText(bundle.getString(LYRICS_BODY));
((TextView)findViewById(R.id.lyricsHeader)).setText(bundle.getString(TRACK_NAME) + ", " + bundle.getString(ARTIST_NAME));
}
}
|
package treesTest;
import org.junit.Test;
import trees.Map;
import trees.RangeMap;
import trees.skipList.DominationLockingSkipList;
public class DominationLockingSkipListTest {
// @Test
// public void test() {
// System.out.println("Starting BinaryTreeTest - TestSequential");
// Map<Integer,Integer> tree = new DominationLockingSkipList<Integer,Integer>(50,Integer.MIN_VALUE,Integer.MAX_VALUE);
// MapTest test = new MapTest();
// test.TestSequential(tree);
// }
//
// @Test
// public void multiTest1() {
// int numThreads = 1;
// int maxKey = 5000;
// int insertProbability = 5;
// int removeProbability = 5;
// int numOps =2000000;
// Map<Integer,Integer> tree = new DominationLockingSkipList<Integer,Integer>(maxKey,-1,maxKey);
//
// MapTest test = new MapTest();
//
// test.runTest(tree, numThreads, maxKey, insertProbability,
// removeProbability, numOps);
// }
//
// @Test
// public void multiTest2() {
// int numThreads = 8;
// int maxKey = 50;
// int insertProbability = 10;
// int removeProbability = 10;
// int numOps =100;
// Map<Integer,Integer> tree = new DominationLockingSkipList<Integer,Integer>(maxKey,-1,maxKey);
//
// MapTest test = new MapTest();
//
// test.runTest(tree,numThreads, maxKey, insertProbability,
// removeProbability, numOps);
// }
// @Test
// public void multiTest3() {
// int numThreads = 8;
// int maxKey = 50000;
// int insertProbability = 50;
// int removeProbability = 50;
// int numOps = 2000000;
// Map<Integer,Integer> tree = new DominationLockingSkipList<Integer,Integer>(maxKey,-1,maxKey);
//
// MapTest test = new MapTest();
//
// test.runTest(tree,numThreads, maxKey, insertProbability,
// removeProbability, numOps);
// }
// @Test
// public void smallSequentialRangeTest(){
// int maxKey = 20;
// int maxRange = 5;
// int minRange = 2;
// RangeMap<Integer,Integer> tree = new DominationLockingSkipList<Integer,Integer>(maxKey,-1,maxKey);
//
// RangeMapTest test = new RangeMapTest();
// test.TestSequentialRange(tree, maxKey, minRange, maxRange);
//
// }
//
// @Test
// public void mediumSequentialRangeTest(){
// int maxKey = 120;
// int maxRange = 10;
// int minRange = 5;
// RangeMap<Integer,Integer> tree = new DominationLockingSkipList<Integer,Integer>(maxKey,-1,maxKey);
//
// RangeMapTest test = new RangeMapTest();
// test.TestSequentialRange(tree, maxKey, minRange, maxRange);
//
// }
//
// @Test
// public void largeSequentialRangeTest(){
// int maxKey = 1200;
// int maxRange = 20;
// int minRange = 10;
// RangeMap<Integer,Integer> tree = new DominationLockingSkipList<Integer,Integer>(maxKey,-1,maxKey);
//
// RangeMapTest test = new RangeMapTest();
// test.TestSequentialRange(tree, maxKey, minRange, maxRange);
//
// }
//
//
@Test
public void veryLargeSequentialRangeTest(){
int maxKey = 200000;
int maxRange = 2000;
int minRange = 1000;
RangeMap<Integer,Integer> tree = new DominationLockingSkipList<Integer,Integer>(maxKey,-1,maxKey);
RangeMapTest test = new RangeMapTest();
test.TestSequentialRange(tree, maxKey, minRange, maxRange);
}
// @Test
// public void smallMultiRangeTest() {
// int numThreads = 8;
// int maxKey = 10000;
// int rangeProbability = 20;
// int insertProbability = 10;
// int removeProbability = 10;
// int numOps = 200000;
// int maxRange = 200;
// int minRange = 100;
//
// RangeMap<Integer,Integer> tree = new DominationLockingSkipList<Integer,Integer>(maxKey,-1,maxKey);
//
// RangeMapTest test = new RangeMapTest();
//
// test.TestMultiRange(tree, numThreads, maxKey, rangeProbability, insertProbability, removeProbability, numOps, minRange, maxRange);
// }
//
// @Test
// public void mediumMultiRangeTest() {
// int numThreads = 8;
// int maxKey = 100000;
// int rangeProbability = 20;
// int insertProbability = 10;
// int removeProbability = 10;
// int numOps = 200000;
// int maxRange = 600;
// int minRange = 400;
//
// RangeMap<Integer,Integer> tree = new DominationLockingSkipList<Integer,Integer>(maxKey,-1,maxKey);
//
// RangeMapTest test = new RangeMapTest();
//
// test.TestMultiRange(tree, numThreads, maxKey, rangeProbability, insertProbability, removeProbability, numOps, minRange, maxRange);
// }
//
@Test
public void largeMultiRangeTest() {
int numThreads = 1;
int maxKey = 200000;
int rangeProbability = 50;
int insertProbability = 25;
int removeProbability = 25;
int numOps = 20000;
int maxRange = 2000;
int minRange = 1000;
RangeMap<Integer,Integer> tree = new DominationLockingSkipList<Integer,Integer>(maxKey,-1,maxKey);
RangeMapTest test = new RangeMapTest();
test.TestMultiRange(tree, numThreads, maxKey, rangeProbability, insertProbability, removeProbability, numOps, minRange, maxRange);
}
}
|
package specification.definitions;
import designer.ui.editor.element.Element;
import designer.ui.editor.element.SplitElementEnd;
import specification.Start;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
/**
* Created by Tomas Hanus on 4/8/2015.
*/
@XmlAccessorType(XmlAccessType.NONE)
public class AdditionalElement {
@XmlElements({
@XmlElement(name = "start", type = Start.class),
@XmlElement(name = "splitEnd", type = SplitElementEnd.class)
})
private Element element;
@XmlElement(required = true)
private Position position;
@XmlElement(required = true)
private String designerContextid;
public AdditionalElement() {
}
public AdditionalElement(Element element) {
this.element = element;
this.position = new Position(element.getPosition().x, element.getPosition().y);
this.designerContextid = element.getDesignerContext().getContextId();
}
public Element getElement() {
return element;
}
public Position getPosition() {
return position;
}
public String getDesignerContextid() {
return designerContextid;
}
}
|
public class MinorChord extends Chord
{
//create specific chords in scale generation?
MinorChord(Note root)
{
this.root = root;
name = root + "Minor";
notes.add(root);
notes.add(root.plus(Interval.MINOR_THIRD));
notes.add(root.plus(Interval.FIFTH));
}
public void addNotes()
{
notes.add(root);
notes.add(root.plus(Interval.MINOR_THIRD));
notes.add(root.plus(Interval.FIFTH));
}
}
|
package com.mengdo.pub.biz;
import com.mengdo.pub.exception.SysException;
import com.mengdo.pub.model.PUBRewardInfoDTO;
/**
* @author piaoxj
* @email piaoxj89@gmail.com
* @mobile 15901283289
*/
public interface PubRewardBiz {
void getRandomAndBlockReward(PUBRewardInfoDTO pubRewardInfoDTO) throws SysException;
void saveUserRewardInfoBiz(PUBRewardInfoDTO pubRewardInfoDTO) throws SysException;
void checkMobileAndMinuxRepo(PUBRewardInfoDTO pubRewardInfoDTO)throws SysException;
void saveOnlyUserRewardInfoBiz(PUBRewardInfoDTO pubRewardInfoDTO)throws SysException;
}
|
package primeiros_exercicios;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ArrayDe9 {
public static void main(String[] args) {
int[] lista = new int[4];
Scanner leia = new Scanner(System.in);
List<Integer> listaDePrimos = new ArrayList();
// loop para captar os valores da tela
for (int i = 0; i < lista.length; i++) {
System.out.print("Digite o " + (i + 1) + "º valor: ");
lista[i] = leia.nextInt();
}
// loop
for (int j = 0; j < lista.length; j++) {
boolean ehPrimo = true;
for (int i = 2; i <lista[j] ; i++) {
if (lista[j] % i == 0) {
ehPrimo =false;
break;
}
}
if(ehPrimo){
listaDePrimos.add(lista[j]);
}
}
for (Integer numero : listaDePrimos) {
System.out.print(numero+" ");
}
}
}
|
package com.xiruan.demand.web.job;
import com.xiruan.demand.entity.automation.TemplateSort;
import com.xiruan.demand.demand.job.TemplateSortService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import com.google.common.collect.Maps;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
@Controller
@RequestMapping(value="/templateSort")
public class TemplateSortController {
private static final String PAGE_SIZE = "10";
private static final String navigation = "1";
private static Map<String, String> sortTypes = Maps.newLinkedHashMap();
static {
sortTypes.put("auto", "自动");
}
@Autowired
TemplateSortService templateSortService;
@RequestMapping(method= RequestMethod.GET)
public String list(@RequestParam(value="page",defaultValue = "1")int pageNumber,
@RequestParam(value="page.size",defaultValue = PAGE_SIZE)int pageSize,
@RequestParam(value="sortType",defaultValue = "auto")String sortType,Model model,
ServletRequest request){
//Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
Page<TemplateSort> templateSorts = templateSortService.getTemplateSort( pageNumber, pageSize, sortType);
model.addAttribute("templateSorts",templateSorts);
model.addAttribute("sortType", sortType);
model.addAttribute("sortTypes", sortTypes);
// 将搜索条件编码成字符串,用于排序,分页的URL
//model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
return "templateSort/list";
}
@RequestMapping(value="create",method=RequestMethod.GET)
public String createForm(Model model){
model.addAttribute("templateSort",new TemplateSort());
model.addAttribute("navigation",navigation);
return "templateSort/createForm";
}
@RequestMapping(value="create",method=RequestMethod.POST)
public String create(@Valid TemplateSort templateSort,RedirectAttributes redirectAttributes){
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String createDate=simpleDateFormat.format(new Date());
templateSort.setCreateDate(createDate);
templateSortService.saveTemplateSort(templateSort);
redirectAttributes.addFlashAttribute("message", "创建模板类别成功");
return "redirect:/templateSort";
}
@RequestMapping(value = "delete/{id}", method = RequestMethod.GET)
public String delete(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
templateSortService.deleteTemplateSort(id);
redirectAttributes.addFlashAttribute("message", "删除成功");
return "redirect:/templateSort";
}
@RequestMapping(value="updateForm/{id}",method=RequestMethod.GET)
public String updateForm(@PathVariable("id")Long id,Model model){
TemplateSort templateSort=templateSortService.findOne(id);
model.addAttribute("templateSort", templateSort);
return "templateSort/updateForm";
}
@RequestMapping(value="update",method=RequestMethod.POST)
public String update(@Valid@ModelAttribute("templateSort")TemplateSort templateSort,
HttpServletRequest request,
RedirectAttributes redirectAttributes){
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String createDate=simpleDateFormat.format(new Date());
templateSort.setCreateDate(createDate);
templateSort.setTemplateSortName(templateSort.getTemplateSortName());
templateSortService.saveTemplateSort(templateSort);
redirectAttributes.addFlashAttribute("message","模板类别修改成功");
return "redirect:/templateSort";
}
}
|
package ars.ramsey.interviewhelper.widget;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.ListPopupWindow;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import ars.ramsey.interviewhelper.R;
/**
* Created by Ramsey on 2017/4/22.
*/
public class DropEditText extends RightIconEditText implements RightIconEditText.RightIconClickListener{
private ListPopupWindow mListPopupWindow;
private String[] mData;
public DropEditText(Context context) {
super(context);
init();
}
public DropEditText(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public DropEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init()
{
mData = new String[]{"笔试","一面","二面","三面","HR面","待定"};
setIconClickListener(this);
}
@Override
public void onRightIconClick() {
mListPopupWindow = new ListPopupWindow(getContext());
mListPopupWindow.setAdapter(new ArrayAdapter<>(getContext(),
android.R.layout.simple_list_item_1, mData));
mListPopupWindow.setAnchorView(this);
mListPopupWindow.setModal(true);
mListPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
DropEditText.this.setText(mData[i]);
mListPopupWindow.dismiss();
}
});
mListPopupWindow.show();
}
}
|
package com.example.robot.model;
public class Deliveryman extends BasisRobot {
protected static int countRobot = 0;
@Override
public String mainFunctional() {
return "Robot " + getName() + " started delivery";
}
public Deliveryman(){
getOperationCode().add("delivery");
countRobot += 1;
setName("Deliveryman #" + countRobot);
}
}
|
/****
Copyright (c) 2015, Skyley Networks, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the Skyley Networks, Inc. nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Skyley Networks, Inc. BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
****/
package com.skyley.skstack_ip.api.skenums;
/**
* "EVENT"イベントのイベント番号を列挙
* @author Skyley Networks, Inc.
* @version 0.1
*/
public enum SKEventNumber {
/** NSを受信した */
NS_RECEIVED(0x01),
/** NAを受信した */
NA_RECEIVED(0x02),
/** Echo Requestを受信した */
ECHO_REQUEST_RECEIVED(0x05),
/** EDスキャンが完了した */
ED_SCAN_DONE(0x1F),
/** Beaconを受信した */
BEACON_RECEIVED(0x20),
/** UDP送信処理が完了した */
UDP_TX_DONE(0x21),
/** アクティブスキャンが完了した */
ACTIVE_SCAN_DONE(0x22),
/** PANA接続が完了しなかった */
PANA_CONNECT_FAIL(0x24),
/** PANA接続が完了した */
PANA_CONNECT_DONE(0x25),
/** PANAセッションの終了要求を受信した */
PANA_SESSION_CLOSE_REQUEST_RECEIVED(0x26),
/** PANAセッションの終了に成功した */
PANA_SESSION_CLOSE_DONE(0x27),
/** PANAセッションの終了要求がタイムアウトした(セッションは終了) */
PANA_SESSION_CLOSE_TIMEOUT(0x28),
/** PANAセッションのライフタイムが期限切れになった */
PANA_SESSION_LIFETIME_EXPIRED(0x29),
/** 送信総和時間の制限が発動した */
TX_LIMIT_START(0x32),
/** 送信総和時間の制限が解除された */
TX_LIMIT_END(0x33),
/** 鍵要求メッセージを送信した(PaCで発生) */
KEY_REQUEST_TX_DONE(0x40),
/** 鍵要求に対する応答を受信した(PaCで発生) */
KEY_REQUEST_RESPONSE_RECEIVED(0x41),
/** 鍵要求に対する応答が受信できなかった(PaCで発生) */
KEY_REQUEST_RESPONSE_NOT_RECEIVED(0x42),
/** 鍵配布メッセージを受信した(PaCで発生) */
KEY_DISTRIBUTION_RECEIVED(0x43),
/** 鍵切り替えメッセージを受信した(PaCで発生) */
KEY_UPDATE_RECEIVED(0x44),
/** 現在使用中の暗号鍵と異なるキーインデックスの暗号文を受信した(PaCで発生) */
KEY_INDEX_UNMATCHED(0x45),
/** 鍵切り替えメッセージが受信できずタイムアウトした(PaCで発生) */
KEY_UPDATE_TIMEOUT(0x46),
/** 鍵配布メッセージを送信した(PAAで発生) */
KEY_DISTRIBUTION_TX_DONE(0x50),
/** 鍵配布に対する応答を受信した(PAAで発生) */
KEY_DISTRIBUTION_RESPONSE_RECEIVED(0x51),
/** 鍵配布に対する応答が受信できなかった(PAAで発生) */
KEY_DISITRIBUTION_RESPONSE_NOT_RECEIVED(0x52),
/** 鍵要求メッセージを受信した(PAAで発生) */
KEY_REQUEST_RECEIVED(0x53),
/** 自動鍵配信処理を開始した(PAAで発生) */
KEY_AUTO_DISTRIBUTION_START(0x54),
/** 自動鍵配信処理を終了した(PAAで発生) */
KEY_AUTO_DISTRIBUTION_END(0x55),
/** イニシャルモードを開始した */
INITIAL_MODE_START(0x56),
/** イニシャルモードが終了した */
INITIAL_MODE_END(0x57);
/** イベント番号 */
private short number;
/**
* コンストラクタ
* @param number イベント番号
*/
private SKEventNumber(int number) {
this.number = (short)number;
}
/**
* イベント番号を取得
* @return イベント番号
*/
public short getNumber() {
return number;
}
/**
* イベント番号からイベント名を取得
* @param number イベント番号
* @return numberに対応するイベント名
*/
public static String getEventName(short number) {
for (SKEventNumber en : SKEventNumber.values()) {
if (en.number == number) {
return en.name();
}
}
return "";
}
}
|
package org.yipuran.gsonhelper.http;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.GsonBuilder;
/**
* HTTPS通信用のJsonHttpClientを生成する。
*/
public final class JsonHttpsClientBuilder{
private URL url;
private String proxy_server;
private String proxy_user;
private String proxy_passwd;
private Integer proxy_port;
private GsonBuilder gsonbuilder;
private boolean forceUtf8 = false;
private Map<String, String> headerOptions;
private String method = "POST";
/**
* コンストラクタ.
* @param path 送信先URLパス
* @param gsonbuilder GsonBuilder 送信するObject をJSONにする為のGsonBuilder
*/
private JsonHttpsClientBuilder(String path, GsonBuilder gsonbuilder){
this.gsonbuilder = gsonbuilder;
headerOptions = new HashMap<>();
try{
url = new URL(path);
}catch(MalformedURLException e){
throw new RuntimeException(e);
}
}
/**
* JsonHttpClientBuilderインスタンス生成.
* @param path 送信先URLパス
* @param gsonbuilder GsonBuilder 送信するObject をJSONにする為のGsonBuilder
* @return JsonHttpClientBuilder
*/
public static JsonHttpsClientBuilder of(String path, GsonBuilder gsonbuilder){
return new JsonHttpsClientBuilder(path, gsonbuilder);
}
/**
* プロキシ設定.
* @param proxyServer プロキシサーバ
* @param proxyPort プロキシポート番号
* @return JsonHttpsClientBuilder
*/
public JsonHttpsClientBuilder setProxy(String proxyServer, int proxyPort){
this.proxy_server = proxyServer;
this.proxy_port = proxyPort;
return this;
}
/**
* プロキシユーザ設定
* @param user プロキシユーザ
* @param passwd プロキシパスワード
* @return JsonHttpsClientBuilder
*/
public JsonHttpsClientBuilder setProxyUser(String user, String passwd){
this.proxy_user = user;
this.proxy_passwd = passwd;
return this;
}
/**
* 生成されるJsonHttpClient の受信JSON出力を強制的にUTF-8変換して出力
*/
public JsonHttpsClientBuilder setForceUtf8(){
this.forceUtf8 = true;
return this;
}
/**
* Header property 追加.
* @param name key
* @param value value
* @return HttpClientBuilder
*/
public JsonHttpsClientBuilder addHeaderProperty(String name, String value) {
headerOptions.put(name, value);
return this;
}
public JsonHttpsClientBuilder setMethod(String method) {
this.method = method.toUpperCase();
return this;
}
/**
* JsonHttpClient生成 HTTPS用
* @return JsonHttpClient
*/
public JsonHttpClient build(){
if (forceUtf8){
if (proxy_server != null) {
return new JsonHttpsClientUtf8Impl(url, proxy_server, proxy_user, proxy_passwd, proxy_port, gsonbuilder, headerOptions, method);
}
return new JsonHttpsClientUtf8Impl(url, gsonbuilder, headerOptions, method);
}
return proxy_server==null ? new JsonHttpsClientImpl(url, gsonbuilder, headerOptions, method) : new JsonHttpsClientImpl(url, proxy_server, proxy_user, proxy_passwd, proxy_port, gsonbuilder, headerOptions, method);
}
}
|
package com.emily.framework.context.httpclient.po;
import com.emily.framework.common.base.BaseLog;
import java.util.Date;
/**
* @program: spring-parent
* @description: RestTemplate拦截日志实体类
* @create: 2020/08/24
*/
public class AsyncLogHttpClientResponse extends BaseLog {
//响应时间
private Date responseTime;
//耗时
private long spentTime;
//响应结果
private Object responseBody;
//数据大小
private String dataSize;
public Date getResponseTime() {
return responseTime;
}
public void setResponseTime(Date responseTime) {
this.responseTime = responseTime;
}
public long getSpentTime() {
return spentTime;
}
public void setSpentTime(long spentTime) {
this.spentTime = spentTime;
}
public Object getResponseBody() {
return responseBody;
}
public void setResponseBody(Object responseBody) {
this.responseBody = responseBody;
}
public String getDataSize() {
return dataSize;
}
public void setDataSize(String dataSize) {
this.dataSize = dataSize;
}
}
|
import java.util.List;
public class Course {
String courseid;
String coursename;
String credit;
List<Student> studentList;
List<Teacher> teacherList;
}
|
package polydungeons.entity.charms;
import net.minecraft.entity.EntityType;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import polydungeons.entity.IServerWorld;
import polydungeons.item.PolyDungeonsItems;
import java.util.Map;
import java.util.UUID;
public class AnchorEntity extends CharmEntity {
public static final float RADIUS = 100;
public AnchorEntity(EntityType<?> type, World world) {
super(type, world);
}
@Override
public boolean hasNoGravity() {
return true;
}
public boolean collides() {
return true;
}
@Override
public ItemStack getItem() {
return new ItemStack(PolyDungeonsItems.ANCHOR);
}
@Override
protected Map<UUID, Vec3d> getPositionList(IServerWorld world) {
return world.polydungeons_getAnchorPositions();
}
}
|
package com.greenfox.workshopdi.colors;
import com.greenfox.workshopdi.interfaces.MyColor;
import com.greenfox.workshopdi.services.Printer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
public class RedColor implements MyColor {
private Printer printer;
public RedColor(Printer printer) {
this.printer = printer;
}
@Override
public void printColor() {
printer.log("It's red");
}
}
|
/**
* use double pointer, compare node by node. the time is (n^2),
*/
public class Solution01 {
// the structure of list node
public static class linkedNode {
public int val;
public linkedNode next;
linkedNode(int x) { this.val = x; }
}
// use double pointer, the time is (n^2)
public static void removeDup(linkedNode list) {
linkedNode pre = list;
linkedNode current = list;
while (pre != null) {
while (current.next != null) {
if (current.next.val == pre.val) {
current.next = current.next.next;
} else
current = current.next;
}
pre = pre.next;
current = pre;
}
}
// test
public static void main(String[] args) {
// TODO Auto-generated method stub
linkedNode a = new linkedNode(1);
linkedNode current = a;
for (int i = 0; i < 5; i++) {
current.next = new linkedNode(i);
current = current.next;
}
current.next = new linkedNode(4);
current = current.next;
linkedNode c = a;
while(c != null) {
System.out.print(c.val + " ");
c = c.next;
}
System.out.println();
System.out.println("After");
removeDup(a);
c = a;
while(c != null) {
System.out.print(c.val + " ");
c = c.next;
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package InterfazPolim;
import InterfazPolim.IAnimal;
/**
*
* @author capacitacion16
*/
public class Pez implements IAnimal{
private String nombre;
public Pez(String nomb){
this.nombre= nomb;
}
@Override
public void comer (){
System. out .println( "El pez " + nombre + " come plancton." );
}
@Override
public void jugar (){
System. out .println( "El pez " + nombre + " juega" );
}
}
|
import java.util.*;
public class gcdLCM {
/*Gcd And Lcm*/
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int num1 = scn.nextInt();
int num2 = scn.nextInt();
int n1n2 = num1 * num2;
while (num1 % num2 != 0) {
int rem = num1 % num2;
num1 = num2;
num2 = rem;
}
int gcd = num2;
int lcm = n1n2 / gcd;
System.out.println(gcd);
System.out.println(lcm);
}
}
|
package org.opentosca.planbuilder.provphase.plugin.scriptoperation.handler;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.io.FileUtils;
import org.eclipse.core.runtime.FileLocator;
import org.opentosca.planbuilder.model.plan.BuildPlan;
import org.opentosca.planbuilder.model.tosca.AbstractArtifactReference;
import org.opentosca.planbuilder.model.tosca.AbstractImplementationArtifact;
import org.opentosca.planbuilder.model.tosca.AbstractNodeTemplate;
import org.opentosca.planbuilder.model.tosca.AbstractOperation;
import org.opentosca.planbuilder.model.tosca.AbstractParameter;
import org.opentosca.planbuilder.model.tosca.AbstractProperties;
import org.opentosca.planbuilder.model.tosca.AbstractRelationshipTemplate;
import org.opentosca.planbuilder.plugins.commons.PluginUtils;
import org.opentosca.planbuilder.plugins.commons.Properties;
import org.opentosca.planbuilder.plugins.context.TemplatePlanContext;
import org.opentosca.planbuilder.plugins.context.TemplatePlanContext.Variable;
import org.opentosca.planbuilder.provphase.plugin.invoker.Plugin;
import org.opentosca.planbuilder.utils.Utils;
import org.osgi.framework.FrameworkUtil;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* <p>
* This class is contains the logic to add BPEL Fragments, which executes
* Scripts on remote machine. The class assumes that the script that must be
* called are already uploaded to the appropiate path. For example by the
* ScriptIAOnLinux Plugin
* </p>
* Copyright 2013 IAAS University of Stuttgart <br>
* <br>
*
* @author Kalman Kepes - kepeskn@studi.informatik.uni-stuttgart.de
*
*/
public class Handler {
private Plugin invokerPlugin = new Plugin();
private final static org.slf4j.Logger LOG = LoggerFactory.getLogger(Handler.class);
private DocumentBuilderFactory docFactory;
private DocumentBuilder docBuilder;
/**
* Contructor
*/
public Handler() {
try {
this.docFactory = DocumentBuilderFactory.newInstance();
this.docFactory.setNamespaceAware(true);
this.docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
}
/**
* Adds logic to the BuildPlan to call a Script on a remote machine
*
* @param context the TemplatePlanContext where the logical provisioning
* operation is called
* @param operation the operation to call
* @param ia the ia that implements the operation
* @return true iff adding BPEL Fragment was successful
*/
public boolean handle(TemplatePlanContext templateContext, AbstractOperation operation, AbstractImplementationArtifact ia) {
AbstractArtifactReference scriptRef = this.fetchScriptRefFromIA(ia);
if (scriptRef == null) {
return false;
}
/*
* fetch relevant variables/properties
*/
if (templateContext.getNodeTemplate() == null) {
Handler.LOG.warn("Appending logic to relationshipTemplate plan is not possible by this plugin");
return false;
}
// fetch server ip of the vm this apache http php module will be
// installed on
Variable serverIpPropWrapper = templateContext.getPropertyVariable(Properties.OPENTOSCA_DECLARATIVE_PROPERTYNAME_SERVERIP);
if (serverIpPropWrapper == null) {
serverIpPropWrapper = templateContext.getPropertyVariable(Properties.OPENTOSCA_DECLARATIVE_PROPERTYNAME_SERVERIP, true);
if (serverIpPropWrapper == null) {
serverIpPropWrapper = templateContext.getPropertyVariable(Properties.OPENTOSCA_DECLARATIVE_PROPERTYNAME_SERVERIP, false);
}
}
if (serverIpPropWrapper == null) {
Handler.LOG.warn("No Infrastructure Node available with ServerIp property");
return false;
}
// find sshUser and sshKey
Variable sshUserVariable = templateContext.getPropertyVariable("SSHUser");
if (sshUserVariable == null) {
sshUserVariable = templateContext.getPropertyVariable("SSHUser", true);
if (sshUserVariable == null) {
sshUserVariable = templateContext.getPropertyVariable("SSHUser", false);
}
}
// if the variable is null now -> the property isn't set properly
if (sshUserVariable == null) {
return false;
} else {
if (Utils.isVariableValueEmpty(sshUserVariable, templateContext)) {
// the property isn't set in the topology template -> we set it
// null here so it will be handled as an external parameter
sshUserVariable = null;
}
}
Variable sshKeyVariable = templateContext.getPropertyVariable("SSHPrivateKey");
if (sshKeyVariable == null) {
sshKeyVariable = templateContext.getPropertyVariable("SSHPrivateKey", true);
if (sshKeyVariable == null) {
sshKeyVariable = templateContext.getPropertyVariable("SSHPrivateKey", false);
}
}
// if variable null now -> the property isn't set according to schema
if (sshKeyVariable == null) {
return false;
} else {
if (Utils.isVariableValueEmpty(sshKeyVariable, templateContext)) {
// see sshUserVariable..
sshKeyVariable = null;
}
}
// add sshUser and sshKey to the input message of the build plan, if
// needed
if (sshUserVariable == null) {
LOG.debug("Adding sshUser field to plan input");
templateContext.addStringValueToPlanRequest("sshUser");
}
if (sshKeyVariable == null) {
LOG.debug("Adding sshKey field to plan input");
templateContext.addStringValueToPlanRequest("sshKey");
}
// find the ubuntu node and its nodeTemplateId
String templateId = "";
for (AbstractNodeTemplate nodeTemplate : templateContext.getNodeTemplates()) {
if (PluginUtils.isSupportedUbuntuVMNodeType(nodeTemplate.getType().getId())) {
templateId = nodeTemplate.getId();
}
}
if (templateId.equals("")) {
Handler.LOG.warn("Couldn't determine NodeTemplateId of Ubuntu Node");
return false;
}
// adds field into plan input message to give the plan it's own address
// for the invoker PortType (callback etc.). This is needed as WSO2 BPS
// 2.x can't give that at runtime (bug)
LOG.debug("Adding plan callback address field to plan input");
templateContext.addStringValueToPlanRequest("planCallbackAddress_invoker");
// add csarEntryPoint to plan input message
LOG.debug("Adding csarEntryPoint field to plan input");
templateContext.addStringValueToPlanRequest("csarEntrypoint");
Map<String, Variable> runScriptRequestInputParams = new HashMap<String, Variable>();
runScriptRequestInputParams.put("hostname", serverIpPropWrapper);
runScriptRequestInputParams.put("sshKey", sshKeyVariable);
runScriptRequestInputParams.put("sshUser", sshUserVariable);
Variable runShScriptStringVar = this.appendBPELAssignOperationShScript(templateContext, operation, scriptRef);
runScriptRequestInputParams.put("script", runShScriptStringVar);
this.invokerPlugin.handle(templateContext, templateId, true, "runScript", "InterfaceUbuntu", "planCallbackAddress_invoker", runScriptRequestInputParams, new HashMap<String, Variable>(),false);
return true;
}
private Variable appendBPELAssignOperationShScript(TemplatePlanContext templateContext, AbstractOperation operation, AbstractArtifactReference reference) {
/*
* First we initialize a bash script of this form: sudo sh
* $InputParamName=ValPlaceHolder* referenceShFileName.sh
*
* After that we try to generate a xpath 2.0 query of this form:
* ..replace
* (replace($runShScriptStringVar,"ValPlaceHolder",$PropertyVariableName
* ),"ValPlaceHolder",$planInputVar.partName/inputFieldLocalName)..
*
* With both we have a string with runtime property values or input
* params
*/
Map<String, Variable> inputMappings = new HashMap<String, Variable>();
String runShScriptString = "sudo ";
String runShScriptStringVarName = "runShFile" + templateContext.getIdForNames();
String xpathQueryPrefix = "";
String xpathQuerySuffix = "";
for (AbstractParameter parameter : operation.getInputParameters()) {
// First compute mappings from operation parameters to
// property/inputfield
Variable var = templateContext.getPropertyVariable(parameter.getName());
if (var == null) {
var = templateContext.getPropertyVariable(parameter.getName(), true);
if (var == null) {
var = templateContext.getPropertyVariable(parameter.getName(), false);
}
}
inputMappings.put(parameter.getName(), var);
// Initialize bash script string variable with placeholders
runShScriptString += parameter.getName() + "=$" + parameter.getName() + "$ ";
// put together the xpath query
xpathQueryPrefix += "replace(";
// set the placeholder to replace
xpathQuerySuffix += ",'\\$" + parameter.getName() + "\\$',";
if (var == null) {
// param is external, query value form input message e.g.
// $input.payload//*[local-name()='csarEntrypoint']/text()
xpathQuerySuffix += "$" + templateContext.getPlanRequestMessageName() + ".payload//*[local-name()='" + parameter.getName() + "']/text())";
} else {
// param is internal, so just query the bpelvar e.g. $Varname
xpathQuerySuffix += "$" + var.getName() + ")";
}
}
// add path to script
runShScriptString += "sh ~/" + templateContext.getCSARFileName() + "/" + reference.getReference();
// generate string var with script
Variable runShScriptStringVar = templateContext.createGlobalStringVariable(runShScriptStringVarName, runShScriptString);
// Reassign string var with runtime values and replace their
// placeholders
try {
// create xpath query
String xpathQuery = xpathQueryPrefix + "$" + runShScriptStringVar.getName() + xpathQuerySuffix;
// create assign and append
Node assignNode = this.loadAssignXpathQueryToStringVarFragmentAsNode("assignShCallScriptVar", xpathQuery, runShScriptStringVar.getName());
assignNode = templateContext.importNode(assignNode);
templateContext.getProvisioningPhaseElement().appendChild(assignNode);
} catch (IOException e) {
// TODO Auto-generated catch block
LOG.error("Couldn't load fragment from file", e);
} catch (SAXException e) {
// TODO Auto-generated catch block
LOG.error("Couldn't parse fragment to DOM", e);
}
return runShScriptStringVar;
}
/**
* Returns the first occurence of *.sh file, inside the given
* ImplementationArtifact
*
* @param ia an AbstractImplementationArtifact
* @return a String containing a relative file path to a *.sh file, if no
* *.sh file inside the given IA is found null
*/
private AbstractArtifactReference fetchScriptRefFromIA(AbstractImplementationArtifact ia) {
List<AbstractArtifactReference> refs = ia.getArtifactRef().getArtifactReferences();
for (AbstractArtifactReference ref : refs) {
if (ref.getReference().endsWith(".sh")) {
return ref;
}
}
return null;
}
/**
* Loads a BPEL Assign fragment which queries the csarEntrypath from the
* input message into String variable.
*
* @param assignName the name of the BPEL assign
* @param xpath2Query the csarEntryPoint XPath query
* @param stringVarName the variable to load the queries results into
* @return a String containing a BPEL Assign element
* @throws IOException is thrown when reading the BPEL fragment form the
* resources fails
*/
public String loadAssignXpathQueryToStringVarFragmentAsString(String assignName, String xpath2Query, String stringVarName) throws IOException {
// <!-- {AssignName},{xpath2query}, {stringVarName} -->
URL url = FrameworkUtil.getBundle(this.getClass()).getBundleContext().getBundle().getResource("assignStringVarWithXpath2Query.xml");
File bpelFragmentFile = new File(FileLocator.toFileURL(url).getPath());
String template = FileUtils.readFileToString(bpelFragmentFile);
template = template.replace("{AssignName}", assignName);
template = template.replace("{xpath2query}", xpath2Query);
template = template.replace("{stringVarName}", stringVarName);
return template;
}
/**
* Loads a BPEL Assign fragment which queries the csarEntrypath from the
* input message into String variable.
*
* @param assignName the name of the BPEL assign
* @param csarEntryXpathQuery the csarEntryPoint XPath query
* @param stringVarName the variable to load the queries results into
* @return a DOM Node representing a BPEL assign element
* @throws IOException is thrown when loading internal bpel fragments fails
* @throws SAXException is thrown when parsing internal format into DOM
* fails
*/
public Node loadAssignXpathQueryToStringVarFragmentAsNode(String assignName, String xpath2Query, String stringVarName) throws IOException, SAXException {
String templateString = this.loadAssignXpathQueryToStringVarFragmentAsString(assignName, xpath2Query, stringVarName);
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(templateString));
Document doc = this.docBuilder.parse(is);
return doc.getFirstChild();
}
}
|
package com.AxiusDesigns.AxiusPlugins.ResourcePack.Commands;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.AxiusDesigns.AxiusPlugins.ResourcePack.ResourcePack;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
public class PackCommand implements CommandExecutor {
private ResourcePack plugin;
String resourcePack;
String resourcePack2;
String hereText;
String hereHover;
String url = "";
public PackCommand(ResourcePack main) {
plugin = main;
}
@Override
public boolean onCommand(CommandSender sndr, Command arg1, String arg2, String[] arg3) {
if(sndr instanceof Player) {
Player p = Bukkit.getPlayer(sndr.getName());
if(this.plugin.configData.get("Method").equalsIgnoreCase("CHAT")) {
showClick(p);
}
else
{
if(this.plugin.configData.get("Method").equalsIgnoreCase("PROMPT")/*||this.plugin.configData.get("Method").equalsIgnoreCase("FORCE")*/) {
String url = "";
if(this.plugin.configData.containsKey("URL." + p.getWorld().getName())) url = this.plugin.configData.get("URL." + p.getWorld().getName());
else url = this.plugin.configData.get("URL.Default");
p.setResourcePack(url);
}
else
{
System.out.print("The \"Method\" field in the Config.YML doesn't have an applicable method type, types: PROMPT, CHAT");
System.out.print("Using default \"CHAT\" Method.");
showClick(p);
}
}
return true;
}
else
{
System.out.print("YOU MUST BE A PLAYER TO USE THE RESOURCE PACK!");
return true;
}
}
public void showClick(Player p) {
resourcePack = ChatColor.translateAlternateColorCodes('&', this.plugin.messageData.get("Method.CHAT.Message.Begin"));
resourcePack2 = ChatColor.translateAlternateColorCodes('&', this.plugin.messageData.get("Method.CHAT.Message.End"));
hereText = ChatColor.translateAlternateColorCodes('&', this.plugin.messageData.get("Method.CHAT.Link.Text"));
hereHover = ChatColor.translateAlternateColorCodes('&', this.plugin.messageData.get("Method.CHAT.Link.Hover"));
if(this.plugin.configData.containsKey("URL." + p.getWorld().getName())) url = this.plugin.configData.get("URL." + p.getWorld().getName());
else url = this.plugin.configData.get("URL.Default");
TextComponent here = new TextComponent(hereText);
here.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, url));
here.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(hereHover).create()));
TextComponent a = new TextComponent(resourcePack);
a.addExtra(here);
a.addExtra(resourcePack2);
p.spigot().sendMessage(a);
}
}
|
package ba.ih_sonification.headsetx;
import org.osmdroid.util.GeoPoint;
public class BuildingPoint {
private GeoPoint position;
private int height;
public BuildingPoint(GeoPoint position, int height) {
this.position = position;
this.height = height;
}
public GeoPoint getPosition() {
return position;
}
public void setPosition(GeoPoint position) {
this.position = position;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
}
|
package com.tencent.mm.plugin.appbrand.jsapi.media;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import com.tencent.mm.plugin.appbrand.jsapi.media.JsApiChooseVideo.a;
class JsApiChooseVideo$a$1 implements OnCancelListener {
final /* synthetic */ a fUU;
JsApiChooseVideo$a$1(a aVar) {
this.fUU = aVar;
}
public final void onCancel(DialogInterface dialogInterface) {
a.a(this.fUU).bjW = 0;
a.a(this.fUU, a.a(this.fUU));
}
}
|
package BankTura;
public class Cliente extends Pessoa {
// Atributo
private boolean vip;
// Métodos construtores de permissão de acesso
public boolean isVip() {
return vip;
}
public void setVip(boolean vip) {
this.vip = vip;
}
public Cliente(){
}
// Mesmo nome de métodos, mais com retornos diferentes
public void clienteVip(String teste){
}
public void clienteVip(int teste){
}
}
|
package com.motorola.android.server.ims;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.Parcelable.Creator;
public class IMSCSmsMtEvent
implements Parcelable
{
public static final Parcelable.Creator<IMSCSmsMtEvent> CREATOR = new Parcelable.Creator()
{
public IMSCSmsMtEvent createFromParcel(Parcel paramParcel)
{
long l1 = paramParcel.readLong();
long l2 = paramParcel.readLong();
int i = paramParcel.readInt();
String str = paramParcel.readString();
int j = paramParcel.readInt();
byte[] arrayOfByte = new byte[paramParcel.readInt()];
paramParcel.readByteArray(arrayOfByte);
return new IMSCSmsMtEvent(l1, l2, i, str, j, arrayOfByte);
}
public IMSCSmsMtEvent[] newArray(int paramInt)
{
return new IMSCSmsMtEvent[paramInt];
}
};
private String mFromAddr;
private int mMsgFormat;
private long mMsgId;
private long mRegId;
private int mResponse = -2;
private byte[] mSmsBody;
public IMSCSmsMtEvent()
{
}
public IMSCSmsMtEvent(long paramLong1, long paramLong2, int paramInt1, String paramString, int paramInt2, byte[] paramArrayOfByte)
{
this.mRegId = paramLong1;
this.mMsgId = paramLong2;
this.mResponse = paramInt1;
this.mFromAddr = paramString;
this.mMsgFormat = paramInt2;
if ((paramArrayOfByte == null) || (paramArrayOfByte.length == 0))
this.mSmsBody = null;
while (true)
{
return;
this.mSmsBody = new byte[paramArrayOfByte.length];
for (int i = 0; i < paramArrayOfByte.length; i++)
this.mSmsBody[i] = paramArrayOfByte[i];
}
}
public int describeContents()
{
return 0;
}
public String getFromAddress()
{
return this.mFromAddr;
}
public int getMsgFormat()
{
return this.mMsgFormat;
}
public String getMsgFormatStr()
{
String str = "3gpp2";
if (this.mMsgFormat == 0)
str = "0 -- 3gpp2";
while (true)
{
return str;
if (this.mMsgFormat == 1)
{
str = "1 -- 3gpp";
continue;
}
if (this.mMsgFormat != 2)
continue;
str = "2 -- Trans";
}
}
public long getMsgId()
{
return this.mMsgId;
}
public long getRegId()
{
return this.mRegId;
}
public int getResponse()
{
return this.mResponse;
}
public String getResponseStr()
{
if (this.mResponse == -2);
for (String str = "-2 -- not initialized"; ; str = IMSCRegistrationEvent.parseFailedReasonCode(this.mResponse))
return str;
}
public byte[] getSmsBody()
{
return this.mSmsBody;
}
public void setFromAddress(String paramString)
{
this.mFromAddr = paramString;
}
public void setMsgFormat(int paramInt)
{
this.mMsgFormat = paramInt;
}
public void setMsgId(long paramLong)
{
this.mMsgId = paramLong;
}
public void setRegId(long paramLong)
{
this.mRegId = paramLong;
}
public void setResponse(int paramInt)
{
this.mResponse = paramInt;
}
public void setSmsBody(byte[] paramArrayOfByte)
{
if ((paramArrayOfByte == null) || (paramArrayOfByte.length == 0))
this.mSmsBody = null;
while (true)
{
return;
this.mSmsBody = new byte[paramArrayOfByte.length];
for (int i = 0; i < paramArrayOfByte.length; i++)
this.mSmsBody[i] = paramArrayOfByte[i];
}
}
public String toString()
{
StringBuffer localStringBuffer = new StringBuffer();
localStringBuffer.append("IMS-SMS-MT event:\n");
localStringBuffer.append("mRegId: ").append(this.mRegId).append('\n');
localStringBuffer.append("mMsgId: ").append("0x").append(Long.toHexString(this.mMsgId)).append('\n');
localStringBuffer.append("mResponse: ").append(getResponseStr()).append('\n');
localStringBuffer.append("mFromAddr: ").append(this.mFromAddr).append('\n');
localStringBuffer.append("mMsgFormat: ").append(getMsgFormatStr()).append('\n');
localStringBuffer.append("mSmsBody: ");
if ((this.mSmsBody == null) || (this.mSmsBody.length == 0))
{
localStringBuffer.append("null");
localStringBuffer.append('\n');
return localStringBuffer.toString();
}
int i = 0;
label162: int j;
if (i < this.mSmsBody.length)
{
if (i % 20 == 0)
localStringBuffer.append('\n');
j = 0xFF & this.mSmsBody[i];
if ((j >= 128) || (!Character.isLetterOrDigit(j)))
break label273;
String str2 = Character.toString((char)j);
if (str2.length() == 1)
str2 = "_" + str2;
localStringBuffer.append(str2).append(" ");
}
while (true)
{
i++;
break label162;
break;
label273: String str1 = Integer.toHexString(j);
if (str1.length() == 1)
str1 = '0' + str1;
localStringBuffer.append(str1.toUpperCase()).append(" ");
}
}
public void writeToParcel(Parcel paramParcel, int paramInt)
{
paramParcel.writeLong(this.mRegId);
paramParcel.writeLong(this.mMsgId);
paramParcel.writeInt(this.mResponse);
paramParcel.writeString(this.mFromAddr);
paramParcel.writeInt(this.mMsgFormat);
paramParcel.writeInt(this.mSmsBody.length);
paramParcel.writeByteArray(this.mSmsBody);
}
}
/* Location: /home/dhacker29/jd/classes_dex2jar.jar
* Qualified Name: com.motorola.android.server.ims.IMSCSmsMtEvent
* JD-Core Version: 0.6.0
*/
|
package com.ingenico.pay.dao;
import com.ingenico.pay.entity.AccountEntity;
import org.springframework.stereotype.Repository;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* Created by mohamedtantawy on 10/17/17.
*/
@Repository
public class AccountDao {
// work as the memory to save account data
private static final Map<String, AccountEntity> accountMap = new ConcurrentHashMap<String, AccountEntity>();
/**
* @param id for account
* @return account entity
*/
public AccountEntity find(String id) {
if (id != null) {
AccountEntity accountEntity = accountMap.get(id);
return accountEntity;
}
return null;
}
/**
* @param accountEntity account entity to save
* @return account dto
*/
public void save(AccountEntity accountEntity) {
if (accountEntity != null && accountEntity.getId() == null) {
UUID uuid = UUID.randomUUID();
String id = uuid.toString();
accountEntity.setId(id);
accountMap.put(accountEntity.getId(), accountEntity);
}
}
/**
*
* @param id deleted account id
*/
public void delete(String id) {
if (id != null && accountMap.containsKey(id)) {
accountMap.remove(id);
}
}
/**
* @return all account as dtos List
*/
public List<AccountEntity> findAll() {
List<AccountEntity> accountEntities = new ArrayList<AccountEntity>();
Set<String> keyset = accountMap.keySet();
for(String key : keyset) {
accountEntities.add(accountMap.get(key));
}
return accountEntities;
}
}
|
package shapes
public interface Shape{
public void moveTo(int x, int y);
public void redraw();
public void update();
public void scale( int dx, int dy);
public void delete();
public void mergeWithShape(Shape shape);
public void change();
}
|
package week4day2;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import io.github.bonigarcia.wdm.WebDriverManager;
public class Amazon {
public static void main(String[] args) throws IOException, InterruptedException {
WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-notifications");
ChromeDriver driver = new ChromeDriver(options);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://www.amazon.in/");
driver.findElement(By.id("twotabsearchtextbox")).sendKeys("oneplus 9 pro", Keys.ENTER);
driver.findElement(By.xpath("(//div//div[@data-component-type='s-search-result'])[2]"));
String price = driver.findElement(By.xpath("(//span[@class='a-price-whole'])[2]")).getText();
System.out.println("The price of the first product is:" + price);
String customerReview = driver.findElement(By.xpath("(//a//span[@class='a-size-base'])[2]")).getText();
System.out.println("The total number of customer ratings are:" + customerReview);
WebElement rating = driver.findElement(By.xpath("(//a//span[@class='a-icon-alt'])[2]"));
Actions builder = new Actions(driver);
builder.moveToElement(rating).click().perform();
Thread.sleep(1000);
String fiveStarPrcnt=driver.findElement(By.xpath("(//a[contains(@title,'reviews have 5 stars')])[3]")).getText();
System.out.println("Five start percentage is: "+fiveStarPrcnt);
driver.findElement(By.xpath("(//h2[contains(@class,'a-size-mini')])[2]")).click();
Set<String> winHand = driver.getWindowHandles();
List<String> list = new ArrayList<String>(winHand);
driver.switchTo().window(list.get(1));
File src = driver.getScreenshotAs(OutputType.FILE);
File dst = new File("./snaps/Amazon.png");
FileUtils.copyFile(src, dst);
Thread.sleep(1000);
driver.findElement(By.id("add-to-cart-button")).click();
Thread.sleep(3000);
String cartSubTotal = driver.findElement(By.xpath("//span[@id='attach-accessory-cart-subtotal']")).getText();
System.out.println("The cart total is:"+cartSubTotal);
if (cartSubTotal.contains(price)) {
System.out.println("Price matches:" + cartSubTotal);
} else
System.out.println("Price does not match:" + cartSubTotal);
driver.quit();
}
}
|
import Piece;
public class Case {
private int positionX;
private int positionY;
private String nameOfCase;
private Piece piece;
public Case(int posX, int posY) {
this.positionX = posX;
this.positionY = posY;
}
public void setPositionX(double positionX1)
{
this.positionX= positionX1;
}
public void setPositionY(double positionY1)
{
this.positionY= positionY1;
}
public void setNameOfCase(String nameOfCase1)
{
this.nameOfCase=nameOfCase1;
}
public double getPositionX()
{
return this.positionX;
}
public double getPositionY()
{
return this.positionY;
}
public String getNameOfCase()
{
return this.nameOfCase;
}
/**
* Methode estOccupe servant a savoir si la case est occupe ou non.
*
*/
public boolean estOccupe()
{
return (piece != null);
}
/**
* Methode estOccupe servant a savoir si la case est occupe ou non d'une piece d'une couleur entrer en parametre.
*
*/
public boolean estOccupe(String couleur)
{
if (piece == null)
return false;
else
return (piece.getColor().equals(couleur));
}
}
|
package com.project.database.serviceHibernate;
import com.project.database.entities.GroupEntity;
import com.project.database.entities.SubjectEntity;
import com.project.database.entities.TutorEntity;
import com.project.database.repository.GroupRepository;
import com.project.database.repository.SubjectRepository;
import com.project.database.repository.TutorRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
@Service
@Transactional
@RequiredArgsConstructor
public class GroupServiceH {
@Autowired
private GroupRepository groupRepository;
@Autowired
private TutorRepository tutorRepository;
@Autowired
private SubjectRepository subjectRepository;
/**
* @return [GroupEntity(groupCode = 1, groupName = Група1, eduYear = 2020 - 2021, trim = 2, course = 3, subject = SubjectEntity ( subjectNo = 1, subjectName = БД, eduLevel = бакалавр, faculty = ФІ)),...]
*/
public Page<GroupEntity> findAll(int page, int numberPerPage) {
Pageable pageable = PageRequest.of(page - 1, numberPerPage);
return groupRepository.findAll(pageable);
}
public void deleteByGroupCode(int groupId) {
groupRepository.deleteByGroupCode(groupId);
}
public Page<GroupEntity> findAllByGroupName(int page, int numberPerPage) {
Pageable pageable = PageRequest.of(page - 1, numberPerPage);
return groupRepository.findAllByGroupName(pageable);
}
/**
* @return [Група1, Група2, Група3, Група4]
*/
public List<String> findAllGroupNames() {
return groupRepository.findAllGroupNames();
}
public Page<String> findAllByEduYear(Pageable pageable) {
return groupRepository.findAllByEduYear(pageable);
}
public List<String> findAllYears() {
return groupRepository.findAllYears();
}
/**
* @return [2020-2021, 2021-2022]
*/
public List<String> findAllGroupEduYears() {
return groupRepository.findAllGroupEduYears();
}
// insert
public void insertGroup(GroupEntity group, SubjectEntity subject) {
// тут треба перевірити за назвагрупи+назвапредмету+навчальний рік+семестр+курс
if (findGroupByNameYearTrimCourseSubject(group, subject) == null) {
groupRepository.save(group);
}
}
// delete
public void deleteGroupById(int groupCode) {
groupRepository.deleteByGroupCode(groupCode);
}
public GroupEntity findGroupByNameYearTrimCourseSubject(GroupEntity group, SubjectEntity subject) {
return groupRepository.findGroupByNameYearTrimCourseSubject(
group.getGroupName(), group.getEduYear(), group.getTrim(), group.getCourse(), subject.getSubjectName());
}
public List<GroupEntity> findAllBySubjectName(String subjectName) {
return groupRepository.findAllBySubjectName(subjectName);
}
public List<String> findAllGroupsByTeacherPIBAndSubjectName(String tutor, String subjet) {
List<Integer> listTutor = getTutorList(tutor);
List<String> listSubject = getSubjectList(subjet);
return groupRepository.findAllGroupsByTeacherPIBAndSubjectName(listTutor, listSubject);
}
private List<Integer> getTutorList(String tutorName) {
return tutorName == null || tutorName.isBlank()
? tutorRepository.findAll()
.stream().map(TutorEntity::getTutorNo).distinct().collect(Collectors.toList())
: tutorRepository.findAllTutorsByFullName(tutorName);
}
private List<String> getSubjectList(String subjectName) {
return subjectName == null || subjectName.isBlank()
? subjectRepository.findAll()
.stream().map(SubjectEntity::getSubjectName).distinct().collect(Collectors.toList())
: subjectRepository.findDistinctBySubjectNameIn(Collections.singletonList(subjectName))
.stream().map(SubjectEntity::getSubjectName).distinct().collect(Collectors.toList());
}
}
|
package com.xhpower.qianmeng.controller;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.xhpower.qianmeng.entity.Article;
import com.xhpower.qianmeng.entity.Category;
import com.xhpower.qianmeng.entity.FileUploadPath;
import com.xhpower.qianmeng.entity.User;
import com.xhpower.qianmeng.service.ArticleService;
import com.xhpower.qianmeng.service.CategoryService;
import com.xhpower.qianmeng.utils.Result;
import com.xhpower.qianmeng.utils.SystemCode;
import com.xhpower.qianmeng.utils.UploadUtil;
/**
* <p>
* 前端控制器
* </p>
*
* @author lyc
* @since 2018-07-27
*/
@RestController
@RequestMapping("/admin/article")
public class ArticleController {
@Autowired
private ArticleService articleService;
@Autowired
private CategoryService categoryService;
@Autowired
private FileUploadPath fileUploadPath;
/**
* 文章列表查询
*
* @Title: list
* @param page
* @return Result 返回类型
* @author Liu Youcheng
* @date 2018年7月27日
*/
@RequestMapping("/list")
public Result list(Page<Article> page) {
EntityWrapper<Article> wrapper = new EntityWrapper<>();
Map<String,Object> condition = page.getCondition();
if(condition != null){
String[] eqs = {"category_id","status"};
for (String key : condition.keySet()) {
if("title".equals(key))
wrapper.like(key, condition.get(key).toString());
if(Arrays.asList(eqs).contains(key))
wrapper.eq(key, condition.get(key).toString());
}
condition.clear();
}
wrapper.orderBy("update_time", false);
page = articleService.selectPage(page,wrapper);
List<Article> artList = page.getRecords();
for (Article article : artList) {
Category category = categoryService.selectById(article.getCategoryId());
article.setCategoryName(category.getCategoryName());
}
page.setRecords(artList);
return Result.success().page(page);
}
/**
*
* 文章保存
*
* @Title: save
* @param article
* @param bindingResult
* @param file
* @return Result 返回类型
* @author Liu Youcheng
* @date 2018年5月9日
*/
@RequestMapping("/save")
public Result save(@Valid Article article, BindingResult bindingResult, MultipartFile file, HttpServletRequest request) {
if (bindingResult.hasErrors()) {
ObjectError error = bindingResult.getAllErrors().get(0);
return Result.error(SystemCode.VERIFICATION_FAILURE, error.getDefaultMessage());
}
if(file != null && !file.isEmpty()){
String path = UploadUtil.uploadFile(fileUploadPath.getArticleImagesPath(), file, fileUploadPath.getRootPath());
article.setImage(path);
}
if(StringUtils.isEmpty(article.getAuthor())){
User user = (User) request.getSession().getAttribute("ADMIN_USER");
article.setAuthor(user.getRealName());
}
return articleService.insertOrUpdate(article) ? Result.success() : Result.error();
}
/**
* 文章删除
*
* @Title: delete
* @param page
* @return Result 返回类型
* @author Liu Youcheng
* @date 2018年7月27日
*/
@RequestMapping("/delete")
public Result delete(Integer id) {
if (null == id) {
return Result.error("文章不存在");
}
return articleService.deleteById(id) ? Result.success() : Result.error();
}
/**
*
* 上传文章内容媒体文件
*
* @Title: upload
* @param request
* @param dir
* @return Result 返回类型
* @author Lian Youjie
* @throws IOException
* @date 2018年7月1日
*/
@RequestMapping("/upload")
public JSONObject upload(HttpServletRequest httpRequest, String action) throws IOException {
JSONObject jsonObject = new JSONObject();
if ("config".equals(action)) {
InputStreamReader reader = new InputStreamReader(
this.getClass().getClassLoader().getResourceAsStream("config.json"));
BufferedReader bufferedReader = new BufferedReader(reader);
StringBuffer input = new StringBuffer();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
input.append(line);
}
jsonObject = JSONObject.parseObject(input.toString());
System.out.println(jsonObject+"test");
return jsonObject;
}
jsonObject.put("state", "SUCCESS");
jsonObject.put("info", "上传成功!");
String imageExt = "gif,jpg,jpeg,png,bmp";
MultipartHttpServletRequest request = (MultipartHttpServletRequest) httpRequest;
Iterator<String> item = request.getFileNames();
while (item.hasNext()) {
String fileName = (String) item.next();
MultipartFile file = request.getFile(fileName);
String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1)
.toLowerCase();
if (!"image".equals(action)) {
jsonObject.put("state", "ERROR");
jsonObject.put("info", "文件类型不允许上传!");
}
if (!Arrays.asList(imageExt.split(",")).contains(fileExt)) {
jsonObject.put("state", "ERROR");
jsonObject.put("info", action + "文件只允许" + imageExt + "格式。");
}
String uploadFolder = File.separator + "uploadcmsimages" + File.separator + "content" + File.separator
+ action;
String fileParh = UploadUtil.uploadFile(uploadFolder, file, fileUploadPath.getRootPath());
jsonObject.put("url", fileParh);
}
return jsonObject;
}
}
|
package com.team_linne.digimov.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
@Data
@EqualsAndHashCode
@NoArgsConstructor
@AllArgsConstructor
public class HouseRequest {
private String cinemaId;
private String name;
private Integer capacity;
}
|
package search_engine;
/*
* @author chandra
*/
public class parser {
String title;
static String id;
String Rawdata;
public parser(String message,String title_page,String id_page)
{
super();
this.id=id_page;
this.title=title_page;
this.Rawdata = message;
}
//to check whether the string is numeric
public boolean isNumeric(String s) {
return java.util.regex.Pattern.matches("\\d+", s);
}
public void parse_body()
{
extract_info ei=new extract_info();
int length = title.length() , info_braces_count = 0;
String tit="";
for(int i=0;i<length;i++)
{
char ch=title.charAt(i);
if((ch >='a'&&ch<='z')||(ch>='A'&&ch<='Z')|| (ch>=48&&ch<58))
tit+=ch;
else if((ch==39||ch==44||ch==48)&&tit.length()==1)
{}
}
if(tit.length()>0)
{
ei.field_title(tit);
tit="";
}
//title extraction complete
Boolean ref_flag=false,cat_flag=false,ext_flag=false,info_flag=false;
String Body="",infobox="",ref="",extlinks="",category="";
length = Rawdata.length();
//text processing
for(int i=0;i<length;i++)
{
char ch = Rawdata.charAt(i);
if(ch=='{')
{
int j=i;
while(Rawdata.charAt(++j)==' ');
if(Rawdata.charAt(j)=='{')
{
while(Rawdata.charAt(++j)==' ');
if(j+4<length&&Rawdata.substring(j,j+4).equalsIgnoreCase("cite"))
{
//skipping the data within cite
i=j+4;
int bracescheck=2;
while(bracescheck>0)
{
ch=Rawdata.charAt(++i);
if(ch=='{')
bracescheck++;
else if(ch=='}')
bracescheck--;
}
}
else if(info_flag==false&&j+7<length&&Rawdata.substring(j,j+7).equalsIgnoreCase("infobox"))
{
info_flag=true;
i=j+7;
info_braces_count=2;
}
}
}
else if(ch=='=')
{
int j=i;
while(Rawdata.charAt(++j)==' ');
if(Rawdata.charAt(j)=='=')
{
while(Rawdata.charAt(++j)==' ');
if(ext_flag==false&&j+14<length&&Rawdata.substring(j,j+14).contains("External links"))
{
ref_flag=false;
ext_flag=true;
info_flag=false;
i=j+16;
}
else if(ref_flag==false&&j+10<length&&Rawdata.substring(j,j+10).equalsIgnoreCase("references"))
{
ref_flag=true;
info_flag=false;
i=j+9;
}
}
}
else if(ch=='[')
{
int j=i;
while(Rawdata.charAt(++j)==' ');
if(Rawdata.charAt(j)=='[')
{
while(Rawdata.charAt(++j)==' ');
if(j+8<length&&Rawdata.substring(j,j+8).equalsIgnoreCase("category"))
{
ref_flag=false;
ext_flag=false;
info_flag=false;
cat_flag=true;
i=j+9;
}
}
}
ch=Rawdata.charAt(i);
if(info_flag)
{
if(ch=='}')
{
info_braces_count--;
if(info_braces_count==0)
info_flag=false;
}
else if(ch=='{')
info_braces_count++;
else
{
if((ch >='a'&&ch<='z')||(ch>='A'&&ch<='Z')|| (ch>=48&&ch<58))
infobox+=ch;
else if((ch==39||ch==44)&&infobox.length()==1) //for strings like O'neil
{}
else
{
ei.extract(infobox,"I");
infobox="";
}
}
}
else if(ref_flag)
{
if((ch >='a'&&ch<='z')||(ch>='A'&&ch<='Z')|| (ch>=48&&ch<58))
ref+=ch;
else if((ch==39||ch==44)&&ref.length()==1) //for strings like O'neil
{}
else
{
ei.extract(ref,"R");
ref="";
}
}
else if(ext_flag)
{
if((ch >='a'&&ch<='z')||(ch>='A'&&ch<='Z')|| (ch>=48&&ch<58))
extlinks+=ch;
else if((ch==39||ch==44)&&extlinks.length()==1) //for strings like O'neil
{}
else
{
ei.extract(extlinks,"E");
extlinks="";
}
}
else if(cat_flag)
{
if((ch >='a'&&ch<='z')||(ch>='A'&&ch<='Z')|| (ch>=48&&ch<58))
category+=ch;
else if((ch==39||ch==44)&&category.length()==1) //for strings like O'neil
{}
else
{
ei.extract(category,"C");
category="";
}
}
else
{
if((ch >='a'&&ch<='z')||(ch>='A'&&ch<='Z')|| (ch>=48&&ch<58))
Body+=ch;
else if((ch==39||ch==44)&&Body.length()==1) //for strings like O'neil
{}
else
{
ei.extract(Body,"B");
Body="";
}
}
}
//end of parsing
if(Body.length()>0)
{
ei.extract(Body,"B");
Body="";
}
if(category.length()>0)
{
ei.extract(category,"C");
category="";
}
}//enf of method parse_body
} //end of class
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class AlgorithmsProvider {
public static void main(String[] args) throws MyException {
int[] numbers = readNumbers();
int[] ascendingNumbers = sortAscending(numbers);
int[] descendingNumbers = sortDescending(numbers);
System.out.println("Posortowane rosnaco:");
printNumbers(ascendingNumbers);
System.out.println("\n Posortowane malejaco:");
printNumbers(descendingNumbers);
}
public static int[] sortAscending(int[] array) {
int[] arr = Arrays.copyOf(array, array.length);
int n = arr.length;
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
return arr;
}
public static int[] sortDescending(int[] array) {
int[] arr = Arrays.copyOf(array, array.length);
int n = arr.length;
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] <= arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
return arr;
}
public static int[] readNumbers() throws MyException {
int[] numbers = new int[5];
Scanner input = new Scanner(System.in);
System.out.println("Podaj 5 liczb które posortuje...");
for (int i = 0; i < 5; i++) {
System.out.println("Podaj liczbe nr " + i + ": ");
Integer number = parseNumber(input.nextLine());
numbers[i] = number;
}
return numbers;
}
public static int parseNumber(String input) throws MyException {
try {
return Integer.parseInt(input);
} catch(NumberFormatException exc) {
throw new MyException();
}
}
public static void printNumbers(int[] numbers) {
for (int number : numbers) {
System.out.print(number + " ");
}
}
}
|
package be.spring.app.service;
import be.spring.app.model.Account;
import be.spring.app.model.Match;
import be.spring.app.model.Presence;
import java.util.Set;
/**
* Created by u0090265 on 10/1/14.
*/
public interface DoodleService {
public String changeMatchPresence(Account account, long matchId, boolean present);
Presence changePresence(Account account, long accountId, long doodleId);
boolean sendDoodleNotificationsFor(Match match, Set<Account> accounts);
}
|
package com.example.ian.rentermanager11;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private EditText name;//用户名
private EditText password;//用户密码
private Button login;//登录按钮
private TextView register;//注册
private TextView forgetNum;//忘记密码
private myDatabaseHelper dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = myDatabaseHelper.getInstance(this);
name = (EditText) findViewById(R.id.admin_login_activity_name_input);
password = (EditText) findViewById(R.id.admin_login_activity_password_input);
login = (Button) findViewById(R.id.admin_login_activity_login);
register = (TextView) findViewById(R.id.admin_login_activity_register);
forgetNum = (TextView) findViewById(R.id.admin_login_activity_forgetNum);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String nameInfo = name.getText().toString();
String passwordInfo = password.getText().toString();
//从数据库获取密码并判断是否相同
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor cursor = db.rawQuery("select password from admin where name=?", new String[]{nameInfo});
String pi =null;
if (cursor.moveToNext()){
pi = cursor.getString(cursor.getColumnIndex("password"));
}
if (passwordInfo.equals(pi)){
admin_activity.actionStart(MainActivity.this,nameInfo);
cursor.close();
}else {
Toast.makeText(MainActivity.this,"用户名或者密码错误",Toast.LENGTH_SHORT).show();
}
}
});
register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
LayoutInflater factory = LayoutInflater.from(MainActivity.this);
final View textEntryView = factory.inflate(R.layout.register,null);
builder.setTitle("管理员注册");
builder.setView(textEntryView);
final EditText code = textEntryView.findViewById(R.id.admin_register_info);
final EditText name = textEntryView.findViewById(R.id.admin_register_name);
final EditText firstPassword = textEntryView.findViewById(R.id.admin_register_first_password);
final EditText secondPassword = textEntryView.findViewById(R.id.admin_register_second_password);
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String codeInfo = code.getText().toString();
if (codeInfo.equals("10086")) {
String nameInfo = name.getText().toString();
String firstPasswordInfo = firstPassword.getText().toString();
String secondPasswordInfo = secondPassword.getText().toString();
SQLiteDatabase db = dbHelper.getWritableDatabase();
if (firstPasswordInfo.matches("[0-9]{6}")) {
if (firstPasswordInfo.equals(secondPasswordInfo)) {
Cursor cursor = db.rawQuery("select name from admin where name =?", new String[]{nameInfo});
if (cursor.moveToNext()) {
Toast.makeText(MainActivity.this, "该用户已存在", Toast.LENGTH_SHORT).show();
} else {
db.execSQL("insert into admin(name,password)values(?,?)", new String[]{nameInfo, firstPasswordInfo});
}
} else {
Toast.makeText(MainActivity.this, "两次密码不相同", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this, "密码为6位纯数字", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this, "注册码错误", Toast.LENGTH_SHORT).show();
}
}
});
builder.create().show();
}
});
forgetNum.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,forgetNum_activity.class);
startActivity(intent);
}
});
}
}
|
package gov.smart.health.activity.self;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import gov.smart.health.R;
import gov.smart.health.activity.self.model.LikeAttentionInfoListModel;
import gov.smart.health.activity.vr.model.SportVideoListModel;
import gov.smart.health.utils.SHConstants;
public class MyAttentionDetailActivity extends AppCompatActivity {
private LikeAttentionInfoListModel model = new LikeAttentionInfoListModel();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_attention_detail);
if(getIntent() != null && getIntent().getSerializableExtra(SHConstants.PersonAttentionModelKey)!= null){
model = (LikeAttentionInfoListModel) getIntent().getSerializableExtra(SHConstants.PersonAttentionModelKey);
}
TextView title = (TextView)findViewById(R.id.tv_title);
title.setText(model.person_name == null?"详细信息":model.person_name);
//TODO detail view.
}
}
|
package com.example.bilp210_5_2;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private int sayac = 0;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=findViewById(R.id.textView);
}
public void azalt(View view) {
sayac--;
textView.setText("SAYAÇ = "+sayac);
}
public void artir(View view) {
sayac++;
textView.setText("SAYAÇ = "+sayac);
}
}
|
package no.ntnu.tollefsen.crazychat;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.provider.SearchRecentSuggestions;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import java.util.ArrayList;
import java.util.List;
import no.ntnu.tollefsen.crazychat.domain.Conversation;
import no.ntnu.tollefsen.crazychat.domain.Message;
import no.ntnu.tollefsen.crazychat.domain.MessageService;
public class SearchActivity extends AppCompatActivity {
private MessageAdapter messageAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
RecyclerView conversationView = (RecyclerView) findViewById(R.id.messageView);
conversationView.setLayoutManager(new LinearLayoutManager(this));
conversationView.setHasFixedSize(true);
messageAdapter = new MessageAdapter(this);
messageAdapter.setLayoutLeft(R.layout.conversation_row);
messageAdapter.setLayoutRight(R.layout.conversation_row);
messageAdapter.setOnClickListener(conversationId -> {
Intent intent = new Intent(this, MessageActivity.class);
intent.putExtra(MessageActivity.INTENT_CONVERSATION_ID, conversationId);
startActivity(intent);
});
conversationView.setAdapter(messageAdapter);
Intent intent = getIntent();
if(Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
MySuggestionProvider.AUTHORITY, MySuggestionProvider.MODE);
suggestions.saveRecentQuery(query, null);
doSearch(query);
}
}
/**
*
* @param query
*/
private void doSearch(String query) {
query = query.toLowerCase();
List<Message> result = new ArrayList<>();
for(Conversation item : MessageService.getSingleton(this).getConversations()) {
for(Message message : item.getMessages()) {
if (message.getText().toLowerCase().contains(query)) {
result.add(message);
}
}
}
doPresentResult(result);
}
/**
*
* @param results
*/
private void doPresentResult(List<Message> results) {
messageAdapter.getItems().addAll(results);
messageAdapter.notifyDataSetChanged();
}
}
|
package myServer;
import java.nio.channels.SocketChannel;
import myServer.*;
import java.net.InetSocketAddress;
public class MyClient {
private int portWrite;
private String ip;
private int portRead;
private SocketChannel clientsocketChanel;
public int getPortWrite() {
return portWrite;
}
public void setPortWrite(int portWrite) {
this.portWrite = portWrite;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public int getPortRead() {
return portRead;
}
public void setPortRead(int portRead) {
this.portRead = portRead;
}
public MyClient(int portWrite, String ip, int portRead) {
super();
this.portWrite = portWrite;
this.ip = ip;
this.portRead = portRead;
}
public void conectServer() {
//Server serv= new Server(8080);
//MyServer sl = new MyServer(3452, "124.0.0");
// get
// clientsocketChanel = SocketChannel.open(new InetSocketAddress(portVer, ipVer));
}
}
|
package swm11.jdk.jobtreaming.back.app.expert.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import swm11.jdk.jobtreaming.back.app.expert.model.Expert;
public interface ExpertRepository extends JpaRepository <Expert, Long> {
}
|
package com.example.topics.delete.lambdaauthorizer.infra;
import com.example.topics.core.Topic;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.lambda.LambdaClient;
import software.amazon.awssdk.services.lambda.model.InvokeRequest;
public class TopicDetailsGateway {
private final Region REGION = Region.EU_WEST_3;
private final String FUNCTION_NAME = "topic-details";
@SneakyThrows
public Topic getTopicDetails(String topicName) {
try (LambdaClient awsLambda = LambdaClient.builder()
.region(REGION)
.build()) {
//Setup an InvokeRequest
InvokeRequest request = InvokeRequest.builder()
.functionName(FUNCTION_NAME)
.payload(SdkBytes.fromUtf8String("{\"topicName\": \"" + topicName + "\"}"))
.build();
//Invoke the Lambda function
String responseString = awsLambda.invoke(request).payload().asUtf8String();
return new ObjectMapper().readValue(responseString, Topic.class);
}
}
}
|
package sorting;
/**
* https://www.geeksforgeeks.org/insertion-sort/ for a nicer implementation without a break and helper method;
*/
public class Insertion {
public static void main(String[] args) {
int[] a = new int[]{6, 5, 10, 9};
insertion(a);
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
public static void swap(int[] a, int i, int j) {
int temp = a[j];
a[j] = a[i];
a[i] = temp;
}
public static void insertion(int[] a) {
for (int i = 1; i < a.length; i++) {
for (int j = i - 1; j >= 0; j--) {
if (a[j] > a[i]) {
swap(a, i, j);
} else {
break;
}
}
}
}
}
|
package csi403;
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class DiscernJsonService extends HttpServlet { //EndpointHandler
// Standard servlet method
public void init() throws ServletException
{
// Do any required initialization here - likely none
}
// Standard servlet method - we will handle a POST operation
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Catch exceptions
try
{
doService(request, response);
}
catch(Exception e)
{
response.setContentType("application/json");
PrintWriter out = response.getWriter();
out.println("{ \"message\" : \"Malformed JSON\"}");
}
}
// Standard servlet method - we will not respond to GET
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type and return an error message
response.setContentType("application/json");
PrintWriter out = response.getWriter();
out.println("{ 'message' : 'Use POST!'}");
}
private void doService(HttpServletRequest request,
HttpServletResponse response)
throws Exception {
// Set response content type to be JSON
response.setContentType("application/json");
// Send back the response JSON message
PrintWriter out = response.getWriter();
// Get received JSON data from HTTP request
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
String jsonStr = "";
if(br != null){
jsonStr = br.readLine();
}
JsonParser parser = new JsonParser();
Polygon poly = parser.ParsePolygon(jsonStr);
int n = 0;
for(int i = 0; i < 19; i++)
{
for(int j = 0; j < 19; j++)
{
if(poly.containsPoint(new Point(i,j)) )
{
n++;
}
}
}
out.println("{ \"count\" : "+ n +" }");
}
}
|
package cn.ehanmy.hospital.mvp.model.entity.reg;
import cn.ehanmy.hospital.mvp.model.entity.request.BaseRequest;
/**
* Created by guomin on 2018/7/25.
*/
public class RegisterRequest extends BaseRequest {
private String step1Token;
private String mobile;
private String nickName;
private String sex;
private String birthday;
private String type;
private String code;
private int cmd = 10060;
private String token;
private String realName;
public String getStep1Token() {
return step1Token;
}
public void setStep1Token(String step1Token) {
this.step1Token = step1Token;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public int getCmd() {
return cmd;
}
public void setCmd(int cmd) {
this.cmd = cmd;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
@Override
public String toString() {
return "RegisterRequest{" +
"step1Token='" + step1Token + '\'' +
", mobile='" + mobile + '\'' +
", nickName='" + nickName + '\'' +
", sex='" + sex + '\'' +
", birthday='" + birthday + '\'' +
", type='" + type + '\'' +
", code='" + code + '\'' +
", cmd=" + cmd +
", token='" + token + '\'' +
", realName='" + realName + '\'' +
'}';
}
}
|
package edu.buet.cse.spring.ch03.v2;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import edu.buet.cse.spring.ch03.v2.model.Performer;
public class App3 {
public static void main(String... args) {
ApplicationContext appContext = new ClassPathXmlApplicationContext("/edu/buet/cse/spring/ch03/v2/spring-beans.xml");
Performer yanni = (Performer) appContext.getBean("yanni");
yanni.perform();
}
}
|
package edu.cnm.deepdive.stockrollersservice.service;
import com.google.gson.Gson;
import edu.cnm.deepdive.stockrollersservice.model.entity.History;
import edu.cnm.deepdive.stockrollersservice.model.entity.Stock;
import edu.cnm.deepdive.stockrollersservice.model.pojo.HistoryResponse;
import edu.cnm.deepdive.stockrollersservice.model.pojo.StockResponse;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class WorldTradingDataService {
RestTemplate restTemplate = new RestTemplateBuilder().build();
// static WorldTradingDataService getInstance() {
// return InstanceHolder.INSTANCE;
// }
public Stock getPostsPlainJSONStock(String token, String symbol) {
try {
Map<String, String> params = new HashMap<>();
params.put("token", token);
params.put("symbol", symbol);
String url = "https://api.worldtradingdata.com/api/v1/stock?api_token={token}&symbol={symbol}";
StockResponse response = restTemplate.getForObject(url, StockResponse.class, params);
return response.getData().get(0);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public List<History> getPostsPlainJSONHistory(String token, String symbol) {
try {
List<History> histories = new LinkedList<>();
Map<String, String> params = new HashMap<>();
params.put("token", token);
params.put("symbol", symbol);
String url = "https://api.worldtradingdata.com/api/v1/history?api_token={token}&symbol={symbol}";
HistoryResponse response = restTemplate.getForObject(url, HistoryResponse.class, params);
return response.getHistoryList().getHistories();
} catch (Exception e) {
throw new RuntimeException();
}
}
public List<History> getPostsPlainJSONHistoryByDate(String token, String symbol, String from, String to) {
try {
List<History> histories = new LinkedList<>();
String url = "https://api.worldtradingdata.com/api/v1/history?api_token={token}&symbol={symbol}&date_from={from}&date_to={to}";
HistoryResponse response = restTemplate.getForObject(url, HistoryResponse.class, token, symbol, from, to);
return response.getHistoryList().getHistories();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
|
package designer.ui.properties.renderer;
import specification.ExceptionClasses;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
/**
* Created by Tomas Hanus on 4/15/2015.
*/
public class ExceptionsCellRenderer extends DefaultTableCellRenderer {
public ExceptionsCellRenderer() {
super();
}
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component comp = super.getTableCellRendererComponent(table, value, isSelected,
hasFocus, row, column);
((JLabel) comp).setOpaque(true);
if (value instanceof ExceptionClasses) {
String textToDisplay = "No exceptions set";
ExceptionClasses exceptionClasses = (ExceptionClasses) table.getModel().getValueAt(row, column);
if (exceptionClasses != null) {
if ((exceptionClasses.getExcludeClasses() != null) || (exceptionClasses.getIncludeClasses() != null)) {
int numberOfClasses = 0;
if (exceptionClasses.getIncludeClasses() != null)
numberOfClasses += exceptionClasses.getIncludeClasses().size();
if (exceptionClasses.getExcludeClasses() != null)
numberOfClasses += exceptionClasses.getExcludeClasses().size();
if (numberOfClasses == 0)
textToDisplay = "No exceptions set";
else if (numberOfClasses == 1)
textToDisplay = "1 class set";
else {
textToDisplay = Integer.toString(numberOfClasses) + " classes set";
}
}
}
((JLabel) comp).setText(textToDisplay);
}
return comp;
}
}
|
// Sun Certified Java Programmer
// Chapter 1, P16
// Declarations and Access Control
package exam.stuff;
import cert.Beverage;
class Tea extends Beverage {
}
|
package Algorithm.Arithemic;
import Algorithm.Fraction;
import Algorithm.MyAlgorithm;
/**
* Created by MSDK on 7/15/16.
*/
public class RepeatedDecimal extends MyAlgorithm {
private final int MAX_NUM_DIGITS = 5;
private final int MIN_NUM_DIGITS = 3;
private int numDigits;
private int numRepeatedDigits;
private int repeatedDigitValue;
private int whole;
private Fraction nonRepeatedDecimal;
private Fraction answer;
@Override
public String generateQuestion(int max) {
numDigits = (int)(Math.random() * ((MAX_NUM_DIGITS - MIN_NUM_DIGITS) + 1) + MIN_NUM_DIGITS);
numRepeatedDigits = (int)(Math.random() * numDigits + 1);
repeatedDigitValue = (int)(Math.random() * Math.pow(10, numRepeatedDigits) + 1);
whole = (int)(Math.random() * MAX_NUM_DIGITS);
int numerNonRepeat = (int)(Math.random() * Math.pow(10, numDigits - numRepeatedDigits));
int denomNonRepeat = (int)(Math.pow(10, numDigits - numRepeatedDigits));
nonRepeatedDecimal = numDigits == numRepeatedDigits ? new Fraction(0, 1) : new Fraction(numerNonRepeat, denomNonRepeat);
int denomAns = (int)(Math.pow(10, numDigits) - Math.pow(10, numDigits - numRepeatedDigits));
answer = new Fraction(repeatedDigitValue, denomAns);
answer = answer.add(whole);
answer = answer.add(nonRepeatedDecimal);
String nonRepeatedDecimalFormat = "%0" + (numDigits - numRepeatedDigits) + "d";
String question = "Convert " + whole + ".";
question += nonRepeatedDecimal.getNumer() == 0 ? "" : String.format(nonRepeatedDecimalFormat, nonRepeatedDecimal.getNumer());
question += " " + repeatedDigitValue + " to fraction.";
return question;
}
@Override
public String toLatexFormat() {
String nonRepeatedDecimalFormat = "%0" + (numDigits - numRepeatedDigits) + "d";
String question = "Convert $" + whole + ".";
question += nonRepeatedDecimal.getNumer() == 0 ? "" : String.format(nonRepeatedDecimalFormat, nonRepeatedDecimal.getNumer());
question += "\\overline{" + repeatedDigitValue + "}$ to fraction.";
return question;
}
@Override
public String getAnswerLatex() {
return "Answer: $" + answer.toLatexFormat() + "$";
}
public static void main(String[] args) {
RepeatedDecimal r = new RepeatedDecimal();
r.generateQuestion(30);
System.out.println(r.toLatexFormat());
System.out.println(r.getAnswerLatex());
System.out.println(r.answer.toValue());
}
}
|
package enity;
public class TradeOrder {
private String traderId;
private String stockId;
private long price;
private int amount;
public String getTraderId() {
return traderId;
}
public void setTraderId(String traderId) {
this.traderId = traderId;
}
public String getStockId() {
return stockId;
}
public void setStockId(String stockId) {
this.stockId = stockId;
}
public long getPrice() {
return price;
}
public void setPrice(long price) {
this.price = price;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public TradeOrder( String traderId, String stockId, long price, int amount) {
this.traderId = traderId;
this.stockId = stockId;
this.price = price;
this.amount = amount;
}
public TradeOrder() {
}
@Override
public String toString() {
return "TradeOrder [traderId=" + traderId + ", stockId=" + stockId + ", price=" + price + ", amount=" + amount
+ "]";
}
}
|
package com.cnk.travelogix.suppliers.interceptors;
import java.io.IOException;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
/**
* @author I077988
*/
public class LoggingInterceptor implements ClientHttpRequestInterceptor {
private static final Logger LOG = LoggerFactory.getLogger(LoggingInterceptor.class);
@Override
public ClientHttpResponse intercept(final HttpRequest request, final byte[] body, final ClientHttpRequestExecution execution) throws IOException {
traceRequest(request, body);
final ClientHttpResponse response = execution.execute(request, body);
traceResponse(response);
return response;
}
private void traceRequest(HttpRequest request, byte[] body) throws IOException {
LOG.info("=======================Request begin==============================================");
LOG.info("URI: {}", request.getURI());
LOG.info("Method: {}", request.getMethod());
LOG.info("RequestBody: {}", new String(body, "UTF-8"));
LOG.info("=======================Request end================================================");
}
private void traceResponse(final ClientHttpResponse response) throws IOException {
final String responseXML = IOUtils.toString(response.getBody());
LOG.info("=======================Response begin==============================================");
LOG.info("StatusCode: {}", response.getStatusCode());
LOG.info("StatusText: {}", response.getStatusText());
LOG.info("ResponseBody: {}", responseXML);
LOG.info("=======================Response end=================================================");
}
}
|
package com.gmail.volodymyrdotsenko.cms.fe.vaadin;
import com.gmail.volodymyrdotsenko.cms.fe.vaadin.views.AccessDeniedView;
import com.gmail.volodymyrdotsenko.cms.fe.vaadin.views.ErrorView;
import com.vaadin.annotations.Theme;
import com.vaadin.navigator.Navigator;
import com.vaadin.server.DefaultErrorHandler;
import com.vaadin.server.VaadinRequest;
import com.vaadin.spring.annotation.SpringUI;
import com.vaadin.spring.navigator.SpringViewProvider;
import com.vaadin.ui.CssLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Notification;
import com.vaadin.ui.UI;
import com.vaadin.ui.themes.ValoTheme;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.vaadin.spring.i18n.I18N;
import org.vaadin.spring.security.VaadinSecurity;
import org.vaadin.spring.security.util.SecurityExceptionUtils;
import org.vaadin.spring.sidebar.components.ValoSideBar;
import org.vaadin.spring.sidebar.security.VaadinSecurityItemFilter;
/**
* Main application UI that allows the user to navigate between views, and log
* out.
*/
@SpringUI(path = "/cms")
@Theme(ValoTheme.THEME_NAME)
public class MainUI extends UI {
private static final long serialVersionUID = 1L;
@Autowired
private ApplicationContext applicationContext;
@Autowired
private VaadinSecurity vaadinSecurity;
@Autowired
private SpringViewProvider springViewProvider;
@Autowired
private ValoSideBar sideBar;
@Autowired
private I18N i18n;
@Override
protected void init(VaadinRequest request) {
//setLocale(new Locale(lang == null ? "en" : lang));
getPage().setTitle(i18n.get("application.title"));
// Let's register a custom error handler to make the 'access denied'
// messages a bit friendlier.
setErrorHandler(new DefaultErrorHandler() {
private static final long serialVersionUID = 1L;
@Override
public void error(com.vaadin.server.ErrorEvent event) {
if (SecurityExceptionUtils.isAccessDeniedException(event.getThrowable())) {
Notification.show("Sorry, you don't have access to do that.");
} else {
super.error(event);
}
}
});
HorizontalLayout layout = new HorizontalLayout();
layout.setSizeFull();
// By adding a security item filter, only views that are accessible to
// the user will show up in the side bar.
sideBar.setItemFilter(new VaadinSecurityItemFilter(vaadinSecurity));
layout.addComponent(sideBar);
CssLayout viewContainer = new CssLayout();
viewContainer.setSizeFull();
layout.addComponent(viewContainer);
layout.setExpandRatio(viewContainer, 1f);
Navigator navigator = new Navigator(this, viewContainer);
// Without an AccessDeniedView, the view provider would act like the
// restricted views did not exist at all.
springViewProvider.setAccessDeniedViewClass(AccessDeniedView.class);
navigator.addProvider(springViewProvider);
navigator.setErrorView(ErrorView.class);
navigator.navigateTo(navigator.getState());
setContent(layout); // Call this here because the Navigator must have
// been configured before the Side Bar can be
// attached to a UI.
}
public void closeWindow() {
getWindows().stream().forEach(w -> removeWindow(w));
}
}
|
package com.bingo.code.example.design.memento.rewrite;
import java.io.*;
/**
* ģ����������A�Ķ���ı���¼�ӿڣ��Ǹ�խ�ӿ�
*/
public interface FlowAMockMemento extends Serializable{
//�յ�
}
|
package net.sssanma.mc.world;
public class WorldException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public WorldException(String paramString) {
super(paramString);
}
public WorldException(Throwable arg0) {
super(arg0);
}
public WorldException(String arg0, Throwable arg1) {
super(arg0, arg1);
}
}
|
package com.smartup.manageorderapplication.exceptions;
import lombok.Getter;
@Getter
public class ProductNotFoundException extends RuntimeException {
private static final long serialVersionUID = 1L;
public static final String ERROR_CODE="002";
private Long idProduct;
public ProductNotFoundException(Long idProduct) {
this.idProduct=idProduct;
}
}
|
package shopify.app.shopifyme.presentation.application;
import android.app.Activity;
import javax.inject.Singleton;
import dagger.Component;
import shopify.app.shopifyme.data.repository.LoginRepository;
import shopify.app.shopifyme.data.repository.OfferRepository;
import shopify.app.shopifyme.data.repository.WishRepository;
@Singleton
@Component(modules = {ApplicationModule.class})
public interface ApplicationComponent {
void inject(Activity activity);
LoginRepository provideLoginRepository();
WishRepository provideWishListRepository();
OfferRepository provideOfferListRepository();
}
|
package dsp.api;
interface IModule {}
|
package com.example.smartparkingsystem;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class P_Adapter extends RecyclerView.Adapter<P_Adapter.productViewHolder>implements View.OnClickListener {
private Context mCtx;
private List<P_Model> pList;
public P_Adapter(Context mCtx, List<P_Model> pList) {
this.mCtx = mCtx;
this.pList = pList;
}
@NonNull
@Override
public productViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mCtx).inflate(R.layout.recycler_layout, parent, false);
return new productViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull productViewHolder holder, int position) {
final P_Model p_model = pList.get(position);
holder.textViewpName.setText( p_model.getP_name());
holder.textViewaddrs.setText( p_model.getCity_name());
holder.textViewsa.setText("Available Slots: " + p_model.getP_space());
holder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent =new Intent(mCtx,BookingMain.class);
intent.putExtra("key",p_model.getId());
intent.putExtra("longi",p_model.getLongi());
intent.putExtra("lati",p_model.getLati());
mCtx.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return pList.size();
}
@Override
public void onClick(View v) {
}
class productViewHolder extends RecyclerView.ViewHolder {
TextView textViewpName, textViewaddrs, textViewsa;
CardView cardView;
public productViewHolder(@NonNull View itemView) {
super(itemView);
textViewpName = itemView.findViewById(R.id.text_view_pname);
textViewaddrs = itemView.findViewById(R.id.text_address);
textViewsa = itemView.findViewById(R.id.text_view_sa);
cardView=itemView.findViewById(R.id.card1);
}
}
}
|
package org.sonar.api.test;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.HiddenFileFilter;
import org.apache.maven.it.VerificationException;
import org.apache.maven.it.Verifier;
import org.junit.Assert;
import org.junit.BeforeClass;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* Inspired by <a href="http://svn.sonatype.org/flexmojos/trunk/flexmojos-testing/flexmojos-test-harness">flexmojos-test-harness</a>.
*
* @author Evgeny Mandrikov
*/
public class AbstractSonarMavenTest {
private static final ReadWriteLock copyProjectLock = new ReentrantReadWriteLock();
protected static File projectsSource;
protected static File projectsWorkdir;
private static File mavenHome;
private static Properties props;
private static Properties profilerPropertis;
@BeforeClass
public static void init() throws IOException {
if (props != null) {
return;
}
props = new Properties();
ClassLoader cl = AbstractSonarMavenTest.class.getClassLoader();
InputStream is = cl.getResourceAsStream("baseTest.properties");
if (is != null) {
try {
props.load(is);
} finally {
is.close();
}
}
projectsSource = new File(getProperty("projects-source"));
projectsWorkdir = new File(getProperty("projects-target"));
mavenHome = new File(getProperty("fake-maven"));
// Profiler configuration
String jprofilerHome = getProperty("profiler-home");
profilerPropertis = new Properties();
profilerPropertis.setProperty("LD_LIBRARY_PATH", jprofilerHome + "/bin/linux-x86"); // TODO
StringBuilder profilerOpts = new StringBuilder();
profilerOpts.append("-agentlib:jprofilerti=offline,id=106,config=").append(getProperty("profiler-config")).append(' ');
profilerOpts.append("-Xbootclasspath/a:").append(jprofilerHome).append("/bin/agent.jar");
profilerPropertis.setProperty("MAVEN_OPTS", profilerOpts.toString());
}
protected static Verifier test(File projectDirectory) throws VerificationException {
Verifier verifier = getVerifier(projectDirectory);
// First of all we should compile project
verifier.executeGoal("compile");
// Execute sonar with profiler
verifier.executeGoal("sonar:sonar", profilerPropertis);
// TODO resave snapshot with proper name
return verifier;
}
protected static synchronized String getProperty(String key) {
return props.getProperty(key);
}
@SuppressWarnings({"unchecked"})
protected static Verifier getVerifier(File projectDirectory) throws VerificationException {
System.setProperty("maven.home", mavenHome.getAbsolutePath());
Verifier verifier = new Verifier(projectDirectory.getAbsolutePath());
List<String> options = verifier.getCliOptions();
// options.add("--offline");
options.add("--no-plugin-updates");
options.add("--batch-mode");
options.add("--debug");
// TODO use local repo
// verifier.getVerifierProperties().put( "use.mavenRepoLocal", "true" );
// verifier.setLocalRepo( getProperty( "fake-repo" ) );
// verifier.setLogFileName(getTestName() + ".log");
verifier.setAutoclean(false);
return verifier;
}
protected static File getProject(String projectName) throws IOException {
copyProjectLock.writeLock().lock();
try {
File projectFolder = new File(projectsSource, projectName);
Assert.assertTrue(
"Project " + projectName + " folder not found.\n" + projectFolder.getAbsolutePath(),
projectFolder.isDirectory()
);
File destDir = new File(projectsWorkdir, projectName); // TODO include testName
FileUtils.copyDirectory(projectFolder, destDir, HiddenFileFilter.VISIBLE);
return destDir;
} finally {
copyProjectLock.writeLock().unlock();
}
}
}
|
package com.facebook.react;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ScriptLoadBridge;
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
import com.facebook.react.modules.core.PermissionAwareActivity;
import com.facebook.react.modules.core.PermissionListener;
import com.rnsplitbundle.util.ScriptUtil;
import java.io.File;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public abstract class ScriptReactActivity extends AppCompatActivity
implements DefaultHardwareBackBtnHandler, PermissionAwareActivity {
// BUNDLE 存储位置类型
protected enum BUNDLE_TYPE{
ASSET_TYPE,
FILE_TYPE
}
protected abstract String getBundlePath(); // 返回 Bundle 文件路径
protected abstract BUNDLE_TYPE getBundlePathType(); // Bundle 文件存储路径类型
private final ReactActivityTestDelegate mDelegate;
protected ScriptReactActivity() {
mDelegate = createReactActivityDelegate();
}
/**
* 初始化 ReactContext 上下文环境
*/
private void initialReactContext(final Bundle saveInstanceState) {
mDelegate.initReactDelegate();
ReactInstanceManager rim = mDelegate.getReactInstanceManager();
boolean hasStartedCreatingInitialContext = rim.hasStartedCreatingInitialContext();
if(!hasStartedCreatingInitialContext){
rim.createReactContextInBackground();
rim.addReactInstanceEventListener(new ReactInstanceManager.ReactInstanceEventListener() {
@Override
public void onReactContextInitialized(ReactContext context) {
// 加载子模块,并绑定视图
loadJSBundle();
mDelegate.onCreate(saveInstanceState);
rim.removeReactInstanceEventListener(this);
}
});
}else{
loadJSBundle();
mDelegate.onCreate(saveInstanceState);
}
}
/**
* 加载 bundle
*/
private void loadJSBundle() {
String bundlePath = getBundlePath();
BUNDLE_TYPE bundleType = getBundlePathType();
if(bundleType == BUNDLE_TYPE.ASSET_TYPE) {
// 从 Asset 目录下加载 bundle 文件
ScriptLoadBridge.loadScriptFromAsset(this,getReactInstanceManager().getCurrentReactContext().getCatalystInstance(),bundlePath,false);
//ScriptUtil.loadScriptFromAsset(this,rim.getCurrentReactContext().getCatalystInstance(),bundlePath,false);
} else {
// 从 File 目录下加载 bundle 文件
File scriptFile = new File(getApplicationContext().getFilesDir()
+ File.separator + bundlePath);
ScriptUtil.loadScriptFromFile(scriptFile.getAbsolutePath(), getReactInstanceManager().getCurrentReactContext().getCatalystInstance(), bundlePath,false);
}
}
/**
* Returns the name of the main component registered from JavaScript. This is used to schedule
* rendering of the component. e.g. "MoviesApp"
*/
protected @Nullable
String getMainComponentName() {
return null;
}
/** Called at construction time, override if you have a custom delegate implementation. */
protected ReactActivityTestDelegate createReactActivityDelegate() {
Log.e("lookat","createReactActivityDelegate");
return new ReactActivityTestDelegate(this, getMainComponentName());
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initialReactContext(savedInstanceState);
}
@Override
protected void onPause() {
super.onPause();
mDelegate.onPause();
}
@Override
protected void onResume() {
super.onResume();
mDelegate.onResume();
}
@Override
protected void onDestroy() {
super.onDestroy();
mDelegate.onDestroy();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
mDelegate.onActivityResult(requestCode, resultCode, data);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return mDelegate.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
return mDelegate.onKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
}
@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
return mDelegate.onKeyLongPress(keyCode, event) || super.onKeyLongPress(keyCode, event);
}
@Override
public void onBackPressed() {
if (!mDelegate.onBackPressed()) {
super.onBackPressed();
}
}
@Override
public void invokeDefaultOnBackPressed() {
super.onBackPressed();
}
@Override
public void onNewIntent(Intent intent) {
if (!mDelegate.onNewIntent(intent)) {
super.onNewIntent(intent);
}
}
@Override
public void requestPermissions(
String[] permissions, int requestCode, PermissionListener listener) {
mDelegate.requestPermissions(permissions, requestCode, listener);
}
@Override
public void onRequestPermissionsResult(
int requestCode, String[] permissions, int[] grantResults) {
mDelegate.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
mDelegate.onWindowFocusChanged(hasFocus);
}
protected final ReactNativeHost getReactNativeHost() {
return mDelegate.getReactNativeHost();
}
protected final ReactInstanceManager getReactInstanceManager() {
return mDelegate.getReactInstanceManager();
}
protected final void loadApp(String appKey) {
mDelegate.loadApp(appKey);
}
}
|
package com.vilio.bps.inquiry.util;
import net.sf.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* Hello world!
*
*/
public class CaadDemo {
public static void main(String[] args) throws Exception {
Map map = new HashMap();
map.put("CaseId", UUID.randomUUID().toString().toLowerCase().replace("-", ""));
map.put("Key", "a1b20c2a3f10c235962408d37e0206d5");
map.put("TypeCode", 0);
map.put("AreaCode", "410202");
map.put("PropertyID ", "Residential");
map.put("ThirdProperty", "Apartment");
map.put("Address", "香樟公寓2期2栋");
map.put("BuildArea", 100);
map.put("ProjectName", "香樟公寓");
String content = JSONObject.fromObject(map).toString();
System.out.println(content);
String privateKey = "<RSAKeyValue><Modulus>p3hLthaU4ei0dWI1QP99JaVYbghOooJWet7bNXyOWyOAQQzfITRbMCGaBZXg7M0w2SMtxyPr+w54kcsQQfDpMn61BXpWLg/5lYvYKkIG5DzFmhjyUwUC+g91bR7hHfj55YOFehvUwX6x6CFC9CQ2jJRsIWfqT3pTFfrFmfmgdiM=</Modulus><Exponent>AQAB</Exponent><P>0JvjbXXIb6ndTeDVlIWZeJZ3CYxMIXII8qvKQ0cYh3K0NOQLFZJIcCQitJ7rL2gNadDLijr5p+fp9ovZlbKX6Q==</P><Q>zYPgWmK47mje4MUF+KzZNQ05SPj/iU/nL+X3v90d9eat1Rtf7iito0qsdFp3LgTfle294jrEJy6ji5CZpFQiKw==</Q><DP>w2Vg70RlzAHlom64X3eMOyFkunLJVIKF0xgKSl4roaNVHD2GDFyKsU+HmntIe40RE05ZeE6pThayVRbFZax1EQ==</DP><DQ>UlNqsypq5G40IhwqyTQMirjyYq4ER3AvrztTJJOiJdgzeHPP2OqIrCoErVNz/IZNPpUPBKn/26ZOM2FIetCNIw==</DQ><InverseQ>rPqhs20F8gxmLbgqIj0EOloUaQIe+AdIrgqNQYr67J7YE4m7+pKutOt+TMl8HsOQR0Gpyf7FsoPouIJpJMy2vw==</InverseQ><D>NYKiCnYPr1loI+Oz6WdZSQiah1n/KjzkPhFsUJxSbjubNO3Uc+sjQe9So/s+adusgo0TiQBo3AjFLKyKLs+36wavmlTahC45+XUmaHCuOvTFnMlquAE2K+I14swToZFmeewAEl2cjFtjDpzzAPHYJbXfe+L8Xbktt9t6DOgGysk=</D></RSAKeyValue>";
String publicKey = "<RSAKeyValue><Modulus>6TugMLi2nrkd7WGgBA9o4rgQ73Xk9SzTWqaNfH+f8ahTulMGYvmPWv6mF3xMkRhVLwQWX0zu3+d9Ofzni000XyfQsnk9GPfJ4o/yxaU6axB6ys8oy23ON+k1+571bPu8Ifh4shSxTHpzv5CTFkefsHDqQI3NXp/pA1ArzCsNsVE=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
String aesKey = "slpgenquirysvcxx";
// 加密
String cryptContent = AES.encrypt(content, aesKey);
String dCryptContent = AES.decrypt(cryptContent, aesKey);
// 加签
String signData = Sha1RSA.sign(cryptContent, privateKey);
// 组合
String data = cryptContent + "," + signData;
System.out.println(data);
Map mapParam = new HashMap();
mapParam.put("Data", data);
String tmp = JSONObject.fromObject(mapParam).toString();
//测试环境内网ip "http://172.16.2.1:8077/api/webapiaccess/PublicTestEnquiry/Enquiry",
//测试环境外网ip "http://116.228.48.92:8077/api/webapiaccess/PublicTestEnquiry/Enquiry",
String result =
WebUtil.sendPost(
"http://116.228.48.92:8077/api/webapiaccess/PublicTestEnquiry/Enquiry",tmp
);
System.out.println(result);
if (!Sha1RSA.doCheck(result.split(",")[0], result.split(",")[1],publicKey)) {
System.out.println("验签失败");
} else {
System.out.println(AES.decrypt(result.split(",")[0], aesKey));
}
}
}
|
package com.yougou.merchant.dao;
import static org.junit.Assert.assertTrue;
import java.util.List;
import javax.annotation.Resource;
import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.session.RowBounds;
import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import com.yougou.merchant.api.monitor.dao.WarnMapper;
import com.yougou.merchant.api.monitor.vo.MonitorAppkeyWarnDetail;
import com.yougou.merchant.api.monitor.vo.MonitorDayWarnDetail;
import com.yougou.merchant.api.monitor.vo.MonitorEarlyWarnQueryVo;
import com.yougou.merchant.api.monitor.vo.MonitorEarlyWarning;
import com.yougou.merchant.api.monitor.vo.MonitorRateWarnDetail;
import com.yougou.merchant.api.monitor.vo.MonitorSuccRateWarnDetail;
/**
*
* @ClassName: WarnDaoTest
* @author huang.tao
* @date 2013-12-16 下午6:03:41
*
*/
@ContextConfiguration(locations = { "classpath:applicationContext.xml" })
public class WarnDaoTest extends AbstractTransactionalJUnit4SpringContextTests {
@Resource
private WarnMapper warnMapper;
@Test
public void insertMonitorEarlyWarning() {
MonitorEarlyWarning vo = new MonitorEarlyWarning();
vo.setId("112");
vo.setAppKey("6242ebb2_1407b95bc46__7fb7");
vo.setTimeQuantum("2014-02-26");
vo.setWarmAppkeyCallCount(1);
vo.setWarmDayCallCount(1);
vo.setWarmRateCount(1);
vo.setWarmSuccessCount(1);
warnMapper.insertMonitorEarlyWarning(vo);
}
@Test
public void insertMonitorAppkeyWarnDetail() {
MonitorAppkeyWarnDetail vo = new MonitorAppkeyWarnDetail();
vo.setId("110");
vo.setAppKey("6242ebb2_1407b95bc46__7fb7");
vo.setTimeQuantum("2014-02-26");
vo.setAppkeyCallCount(100000);
vo.setWarmAppkeyCallCount(80000);
warnMapper.insertMonitorAppkeyWarnDetail(vo);
}
@Test
public void insertMonitorDayWarnDetail() {
MonitorDayWarnDetail vo = new MonitorDayWarnDetail();
vo.setId("110");
vo.setAppKey("6242ebb2_1407b95bc46__7fb7");
vo.setApiId("ee5010b0c4f511e19c4f5cf3fc0c2d70");
vo.setDayCallCount(10000);
vo.setTimeQuantum("2014-02-26");
vo.setWarmDayCallCount(8000);
warnMapper.insertMonitorDayWarnDetail(vo);
}
@Test
public void insertMonitorSuccRateWarnDetail() {
MonitorSuccRateWarnDetail vo = new MonitorSuccRateWarnDetail();
vo.setId("110");
vo.setAppKey("6242ebb2_1407b95bc46__7fb7");
vo.setApiId("ee5010b0c4f511e19c4f5cf3fc0c2d70");
vo.setTimeQuantum("2014-02-26");
vo.setFailCallCount(20000);
vo.setSuccessCallCount(30000);
warnMapper.insertMonitorSuccRateWarnDetail(vo);
}
@Test
public void insertMonitorRateWarnDetail() {
MonitorRateWarnDetail vo = new MonitorRateWarnDetail();
vo.setId("110");
vo.setAppKey("6242ebb2_1407b95bc46__7fb7");
vo.setApiId("ee5010b0c4f511e19c4f5cf3fc0c2d70");
vo.setTimeQuantum("2014-02-26");
vo.setRateCallCount(12000);
vo.setWarmRateCallCount(10000);
warnMapper.insertMonitorRateWarnDetail(vo);
}
@Test
public void queryMonitorEarlyWarning() {
MonitorEarlyWarnQueryVo vo = new MonitorEarlyWarnQueryVo();
vo.setAppKey("6242ebb2_1407b95bc46__7fb7");
vo.setStartTime("2014-02-26");
vo.setEndTime("2014-02-26");
List<MonitorEarlyWarning> list = warnMapper.queryMonitorEarlyWarning(vo, new RowBounds());
assertTrue(CollectionUtils.isNotEmpty(list));
}
@Test
public void queryMonitorEarlyWarningCount() {
MonitorEarlyWarnQueryVo vo = new MonitorEarlyWarnQueryVo();
vo.setAppKey("6242ebb2_1407b95bc46__7fb7");
vo.setStartTime("2014-02-26");
vo.setEndTime("2014-02-26");
Integer count = warnMapper.queryMonitorEarlyWarningCount(vo);
assertTrue(count > 0);
}
@Test
public void queryAppKeyEarlyWarningDetail() {
MonitorEarlyWarnQueryVo vo = new MonitorEarlyWarnQueryVo();
vo.setAppKey("6242ebb2_1407b95bc46__7fb7");
vo.setStartTime("2014-02-26");
vo.setEndTime("2014-02-26");
List<MonitorAppkeyWarnDetail> list = warnMapper.queryAppKeyEarlyWarningDetail(vo);
assertTrue(CollectionUtils.isNotEmpty(list));
}
@Test
public void queryApiEarlyWarningDetail() {
MonitorEarlyWarnQueryVo vo = new MonitorEarlyWarnQueryVo();
vo.setAppKey("6242ebb2_1407b95bc46__7fb7");
vo.setStartTime("2014-02-26");
vo.setEndTime("2014-02-26");
List<MonitorDayWarnDetail> list = warnMapper.queryApiEarlyWarningDetail(vo);
assertTrue(CollectionUtils.isNotEmpty(list));
}
@Test
public void querySuccRateWarnDetail() {
MonitorEarlyWarnQueryVo vo = new MonitorEarlyWarnQueryVo();
vo.setAppKey("6242ebb2_1407b95bc46__7fb7");
vo.setStartTime("2014-02-26");
vo.setEndTime("2014-02-26");
List<MonitorSuccRateWarnDetail> list = warnMapper.querySuccRateWarnDetail(vo);
assertTrue(CollectionUtils.isNotEmpty(list));
}
@Test
public void queryRateWarnDetail() {
MonitorEarlyWarnQueryVo vo = new MonitorEarlyWarnQueryVo();
vo.setAppKey("6242ebb2_1407b95bc46__7fb7");
vo.setStartTime("2014-02-26");
vo.setEndTime("2014-02-26");
List<MonitorRateWarnDetail> list = warnMapper.queryRateWarnDetail(vo);
assertTrue(CollectionUtils.isNotEmpty(list));
}
@Test
public void queryApiFrequencyBynow() {
MonitorEarlyWarnQueryVo vo = new MonitorEarlyWarnQueryVo();
vo.setStartTime("2014-02-01");
vo.setEndTime("2014-02-26");
List<MonitorRateWarnDetail> list = warnMapper.queryApiFrequencyBynow(vo);
assertTrue(CollectionUtils.isNotEmpty(list));
}
}
|
package app;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.text.MessageFormat;
import java.awt.Color;
import javax.swing.JLabel;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.border.Border;
import javax.swing.border.SoftBevelBorder;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JComboBox;
import javax.swing.JComponent;
//import javax.swing.JFileChooser;
/** User dialog widget */
public class UserDialog {
private Localization lang;
protected JFrame mainFrame;
private SearchWords jsonSearchWords;
private LabelledField field_topic, field_targetFile, field_status;
private LabelledField field_fileToAnalyze;
private LabelledArea field_supplinfo;
private JLabel textareaLabel, searchTermBoxLabel, extractLengthLabel;
private JLabel headline;
private JLabel copyright = new JLabel("© 2021 Daniela Grothe");
private JButton github = new JButton("GitHub");
private WButton fileDialogButton, startButton, openButton, closeButton, clearButton;
private JScrollPane listScroller;
private JTextArea userTermsTextArea;
private JCBox searchTermBox, localizationBox;
private ToggleFunction chkNumbers, chkSymbols, chkWords, chkUserTerms;
private JComboBox<Integer> extractLength;
private Integer[] extractLengthValues = new Integer[] { 10, 20, 50, 75, 100, 120, 150 };
private JPanel controlPanel, statusPanel, top;
private ImagePanel background;
private Image image;
private GridBagConstraints fieldGridConfig, pgc;
private GridBagLayout panelgrid, grid3;
private String workingFolder;
private FileDialog fileDialog;
// private JFileChooser fileDialog;
private int mode;
public void switchMode(int mode) {
this.mode += mode;
}
private String selFile, selTargetFile, fileType = "";
private static final String[] ALLOWED_INPUT_FILES = { ".txt", ".md", ".tex", ".py", ".rb", ".yml", "html", "eml",
".java", ".cpp", ".hpp", ".csv", ".cs" };
private static final char[] ILLEGAL_CHARACTERS = { '/', '\n', '\r', '\t', '\0', '\f', '`', '?', '*', '\\', '<', '>',
'|', '\"', ':' };
private TimeCalc tc;
// Colors
private Color warnFG = new Color(255, 0, 0);
private Color normalFG = new Color(0, 0, 0);
private Color openFileBG = new Color(255, 177, 91);
private Color startButtonBG = new Color(232, 111, 55);
private Color openHTMLBG = new Color(92, 177, 92);
private Color moss = new Color(170, 200, 170);
private Color clearBG = moss;
private Color light = new Color(190, 220, 190);
private Color darker = new Color(130, 170, 130);
private Color hint = new Color(130, 170, 130);
private Color green = new Color(160, 180, 170);
public UserDialog() {
try {
lang = new Localization();
jsonSearchWords = new SearchWords();
headline = new JLabel(lang.getLocalizedText("description"));
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
System.out.println("Screen width = " + d.width);
System.out.println("Screen height = " + d.height);
mainFrame = new JFrame("Java Wordchecker");
mainFrame.setSize(600, 460);
mainFrame.setLayout(new GridLayout());
makeFields();
makeButtons();
prepareGUI();
searchTermBox = new JCBox("...", jsonSearchWords);
listScroller = new JScrollPane(userTermsTextArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
int height_of_scrollbar = listScroller.getVerticalScrollBar().getHeight();
listScroller.getVerticalScrollBar().setPreferredSize(new Dimension(19, height_of_scrollbar));
localizationBox = new JCBox("Language settings", lang);
addButtons();
addCheckboxGroup();
positionFields();
addListenersToUI();
addListenersToButtons();
showFileDialog();
statusPanel.setVisible(true);
searchTermBox.connect(this, userTermsTextArea, jsonSearchWords);
localizationBox.connect(this, lang);
mainFrame.setVisible(true);
mainFrame.requestFocus();
}
catch (Exception awe) {
// intended as fallback if UI cannot be shown on system
System.out.println("Application window could not be opened. Reason:");
System.out.println(awe.toString());
}
}
public String getSelectedFile() {
return selFile;
}
public void getSearchWordsFromJson(String key) {
String rjs = jsonSearchWords.getText(key);
userTermsTextArea.setText(rjs);
}
private void githubOpen() {
Desktop desktop = Desktop.getDesktop();
try {
URL url = new URL("https://github.com/DGrothe-PhD/WordCheckerJava/");
desktop.browse(url.toURI());
} catch (Exception oError) {
setMessage(lang.getLocalizedText("GitHubNotOpening"), 1);
}
}
/** Open the results HTML file */
private void htmlOpen() {
Desktop desktop = Desktop.getDesktop();
try {
URI uri = new File(selTargetFile).toURI();
desktop.browse(uri);
} catch (Exception oError) {
setMessage(lang.getLocalizedText("OutputFileNotOpening"), 1);
} finally {
mainFrame.revalidate();
}
}
/** Lets user select which tokens to collect */
private void addCheckboxGroup() {
mode = 15;
chkNumbers = new ToggleFunction(lang.getLocalizedText("Numbers"), this,
CountWords.switchMode.c_Numbers.getMode());
chkSymbols = new ToggleFunction(lang.getLocalizedText("Symbols"), this,
CountWords.switchMode.c_Symbols.getMode());
chkWords = new ToggleFunction(lang.getLocalizedText("Words"), this, CountWords.switchMode.c_Words.getMode());
chkUserTerms = new ToggleFunction(lang.getLocalizedText("Search terms"), this,
CountWords.switchMode.c_UserTerms.getMode());
extractLengthLabel = new JLabel(lang.getLocalizedText("Extract length:"));
extractLength = new JComboBox<Integer>(extractLengthValues);
controlPanel.add(chkNumbers);
controlPanel.add(chkSymbols);
controlPanel.add(chkWords);
controlPanel.add(chkUserTerms);
controlPanel.add(extractLengthLabel);
controlPanel.add(extractLength);
}
private void prepareGUI() {
grid3 = new GridBagLayout();
statusPanel = new JPanel();
statusPanel.setBackground(moss);
statusPanel.setSize(424, 280);
statusPanel.setLayout(grid3);
controlPanel = new JPanel();
controlPanel.setLayout(new GridLayout(3, 2));
controlPanel.setBackground(darker);
controlPanel.setSize(424, 280);
top = new JPanel();
panelgrid = new GridBagLayout();
top.setLayout(panelgrid);
fieldGridConfig = new GridBagConstraints();
pgc = new GridBagConstraints();
pgc.fill = GridBagConstraints.HORIZONTAL;
pgc.anchor = GridBagConstraints.NORTH;
pgc.gridheight = 1;
pgc.gridx = 0;
pgc.gridy = 0;
top.add(controlPanel, pgc);
pgc.gridheight = 2;
pgc.gridx = 0;
pgc.gridy = 2;
top.add(statusPanel, pgc);
try {
image = ImageIO.read(getClass().getResource("/app/background.JPG"));
background = new ImagePanel(image);
background.setLayout(new FlowLayout());
background.add(headline);
background.add(top, "Center");
background.add(copyright);
Border raised = new SoftBevelBorder(SoftBevelBorder.RAISED);
github.setBorder(raised);
github.setSize(20, 50);
github.setBackground(moss);
background.add(github);
mainFrame.add(background);
} catch (Exception e) {
mainFrame.setBackground(moss);
mainFrame.add(headline);
mainFrame.add(top, "Center");
mainFrame.add(copyright);
mainFrame.add(github);
}
}
private void makeFields() {
searchTermBoxLabel = new JLabel(lang.getLocalizedText("Search terms:"));
searchTermBoxLabel.setFont(WFont.labelfont);
textareaLabel = new JLabel(lang.getLocalizedText("Edit search terms:"));
textareaLabel.setFont(WFont.labelfont);
field_topic = new LabelledField(lang.getLocalizedText("Type topic:"),
lang.getLocalizedText("Result word list"));
field_targetFile = new LabelledField(lang.getLocalizedText("Target file:"), "Word_occurrences.html");
field_status = new LabelledField(lang.getLocalizedText("Selected folder:"), "", hint, false);
field_fileToAnalyze = new LabelledField(lang.getLocalizedText("Selected file:"),
"- " + lang.getLocalizedText("Please select a file") + " -", light, false);
field_supplinfo = new LabelledArea(lang.getLocalizedText("Info:"), "", green, false);
userTermsTextArea = new JTextArea();
userTermsTextArea.setFont(WFont.descriptionFont);
userTermsTextArea.setColumns(LabelledField.FIELD_WIDTH);
userTermsTextArea.setRows(5);
userTermsTextArea.setToolTipText(lang.getLocalizedText("Edit tooltip"));
userTermsTextArea.setEditable(true);
}
private void makeButtons() {
fileDialog = new FileDialog(mainFrame, lang.getLocalizedText("Select file"));
// fileDialog = new JFileChooser(mainFrame);
// fileDialog.setDialogTitle(lang.getANSI("Select file"));
fileDialogButton = new WButton(lang.getLocalizedText("Open file"), openFileBG);
startButton = new WButton(lang.getLocalizedText("Start"), startButtonBG);
startButton.setPreferredSize(new Dimension(116, 30));
openButton = new WButton(lang.getLocalizedText("Show Results"), openHTMLBG);
closeButton = new WButton(lang.getLocalizedText("Close window"), moss);
clearButton = new WButton(lang.getLocalizedText("Clear search"), clearBG);
}
protected void addTextToButtons() {
fileDialog.setTitle(lang.getLocalizedText("Select file"));
fileDialogButton.setText(lang.getLocalizedText("Open file"));
startButton.setText(lang.getLocalizedText("Start"));
openButton.setText(lang.getLocalizedText("Show Results"));
closeButton.setText(lang.getLocalizedText("Close window"));
clearButton.setText(lang.getLocalizedText("Clear search"));
headline.setText(lang.getLocalizedText("description"));
chkNumbers.setText(lang.getLocalizedText("Numbers"));
chkSymbols.setText(lang.getLocalizedText("Symbols"));
chkWords.setText(lang.getLocalizedText("Words"));
chkUserTerms.setText(lang.getLocalizedText("Search terms"));
searchTermBoxLabel.setText(lang.getLocalizedText("Search terms:"));
extractLengthLabel.setText(lang.getLocalizedText("Extract length:"));
textareaLabel.setText(lang.getLocalizedText("Edit search terms:"));
userTermsTextArea.setToolTipText(lang.getLocalizedText("Edit tooltip"));
field_topic.setText(lang.getLocalizedText("Result word list"));
field_topic.thelabel.setText(lang.getLocalizedText("Type topic:"));
field_targetFile.thelabel.setText(lang.getLocalizedText("Target file:"));
field_status.thelabel.setText(lang.getLocalizedText("Selected folder:"));
field_fileToAnalyze.thelabel.setText(lang.getLocalizedText("Selected file:"));
if (field_fileToAnalyze.getText().startsWith("-")) {
field_fileToAnalyze.setText(lang.getLocalizedText("Please select a file"));
}
field_supplinfo.thelabel.setText(lang.getLocalizedText("Info:"));
}
private void addButtons() {
JComponent[] abc = { fileDialogButton, startButton, openButton, closeButton, clearButton };
for (JComponent s : abc)
controlPanel.add(s);
}
// placement of UI elements
private void positionFields() {
/// ~~~ gbc region ~~~
fieldGridConfig.fill = GridBagConstraints.HORIZONTAL;
fieldGridConfig.anchor = GridBagConstraints.NORTH;
// left column
fieldGridConfig.gridx = 0;
fieldGridConfig.gridy = 0;
statusPanel.add(field_topic.thelabel, fieldGridConfig);
// gbc.gridx = 0;
fieldGridConfig.gridy = 1;
statusPanel.add(field_targetFile.thelabel, fieldGridConfig);
fieldGridConfig.gridy = 3;
statusPanel.add(field_status.thelabel, fieldGridConfig);
fieldGridConfig.gridy = 4;
statusPanel.add(field_fileToAnalyze.thelabel, fieldGridConfig);
fieldGridConfig.weightx = 1.0;
fieldGridConfig.gridy = 5;
statusPanel.add(field_supplinfo.thelabel, fieldGridConfig);
fieldGridConfig.gridy = 32;
statusPanel.add(textareaLabel, fieldGridConfig);
// right column is broader
fieldGridConfig.gridwidth = 2;
fieldGridConfig.gridx = 1;
fieldGridConfig.gridy = 0;
statusPanel.add(field_topic.jcomp, fieldGridConfig);
fieldGridConfig.gridy = 1;
statusPanel.add(field_targetFile.jcomp, fieldGridConfig);
fieldGridConfig.gridy = 3;
statusPanel.add(field_status.jcomp, fieldGridConfig);
fieldGridConfig.gridy = 4;
statusPanel.add(field_fileToAnalyze.jcomp, fieldGridConfig);
fieldGridConfig.gridy = 5;
statusPanel.add(field_supplinfo.jcomp, fieldGridConfig);
/// snippet searchtermbox start
fieldGridConfig.gridx = 0;
fieldGridConfig.gridy = 6;
fieldGridConfig.gridwidth = 2;
statusPanel.add(searchTermBoxLabel, fieldGridConfig);
fieldGridConfig.gridx = 1;
fieldGridConfig.gridy = 6;
statusPanel.add(listScroller);
statusPanel.add(searchTermBox, fieldGridConfig);
fieldGridConfig.gridy = 8;
statusPanel.add(localizationBox, fieldGridConfig);
/// snippet end
fieldGridConfig.gridy = 32;
statusPanel.add(listScroller, fieldGridConfig);
}
/** show status messages */
private void setMessage(String settext, int warning) {
field_status.setText(settext);
field_status.jcomp.setForeground(warning == 1 ? warnFG : normalFG);
}
/** show extra message @param up to 3 strings */
private void setSupplMessage(String s, String... t) {
String t1 = t.length > 0 ? t[0] : "";
String t2 = t.length > 1 ? t[1] : "";
field_supplinfo.setText(s + " " + t1 + " " + t2);
field_supplinfo.setForeground(normalFG);
}
private void setSupplWarning(String s, String... t) {
String t1 = t.length > 0 ? t[0] : "";
String t2 = t.length > 1 ? t[1] : "";
field_supplinfo.setText(s + " " + t1 + " " + t2);
field_supplinfo.setForeground(warnFG);
}
private String setWritingTarget() {
// Validate results filename from input text field
String s = field_targetFile.getText();
String illchar = "";
for (char c : ILLEGAL_CHARACTERS) {
if (s.contains("" + c)) {
illchar += ("" + c);
}
}
if (illchar.length() > 0) {
setMessage(MessageFormat.format(lang.getLocalizedText("BadSymbolInFilename"), illchar), 1);
return null;
}
String fileprefix = lang.getLocalizedText("Results") + "_";
if (s.length() > 5 && s.endsWith(".html"))
return fileprefix + s;
return workingFolder + fileprefix + s + ".html";
}
private void addListenersToUI() {
github.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
githubOpen();
}
});
userTermsTextArea.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyChar() == KeyEvent.VK_ESCAPE) {
mainFrame.requestFocus();
}
}
});
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setFocusable(true);
mainFrame.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent event) {
if (event.getKeyChar() == KeyEvent.VK_ESCAPE) {
mainFrame.dispose();
}
}
});
}
private void addListenersToButtons() {
/** Opens the result HTML file (in the standard browser). */
openButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
htmlOpen();
mainFrame.revalidate();
}
});
openButton.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent event) {
if (event.getKeyChar() == KeyEvent.VK_ENTER) {
htmlOpen();
mainFrame.revalidate();
}
}
});
}
/** File dialog and button actions */
private void showFileDialog() {
/** The Open File or Browse... button to select input text file. */
fileDialogButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setMessage("", 0);
fileDialog.setVisible(true);
processFile();
mainFrame.revalidate();
}
});
fileDialogButton.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent event) {
if (event.getKeyChar() == KeyEvent.VK_TAB) {
fileDialogButton.requestFocus();
} else if (event.getKeyChar() == KeyEvent.VK_ENTER) {
setMessage("", 0);
fileDialog.setVisible(true);
processFile();
}
mainFrame.revalidate();
}
});
// internal file reading error
/**
* The start button. When pressed, chosen file is processed, and results are
* written into the target file.
*/
startButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
tc = new TimeCalc();
try {
Settings.setExtractSize((int) extractLength.getSelectedItem());
if (selFile == null || selFile.length() < 2) {
setMessage(lang.getLocalizedText("PleaseSelectFile"), 1);
throw new WriteException("");
} else if (fileType.length() < 2) {
setMessage(lang.getLocalizedText("suggestFileType") + " .txt, .html, .tex, .csv, ...", 1);
throw new WriteException("");
}
selTargetFile = setWritingTarget();
String str = userTermsTextArea.getText();
EvaluateText etx = new EvaluateText(str, mode, lang);
try {
etx.eTextToolBox(selFile, lang);
Writeinfile WordPlace = new Writeinfile(selTargetFile, field_topic.getText(), mode, lang);
WordPlace.storeAllItems(etx.GetWordsList());
WordPlace.finishWriting();
fileType = "";
setSupplMessage(
Integer.toString(etx.GetNumberOfWords()) + lang.getLocalizedText("wordscounted"),
tc.getDuration());
} catch (IOException exc) {
setSupplWarning(lang.getLocalizedText("FileNotRead"));
} catch (WriteException wfe) {
setSupplWarning(wfe.getMessage());
System.out.println(wfe.getCause());
} catch (Exception exc) {
setSupplWarning(lang.getLocalizedText("Internal error"));
}
}
catch (WriteException wfe) {
if (wfe.getMessage() != "") {
setSupplWarning(wfe.getMessage());
System.out.println(wfe.getCause());
}
} catch (Exception exc) {
System.out.println("Some UI or other exception." + exc.getCause() + exc.toString());
} finally {
mainFrame.revalidate();
}
}
});
closeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
mainFrame.dispose();
}
});
closeButton.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent event) {
if (event.getKeyChar() == KeyEvent.VK_ENTER) {
mainFrame.dispose();
}
}
});
clearButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
userTermsTextArea.setText("");
}
});
clearButton.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyChar() == KeyEvent.VK_ENTER) {
userTermsTextArea.setText("");
}
}
});
}
private void processFile() {
workingFolder = "" + fileDialog.getDirectory();
selFile = workingFolder + fileDialog.getFile();
field_status.setText("..." + workingFolder);
field_fileToAnalyze.setText(fileDialog.getFile());
field_supplinfo.setText("");
fileType = "";
for (String str : ALLOWED_INPUT_FILES) {
if (selFile.endsWith(str)) {
fileType = str;
break;
}
}
String str = field_fileToAnalyze.getText();
if (str.lastIndexOf('.') > 0)
str = str.substring(0, str.lastIndexOf('.'));
field_targetFile.setText(str);
field_topic.setText(str);
}
}
class ImagePanel extends JPanel {
/**
*
*/
private static final long serialVersionUID = -617389724139894161L;
private Image image;
private boolean tile;
ImagePanel(Image image) {
this.image = image;
this.tile = false;
this.setSize(getWidth(), getHeight());
};
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (tile) {
int iw = image.getWidth(this);
int ih = image.getHeight(this);
if (iw > 0 && ih > 0) {
for (int x = 0; x < getWidth(); x += iw) {
for (int y = 0; y < getHeight(); y += ih) {
g.drawImage(image, x, y, iw, ih, this);
}
}
}
} else {
Image scaled = image.getScaledInstance(getWidth(), getHeight(), Image.SCALE_SMOOTH);
g.drawImage(scaled, 0, 0, this);
}
}
}
class JCBox extends JComboBox<String> {
/**
*
*/
private static final long serialVersionUID = 6742906931820220645L;
String rjs = "";
String defaultDescription = "";
public String[] choices;
public String getSelectedList() {
return rjs;
}
public JCBox(String defaultDescription, ReadJson jsonData) {
try {
this.defaultDescription = defaultDescription;
this.setFont(WFont.labelfont);
this.setLightWeightPopupEnabled(false);
choices = jsonData.getAll();
this.addItem(defaultDescription);
this.setSelectedItem(defaultDescription);
for (String s : choices) {
this.addItem(s);
}
} catch (Exception exc) {
this.setSelectedItem(exc.toString());
}
}
public void connect(UserDialog ud, JTextArea textarea, SearchWords jsonData) {
/// adding functionality
/// add listener
this.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
rjs = jsonData.getText(getSelectedItem().toString());
textarea.setText(rjs);
ud.mainFrame.revalidate();
}
}
});
}
public void connect(UserDialog ud, Localization lang) {
this.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
String foo = getSelectedItem().toString();
lang.switchTo(foo);
ud.addTextToButtons();
ud.mainFrame.revalidate();
}
}
});
}
}
|
package com.example.jackson;
public class MyJson {
private int intValue;
private String stringValue;
private double doubleValue;
public MyJson() {
}
public int getIntValue() {
return intValue;
}
public void setIntValue(int intValue) {
this.intValue = intValue;
}
public String getStringValue() {
return stringValue;
}
public void setStringValue(String stringValue) {
this.stringValue = stringValue;
}
public double getDoubleValue() {
return doubleValue;
}
public void setDoubleValue(double doubleValue) {
this.doubleValue = doubleValue;
}
}
|
package com.jeysin.TimeServer;
import com.sun.corba.se.internal.CosNaming.BootstrapServer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import java.net.InetSocketAddress;
/**
* @Author: Jeysin
* @Date: 2019/3/19 17:47
* @Desc:
*/
public class TimeServerImpl {
public static void server(int port) throws Exception{
EventLoopGroup group = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(group).channel(NioServerSocketChannel.class)
.localAddress(new InetSocketAddress(port))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new TimeEncode(), new TimeServerHandler());
}
});
ChannelFuture f = b.bind().sync();
f.channel().closeFuture().sync();
} finally {
group.shutdownGracefully().sync();
}
}
public static void main(String[] args) throws Exception{
TimeServerImpl.server(10001);
}
}
|
package com.jack.jkbase.entity;
import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
//@Entity
//@Table(name = "sys_Company",indexes = {@Index(name="sys_Company_idx1",columnList = "C_CName",unique = true)})
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("sys_company")
public class SysCompany implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "CompanyID", type = IdType.AUTO)
private int companyid;
@TableField("C_AreaId")
private int cAreaid;
@TableField("C_ChildCount")
private int cChildcount;
@TableField("C_CName")
private String cCname;
@TableField("C_Level")
private int cLevel;
@TableField("C_ParentID")
private int cParentid;
@TableField("C_ShowOrder")
private int cShoworder;
public static Map<String,String> getHeadMap(){
Map<String,String> map = new LinkedHashMap<String,String>();
map.put("cCname","部门名称");
map.put("cParentname","所属部门");
map.put("cLevel","部门级别");
map.put("cAreaName","所属行政区");
return map;
}
public int getCompanyid() {
return companyid;
}
public void setCompanyid(int companyid) {
this.companyid = companyid;
}
public String getcCname() {
return cCname;
}
public void setcCname(String cCname) {
this.cCname = cCname == null ? null : cCname.trim();
}
public int getcParentid() {
return cParentid;
}
public void setcParentid(int cParentid) {
this.cParentid = cParentid;
}
public int getcShoworder() {
return cShoworder;
}
public void setcShoworder(int cShoworder) {
this.cShoworder = cShoworder;
}
public int getcLevel() {
return cLevel;
}
public void setcLevel(int cLevel) {
this.cLevel = cLevel;
}
public int getcChildcount() {
return cChildcount;
}
public void setcChildcount(int cChildcount) {
this.cChildcount = cChildcount;
}
public int getcAreaid() {
return cAreaid;
}
public void setcAreaid(int cAreaid) {
this.cAreaid = cAreaid;
}
}
|
package pages;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
/**
* Page object class for LinkedInPasswordResetSubmitPage
*/
public class LinkedInPasswordResetSubmitPage extends BasePage{
/**
* Constructor of LinkedInPasswordResetSubmitPage class.
* @param browser - WebDriver instance from test.
*/
public LinkedInPasswordResetSubmitPage(WebDriver browser) {
this.browser = browser;
PageFactory.initElements(browser, this);
}
/**
* This method checks that required page was loaded
*/
public boolean isLoaded() {
return getCurrentPageTitle().contains("") && getCurrentUrl().contains("checkpoint/rp/request-password-reset-submit");
}
/**
* This method navigates to forgotPasswordlink from email and returns LinkedInSetNewPasswordPage
*/
public LinkedInSetNewPasswordPage navigateToLinkFromEmail() {
String messageSubject = "данное сообщение содержит ссылку для изменения пароля";
String messageTo = "mrentertheusername@gmail.com";
String messageFrom = "security-noreply@linkedin.com";
String message = gMailService.waitMessage(messageSubject, messageTo, messageFrom, 60);
System.out.println("Content: " + message);
String linkForPasswordChange = StringUtils.substringBetween("нажмите <a href=\\\"<a href="","">[text]</a>").replace("amp;","");
System.out.println("Content: " + linkForPasswordChange);
browser.get(linkForPasswordChange);
return new LinkedInSetNewPasswordPage(browser);
}
}
|
public enum State {
FISHING ("Fishing"),
SWITCHSPOT ("Switching fishing spot"),
DROPPING ("Dropping"),
ERROR ("[ERROR]: No State found");
private String message;
State(String message){
this.message = message;
}
public String toString(){
return message;
}
public static State getState(){
if(needToFish()){
return FISHING;
}else if(needToDrop()){
return DROPPING;
}else{
return ERROR;
}
}
private static boolean needToFish(){
return true;
}
private static boolean needToDrop(){
return true;
}
}
|
package model;
import ui.DeadAhead;
import java.awt.*;
import java.util.Random;
// represents a zombie enemy from the game
public class Zombie {
public static final Color COLOR = new Color(250, 0, 40);
public static final int SIZE_X = 16;
public static final int SIZE_Y = 16;
public static final int MAX_HEALTH = 20;
private float xc;
private float yc;
private float velX;
private float velY;
private Player player;
private int health;
Random rand = new Random();
// EFFECTS: creates a zombie object
public Zombie(Player player, int width, int height) {
this.player = player;
xc = rand.nextInt(width);
yc = rand.nextInt(height);
health = MAX_HEALTH;
}
// MODIFIES: this
// EFFECTS: moves zombie in direction of player
public void move() {
float diffX = xc - player.getX() - player.SIZE_X / 2;
float diffY = yc - player.getY() - player.SIZE_Y / 2;
float distance = (float) Math.sqrt(
((xc - player.getX()) * (xc - player.getX())) + ((yc - player.getY()) * (yc - player.getY())));
velX = (float) ((-1.0 / distance) * diffX);
velY = (float) ((-1.0 / distance) * diffY);
// if (yc <= 0 || yc >= game.HEIGHT - SIZE_Y) {
// velY *= -1;
// }
// if (xc <= 0 || xc >= game.WIDTH - SIZE_X) {
// velX *= -1;
// }
xc += velX;
yc += velY;
}
// getters and setters
public int getHealth() {
return health;
}
public float getX() {
return xc;
}
public float getY() {
return yc;
}
public void setX(float x) {
xc = x;
}
public void setY(float y) {
yc = y;
}
public void setHealth(int health) {
this.health = health;
}
}
|
package com.ece6133.model.tech.k6_n10;
import com.ece6133.model.arch.k6_n10.K6Arch;
import com.ece6133.model.timing.NetNode;
public class SubcktBuilder {
protected static SubcktBuilder instance;
static {
instance = new SubcktBuilder();
}
/**
* get singleton instance
* @return
*/
public static SubcktBuilder getInstance() {
return instance;
}
private boolean buildActive = false;
private Subckt subckt = null;
private K6Arch arch;
private SubcktBuilder() {}
/**
* clears an active build
*/
public void resetBuild() {
buildActive = false;
}
/**
* flag start of a new instance creation
* @param arch
*/
public void flagStartBuild(final K6Arch arch) {
this.arch = arch;
subckt = new Subckt();
buildActive = true;
}
/**
* checks if an instance is being built
* @return
*/
public boolean isBuildActive() {
return buildActive;
}
/**
* parses an appended line
* @param line
*/
public void appendDefLine(String line) {
int startIndex = 0;
String[] els = line.split(" ");
if (line.contains(".subckt")) {
if (!els[0].equalsIgnoreCase(".subckt")) {
throw new RuntimeException("invalid subckt header");
}
subckt.setTypeName(els[1]);
if (!arch.supportsSubckt(subckt.getName())) {
throw new RuntimeException("cannot build subckt for unsupported subckt type");
}
subckt.setBackingType(arch.getModelByName(subckt.getTypeName()));
startIndex = 2;
}
for (int i = startIndex; i < els.length; i++) {
if (els[1].equalsIgnoreCase("\\")) {
break;
}
String[] portBind = els[i].split("=");
String assignment = portBind[0];
String driver = portBind[1];
String port = assignment;
short index = -1;
if (assignment.contains("]")) {
String[] portComp = assignment.replaceAll("]", "").split("\\[");
port = portComp[0];
index = Short.parseShort(portComp[1]);
}
Port assn = new Port(port, index);
NetNode driverNode = new NetNode(driver);
PortAssn subcktPort = new PortAssn(assn, driverNode);
if (subckt.getBackingType().getInputPortNames().contains(assignment)) {
subckt.getInputs().add(subcktPort);
subckt.getInputDrivingNet().add(driverNode);
} else {
subckt.getOutputs().add(subcktPort);
subckt.getDrivenOutputNets().add(driverNode);
}
}
}
/**
* get the constructed instance
* @return
*/
public Subckt get() {
return subckt;
}
}
|
package com.dmp.beans;
import java.util.Date;
public class Evolution {
private int idEvolution;
private String observationEvolution;
private Date dateObservation;
public int getIdEvolution() {
return idEvolution;
}
public void setIdEvolution(int idEvolution) {
this.idEvolution = idEvolution;
}
public String getObservationEvolution() {
return observationEvolution;
}
public void setObservationEvolution(String observationEvolution) {
this.observationEvolution = observationEvolution;
}
public Date getDateObservation() {
return dateObservation;
}
public void setDateObservation(Date dateObservation) {
this.dateObservation = dateObservation;
}
}
|
import java.util.ArrayList;
public class Grades {
private ArrayList<Integer> grades;
private int failed;
public Grades() {
grades = new ArrayList<Integer>();
failed = 0;
}
public void addGrade(int score) {
if (score >= 0 && score <= 60) {
if (score >= 0 && score <= 29) {
grades.add(0);
failed++;
} else if (score >= 30 && score <= 34) {
grades.add(1);
} else if (score >= 35 && score <= 39) {
grades.add(2);
} else if (score >= 40 && score <= 44) {
grades.add(3);
} else if (score >= 45 && score <= 49) {
grades.add(4);
} else if (score >= 50 && score <= 60) {
grades.add(5);
}
}
}
public void printGrades() {
System.out.println("Grade distribution:");
for (int i = 5; i >= 0; i--) {
System.out.print(i + ": ");
for (int grade : grades) {
if (grade == i) {
System.out.print("*");
}
}
System.out.println("");
}
System.out.println("Acceptance percentage: " + String.format("%.2f", acceptance()));
}
private double acceptance() {
double accepted = grades.size() - failed;
accepted = 100.0 * (accepted / grades.size());
return accepted;
}
}
|
package inheritance;
public class Review {
private String body;
private String author;
private int stars;
private InterfaceOfReview ReviewInterface;
// Constructors
Review(String body, String author, int stars) {
this.body = body;
this.author = author;
this.stars = stars;
}
public String getBody() {
return this.body;
}
public String getAuthor() {
return this.author;
}
public int getStars() {
return this.stars;
}
void setReviewInterface(InterfaceOfReview ReviewInterface) {
this.ReviewInterface = ReviewInterface;
}
@Override
public String toString() {
return String.format(
"Author is %s with number of stars %s and he/she wrote: %s",
getAuthor(), getStars(), getBody()
);
}
}
|
import java.awt.*;
import javax.swing.*;
public class GraphicCalculator implements Runnable {
private JFrame frame;
private Calculator calculator;
@Override
public void run() {
frame = new JFrame("Calculator");
frame.setPreferredSize(new Dimension(400, 300));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
createComponents(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
private void createComponents(Container container) {
container.setLayout(new GridLayout(3, 1));
JTextField input = new JTextField("0");
JTextField output = new JTextField("0");
output.setEnabled(false);
calculator = new Calculator(input, output);
container.add(output);
container.add(input);
container.add(operationControls());
}
public JFrame getFrame() {
return frame;
}
public JPanel operationControls() {
JPanel panel = new JPanel(new GridLayout(1, 3));
JButton addButton = new JButton("+");
addButton.addActionListener(new ClickListener("+", calculator));
JButton subtrackButton = new JButton("-");
subtrackButton.addActionListener(new ClickListener("-", calculator));
JButton clearButton = new JButton("Z");
clearButton.addActionListener(new ClickListener("Z", calculator));
clearButton.setEnabled(false);
calculator.addButton(clearButton);
panel.add(addButton);
panel.add(subtrackButton);
panel.add(clearButton);
return panel;
}
}
|
package br.states;
import br.Game;
import java.awt.Graphics;
import java.awt.Font;
import java.awt.Color;
import java.awt.event.KeyEvent;
public class Menu implements State{
private String[] options = {"START", "EXIT"};
private Font font1, font2;
private int choice = 0;
@Override
public void init() {
font1 = new Font("SansSerif", Font.PLAIN, 60);
font2 = new Font("Dialog", Font.PLAIN, 36);
}
@Override
public void update() {
}
@Override
public void render(Graphics graphics) {
graphics.setColor(Color.DARK_GRAY);
graphics.fillRect(0, 0, Game.WIDTH, Game.HEIGHT);
graphics.setColor(Color.ORANGE);
graphics.setFont(font1);
String strTitle = "Tactical Game";
graphics.drawString(strTitle,
Game.WIDTH/2 - graphics.getFontMetrics().stringWidth(strTitle)/2,
Game.HEIGHT * 1/4);
// Options
graphics.setFont(font2);
for (int i = 0; i < options.length; i++) {
graphics.setColor(Color.YELLOW);
if (i == choice) {
graphics.setColor(Color.RED);
}
graphics.drawString(options[i],
Game.WIDTH/2 - graphics.getFontMetrics().stringWidth(options[i])/2,
Game.HEIGHT * 3/4 + graphics.getFontMetrics(font2).getHeight() * i);
}
}
@Override
public void KeyPressed(int key) {
// NOTHING
}
@Override
public void KeyReleased(int key) {
if (key == KeyEvent.VK_W) {
choice --;
if (choice < 0) {
choice = options.length - 1;
}
}
if (key == KeyEvent.VK_S) {
choice++;
if (choice > options.length - 1) {
choice = 0;
}
}
if (key == KeyEvent.VK_ENTER) {
Select();
}
}
private void Select() {
switch (choice) {
case 0:
//Manager.setState(Manager.LEVEL1);
break;
case 1:
break;
case 2:
System.exit(0);
break;
default:
break;
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.opensoft.model.entities;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author MLLERENA
*/
@Entity
@Table(name = "productos")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Productos.findAll", query = "SELECT p FROM Productos p"),
@NamedQuery(name = "Productos.findByCodigo", query = "SELECT p FROM Productos p WHERE p.codigo = :codigo"),
@NamedQuery(name = "Productos.findByProducto", query = "SELECT p FROM Productos p WHERE p.producto = :producto"),
@NamedQuery(name = "Productos.findByUsuarioIngreso", query = "SELECT p FROM Productos p WHERE p.usuarioIngreso = :usuarioIngreso"),
@NamedQuery(name = "Productos.findByUsuarioModificacion", query = "SELECT p FROM Productos p WHERE p.usuarioModificacion = :usuarioModificacion"),
@NamedQuery(name = "Productos.findByFechaIngreso", query = "SELECT p FROM Productos p WHERE p.fechaIngreso = :fechaIngreso"),
@NamedQuery(name = "Productos.findByFechaModificacion", query = "SELECT p FROM Productos p WHERE p.fechaModificacion = :fechaModificacion"),
@NamedQuery(name = "Productos.findByEstado", query = "SELECT p FROM Productos p WHERE p.estado = :estado")})
public class Productos implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "CODIGO")
private Long codigo;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 512)
@Column(name = "PRODUCTO")
private String producto;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 45)
@Column(name = "USUARIO_INGRESO")
private String usuarioIngreso;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 45)
@Column(name = "USUARIO_MODIFICACION")
private String usuarioModificacion;
@Basic(optional = false)
@NotNull
@Column(name = "FECHA_INGRESO")
@Temporal(TemporalType.TIMESTAMP)
private Date fechaIngreso;
@Basic(optional = false)
@NotNull
@Column(name = "FECHA_MODIFICACION")
@Temporal(TemporalType.TIMESTAMP)
private Date fechaModificacion;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 1)
@Column(name = "ESTADO")
private String estado;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "producto")
private List<JovenesEjemplares> jovenesEjemplaresList;
public Productos() {
}
public Productos(Long codigo) {
this.codigo = codigo;
}
public Productos(Long codigo, String producto, String usuarioIngreso, String usuarioModificacion, Date fechaIngreso, Date fechaModificacion, String estado) {
this.codigo = codigo;
this.producto = producto;
this.usuarioIngreso = usuarioIngreso;
this.usuarioModificacion = usuarioModificacion;
this.fechaIngreso = fechaIngreso;
this.fechaModificacion = fechaModificacion;
this.estado = estado;
}
public Long getCodigo() {
return codigo;
}
public void setCodigo(Long codigo) {
this.codigo = codigo;
}
public String getProducto() {
return producto;
}
public void setProducto(String producto) {
this.producto = producto;
}
public String getUsuarioIngreso() {
return usuarioIngreso;
}
public void setUsuarioIngreso(String usuarioIngreso) {
this.usuarioIngreso = usuarioIngreso;
}
public String getUsuarioModificacion() {
return usuarioModificacion;
}
public void setUsuarioModificacion(String usuarioModificacion) {
this.usuarioModificacion = usuarioModificacion;
}
public Date getFechaIngreso() {
return fechaIngreso;
}
public void setFechaIngreso(Date fechaIngreso) {
this.fechaIngreso = fechaIngreso;
}
public Date getFechaModificacion() {
return fechaModificacion;
}
public void setFechaModificacion(Date fechaModificacion) {
this.fechaModificacion = fechaModificacion;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
@XmlTransient
public List<JovenesEjemplares> getJovenesEjemplaresList() {
return jovenesEjemplaresList;
}
public void setJovenesEjemplaresList(List<JovenesEjemplares> jovenesEjemplaresList) {
this.jovenesEjemplaresList = jovenesEjemplaresList;
}
@Override
public int hashCode() {
int hash = 0;
hash += (codigo != null ? codigo.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Productos)) {
return false;
}
Productos other = (Productos) object;
if ((this.codigo == null && other.codigo != null) || (this.codigo != null && !this.codigo.equals(other.codigo))) {
return false;
}
return true;
}
@Override
public String toString() {
return "org.opensoft.model.entities.Productos[ codigo=" + codigo + " ]";
}
}
|
package org.rebioma.client.maps;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.maps.client.MapWidget;
import com.google.gwt.maps.client.base.LatLng;
import com.google.gwt.maps.client.controls.ControlPosition;
import com.google.gwt.maps.client.events.mousemove.MouseMoveMapEvent;
import com.google.gwt.maps.client.events.mousemove.MouseMoveMapHandler;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
/**
* Afficher le coordonnées de la souris sur le map
* @author Mikajy
*
*/
public class CoordinatesControl extends HorizontalPanel implements MouseMoveMapHandler {
private HTML latlongLabel = new HTML();
private Element element;
NumberFormat format1 = NumberFormat.getFormat( "00.00000000");
NumberFormat format2 = NumberFormat.getFormat("000.00000000");
public CoordinatesControl(MapWidget map, ControlPosition position) {
super();
// map.setControls(position, this);
element = addLatLong();
this.setLabel(map.getCenter());
map.getControls(ControlPosition.RIGHT_BOTTOM).push(element);
// map.getControls(ControlPosition.BOTTOM_RIGHT).insertAt(0, this.getElement());
// Window.alert(map.getControls(ControlPosition.RIGHT_BOTTOM).pop().getInnerText());
map.addMouseMoveHandler(this);
latlongLabel.setStyleName("coordinate_label");
// longitudeLabel.setStyleName("coordinate_label");
this.add(latlongLabel);
// this.add(longitudeLabel);
}
public static native com.google.gwt.user.client.Element addLatLong() /*-{
var controlDiv = document.createElement('div');
// var firstChild = document.createElement('button');
// firstChild.style.backgroundColor = '#fff';
// firstChild.style.border = 'none';
// firstChild.style.outline = 'none';
// firstChild.style.width = '28px';
// firstChild.style.height = '28px';
// firstChild.style.borderRadius = '2px';
// firstChild.style.boxShadow = '0 1px 4px rgba(0,0,0,0.3)';
// firstChild.style.cursor = 'pointer';
// firstChild.style.marginRight = '10px';
// firstChild.style.padding = '0';
// firstChild.title = 'Your Location';
// controlDiv.appendChild(firstChild);
//
// var secondChild = document.createElement('div');
// secondChild.style.margin = '5px';
// secondChild.style.width = '18px';
// secondChild.style.height = '18px';
// secondChild.style.backgroundImage = 'url(https://maps.gstatic.com/tactile/mylocation/mylocation-sprite-2x.png)';
// secondChild.style.backgroundSize = '180px 18px';
// secondChild.style.backgroundPosition = '0 0';
// secondChild.style.backgroundRepeat = 'no-repeat';
// firstChild.appendChild(secondChild);
controlDiv.index = 0;
return controlDiv;
// map.controls[google.maps.ControlPosition.BOTTOM_RIGHT].push(controlDiv);
}-*/;
public CoordinatesControl(MapWidget map) {
this(map, ControlPosition.RIGHT_BOTTOM);
}
@Override
public void onEvent(MouseMoveMapEvent evt) {
LatLng coord = evt.getMouseEvent().getLatLng();
this.setLabel(coord);
}
private void setLabel(LatLng coord){
element.setInnerHTML("<div class='coordinate_label'>" + format1.format(coord.getLatitude()) + ", " + format2.format(coord.getLongitude()) + "</div>");
}
}
|
class ExceptionDemo {
public static void main(String[] args) {
/*
for(int x=3, int y=0; x>y;x--, y++){
}
*/
}
}
|
package lucky_stats.analyzer;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class Parser {
int[] distribution;
double[] result;
int counter;
String saveTo ="Users/KB/JAVA_Development/";
private static final int BUFFER_SIZE = 4096;
private String date;
public Parser() throws FileNotFoundException{
distribution = new int[50];
try {
download();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
unzipfile();
reader();
}
public void download() throws IOException{
URL website = new URL("http://www.bclc.com/documents/DownloadableNumbers/CSV/LOTTOMAX.zip");
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream("/Users/KB/JAVA_Developement/LOTTOMAX.zip");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
}
public void unzipfile(){
List<String> fileList;
String inputZip = "/Users/KB/JAVA_Developement/LOTTOMAX.zip";
String outputDir = "/Users/KB/JAVA_Developement/";
byte[] buffer = new byte[1024];
ZipInputStream zis;
try {
zis = new ZipInputStream(new FileInputStream(inputZip));
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
String filePath = outputDir + File.separator + ze.getName();
if (!ze.isDirectory()) {
try {
extractFile(zis, filePath);
} catch (IOException e) {
e.printStackTrace();
}
} else {
File dir = new File(filePath);
dir.mkdir();
}
zis.closeEntry();
ze = zis.getNextEntry();
}
zis.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
byte[] bytesIn = new byte[BUFFER_SIZE];
int read = 0;
while ((read = zipIn.read(bytesIn)) != -1) {
bos.write(bytesIn, 0, read);
}
bos.close();
}
public void reader() throws FileNotFoundException {
String file = "/Users/KB/JAVA_Developement/LOTTOMAX.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
String n1;
int nb1;
try {
counter = 0;
br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] draws = line.split(cvsSplitBy);
if(draws[0].contains("PRODUCT")){
continue;
} else{
countDate(draws[3]);
preAnalyze(draws[4]);
preAnalyze(draws[5]);
preAnalyze(draws[6]);
preAnalyze(draws[7]);
preAnalyze(draws[8]);
preAnalyze(draws[9]);
preAnalyze(draws[10]);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void preAnalyze(String numb) {
String n;
int nb1;
n = numb;
nb1 = Integer.parseInt(n);
counter++;
distribution[nb1]++;
// System.out.println(nb1);
}
public double[] analyze(){
double prob;
double sumup;
sumup = 0;
result = new double[50];
for(int i = 0; i<= 49; i++){
double a = (double) distribution[i];
double b = (double) counter;
prob = a/b * 100;
result[i] = prob;
System.out.println(result[i]);
}
return result;
}
public void countDate(String update){
this.date = update;
}
public String recentDate(){
return date;
}
}
|
package tkhub.project.kesbewa;
public class BR {
public static final int ResetBindingView = 1;
public static final int _all = 0;
public static final int addresItem = 2;
public static final int addressviewmodel = 3;
public static final int cart_details = 4;
public static final int cartitem = 5;
public static final int checkout = 6;
public static final int clickListener = 7;
public static final int item = 8;
public static final int loginBindingView = 9;
public static final int mapBindingView = 10;
public static final int orderitem = 11;
public static final int orderitems = 12;
public static final int pastorderitems = 13;
public static final int product = 14;
public static final int product_details = 15;
public static final int productdetailsbottomsheet = 16;
public static final int products = 17;
public static final int profile_view_model = 18;
public static final int promo_binding_view = 19;
public static final int scrollChangeListener = 20;
public static final int singupBindingView = 21;
public static final int singup_google_binding_view = 22;
public static final int user = 23;
public static final int viewmodelqtydialog = 24;
}
|
package com.ss.lms.dao;
import java.sql.Connection;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import com.ss.lms.entity.Book;
import com.ss.lms.entity.BookLoan;
import com.ss.lms.entity.Borrower;
import com.ss.lms.entity.LibraryBranch;
public class BookLoanDAO extends BaseDAO<BookLoan> {
public BookLoanDAO(Connection connection) {
super(connection);
}
public void create(BookLoan bookLoan) throws ClassNotFoundException, SQLException {
save("insert into tbl_book_loans (bookId, branchId, cardNo, dateOut, dueDate) values(?, ?, ?, ?, ?)",
new Object[] { bookLoan.getBook().getId(), bookLoan.getLibraryBranch().getId(),
bookLoan.getBorrower().getCardNumber(), Date.valueOf(LocalDate.now()),
Date.valueOf(LocalDate.now().plusWeeks(1)) });
}
public void update(BookLoan bookLoan) throws ClassNotFoundException, SQLException {
save("update tbl_book_loans set dateIn = ? where bookId = ? and branchId = ? and cardNo = ?",
new Object[] { Date.valueOf(bookLoan.getDateIn()), bookLoan.getBook().getId(),
bookLoan.getLibraryBranch().getId(), bookLoan.getBorrower().getCardNumber() });
}
public void delete(Integer bookId, Integer libraryBranchId, Integer cardNumber)
throws ClassNotFoundException, SQLException {
save("delete from tbl_book_loans where bookId = ? and branchId = ? and cardNo = ?",
new Object[] { bookId, libraryBranchId, cardNumber });
}
public void deleteByBookId(Integer bookId) throws ClassNotFoundException, SQLException {
save("delete from tbl_book_loans where bookId = ?", new Object[] { bookId });
}
public void deleteByLibraryBranchId(Integer libraryBranchId) throws ClassNotFoundException, SQLException {
save("delete from tbl_book_loans where branchId = ?", new Object[] { libraryBranchId });
}
public void deleteByCardNumber(Integer cardNumber) throws ClassNotFoundException, SQLException {
save("delete from tbl_book_loans where cardNo = ?", new Object[] { cardNumber });
}
public List<BookLoan> readAll() throws ClassNotFoundException, SQLException {
return read("select * from tbl_book_loans", null);
}
@Override
protected List<BookLoan> extractData(ResultSet rs) throws ClassNotFoundException, SQLException {
List<BookLoan> bookLoans = new ArrayList<BookLoan>();
BookDAO bookDao = new BookDAO(connection);
LibraryBranchDAO libraryBranchDao = new LibraryBranchDAO(connection);
BorrowerDAO borrowerDao = new BorrowerDAO(connection);
while (rs.next()) {
BookLoan bookLoan = new BookLoan();
bookLoan.setBook(bookDao.readOneFirstLevel(rs.getInt("bookId")));
bookLoan.setLibraryBranch(libraryBranchDao.readOneFirstLevel(rs.getInt("branchId")));
bookLoan.setBorrower(borrowerDao.readOneFirstLevel(rs.getInt("cardNo")));
bookLoan.setDateOut(rs.getDate("dateOut").toLocalDate());
bookLoan.setDueDate(rs.getDate("dueDate").toLocalDate());
bookLoan.setDateIn(rs.getDate("dateIn").toLocalDate());
bookLoans.add(bookLoan);
}
return bookLoans;
}
@Override
protected List<BookLoan> extractDataFirstLevel(ResultSet rs) throws SQLException {
List<BookLoan> bookLoans = new ArrayList<BookLoan>();
while (rs.next()) {
BookLoan bookLoan = new BookLoan();
Book book = new Book();
book.setId(rs.getInt("bookId"));
bookLoan.setBook(book);
LibraryBranch libraryBranch = new LibraryBranch();
libraryBranch.setId(rs.getInt("branchId"));
bookLoan.setLibraryBranch(libraryBranch);
Borrower borrower = new Borrower();
borrower.setCardNumber(rs.getInt("cardNo"));
bookLoan.setBorrower(borrower);
bookLoan.setDateOut(rs.getDate("dateOut").toLocalDate());
bookLoan.setDueDate(rs.getDate("dueDate").toLocalDate());
bookLoan.setDateIn(rs.getDate("dateIn").toLocalDate());
bookLoans.add(bookLoan);
}
return bookLoans;
}
}
|
package igu;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Point;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import javax.swing.SwingConstants;
import java.awt.Font;
import java.awt.Color;
import javax.swing.border.TitledBorder;
import javax.swing.DefaultListModel;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.border.LineBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.SpinnerNumberModel;
import logica.Inmobiliaria;
import logica.Mansion;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JCheckBox;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
import org.jvnet.substance.SubstanceLookAndFeel;
public class VentanaPrincipal extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JLabel lblNewLabel;
private JLabel lblNewLabel_1;
private JPanel panel;
private JPanel panel_1;
private JButton btnAadirVisita;
private JButton btnEliminarVisita;
private JPanel panel_2;
private JPanel panel_3;
private JScrollPane scrollPane;
private JLabel lblDescription;
private JScrollPane scrollPane_1;
private JList list;
private JPanel panel_4;
private JSpinner spinnerPercentage;
private JButton btnClacular;
private JLabel lblResultado;
private JPanel panel_5;
private JButton btnAceptar;
private JButton btnCancelar;
private Inmobiliaria inmobiliaria= new Inmobiliaria();
private JTabbedPane tpMansiones;
private JPanel pnVentas;
private JPanel pnAlquileres;
private JScrollPane scVentas;
private JTable tVentas;
private ModeloNoEditable modeloTable;
private DefaultListModel modeloLista;
private JPanel pnFiltro;
private JCheckBox checkNorte;
private JCheckBox checkCentro;
private JCheckBox checkSur;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
SubstanceLookAndFeel.setSkin("org.jvnet.substance.skin.MistSilverSkin");
VentanaPrincipal frame = new VentanaPrincipal();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public VentanaPrincipal() {
setIconImage(Toolkit.getDefaultToolkit().getImage(VentanaPrincipal.class.getResource("/img/llave.JPG")));
setTitle("Agencia Inmoviliaria");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 850, 630);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
contentPane.add(getLblNewLabel());
contentPane.add(getLblNewLabel_1());
contentPane.add(getPanel());
contentPane.add(getPanel_3());
contentPane.add(getPanel_4());
contentPane.add(getPanel_5());
contentPane.add(getTpMansiones());
addRows(checkNorte.isSelected(), checkCentro.isSelected(), checkSur.isSelected());
}
private void mostrarMansionesZona() {
modeloTable.getDataVector().clear();
modeloTable.fireTableDataChanged();
addRows(checkNorte.isSelected(), checkCentro.isSelected(), checkSur.isSelected());
}
private JLabel getLblNewLabel() {
if (lblNewLabel == null) {
lblNewLabel = new JLabel("AGENCIA INMOVILIARIA EII");
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setForeground(Color.ORANGE);
lblNewLabel.setFont(new Font("OCR A Extended", Font.BOLD, 30));
lblNewLabel.setBounds(23, 11, 495, 94);
}
return lblNewLabel;
}
private JLabel getLblNewLabel_1() {
if (lblNewLabel_1 == null) {
lblNewLabel_1 = new JLabel("");
lblNewLabel_1.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel_1.setIcon(new ImageIcon(VentanaPrincipal.class.getResource("/img/llave.JPG")));
lblNewLabel_1.setBounds(690, 11, 114, 94);
}
return lblNewLabel_1;
}
private JPanel getPanel() {
if (panel == null) {
panel = new JPanel();
panel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Mansiones a Visitar", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
panel.setBounds(592, 159, 212, 262);
panel.setLayout(new BorderLayout(0, 0));
panel.add(getPanel_1(), BorderLayout.SOUTH);
panel.add(getPanel_2(), BorderLayout.CENTER);
}
return panel;
}
private JPanel getPanel_1() {
if (panel_1 == null) {
panel_1 = new JPanel();
panel_1.setLayout(new GridLayout(0, 2, 0, 0));
panel_1.add(getBtnAadirVisita());
panel_1.add(getBtnEliminarVisita());
}
return panel_1;
}
private JButton getBtnAadirVisita() {
if (btnAadirVisita == null) {
btnAadirVisita = new JButton("A\u00F1adir");
btnAadirVisita.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
int fila = tVentas.getSelectedRow();
if(fila != -1) {
modeloLista.addElement(tVentas.getValueAt(fila, 0));
}
}
});
}
return btnAadirVisita;
}
private JButton getBtnEliminarVisita() {
if (btnEliminarVisita == null) {
btnEliminarVisita = new JButton("Eliminar");
btnEliminarVisita.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(list.getSelectedIndex() != -1)
modeloLista.remove(list.getSelectedIndex());
}
});
}
return btnEliminarVisita;
}
private JPanel getPanel_2() {
if (panel_2 == null) {
panel_2 = new JPanel();
panel_2.setLayout(new BorderLayout(0, 0));
panel_2.add(getScrollPane_1(), BorderLayout.CENTER);
}
return panel_2;
}
private JPanel getPanel_3() {
if (panel_3 == null) {
panel_3 = new JPanel();
panel_3.setBackground(Color.WHITE);
panel_3.setBounds(23, 411, 559, 170);
panel_3.setLayout(new BorderLayout(0, 0));
panel_3.add(getScrollPane(), BorderLayout.CENTER);
}
return panel_3;
}
private JScrollPane getScrollPane() {
if (scrollPane == null) {
scrollPane = new JScrollPane();
scrollPane.setViewportView(getLblDescription());
}
return scrollPane;
}
private JLabel getLblDescription() {
if (lblDescription == null) {
lblDescription = new JLabel("");
lblDescription.setBackground(Color.WHITE);
lblDescription.setForeground(Color.BLACK);
lblDescription.setVerticalAlignment(SwingConstants.TOP);
}
return lblDescription;
}
private JScrollPane getScrollPane_1() {
if (scrollPane_1 == null) {
scrollPane_1 = new JScrollPane();
scrollPane_1.setViewportView(getList());
}
return scrollPane_1;
}
private JList getList() {
if (list == null) {
modeloLista = new DefaultListModel();
list = new JList(modeloLista);
}
return list;
}
private JPanel getPanel_4() {
if (panel_4 == null) {
panel_4 = new JPanel();
panel_4.setBorder(new TitledBorder(null, "Entrada a Pagar", TitledBorder.LEADING, TitledBorder.TOP, null, null));
panel_4.setBounds(592, 441, 208, 94);
panel_4.setLayout(null);
panel_4.add(getSpinnerPercentage());
panel_4.add(getBtnClacular());
panel_4.add(getLblResultado());
}
return panel_4;
}
private JSpinner getSpinnerPercentage() {
if (spinnerPercentage == null) {
spinnerPercentage = new JSpinner();
spinnerPercentage.setModel(new SpinnerNumberModel(15, 0, 20, 1));
spinnerPercentage.setBounds(10, 21, 53, 30);
}
return spinnerPercentage;
}
private JButton getBtnClacular() {
if (btnClacular == null) {
btnClacular = new JButton("Clacular");
btnClacular.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int fila = tVentas.getSelectedRow();
if(fila != -1) {
float entrada = (inmobiliaria.calcularEntrada((Integer) spinnerPercentage.getValue(), (Float) tVentas.getValueAt(fila, 3)));
lblResultado.setText(entrada +" $");
}
}
});
btnClacular.setBounds(91, 25, 89, 23);
}
return btnClacular;
}
private JLabel getLblResultado() {
if (lblResultado == null) {
lblResultado = new JLabel("");
lblResultado.setBorder(new LineBorder(new Color(0, 0, 0)));
lblResultado.setBounds(10, 62, 188, 21);
}
return lblResultado;
}
private JPanel getPanel_5() {
if (panel_5 == null) {
panel_5 = new JPanel();
panel_5.setBounds(592, 541, 208, 40);
panel_5.setLayout(new GridLayout(1, 0, 0, 0));
panel_5.add(getBtnAceptar());
panel_5.add(getBtnCancelar());
}
return panel_5;
}
private JButton getBtnAceptar() {
if (btnAceptar == null) {
btnAceptar = new JButton("Aceptar");
btnAceptar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
grabarFichero();
}
});
}
return btnAceptar;
}
private JButton getBtnCancelar() {
if (btnCancelar == null) {
btnCancelar = new JButton("Cancelar");
btnCancelar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
inicializar();
}
});
}
return btnCancelar;
}
private JTabbedPane getTpMansiones() {
if (tpMansiones == null) {
tpMansiones = new JTabbedPane(JTabbedPane.TOP);
tpMansiones.setBounds(23, 97, 559, 303);
tpMansiones.addTab("Mansiones en Venta", null, getPnVentas(), null);
tpMansiones.addTab("Me cago en tu puta madre muerta", null, getPnAlquileres(), null);
}
return tpMansiones;
}
private JPanel getPnVentas() {
if (pnVentas == null) {
pnVentas = new JPanel();
pnVentas.setLayout(new BorderLayout(0, 0));
pnVentas.add(getScVentas(), BorderLayout.CENTER);
pnVentas.add(getPnFiltro(), BorderLayout.NORTH);
}
return pnVentas;
}
private JPanel getPnAlquileres() {
if (pnAlquileres == null) {
pnAlquileres = new JPanel();
}
return pnAlquileres;
}
private JScrollPane getScVentas() {
if (scVentas == null) {
scVentas = new JScrollPane();
scVentas.setViewportView(getTVentas());
}
return scVentas;
}
private JTable getTVentas() {
if (tVentas == null) {
String[] nombreColumnas = {"Código", "Zona", "Localidad", "Precio"};
modeloTable = new ModeloNoEditable(nombreColumnas, 0);
tVentas = new JTable(modeloTable);
tVentas.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
if(arg0.getClickCount() == 2) {
int fila = tVentas.getSelectedRow();
if(fila != -1) {
modeloLista.addElement(tVentas.getValueAt(fila, 0));
}
}
lblDescription.setText(inmobiliaria.getDescripcionMansion(tVentas.getSelectedRow()));
}
});
tVentas.setDefaultRenderer(Object.class, ((TableCellRenderer) new RendererSubstance()));
tVentas.getTableHeader().setReorderingAllowed(false);
tVentas.getTableHeader().setResizingAllowed(false);
}
return tVentas;
}
private void addRows(boolean norte, boolean centro, boolean sur) {
Object[] nuevaFila = new Object[4];
for(Mansion m : inmobiliaria.getRelacionMansiones()) {
if((norte && m.getZona().equals("Norte")) || ( sur && m.getZona().equals("Sur")) || (centro && m.getZona().equals("Centro")) || (!norte&&!sur&&!centro)) {
nuevaFila[0] = m.getCodigo();
nuevaFila[1] = m.getZona();
nuevaFila[2] = m.getLocalidad();
nuevaFila[3] = m.getPrecio();
modeloTable.addRow(nuevaFila);
}
}
}
private void inicializar() {
tpMansiones.setSelectedIndex(0);
tVentas.clearSelection();
modeloLista.clear();
spinnerPercentage.setValue(15);
lblResultado.setText("");
lblDescription.setText("");
scVentas.getViewport().setViewPosition(new Point(0,0));
}
private void grabarFichero() {
StringBuilder sb = new StringBuilder();
for(Object o : modeloLista.toArray()) {
sb.append(o.toString());
sb.append(" ");
}
if(inmobiliaria.grabarFichero(sb.toString()) == 0) {
JOptionPane.showMessageDialog(this, "Su petición me la suda capullo de mierda!");
inicializar();
}
}
private JPanel getPnFiltro() {
if (pnFiltro == null) {
pnFiltro = new JPanel();
pnFiltro.add(getCheckNorte());
pnFiltro.add(getCheckCentro());
pnFiltro.add(getCheckSur());
}
return pnFiltro;
}
private JCheckBox getCheckNorte() {
if (checkNorte == null) {
checkNorte = new JCheckBox("Norte");
checkNorte.setSelected(false);
checkNorte.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
mostrarMansionesZona();
}
});
}
return checkNorte;
}
private JCheckBox getCheckCentro() {
if (checkCentro == null) {
checkCentro = new JCheckBox("Centro");
checkCentro.setSelected(false);
checkCentro.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
mostrarMansionesZona();
}
});
}
return checkCentro;
}
private JCheckBox getCheckSur() {
if (checkSur == null) {
checkSur = new JCheckBox("Sur");
checkSur.setSelected(false);
checkSur.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent arg0) {
mostrarMansionesZona();
}
});
}
return checkSur;
}
}
|
package com.storybox.culturemapg;
import org.json.JSONObject;
/**
* Created by sunghee on 2016-10-24.
*/
public class Manager {
public int id;
public String name, contact, email, managing_place_ids_string, managing_place_names_string;
public String[] managing_place_ids, managing_place_names;
public Manager(JSONObject object) {
try{
id = object.getInt("id");
name = object.getString("name");
contact = object.getString("contact");
email = object.getString("email");
managing_place_ids_string = object.getString("managing_place_ids");
managing_place_names_string = object.getString("managing_place_names");
managing_place_ids = managing_place_ids_string.split(",");
managing_place_names = managing_place_names_string.split(",");
}catch(Exception e){
}
}
}
|
package com.service.leave.domain;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
@Table(name="EMPLOYEE_FAMILY_DETAILS")
public class EmployeeFamilyDetails implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID",length = 5)
private long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "EMP_ID")
private Employee employee;
@Column(name = "NAME", length = 40)
private String name;
@Column(name = "RELATION", length = 40)
private String relation;
@Column(name = "BIRTH_DATE")
@Temporal(value=TemporalType.DATE)
private Date birthDate;
@Column(name="CONTACT_NO", length = 10)
private String contactNo;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRelation() {
return relation;
}
public void setRelation(String relation) {
this.relation = relation;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public String getContactNo() {
return contactNo;
}
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
}
|
package com.m3.training.inventoryproject;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
public class ItemDAOImpl implements ItemDAO {
private static final String TABLE_NAME = "AJ216";
private String dname;
private String url;
private String user;
private String pass;
public ItemDAOImpl () throws IOException, ClassNotFoundException {
Path path = Paths.get("res", "connection.prop");
FileInputStream file = new FileInputStream(path.toString());
Properties p = new Properties();
p.load(file);
dname = (String) p.get("databaseName");
url = (String) p.get("URL");
user = (String) p.get("user");
pass = (String) p.get("pass");
Class.forName(dname);
//System.out.println(Class.forName(dname));
}
@Override
public boolean insertItem(Item item) throws StatementException, ItemAlreadyExistsException {
//if(item.getID() = getItem())
Connection connection = ConnectionFactory.getConnection(url, user, pass);
Statement stmt;
int result = 0;
try {
stmt = connection.createStatement();
result = stmt.executeUpdate("SELECT ID FROM "+ TABLE_NAME +" WHERE "
+ "ITEM_NAME LIKE '%"+item.getItemName()+"%'");
if(result > 0) throw new ItemAlreadyExistsException("Item " + item.getItemName() + " already exists!");
stmt = connection.createStatement();
result = stmt.executeUpdate("insert into " + TABLE_NAME + " (ITEM_NAME, QTY) " + "values ('"
+ item.getItemName() + "', " + item.getQuantity() + ")");
} catch (SQLException e) {
throw new StatementException("Error while trying to create a "
+ "statement with existing connection.", e);
} catch (NullPointerException e) {
throw new NullItemException("Error trying to access the fields "
+ "Item.itemName and Item.quantity of Null Item", e);
}
if (result == 1)
return true;
return false;
}
@Override
public Item getItem(String itemName) throws StatementException, ItemDoesNotExistException {
if(itemName == null) throw new NullItemException("Error: trying to retrieve item "
+ "with null value.");
Connection connection = ConnectionFactory.getConnection(url, user, pass);
Item item;// = null;
Statement stmt;
try {
stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM " + TABLE_NAME + " where ITEM_NAME = '" + itemName + "'");
if (rs.next()) {
item = new Item();
item.setID(rs.getInt("ID"));
item.setItemName(rs.getString("ITEM_NAME"));
item.setQuantity(rs.getInt("QTY"));
return item;
}
else throw new ItemDoesNotExistException("Item "+ itemName
+ " does not exist and cannot be retrieved.");
} catch (SQLException e) {
throw new StatementException("Error while trying to create a "
+ "statement with existing connection.", e);
}
//return item;
}
@Override
public Item getItemById(int id) throws StatementException, ItemDoesNotExistException {
Connection connection = ConnectionFactory.getConnection(url, user, pass);
Item item = null;
Statement stmt;
try {
stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM " + TABLE_NAME + " where ID = " + id);
if (rs.next()) {
item = new Item();
item.setID(rs.getInt("ID"));
item.setItemName(rs.getString("ITEM_NAME"));
item.setQuantity(rs.getInt("QTY"));
return item;
}
else throw new ItemDoesNotExistException("Item "+ id
+ " does not exist and cannot be retrieved.");
} catch (SQLException e) {
throw new StatementException("Error while trying to create a "
+ "statement with existing connection.", e);
}
// return null;
}
@Override
public Set<Item> getAllItems() throws StatementException {
Connection connection = ConnectionFactory.getConnection(url, user, pass);
Statement stmt;
try {
stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM " + TABLE_NAME);
Set<Item> allItems = new HashSet<Item>();
while (rs.next()) {
Item item = new Item();
item.setID(rs.getInt("ID"));
item.setItemName(rs.getString("ITEM_NAME"));
item.setQuantity(rs.getInt("QTY"));
allItems.add(item);
}
return allItems;
} catch (SQLException e) {
throw new StatementException("Error while trying to create a "
+ "statement with existing connection.", e);
}
}
@Override
public boolean buyItem(String itemName, int purchaseQty) throws ItemDoesNotExistException, BackorderLimitExceededException, StatementException {
Item item = getItem(itemName);
int currentItemQty = item.getQuantity();
int qtyAfterPurchase = currentItemQty - purchaseQty;
return updateItem(item, qtyAfterPurchase);
}
@Override
public boolean returnItem(String itemName, int purchaseQty) throws ItemDoesNotExistException, BackorderLimitExceededException, StatementException {
Item item = getItem(itemName);
int currentItemQty = item.getQuantity();
int qtyAfterReturn = currentItemQty + purchaseQty;
return updateItem(item, qtyAfterReturn);
}
@Override
public boolean updateItem(Item item, int updatedQty) throws StatementException, BackorderLimitExceededException {
int rowsAffected = 0;
if (updatedQty >= -20) {
Connection connection = ConnectionFactory.getConnection(url, user, pass);
PreparedStatement ps;
try {
ps = connection.prepareStatement("UPDATE " + TABLE_NAME + " SET QTY=? WHERE ITEM_Name=?");
ps.setInt(1, updatedQty);
ps.setString(2, item.getItemName());
rowsAffected = ps.executeUpdate();
} catch (SQLException e) {
throw new StatementException("Error while trying to create a "
+ "statement with existing connection.", e);
}
if (rowsAffected == 1) {
//System.out.println("Quantity after Purchase: " + updatedQty);
return true;
}
else return false;
} else {
throw new BackorderLimitExceededException("The updated quantity of "
+ item.getItemName() +" falls below the backorder limit. Order cannot be completed.");
}
}
@Override
public Item deleteItem(String itemName) throws ItemDoesNotExistException, StatementException{
if(itemName == null) throw new NullItemException("Error: trying to delete item "
+ "with null value.");
Connection connection = ConnectionFactory.getConnection(url, user, pass);
Item item = getItem(itemName);
Statement stmt;
int sqlResult = 0;
try {
stmt = connection.createStatement();
sqlResult = stmt.executeUpdate("DELETE FROM " + TABLE_NAME + " WHERE ITEM_NAME = '" + itemName + "'");
} catch (SQLException e) {
throw new StatementException("Error while trying to create a "
+ "statement with existing connection.", e);
}
if (sqlResult == 1) {
return item;
}
else return null;
}
@Override
public Item deleteItemById(int id) throws ItemDoesNotExistException, StatementException {
Connection connection = ConnectionFactory.getConnection(url, user, pass);
Item item = getItemById(id);
Statement stmt;
int sqlResult = 0;
try {
stmt = connection.createStatement();
sqlResult = stmt.executeUpdate("DELETE FROM " + TABLE_NAME + " WHERE ID = " + id);
} catch (SQLException e) {
throw new StatementException("Error while trying to create a "
+ "statement with existing connection.", e);
}
if (sqlResult == 1) {
return item;
}
else return null;
}
public static void main(String[] args) throws SQLException, StatementException, ItemAlreadyExistsException, ItemDoesNotExistException, ClassNotFoundException, IOException {
ItemDAOImpl i = new ItemDAOImpl();
Item item = new Item("BANKBANKcat", 999);
i.insertItem(item);
}
}
//
|
package com.tencent.mm.pluginsdk.ui.tools;
import android.graphics.Bitmap;
import com.tencent.mm.pluginsdk.ui.tools.g.c;
class g$4 extends c<String, Bitmap> {
final /* synthetic */ g qSF;
g$4(g gVar) {
this.qSF = gVar;
super(gVar, 1);
}
protected final /* bridge */ /* synthetic */ void ca(Object obj) {
}
}
|
package exceptions;
public class ChecksumMismatchException extends Exception {}
|
public class TestVar08
{
public static void main(String[] args)
{
char ch1 = 'A';
System.out.println(ch1+90);
System.out.println(155-ch1);
//char类型我们看到的样子就是它本身的字面常量,但是底层在进行计算的时候,实际上是按照ASCII码执行的
//char类型是unicode码表进行存储的(Unicode兼容ASCII码,Unicode的前128位置ASCII)
char ch2 = '中';
System.out.println(ch2);
System.out.println(ch2+90);
System.out.println(20103-ch2);
int num1 = (int)ch2;
System.out.println(num1);
char ch6 = '2'+2;
System.out.println(ch6);
}
}
|
package com.jd.validator.example;
import lombok.Data;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
* @author: wangyingjie1
* @version: 1.0
* @createdate: 2017-12-04 14:45
*/
@Data
public class Car {
@NotNull
private String manufacturer;
@NotNull
@Size(min = 2, max = 14)
private String licensePlate;
@Min(2)
private int seatCount;
public Car() {
}
public Car(String manufacturer, String licencePlate, int seatCount) {
this.manufacturer = manufacturer;
this.licensePlate = licencePlate;
this.seatCount = seatCount;
}
}
|
package Main.Java;
public class Main {
public static void main(String[] args) throws CloneNotSupportedException {
Engine engine = new Engine(1499.99);
engine.setCC(1599.99);
ImmutableCar immutableCar = new ImmutableCar(engine, "Blue");
System.out.printf(immutableCar.toString());
engine.setCC(1899);
System.out.printf(immutableCar.toString());
}
}
|
package com.example.cs246.medtracker;
import android.content.Intent;
import android.database.Cursor;
import android.provider.CalendarContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Set;
import com.google.android.gms.common.api.GoogleApiClient;
public class MainScreen extends AppCompatActivity {
ListView pListView;
ListView aListView;
PrescriptionArrayAdapter prescriptionArrayAdapter;
ArrayList<Prescription> prescriptionList = new ArrayList<Prescription>();
MainController mc;
Button newPrescriptionButton;
Button scheduleButton;
Button editButton;
Button deleteButton;
Prescription selectedPrescription;
private GoogleApiClient client;
/*
* Initially create the activity_main_page.xml page, setting up
* the menu and other starting details
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
mc = new MainController(this);
linkControls();
}
@Override
protected void onResume() {
super.onResume();
mc.cleanPrescriptions();
populatePrescriptions();
}
private void linkControls() {
newPrescriptionButton = (Button) findViewById(R.id.newPrescriptionButton);
scheduleButton = (Button) findViewById(R.id.scheduleButton);
editButton = (Button) findViewById(R.id.editButton);
deleteButton = (Button) findViewById(R.id.deleteButton);
scheduleButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (selectedPrescription != null) {
mc.openSchedulePrescription(selectedPrescription);
}
}
});
editButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mc.openEditPrescription(selectedPrescription);
}
});
deleteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mc.deletePrescription(selectedPrescription);
populatePrescriptions();
}
});
}
public void openEditPrescription(View view) {
Prescription prescription = null;
mc.openEditPrescription(prescription);
}
private void populatePrescriptions() {
prescriptionList = mc.getPrescriptionList();
pListView = (ListView) findViewById(R.id.prescriptionsListView);
pListView.setItemsCanFocus(true);
if (prescriptionList != null && !prescriptionList.isEmpty()) {
prescriptionArrayAdapter = new PrescriptionArrayAdapter(MainScreen.this,
R.layout.main_prescription_layout, prescriptionList);
pListView.setAdapter(prescriptionArrayAdapter);
pListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedPrescription = (Prescription) pListView.getItemAtPosition(position);
view.setSelected(true);
}
});
}
else {
pListView.setAdapter(null);
selectedPrescription = null;
}
// populate alert list view here
// use an activity_main_screen for each alert
long begin = Calendar.getInstance().getTimeInMillis();
//one week
long end = begin + (7*24*60*60*1000);
aListView = (ListView) findViewById(R.id.alertsListView);
aListView.setItemsCanFocus(false);
//fire up the handlers
MyPrescriptionHandler db = new MyPrescriptionHandler(getApplicationContext(), "prescriptionDB.db", null, 7);
MyDoseHandler dh = new MyDoseHandler(getApplicationContext(), "prescriptionDB.db", null, 7);
List<Prescription> prescriptions = db.getAllPrescriptions();
// Spinner Drop down elements - Query the Doses for all upcoming doses first.
List<String> AlertLabels = new ArrayList<>();
//Where Name of prescription , date
String templateAlertMessage = "%s Dose on: %s";
ArrayList<Dose> doses = dh.getAllDosesInRange(begin, end, -1, -1, MyDBContract.COLUMN_DOSEDATE);
if (doses != null && !doses.isEmpty()) {
for (Dose dose : doses) {
AlertLabels.add(String.format(templateAlertMessage, dose.getPrescriptionLabel(),
new SimpleDateFormat("MMM dd, yyyy HH:mm").format(dose.getDate())));
}
}
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, AlertLabels);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
aListView.setAdapter(dataAdapter);
}
//created the menu
//http://www.101apps.co.za/index.php/articles/using-menus-in-your-apps-a-tutorial.html
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
//inflate the menu; this adds items to the action
//bar if it is present
getMenuInflater().inflate(R.menu.main, menu);
String title = "Menu List";
int groupID = Menu.NONE;
int itemId = Menu.FIRST;
int order = 103;
menu.add(groupID, itemId, order, title);
return true;
}
/**
* menu
* @param menuItem
*/
public void calTestClicked (MenuItem menuItem){
//Intent loginIntent = new Intent(this, Medication.class);
Intent loginIntent = new Intent(this, CalTest.class);
startActivity(loginIntent);
}
/**
* menu
* @param menuItem
*/
public void homeAlertPageClicked (MenuItem menuItem){
//Intent loginIntent = new Intent(this, Medication.class);
Intent loginIntent = new Intent(this,MainScreen.class);
startActivity(loginIntent);
}
}
|
package com.chuxin.family.views.chat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.json.JSONException;
import org.json.JSONObject;
import com.ant.liao.chuxin.EnhancedGifView;
import com.ant.liao.chuxin.GifView.GifImageType;
import com.chuxin.family.global.CxGlobalParams;
import com.chuxin.family.models.AnimationMessage;
import com.chuxin.family.models.Message;
import com.chuxin.family.net.ChatApi;
import com.chuxin.family.net.ConnectionManager.JSONCaller;
import com.chuxin.family.resource.CxResourceDarwable;
import com.chuxin.family.utils.CxLog;
import com.chuxin.family.whip.WhipActivity;
import com.chuxin.family.widgets.CxImageView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.chuxin.family.R;
import android.content.Context;
import android.media.MediaPlayer;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.CycleInterpolator;
import android.view.animation.RotateAnimation;
import android.view.animation.Animation.AnimationListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.TextView;
public class PartnerAnimationEntry extends ChatLogEntry{
private static final String TAG = "PartnerAnimationEntry";
private String mMsgText;
private AnimationMessage mAnimationMsg ;
private Context mContext;
private int animation_id, effect;
private PopupWindow mPopWin ; // 播放动画时使用
private LayoutInflater inflater;
private EnhancedGifView gifView;
private static MediaPlayer sVoicePlayer = null;
private int soundResId, gifResId ; // 要播放的声音资源ID、动画资源ID
private View popView; // 播放动画时的视图
private CxImageView shakeHeadImg; // 要晃动的头像对像
private static boolean mIsAnimate = false;
public PartnerAnimationEntry(Message message, Context context, boolean isShowDate) {
super(message, context, isShowDate);
this.mContext = context;
}
@Override
public boolean isOwner() {
return false;
}
@Override
public int getType() {
return ENTRY_TYPE_PEER_ANIMATION;
}
@Override
public View build(View view, ViewGroup parent) {
ChatLogAdapter tag = null;
if (view == null) {
view = LayoutInflater.from(mContext).inflate(R.layout.cx_fa_view_chat_chatting_animation_for_partner, null);
}
mAnimationMsg = (AnimationMessage)mMessage;
int msgType = mAnimationMsg.getType();
final int msgId = mAnimationMsg.getMsgId();
int msgCreatTimeStamp = mAnimationMsg.getCreateTimestamp();
// mMsgText = message.getText();
if (tag == null) {
tag = new ChatLogAdapter();
}
tag.mChatType = msgType;
tag.mMsgId = msgId;
// tag.mMsgText = mMsgText;
// 头像
CxImageView icon = (CxImageView) view.findViewById(R.id.cx_fa_view_chat_chatting_animation_row_for_partner_icon);
/*if(RkGlobalParams.getInstance().getPartnerIconBig()==null || RkGlobalParams.getInstance().getPartnerIconBig().equals("")){
icon.setImageResource(R.drawable.cx_fa_hb_icon_small);
}else{
icon.setImage(RkGlobalParams.getInstance().getPartnerIconBig(),
false, 44, mContext, "head", mContext);
}*/
icon.displayImage(ImageLoader.getInstance(),
CxGlobalParams.getInstance().getPartnerIconBig(),
CxResourceDarwable.getInstance().dr_chat_icon_small_oppo, true,
CxGlobalParams.getInstance().getMateSmallImgConner());
icon.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
CxLog.i(TAG, "click update owner headimage button");
// 跳转到个人资料页
ChatFragment.getInstance().gotoOtherFragment("rkmate");
}
});
// 设置消息时间
TextView dateStamp = (TextView)view.findViewById(R.id.cx_fa_view_chat_chatting_animation_row_datestamp);
TextView timeStamp = (TextView)view.findViewById(R.id.cx_fa_view_chat_chatting_animation_row_for_partner_timestamp);
String format = view.getResources().getString(R.string.cx_fa_nls_reminder_period_time_format);
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date((long)(msgCreatTimeStamp) * 1000));
String time = String.format(format, calendar);
timeStamp.setText(time);
if (mIsShowDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日");
String dateNow = dateFormat.format(new Date((long)(msgCreatTimeStamp) * 1000));
dateStamp.setVisibility(View.VISIBLE);
dateStamp.setText(dateNow);
} else {
dateStamp.setVisibility(View.GONE);
}
try {
animation_id = mAnimationMsg.mData.getInt("animation_id");
effect = mAnimationMsg.mData.getInt("effect");
} catch (JSONException e) {
CxLog.e(TAG, "获取animation_id 和 effect 错误:" + e.getMessage());
}
// 是否需要播放动画 (effect 跟 animation_id相等,表示对方弹了脑壳或抽了鞭子。这时侯才需要播放动画, 如果是对方的回复,则不需要播放动画)
if(effect==animation_id){
// 是否已读
boolean is_read = false;
try {
if( mAnimationMsg.mData.has("is_read") ){
is_read = mAnimationMsg.mData.getBoolean("is_read");
}
} catch (JSONException e) {
CxLog.e(TAG, "得到is_read出错:"+e.getMessage());
}
/* 如果没读,则开始播放动画 */
if(!is_read && !mIsAnimate){
mIsAnimate = true;
// 先把此条消息置为已读 (防止低端手机一播放动画就闪退,再次进来还要播放,继续闪退的问题。先设为已读,即使闪退,下次进来就不会再播了)
try {
mAnimationMsg.mData.put("is_read", true);
mAnimationMsg.update();
ChatFragment.getInstance().updateChatViewDB(); // 强行同步一下视图中的数据(要不然Message会有缓存,还会再次反复播放动画)
} catch (JSONException e) {
CxLog.e(TAG, e.getMessage());
}
inflater = LayoutInflater.from(mContext);
popView = inflater.inflate(R.layout.cx_fa_view_chat_whip_partner_animation, null);
gifView = (EnhancedGifView)popView.findViewById(R.id.cx_fa_view_chat_whip_gif_partner);
mPopWin = new PopupWindow(popView, LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT, true);
if(animation_id==0){
soundResId = R.raw.whip_pumping_whip;
gifResId = R.drawable.whip_gif_whip;
}else if(animation_id==1){
soundResId = R.raw.whip_bullet_head;
gifResId = R.drawable.whip_gif_head;
}
mPopWin.showAtLocation(view, Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL,0,0);
playGifAndSound(); // 播放声音和动画,播放完成后会把本条消息置为已读
}
}
// 根据不同情况,要改变的几个页面对象
TextView title = (TextView)view.findViewById(R.id.cx_fa_view_chat_chatting_animation_reply_title); // 标题
ImageView pic = (ImageView)view.findViewById(R.id.cx_fa_view_chat_chatting_animation_reply_pic); // 配图
TextView info = (TextView)view.findViewById(R.id.cx_fa_view_chat_chatting_animation_reply_info); // 提示信息
/*
* 判断是否需要用户应答
* effect: 动画效果 [0-9] 0:抽鞭子 2,3,4,5 回复抽鞭子
* 1:弹脑壳 6,7,8,9 回复弹脑壳
*/
LinearLayout btnWrap = (LinearLayout) view.findViewById(R.id.cx_fa_view_chat_chatting_animation_btn_wrap);
if(effect==0 || effect==1){ // 需要用户应答
//将按钮区域显示
btnWrap.setVisibility(View.VISIBLE);
TextView btn1 = (TextView)view.findViewById(R.id.cx_fa_view_chat_chatting_animation_reply_btn1); // 回复按钮1 (求饶、撒娇)
TextView btn2 = (TextView)view.findViewById(R.id.cx_fa_view_chat_chatting_animation_reply_btn2); // 回复按钮2 (耍赖、反击)
if(animation_id==0){
//抽鞭子
title.setText( mContext.getString(R.string.cx_fa_animation_0_name) );
pic.setImageResource(R.drawable.whip_imagewhip);
info.setText( mContext.getString(R.string.cx_fa_animation_0_hit) );
btn1.setText(R.string.cx_fa_animation_0_reply_btn_1);
btn2.setText(R.string.cx_fa_animation_0_reply_btn_2);
}else{
// 弹脑壳
title.setText( mContext.getString(R.string.cx_fa_animation_1_name) );
pic.setImageResource(R.drawable.whip_imagehead);
info.setText( mContext.getString(R.string.cx_fa_animation_1_hit) );
btn1.setText(R.string.cx_fa_animation_1_reply_btn_1);
btn2.setText(R.string.cx_fa_animation_1_reply_btn_2);
}
btn1.setOnClickListener(btnClickListener);
btn2.setOnClickListener(btnClickListener);
}else{ // 不需要用户应答,只显示对方回复结果
//将按钮区域隐藏
btnWrap.setVisibility(View.GONE);
// 判断是抽鞭子还是弹脑壳,来显示对应的回复
if(animation_id==0){
// 抽鞭子
title.setText( mContext.getString(R.string.cx_fa_animation_0_reply_title) );
if(effect==2){ // 求饶
pic.setImageResource(R.drawable.whip_replyqiurao);
info.setText( mContext.getString(R.string.cx_fa_animation_0_reply_text_1) );
}else if(effect==3){ // 耍赖
pic.setImageResource(R.drawable.whip_replyshualai);
info.setText( mContext.getString(R.string.cx_fa_animation_0_reply_text_2) );
}
}else{
// 弹脑壳
title.setText( mContext.getString(R.string.cx_fa_animation_1_reply_title) );
if(effect==6){ // 撒娇
pic.setImageResource(R.drawable.whip_replysajiao);
info.setText( mContext.getString(R.string.cx_fa_animation_1_reply_text_1) );
}else if(effect==7){ // 反击
pic.setImageResource(R.drawable.whip_replyfanji);
info.setText( mContext.getString(R.string.cx_fa_animation_1_reply_text_2) );
}
}
}
view.setTag(tag);
return view;
}
// 按钮点击
OnClickListener btnClickListener = new OnClickListener(){
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.cx_fa_view_chat_chatting_animation_reply_btn1:
if(animation_id==0){
effect = 2; // 求饶
}else if(animation_id==1){
effect = 6; // 撒娇
}
break;
case R.id.cx_fa_view_chat_chatting_animation_reply_btn2:
if(animation_id==0){
effect = 3; // 耍赖
}else if(animation_id==1){
effect = 7; // 反击
}
break;
default:
break;
}
String msg2 = animation_id + "," + effect;
ChatFragment.getInstance().sendMessage(msg2, com.chuxin.family.models.Message.MESSAGE_TYPE_ANIMATION);
}
};
/**
* 播放动画和声音
*/
private void playGifAndSound(){
// 播放动画
gifView.setGifImageType(GifImageType.COVER);
gifView.setGifImage(gifResId);
gifView.showCover();
// 播放声音
playSoundTimes = 0;
playSound();
}
int playSoundTimes = 0; // 播放计数器,记录播放了几次
/**
* 播放声音
*/
private void playSound(){
final int maxTimes = 3; // 最多播放几次
// 播放声音
if (sVoicePlayer == null) {
sVoicePlayer = MediaPlayer.create(mContext.getApplicationContext(), soundResId);
sVoicePlayer.setLooping(false);
sVoicePlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
CxLog.w("chat animation", "------complete animation------");
sVoicePlayer.release();
sVoicePlayer = null;
if(playSoundTimes<maxTimes-1){
playSoundTimes = playSoundTimes +1;
playSound(); // 默认重复播放
}else{
/* 动画和声音播放完成后,要去做的事 */
gifView.destroy();
mPopWin.dismiss(); // 关闭本窗口
mIsAnimate = false;
}
}
});
}
try {
if (!sVoicePlayer.isPlaying()){
sVoicePlayer.start();
}
} catch (Exception e) {
e.printStackTrace();
if (sVoicePlayer != null) {
sVoicePlayer.release();
sVoicePlayer = null;
}
}
}
}
|
package com.beiyelin.common.document;
import com.beiyelin.common.utils.StrUtils;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Pattern;
/**
* Created by xinsh on 2017/9/14.
*/
public class DocTypeUtils {
/**
* 根据url判断文件类型
*
* @param fileUrl 文件rul
* @return String类型
* @throws IOException
*/
public static String getTypeByUrl(String fileUrl) throws IOException {
if (StrUtils.isBlank(fileUrl)) {
throw new IOException("not found url");
}
if (fileUrl.startsWith("/") || Pattern.compile("^[a-zA-z]+").matcher(fileUrl).find()) {
fileUrl = "file://" + fileUrl;
return getMimeType(fileUrl);
} else if (!fileUrl.startsWith("http")) {
throw new IOException("请以http开头,或者传入文件的绝对路径");
}
URL u = new URL(fileUrl);
URLConnection uc = u.openConnection();
return uc.getContentType();
}
/**
* 根据物理路径文件,判断文件类型
* @param fileUrl
* @return
* @throws IOException
*/
public static String getMimeType(String fileUrl) throws IOException {
if (StrUtils.isBlank(fileUrl)) {
throw new IOException("not found url");
}
return URLConnection.getFileNameMap().getContentTypeFor(fileUrl);
}
// public static void main(String args[]) throws Exception {
// String fileUrl = "https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=2857526020,1758990106&fm=58";
// String url = "d:/temp/微信图片_20170904132226.jpg";
//
// System.out.println(getTypeByUrl(url));
// }
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.