text
stringlengths 10
2.72M
|
|---|
package com.apress.todo.repository;
import com.apress.todo.domain.Task;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.stereotype.Repository;
/**
* @author max.dokuchaev
*/
@Repository
public interface TaskRepository extends ReactiveMongoRepository<Task, String> {
}
|
package com.rca_gps.app.activity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.Window;
import android.widget.Toast;
import com.rca_gps.app.util.CheckNetwork;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;
/**
* Created by wafer on 2016/10/24.
*/
public class BaseActivity extends Activity {
public Context context;
private ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
initViews();
}
public void initViews() {
context = this;
}
public void http(String url, final String type) {
if (CheckNetwork.isNetworkAvailable(BaseActivity.this)) {
showDia("正在加载中...");
RequestParams params = new RequestParams(url);
x.http().get(params, new Callback.CacheCallback<String>() {
@Override
public boolean onCache(String result) {
return false;
}
@Override
public void onSuccess(String result) {
success(result, type);
hideDia();
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
error(ex.getMessage(), type);
System.out.println(ex.getLocalizedMessage());
hideDia();
}
@Override
public void onCancelled(CancelledException cex) {
// hideDia();
}
@Override
public void onFinished() {
// hideDia();
}
});
} else {
senToa("网络异常");
}
}
public void httpPost(final String type, RequestParams params) {
if (CheckNetwork.isNetworkAvailable(BaseActivity.this)) {
if (!type.equals("commit"))
showDia("正在加载中...");
x.http().post(params, new Callback.CacheCallback<String>() {
@Override
public boolean onCache(String result) {
return false;
}
@Override
public void onSuccess(String result) {
success(result, type);
if (!type.equals("commit"))
hideDia();
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
error(ex.getMessage(), type);
if (!type.equals("commit"))
hideDia();
}
@Override
public void onCancelled(CancelledException cex) {
// hideDia();
}
@Override
public void onFinished() {
// hideDia();
}
});
} else {
senToa("网络异常");
}
}
public void success(String result, String type) {
}
public void error(String result, String type) {
}
public void senToa(String text) {
Toast mToast = null;
if (mToast != null) {
mToast = new Toast(context);
mToast.setText(text);
mToast.setDuration(Toast.LENGTH_LONG);
mToast.show();
}
}
private void showDia(String str) {
if (progressDialog == null) {
progressDialog = new ProgressDialog(this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
}
progressDialog.setMessage(str);
progressDialog.show();
}
private void hideDia() {
try {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
import org.testng.annotations.Test;
import utils.functions.CommonFunctions;
import utils.pages.PageElements;
public class FirstTest {
@Test
public void showSpecificAds() {
// Step 1: Start driver and access link
CommonFunctions.openLink();
// Step 1.2: Accept cookies
CommonFunctions.generalClickPageElement(PageElements.btnAcceptCookies);
// Step 2: Navigate to Imobiliare
CommonFunctions.generalClickPageElement(PageElements.imobiliarePage);
// Step 3: Navigate to 'Apartamente - Garsoniere de vanzare'
CommonFunctions.generalClickPageElement(PageElements.categoryApartamenteDeVanzare);
// Step 4: Show only '3 camere'
CommonFunctions.generalClickPageElement(PageElements.category3Rooms);
// Step 5: Filter by location
CommonFunctions.generalClickPageElement(PageElements.inputLocation);
CommonFunctions.filterByCounty("Cluj");
CommonFunctions.filterByCity("Cluj-Napoca");
// Step 6: Open first ad
CommonFunctions.quitBrowser();
}
}
|
package com.bank.service.ui.userlogin.usecase;
public class ManageAccount {
}
|
package com.tencent.mm.plugin.fav.b.d;
import com.tencent.mm.ab.l;
import com.tencent.mm.plugin.fav.a.ae;
import com.tencent.mm.plugin.fav.a.af;
import com.tencent.mm.plugin.fav.a.b;
import com.tencent.mm.plugin.fav.a.g;
import com.tencent.mm.plugin.fav.a.h;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
class e$1 implements Runnable {
final /* synthetic */ l bFp;
final /* synthetic */ int bFq;
final /* synthetic */ int bFr;
final /* synthetic */ e iXR;
e$1(e eVar, l lVar, int i, int i2) {
this.iXR = eVar;
this.bFp = lVar;
this.bFq = i;
this.bFr = i2;
}
public final void run() {
if (this.bFp.getType() == 401 && (this.bFp instanceof af)) {
e.a(this.iXR);
g gVar = ((af) this.bFp).iWJ;
long j = gVar.field_localId;
e.QV().remove(Long.valueOf(j));
if ((this.bFq == 0 && this.bFr == 0) || this.bFr == -400) {
e.amM().add(Long.valueOf(j));
}
if (!(this.bFq == 0 || this.bFr == -400)) {
e.b(this.iXR);
}
Integer valueOf = Integer.valueOf(bi.a((Integer) e.aMa().get(Long.valueOf(j)), 0));
if (!(this.bFq == 1 || this.bFq == 0)) {
valueOf = Integer.valueOf(valueOf.intValue() - 1);
e.aMa().put(Long.valueOf(gVar.field_localId), valueOf);
}
if (valueOf.intValue() <= 0) {
int cA = h.cA(this.bFq, this.bFr);
com.tencent.mm.plugin.report.service.h.mEJ.h(10659, new Object[]{Integer.valueOf(0), Integer.valueOf(gVar.field_type), Integer.valueOf(cA), Long.valueOf(b.b(gVar)), Long.valueOf(h.dr(gVar.field_localId))});
e.aMa().remove(Long.valueOf(j));
x.e("MicroMsg.Fav.FavSendService", "achieved retry limit, set error, localId:%d", new Object[]{Long.valueOf(j)});
if (gVar.field_itemStatus == 12) {
((ae) com.tencent.mm.kernel.g.n(ae.class)).getFavItemInfoStorage().t(14, gVar.field_localId);
}
if (gVar.field_itemStatus == 9) {
((ae) com.tencent.mm.kernel.g.n(ae.class)).getFavItemInfoStorage().t(11, gVar.field_localId);
}
}
if (e.c(this.iXR) <= 0) {
x.i("MicroMsg.Fav.FavSendService", "klem stopFlag <= 0 , Stop Service");
e.e(this.iXR);
} else if (!e.d(this.iXR)) {
e.startSync();
}
}
}
public final String toString() {
return super.toString() + "|onSceneEnd";
}
}
|
package com.hallowizer.displaySlot.plugin.bungee;
import com.hallowizer.displaySlot.plugin.DisplaySlotMain;
import lombok.Getter;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.plugin.Plugin;
public final class DisplaySlotPlugin extends Plugin {
@Getter
private static DisplaySlotPlugin instance;
@Override
public void onLoad() {
instance = this;
DisplaySlotMain.onLoad(new BungeeDisplaySlotPlatform());
getLogger().info("DisplaySlot has been loaded!");
}
@Override
public void onEnable() {
ProxyServer.getInstance().getPluginManager().registerListener(this, new PlayerJoinListener());
DisplaySlotMain.onEnable();
getLogger().info("DisplaySlot has been enabled!");
}
@Override
public void onDisable() {
DisplaySlotMain.onDisable();
getLogger().info("DisplaySlot has been disabled!");
}
public BungeeDisplaySlotPlatform getPlatform() {
return (BungeeDisplaySlotPlatform) DisplaySlotMain.getPlatform();
}
}
|
package de.jmda.app.cgol;
/**
* Allows to define activities that will be carried out around invocations of {@link Life#getNextPopulation()}.
*
* @param <P>
* @param <L>
*/
public class LifeInterceptorSupport<P extends Population<?>, L extends Life<P>>
implements Life<P>, InterceptorSupport
{
private L life;
private Runnable preNextPopulationInterceptor; // TODO use Optional?
private Runnable postNextPopulationInterceptor; // TODO use Optional?
public LifeInterceptorSupport(
L life,
Runnable preNextPopulationInterceptor,
Runnable postNextPopulationInterceptor)
{
if (life == null) throw new IllegalArgumentException("life must not be null");
this.life = life;
this.preNextPopulationInterceptor = preNextPopulationInterceptor;
this.postNextPopulationInterceptor = postNextPopulationInterceptor;
}
public LifeInterceptorSupport(L life) { this(life, null, null); }
public L getLife() { return life; }
@Override public void setPreActionInterceptor(Runnable interceptor)
{
preNextPopulationInterceptor = interceptor;
}
@Override public Runnable getPreActionInterceptor() { return preNextPopulationInterceptor; }
@Override public void setPostActionInterceptor(Runnable interceptor)
{
postNextPopulationInterceptor = interceptor;
}
@Override public Runnable getPostActionInterceptor() { return postNextPopulationInterceptor; }
@Override public P getCurrentPopulation() { return life.getCurrentPopulation(); }
@Override public P getNextPopulation()
{
P result;
if (preNextPopulationInterceptor != null) preNextPopulationInterceptor.run();
result = life.getNextPopulation();
if (postNextPopulationInterceptor != null) postNextPopulationInterceptor.run();
return result;
}
}
|
package com.tencent.mm.plugin.account.security.a;
import com.tencent.mm.bt.h.d;
import com.tencent.mm.g.a.hp;
import com.tencent.mm.model.ar;
import com.tencent.mm.model.p;
import com.tencent.mm.sdk.b.a;
import com.tencent.mm.sdk.b.b;
import com.tencent.mm.sdk.b.c;
import java.util.HashMap;
public class g implements ar {
private static HashMap<Integer, d> eOr;
private e eOq;
private c eOs = new 2(this);
private c eOt = new c<hp>() {
{
this.sFo = hp.class.getName().hashCode();
}
public final /* synthetic */ boolean a(b bVar) {
hp hpVar = (hp) bVar;
hpVar.bQW.bQX = f.cn(hpVar.bQV.context);
return false;
}
};
private c eOu = new 4(this);
private static synchronized g Yp() {
g gVar;
synchronized (g.class) {
gVar = (g) p.v(g.class);
}
return gVar;
}
public static e Yq() {
com.tencent.mm.kernel.g.Eg().Ds();
if (Yp().eOq == null) {
Yp().eOq = new e(com.tencent.mm.kernel.g.Ei().dqq);
}
return Yp().eOq;
}
static {
HashMap hashMap = new HashMap();
eOr = hashMap;
hashMap.put(Integer.valueOf("SAFE_DEVICE_INFO_TABLE".hashCode()), new 1());
}
public final HashMap<Integer, d> Ci() {
return eOr;
}
public final void gi(int i) {
}
public final void bn(boolean z) {
a.sFg.b(this.eOs);
a.sFg.b(this.eOt);
a.sFg.b(this.eOu);
}
public final void bo(boolean z) {
}
public final void onAccountRelease() {
a.sFg.c(this.eOs);
a.sFg.c(this.eOt);
a.sFg.c(this.eOu);
}
}
|
/*
* 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 baseconverter;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
/**
*
* @author sehga
*/
public class Converter implements Runnable {
private JFrame frame;
@Override
public void run() {
frame = new JFrame("Converter");
frame.setPreferredSize(new Dimension(500, 200));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
createComponents(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
private void createComponents(Container c) {
c.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS));
JTextField input = new JTextField("");
JLabel output = new JLabel("");
c.add(input);
c.add(createPanel(input, output));
c.add(output);
}
private JPanel createPanel(JTextField input, JLabel output) {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
JButton convert = new JButton("convert");
JTextField base1 = new JTextField();
JTextField base2 = new JTextField();
convert.addActionListener(new baseListener(input, output, base1, base2));
c.weightx = 1.;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
panel.add(new JLabel("From:"), c);
c.gridx = 0;
c.gridy = 1;
panel.add(base1, c);
c.gridx = 1;
c.gridy = 0;
panel.add(new JLabel("To:"), c);
c.gridx = 1;
c.gridy = 1;
panel.add(base2, c);
c.gridx = 2;
c.gridy = 1;
panel.add(convert, c);
return panel;
}
}
|
package ru.carlson.characters;
public enum Directions{
UP("Наверх"),
DOWN("Вниз"),
LEFT("Налево"),
RIGHT("Направо");
private final String directionName;
private Directions(String name){
directionName = name;
}
public String toString(){
return directionName;
}
}
|
package com.eyes.uciha.sarringan;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;
import com.eyes.uciha.sarringan.R;
import sponsorpay.User;
import kankan.wheel.widget.OnWheelChangedListener;
import kankan.wheel.widget.OnWheelClickedListener;
import kankan.wheel.widget.OnWheelScrollListener;
import kankan.wheel.widget.WheelView;
import kankan.wheel.widget.adapters.AbstractWheelAdapter;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class TailActivity extends Activity {
public static long Totalscore =500;
public static long partnerscore =0;
public static int ratio=0;
public int currentscore =0;
public static Bitmap bitmap1=null;
public static Bitmap bitmap2=null;
public static Bitmap bitmap3=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.slot_machine_layout);
LinearLayout la = (LinearLayout)findViewById(R.id.layout);
la.setBackgroundResource(R.drawable.b2);
initWheel(R.id.slot_1,1);
// initWheel(R.id.slot_2,2);
// initWheel(R.id.slot_3,3);
TextView text1 = (TextView) findViewById(R.id.score);
text1.setText("You'r point " + User.Coins_points);
final Context c =this;
Button mix = (Button)findViewById(R.id.btn_mix);
mix.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
TextView text = (TextView) findViewById(R.id.pwd_status);
// text.setText("..");
if(User.Coins_points>10)
{
mixWheel(R.id.slot_1);
User.Coins_points=User.Coins_points-10;
v.setVisibility(View.GONE);
}
else
{
Toast.makeText(c, "U Dont have any coin to play", Toast.LENGTH_LONG).show();
}// mixWheel(R.id.slot_3);
// v.setVisibility(View.GONE);
}
});
Button share = (Button)findViewById(R.id.btn_share);
share.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
TextView text = (TextView) findViewById(R.id.pwd_status);
// text.setText("..");
if(User.Coins_points>10)
{
mixWheel(R.id.slot_1);
User.Coins_points=User.Coins_points-10;
}
else
{
Toast.makeText(c, "U Dont have any coin to play", Toast.LENGTH_LONG).show();
}
}
});
Button shae = (Button)findViewById(R.id.btn_shout);
shae.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
}
});
// updateStatus();
}
// Wheel scrolled flag
private boolean wheelScrolled = false;
// Wheel scrolled listener
OnWheelScrollListener scrolledListener = new OnWheelScrollListener() {
public void onScrollingStarted(WheelView wheel) {
wheelScrolled = true;
}
public void onScrollingFinished(WheelView wheel) {
wheelScrolled = false;
updateStatus();
}
};
// Wheel changed listener
private OnWheelChangedListener changedListener = new OnWheelChangedListener() {
public void onChanged(WheelView wheel, int oldValue, int newValue) {
if (!wheelScrolled) {
// updateStatus();
}
}
};
/**
* Updates status
*/
private void updateStatus() {
TextView text = (TextView) findViewById(R.id.pwd_status);
test();
text.setText("Your Tailed Beast point : " + partnerscore+" ");
// text1.setText("You have : " + Totalscore+" coins");
TextView text1 = (TextView) findViewById(R.id.score);
text1.setText("You'r point " + User.Coins_points);
// finish();
}
/**
* Initializes wheel
* @param id the wheel widget Id
*/
private void initWheel(int id,int i) {
WheelView wheel = getWheel(id);
wheel.setViewAdapter(new SlotMachineAdapter(this,i));
wheel.setCurrentItem((int)(Math.random() * 10));
wheel.addChangingListener(changedListener);
wheel.addScrollingListener(scrolledListener);
wheel.setCyclic(true);
wheel.setEnabled(false);
}
/**
* Returns wheel by Id
* @param id the wheel Id
* @return the wheel with passed Id
*/
private WheelView getWheel(int id) {
return (WheelView) findViewById(id);
}
public Bitmap getbit(int i, String[] itemas){
String id=itemas[i];
InputStream is = null;
try {
is = getAssets().open(id);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeStream(is);
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 60, 60, true);
bitmap.recycle();
return scaled;}
/**
* Tests wheels
* @return true
*/
private boolean test() {
int value = getWheel(R.id.slot_1).getCurrentItem();
// int value1 = getWheel(R.id.slot_2).getCurrentItem();
// int value2 = getWheel(R.id.slot_3).getCurrentItem();
////
partnerscore =0;
SlotMachineAdapter s = new SlotMachineAdapter(this, 1);
bitmap1=getbit(value,s.items);
partnerscore =(value+1)*10;
// bitmap2=getbit(value1,s.itemsa);
// bitmap3=getbit(value2,s.itemsb);
/* if(value==6)
{
Toast.makeText(this, "U got sakura, get the hell out of here", Toast.LENGTH_LONG).show();
partnerscore =partnerscore-100;
}
else if(value>6 || value<6)
{ if(value==4)
{
Toast.makeText(this, "U got shikamaru, you have a great chance to win", Toast.LENGTH_LONG).show();
partnerscore =partnerscore+100;
}
else if(value>4)
partnerscore =partnerscore+10;
else if(value<4)
partnerscore =partnerscore-10;
}
if(value1<=2)
{
partnerscore =partnerscore-10;
}
else
partnerscore =partnerscore+15;
if(value2<=2)
{
partnerscore =partnerscore-10;
}
else
partnerscore =partnerscore+25;
*/
// Toast.makeText(this, ""+value, Toast.LENGTH_LONG).show();
return testWheelValue(R.id.slot_2, value) && testWheelValue(R.id.slot_3, value);
}
/**
* Tests wheel value
* @param id the wheel Id
* @param value the value to test
* @return true if wheel value is equal to passed value
*/
private boolean testWheelValue(int id, int value) {
return getWheel(id).getCurrentItem() == value;
}
/**
* Mixes wheel
* @param id the wheel id
*/
private void mixWheel(int id) {
WheelView wheel = getWheel(id);
wheel.scroll(-350 + (int)(Math.random() * 50), 2000);
}
/**
* Slot machine adapter
*/
private class SlotMachineAdapter extends AbstractWheelAdapter {
// Image size
final int IMAGE_WIDTH = 57;
final int IMAGE_HEIGHT = 57;
// Slot machine symbols
public String items[] = new String[] {
"tail/1.jpg",
"tail/2.jpg",
"tail/3.jpg",
"tail/4.jpg",
"tail/5.jpg",
"tail/6.jpg",
"tail/7.jpg",
"tail/8.jpg",
"tail/9.jpg"
};
public final String itemsa[] = new String[] {
"part/p/2.jpg",
"part/p/5.jpg",
"part/p/8.jpg",
"part/vp/3.jpg",
"part/vp/6.jpg",
"part/wp/3.jpg",
"part/wp/6.jpg"
};
public final String itemsb[] = new String[] {
"part/p/3.jpg",
"part/p/6.jpg",
"part/vp/1.jpg",
"part/vp/4.jpg",
"part/wp/1.jpg",
"part/wp/4.jpg"
};
// Cached images
private List<SoftReference<Bitmap>> images;
// Layout inflater
private Context context;
/**
* Constructor
*/
public SlotMachineAdapter(Context context, int i) {
this.context = context;
if(i==1)
{
images = new ArrayList<SoftReference<Bitmap>>(items.length);
for (String id : items) {
images.add(new SoftReference<Bitmap>(loadImage(id)));
}
}
if(i==2)
{
items=itemsa;
images = new ArrayList<SoftReference<Bitmap>>(itemsa.length);
for (String id : itemsa) {
images.add(new SoftReference<Bitmap>(loadImage(id)));
}
}
if(i==3)
{items=itemsb;
images = new ArrayList<SoftReference<Bitmap>>(itemsb.length);
for (String id : itemsb) {
images.add(new SoftReference<Bitmap>(loadImage(id)));
}
}
}
/**
* Loads image from resources
*/
private Bitmap loadImage(String id) {
InputStream is = null;
try {
is = getAssets().open(id);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeStream(is);
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, IMAGE_WIDTH, IMAGE_HEIGHT, true);
bitmap.recycle();
return scaled;
}
@Override
public int getItemsCount() {
return items.length;
}
// Layout params for image view
final LayoutParams params = new LayoutParams(IMAGE_WIDTH, IMAGE_HEIGHT);
@Override
public View getItem(int index, View cachedView, ViewGroup parent) {
ImageView img;
if (cachedView != null) {
img = (ImageView) cachedView;
} else {
img = new ImageView(context);
}
img.setLayoutParams(params);
SoftReference<Bitmap> bitmapRef = images.get(index);
Bitmap bitmap = bitmapRef.get();
if (bitmap == null) {
bitmap = loadImage(items[index]);
images.set(index, new SoftReference<Bitmap>(bitmap));
}
img.setImageBitmap(bitmap);
return img;
}
}
}
|
package dao;
import model.FootballClub;
public class FootballClubDaoImpl extends BaseDaoImpl<Integer, FootballClub> implements FootballClubDao {
private static final FootballClubDaoImpl INSTANCE = new FootballClubDaoImpl();
public static FootballClubDaoImpl getInstance() {
return INSTANCE;
}
public FootballClubDaoImpl() {
super(FootballClub.class);
}
}
|
package com.techlab.chap1.demo.test;
public interface Flyable {
public void fly();
}
|
package com.tencent.mm.e.a;
import com.tencent.mm.compatible.b.f;
import com.tencent.mm.e.a.a.3.1.1;
import com.tencent.mm.sdk.platformtools.as.a;
import com.tencent.mm.sdk.platformtools.x;
class a$3$1$1$1 implements a {
final /* synthetic */ 1 bCZ;
a$3$1$1$1(1 1) {
this.bCZ = 1;
}
public final void wd() {
x.i("MicroMsg.SceneVoicePlayer", "play sound end onCompletion");
if (!this.bCZ.bCY.bCX.bCV.isPlaying()) {
f.yz().b(this.bCZ.bCY.bCX.bCV);
x.i("MicroMsg.SceneVoicePlayer", "onCompletion() continuousPlay:%s", Boolean.valueOf(a.i(this.bCZ.bCY.bCX.bCV)));
if (!a.i(this.bCZ.bCY.bCX.bCV)) {
f.yz().yC();
}
a.j(this.bCZ.bCY.bCX.bCV);
a.c(this.bCZ.bCY.bCX.bCV);
f.yz().setMode(0);
x.i("MicroMsg.SceneVoicePlayer", "onCompletion() resetSpeaker");
}
}
}
|
package com.tt.miniapp.shortcut.adapter;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.content.pm.ResolveInfo;
import android.content.pm.ShortcutInfo;
import android.content.pm.ShortcutManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Looper;
import android.os.Parcelable;
import android.os.PersistableBundle;
import android.support.v4.content.c;
import android.text.TextUtils;
import com.tt.miniapp.shortcut.ShortcutEntity;
import com.tt.miniapphost.AppBrandLogger;
import com.tt.miniapphost.AppbrandContext;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;
public class CustomShortcutManagerCompat {
public static Intent createShortcutResultIntent(Context paramContext, CustomShortcutInfoCompat paramCustomShortcutInfoCompat) {
Intent intent;
if (Build.VERSION.SDK_INT >= 26) {
Intent intent1 = ((ShortcutManager)paramContext.getSystemService(ShortcutManager.class)).createShortcutResultIntent(paramCustomShortcutInfoCompat.toShortcutInfo());
} else {
paramContext = null;
}
Context context = paramContext;
if (paramContext == null)
intent = new Intent();
return paramCustomShortcutInfoCompat.addToIntent(intent);
}
private static void deleteShortcut(Context paramContext, String paramString1, String paramString2) {
Intent intent2 = new Intent("android.intent.action.MAIN");
intent2.setComponent(new ComponentName(paramContext.getPackageName(), paramString2));
Intent intent1 = new Intent("com.android.launcher.action.UNINSTALL_SHORTCUT");
intent1.putExtra("android.intent.extra.shortcut.NAME", paramString1);
intent1.putExtra("android.intent.extra.shortcut.INTENT", (Parcelable)intent2);
intent1.putExtra("duplicate", true);
paramContext.sendBroadcast(intent1);
}
private static String getLauncherAuthority(Context paramContext) {
Intent intent = new Intent("android.intent.action.MAIN");
intent.addCategory("android.intent.category.HOME");
PackageManager packageManager = paramContext.getPackageManager();
ResolveInfo resolveInfo = packageManager.resolveActivity(intent, 0);
if (resolveInfo == null) {
AppBrandLogger.i("CustomShortcutManagerCompat", new Object[] { "resolveInfo not found" });
return "";
}
List list = packageManager.queryContentProviders(resolveInfo.activityInfo.packageName, resolveInfo.activityInfo.applicationInfo.uid, 8);
if (list == null) {
AppBrandLogger.i("CustomShortcutManagerCompat", new Object[] { "providerInfoList not found" });
return "";
}
for (ProviderInfo providerInfo : list) {
if (!TextUtils.isEmpty(providerInfo.readPermission) && Pattern.matches(".*launcher.*READ_SETTINGS", providerInfo.readPermission))
return providerInfo.authority;
}
return "";
}
public static ShortcutStatus getShortcutState(Context paramContext, ShortcutEntity paramShortcutEntity) {
String str;
ShortcutStatus shortcutStatus = new ShortcutStatus();
if (paramContext == null || paramShortcutEntity == null) {
AppBrandLogger.e("CustomShortcutManagerCompat", new Object[] { "query params error" });
return shortcutStatus;
}
if (Looper.myLooper() == Looper.getMainLooper())
AppBrandLogger.e("CustomShortcutManagerCompat", new Object[] { "should not quey in main thread" });
if (Build.VERSION.SDK_INT >= 25) {
Iterator<ShortcutInfo> iterator = ((ShortcutManager)paramContext.getSystemService(ShortcutManager.class)).getPinnedShortcuts().iterator();
while (iterator.hasNext()) {
ShortcutInfo shortcutInfo = iterator.next();
if (TextUtils.equals(shortcutInfo.getId(), paramShortcutEntity.getAppId())) {
shortcutStatus.exist = true;
PersistableBundle persistableBundle = shortcutInfo.getExtras();
if (persistableBundle != null) {
str = persistableBundle.getString("key_shortcut_id");
if (!TextUtils.equals(paramShortcutEntity.getShortcutMd5(), str))
shortcutStatus.needUpdate = true;
}
return shortcutStatus;
}
}
} else {
queryLauncher((Context)str, paramShortcutEntity, shortcutStatus);
}
return shortcutStatus;
}
public static boolean isRequestPinShortcutSupported(Context paramContext) {
return (Build.VERSION.SDK_INT >= 26) ? ((ShortcutManager)paramContext.getSystemService(ShortcutManager.class)).isRequestPinShortcutSupported() : (!(c.a(paramContext, "com.android.launcher.permission.INSTALL_SHORTCUT") != 0));
}
public static boolean isShortcutExist(Context paramContext, String paramString) {
if (Build.VERSION.SDK_INT < 25)
return false;
Iterator<ShortcutInfo> iterator = ((ShortcutManager)paramContext.getSystemService(ShortcutManager.class)).getPinnedShortcuts().iterator();
while (iterator.hasNext()) {
if (TextUtils.equals(((ShortcutInfo)iterator.next()).getId(), paramString))
return true;
}
return false;
}
private static void queryLauncher(Context paramContext, ShortcutEntity paramShortcutEntity, ShortcutStatus paramShortcutStatus) {
Cursor cursor;
String str2 = getLauncherAuthority(paramContext);
String str1 = str2;
if (TextUtils.isEmpty(str2)) {
AppBrandLogger.e("CustomShortcutManagerCompat", new Object[] { "launcherAuthority not found" });
int i = Build.VERSION.SDK_INT;
if (i < 8) {
str1 = "com.android.launcher.settings";
} else if (i < 19) {
str1 = "com.android.launcher2.settings";
} else {
str1 = "com.android.launcher3.settings";
}
}
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("content://");
stringBuffer.append(str1);
stringBuffer.append("/favorites?notify=true");
String str4 = null;
String str3 = null;
str1 = str3;
str2 = str4;
try {
Uri uri = Uri.parse(stringBuffer.toString());
str1 = str3;
str2 = str4;
Cursor cursor1 = paramContext.getContentResolver().query(uri, null, "title=? ", new String[] { paramShortcutEntity.getLabel() }, null);
if (cursor1 != null) {
Cursor cursor2 = cursor1;
cursor = cursor1;
if (cursor1.moveToNext()) {
cursor2 = cursor1;
cursor = cursor1;
paramShortcutStatus.exist = true;
cursor2 = cursor1;
cursor = cursor1;
Intent intent = Intent.parseUri(cursor1.getString(cursor1.getColumnIndex("intent")), 0);
cursor2 = cursor1;
cursor = cursor1;
if (!TextUtils.equals(intent.getStringExtra("key_shortcut_id"), paramShortcutEntity.getShortcutMd5())) {
cursor2 = cursor1;
cursor = cursor1;
paramShortcutStatus.needUpdate = true;
}
cursor2 = cursor1;
cursor = cursor1;
StringBuilder stringBuilder = new StringBuilder("get shortcut intent");
cursor2 = cursor1;
cursor = cursor1;
stringBuilder.append(intent);
cursor2 = cursor1;
cursor = cursor1;
AppBrandLogger.e("CustomShortcutManagerCompat", new Object[] { stringBuilder.toString() });
cursor2 = cursor1;
cursor = cursor1;
if (!cursor1.isClosed()) {
cursor2 = cursor1;
cursor = cursor1;
cursor1.close();
}
}
}
if (cursor1 != null && !cursor1.isClosed()) {
cursor1.close();
return;
}
} catch (Exception exception) {
Cursor cursor1 = cursor;
AppBrandLogger.e("CustomShortcutManagerCompat", new Object[] { exception });
if (cursor != null && !cursor.isClosed())
cursor.close();
} finally {}
}
public static boolean requestPinShortcut(Context paramContext, CustomShortcutInfoCompat paramCustomShortcutInfoCompat, final IntentSender callback) {
if (Build.VERSION.SDK_INT >= 26)
return ((ShortcutManager)paramContext.getSystemService(ShortcutManager.class)).requestPinShortcut(paramCustomShortcutInfoCompat.toShortcutInfo(), callback);
if (!isRequestPinShortcutSupported(paramContext))
return false;
Intent intent = paramCustomShortcutInfoCompat.addToIntent(new Intent("com.android.launcher.action.INSTALL_SHORTCUT"));
if (callback == null) {
paramContext.sendBroadcast(intent);
return true;
}
paramContext.sendOrderedBroadcast(intent, null, new BroadcastReceiver() {
public final void onReceive(Context param1Context, Intent param1Intent) {
try {
callback.sendIntent(param1Context, 0, null, null, null);
return;
} catch (android.content.IntentSender.SendIntentException sendIntentException) {
return;
}
}
}null, -1, null, null);
return true;
}
public static boolean updateShortcut(Context paramContext, final CustomShortcutInfoCompat shortcutInfoCompat, String paramString) {
final ShortcutManager context;
if (Build.VERSION.SDK_INT >= 25) {
shortcutManager = (ShortcutManager)paramContext.getSystemService(ShortcutManager.class);
return (shortcutManager == null) ? false : shortcutManager.updateShortcuts(Collections.singletonList(shortcutInfoCompat.toShortcutInfo()));
}
deleteShortcut((Context)shortcutManager, shortcutInfoCompat.getShortLabel().toString(), paramString);
AppbrandContext.mainHandler.postDelayed(new Runnable() {
public final void run() {
CustomShortcutManagerCompat.requestPinShortcut(context, shortcutInfoCompat, null);
}
}500L);
return false;
}
public static class ShortcutStatus {
public boolean exist;
public boolean needUpdate;
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\shortcut\adapter\CustomShortcutManagerCompat.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package cn.bs.zjzc.ui;
/**
* Created by Ming on 2016/5/27.
*/
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import cn.bs.zjzc.R;
import cn.bs.zjzc.base.BaseActivity;
public class AvSetPassword extends BaseActivity implements View.OnClickListener {
private Context mContext = this;
private EditText passwordConfirm;
private EditText nickName;
private EditText password;
private EditText invitationCode;
private CheckBox agreeRegisterProtocol;
private TextView done;
private TextView registerProtocol;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.av_set_password);
initViews();
initEvents();
}
private void initEvents() {
registerProtocol.setOnClickListener(this);
done.setOnClickListener(this);
}
private void initViews() {
nickName = ((EditText) findViewById(R.id.set_password_et_nickname));
password = ((EditText) findViewById(R.id.set_password_et_password));
passwordConfirm = ((EditText) findViewById(R.id.set_password_et_password_confirm));
invitationCode = ((EditText) findViewById(R.id.set_password_et_invitation_code));
agreeRegisterProtocol = ((CheckBox) findViewById(R.id.set_password_agree_register_protocol));
registerProtocol = ((TextView) findViewById(R.id.set_password_register_protocol));
done = ((TextView) findViewById(R.id.set_password_done));
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.set_password_register_protocol:
break;
case R.id.set_password_done:
}
}
}
|
package com.fatosajvazi;
public class Main {
public static void main(String[] args) {
// write your code here
//
// BankAccount bankAccount = new BankAccount();
//
//// BankAccount bankAccount = new BankAccount("1117179784000123",1000,
//// "Fatos Ajvazi","fatos.ajvazi@hotmail.com","+4367762918675");
//
// System.out.println("Client name: " + bankAccount.getCustomerName());
// System.out.println("Account number: " + bankAccount.getAccountNumber());
// System.out.println("Balance of the account: " + bankAccount.getBalance());
// System.out.println("Phone number: " + bankAccount.getPhoneNumber());
// System.out.println("E-mail: " + bankAccount.getEmail());
//
// bankAccount.deposit(1000);
// bankAccount.withdraw(700);
// System.out.println("Remaining balance: " + bankAccount.getBalance());
System.out.println("*********************************************");
VIPCustomer vipCustomer = new VIPCustomer();
System.out.println("Name: " + vipCustomer.getName());
System.out.println("E-mail: "+ vipCustomer.getEmail());
System.out.println("Credit limit: " + vipCustomer.getCreditLimit());
System.out.println("*********************************************");
VIPCustomer vipCustomer1 = new VIPCustomer("Fatos","fatos.ajvazi@hotmail.com");
System.out.println("Name: " + vipCustomer1.getName());
System.out.println("E-mail: "+ vipCustomer1.getEmail());
System.out.println("Credit limit: " + vipCustomer1.getCreditLimit());
System.out.println("*********************************************");
VIPCustomer vipCustomer2 = new VIPCustomer("Fatos Ajvazi",1500,"fatos.ajvazi@hotmail.com");
System.out.println("Name: " + vipCustomer2.getName());
System.out.println("E-mail: "+ vipCustomer2.getEmail());
System.out.println("Credit limit: " + vipCustomer2.getCreditLimit());
System.out.println("*********************************************");
}
}
|
/**
*
*/
package com.pzhu.topicsys.common.exception;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import com.pzhu.topicsys.common.util.JsonResponse;
/**
* Desc:公共异常Exception Handler
*/
@ControllerAdvice
class GlobalExceptionHandler {
public static final String DEFAULT_ERROR_VIEW = "error";
protected Logger logger = LoggerFactory.getLogger(getClass());
@ExceptionHandler(value = Exception.class)
@ResponseBody
public JsonResponse jsonErrorHandler(HttpServletRequest req, Exception e) {
JsonResponse res = JsonResponse.fail();
res.setMsg("请求处理发生异常");
if (e instanceof BusinessException) {
BusinessException be = (BusinessException) e;
res.setCode(be.getCode());
res.setMsg(e.getMessage());
}
logger.error("系统异常:", e);
return res;
}
}
|
package com.kunsoftware.service;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.kunsoftware.bean.ProductIntroduceRequestBean;
import com.kunsoftware.entity.ProductIntroduce;
import com.kunsoftware.exception.KunSoftwareException;
import com.kunsoftware.mapper.ProductIntroduceMapper;
@Service
public class ProductIntroduceService {
private static Logger logger = LoggerFactory.getLogger(ProductIntroduceService.class);
@Autowired
private ProductIntroduceMapper mapper;
public List<ProductIntroduce> getProductIntroduceListAll(Integer productId) {
logger.info("query");
return mapper.getProductIntroduceListAll(productId);
}
@Transactional
public ProductIntroduce insert(ProductIntroduceRequestBean requestBean) throws KunSoftwareException {
ProductIntroduce record = new ProductIntroduce();
BeanUtils.copyProperties(requestBean, record);
mapper.insert(record);
return record;
}
public ProductIntroduce selectByPrimaryKey(Integer id) throws KunSoftwareException {
return mapper.selectByPrimaryKey(id);
}
@Transactional
public int updateByPrimaryKey(ProductIntroduceRequestBean requestBean,Integer id) throws KunSoftwareException {
ProductIntroduce record = mapper.selectByPrimaryKey(id);
BeanUtils.copyProperties(requestBean, record);
return mapper.updateByPrimaryKeySelective(record);
}
@Transactional
public int deleteByPrimaryKey(Integer id) throws KunSoftwareException {
return mapper.deleteByPrimaryKey(id);
}
@Transactional
public void deleteByPrimaryKey(Integer[] id) throws KunSoftwareException {
for(int i = 0;i < id.length;i++) {
mapper.deleteByPrimaryKey(id[i]);
}
}
}
|
package com.techlab.basic;
import java.util.Scanner;
public class MagicNumbers {
public static void main() {
System.out.println("Enter any number : ");
Scanner scan = new Scanner(System.in);
int inputNumber = scan.nextInt();
if (inputNumber % 9 == 1)
System.out.println(inputNumber + " is a Magic Number");
else
System.out.println(inputNumber + " is NOT a Magic Number");
}
}
|
package edu.uci.ics.sdcl.firefly.util;
import java.util.Calendar;
import java.util.Date;
import java.util.StringTokenizer;
public class TimeStampUtil {
/**
* @return a string representation of current time
*/
/*public static String getTimeStamp(){
Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
int hourOfDay = cal.get(Calendar.HOUR_OF_DAY);
int minutes = cal.get(Calendar.MINUTE);
int seconds = cal.get(Calendar.SECOND);
return (new String(year+":"+month+":"+dayOfMonth+":"+hourOfDay+":"+minutes+":"+seconds));
}*/
/**
* @return current time in milliseconds in String format
* */
public static String getTimeStampMillisec(){
Calendar cal = Calendar.getInstance();
long time = cal.getTimeInMillis();
return Double.toString(time);
}
public static String computeElapsedTime(String timeMillisec, String currentTimeMillisec){
double timeOne = Double.parseDouble(timeMillisec);
double timeTwo = Double.parseDouble(currentTimeMillisec);
double elapsed = timeTwo-timeOne;
return Double.toString(elapsed);
}
/**
* Computes the time span between now and the provided timestamp
* @param initialTimeStamp
* @param currentTime
* @return
*/
public static String computeFullTimeSpan(String initialTimeStamp, Date currentTime){
Calendar cal = Calendar.getInstance();
cal.setTime(currentTime);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
int hourOfDay = cal.get(Calendar.HOUR_OF_DAY);
int minutes = cal.get(Calendar.MINUTE);
int seconds = cal.get(Calendar.SECOND);
//Obtain the data from the initialTimeStam string
StringTokenizer tokenizer = new StringTokenizer(initialTimeStamp);
Integer yearInit = new Integer(tokenizer.nextToken(":"));
Integer monthInit = new Integer(tokenizer.nextToken(":"));
Integer dayOfMonthInit = new Integer(tokenizer.nextToken(":"));
Integer hourOfDayInit = new Integer(tokenizer.nextToken(":"));
Integer minutesInit = new Integer(tokenizer.nextToken(":"));
Integer secondsInit = new Integer(tokenizer.nextToken(":"));
int yearSpan = year - yearInit;
int monthSpan = month - monthInit;
int dayOfMonthSpan = dayOfMonth - dayOfMonthInit;
int hourOfDaySpan = hourOfDay - hourOfDayInit;
int minutesSpan = minutes - minutesInit;
int secondsSpan = seconds - secondsInit;
return (new String(yearSpan+":"+monthSpan+":"+dayOfMonthSpan+":"+hourOfDaySpan+":"+minutesSpan+":"+secondsSpan));
}
}
|
package dnevnik;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import java.util.Stack;
import java.util.TreeSet;
import java.util.stream.Collectors;
public class Article {
private User author;
private String authorName;
private String title;
private String mainText;
// private Stack<Comment> comments;
private List<Integer> comments;
private Set<String> tags;
private Date dateAdded;
private int readCount;
private int articleID;
private static int idCounter = 0;
private static Set<String> allTags = new HashSet<String>();
public Article(User author, String title, String text, Set<String> tags) {
this.author = author;
this.title = title;
this.mainText = text;
if (tags != null ) {
this.tags = tags;
tags.forEach(tag -> allTags.add(tag));
}
readCount = 0;
dateAdded = Calendar.getInstance().getTime();
articleID = ++idCounter;
comments = new ArrayList<Integer>();
this.authorName = this.author.getUsername();
}
public Article(String author2, String title, String mainText, Set<String> tags) {
this.setAuthorName(author2);
this.title = title;
this.mainText = mainText;
this.tags = tags;
tags.forEach(tag -> allTags.add(tag));
readCount = 0;
dateAdded = Calendar.getInstance().getTime();
articleID = ++idCounter;
comments = new ArrayList<Integer>();
}
public void addComment(Comment comment) {
AllComments.addComment(comment);
this.comments.add(comment.getCommentID());
}
public void showComments() {
int commentNum = 0;
for (Integer comment : comments) {
System.out.print(++commentNum + ": ");
System.out.println(comment.toString());
}
}
public String getPreview() {
String articleToString = ("[" + articleID + "] " + title + " Added: " + dateAdded + " Read count: " + this.getReadCount() + " Comments: "+ this.getComments().size());
return articleToString+'\n';
}
public User getAuthor() {
return author;
}
public int getID() {
return articleID;
}
public String getTitle() {
return title;
}
public void setTitle(User user, String title) {
if (user.equals((User) this.getAuthor()))
this.title = title;
}
public String getMainText() {
return mainText;
}
public void setMainText(User user, String mainText) {
if (user.equals((User) this.getAuthor()))
this.mainText = mainText;
}
// Get comments from AllComments
public Stack<Comment> getComments() {
Stack<Comment> comments = new Stack<Comment>();
for (int commentID : this.comments) {
for (Comment comment : AllComments.getAllComments()) {
if (commentID == comment.getCommentID()) {
comments.push(comment);
}
}
}
return comments;
}
public List<Integer> getCommentsID() {
return new ArrayList<Integer>(this.comments);
}
public Comment getComment(int commentID) {
Comment findComment = null;
for (Comment comment : AllComments.getAllComments()) {
if (comment.getCommentID() == commentID) findComment = comment;
}
return findComment;
}
public Date getDateAdded() {
return dateAdded;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + articleID;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Article other = (Article) obj;
if (articleID != other.articleID)
return false;
return true;
}
public Set<String> getTags() {
//return new HashSet<String>(tags);
return this.tags;
}
@Override
public String toString() {
String articleToString = ("[" + articleID + "] " + title + "\nAuthor: " + author.getUsername() + "; Added: " + dateAdded + "\n" + mainText + "\nTags: " + tags);
return '\n' + articleToString + '\n';
}
public Set<Comment> sortCommentsByLikes() {
TreeSet<Comment> result = new TreeSet<Comment>(new Comparator<Comment>() {
@Override
public int compare(Comment o1, Comment o2) {
if(o1.getThumbsUp()==o2.getThumbsDown()) {
return 1;
}
return -(o1.getThumbsUp()-o2.getThumbsUp());
}
});
result.addAll(getComments());
return result;
}
public int getReadCount() {
return readCount;
}
public String getAuthorName() {
return authorName;
}
public void setAuthorName(String authorName) {
if (authorName!=null)
this.authorName = authorName;
}
public void setAuthor(User author) {
if (author!=null)
this.author = author;
}
public void setComments(int[] comments2 ) {
for (int i : comments2) {
this.comments.add(i);
}
}
public void setDateAdded(Date dateAdded) {
this.dateAdded = dateAdded;
}
public void setReadCount(int readCount) {
this.readCount = readCount;
}
public void setArticleID(int articleID) {
this.articleID = articleID;
}
public void showAllComments(int articleID) {
AllArticles.findByID(articleID).comments.forEach(comment -> System.out.println(comment.toString()));
}
}
|
/**
* Action id for lockedBy attribute of SalesOffice type
*/
package com.cnk.travelogix.mdmbackoffice.actions;
import de.hybris.platform.core.model.user.EmployeeModel;
import de.hybris.platform.servicelayer.user.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import com.cnk.travelogix.mdmbackoffice.services.LockUnlockService;
import com.hybris.backoffice.widgets.notificationarea.event.NotificationEvent;
import com.hybris.backoffice.widgets.notificationarea.event.NotificationUtils;
import com.hybris.cockpitng.actions.ActionContext;
import com.hybris.cockpitng.actions.ActionResult;
import com.hybris.cockpitng.actions.CockpitAction;
import com.hybris.cockpitng.core.impl.NotificationStack;
import com.hybris.cockpitng.dataaccess.facades.object.exceptions.ObjectSavingException;
import com.hybris.cockpitng.engine.impl.AbstractComponentWidgetAdapterAware;
import com.hybris.cockpitng.util.BackofficeSpringUtil;
public class EditAction extends AbstractComponentWidgetAdapterAware implements CockpitAction<Object, Object>
{
private static final Logger LOG = Logger.getLogger(EditAction.class);
public static final String SOCKET_INPUT = "selecedObjectforLock";
public static final String SOCKET_OUTPUT = "selecedObjectafterLock";
public LockUnlockService getLockUnlockService()
{
return (LockUnlockService) BackofficeSpringUtil.getBean("lockUnlockService");
}
public NotificationStack getNotificationStack()
{
return (NotificationStack) BackofficeSpringUtil.getBean("notificationStack");
}
public UserService getUserFacade()
{
return (UserService) BackofficeSpringUtil.getBean("userService");
}
@Override
public ActionResult perform(final ActionContext ctx)
{
final Object data = ctx.getData();
try
{
final EmployeeModel user = (EmployeeModel) getUserFacade().getCurrentUser();
getLockUnlockService().lock(data, user);
}
catch (final ObjectSavingException e)
{
LOG.error(e);
showFailureNotification(data);
return new ActionResult(ActionResult.ERROR);
}
final ActionResult result = new ActionResult(ActionResult.SUCCESS);
result.setData(data);
showSuccessNotification("This Record is locked for editing");
sendConfiguredOutput(data);
return result;
}
protected void showSuccessNotification(final String successMessage)
{
if (!(StringUtils.isNotEmpty(successMessage)))
{
return;
}
final String id = getNotificationStack().getFailId();
final NotificationEvent.Type type = NotificationEvent.Type.SUCCESS;
NotificationUtils.notifyUserVia(successMessage, type, id, new Object[]
{ type });
}
protected void showFailureNotification(final Object object)
{
final NotificationEvent.Type type = NotificationEvent.Type.FAILURE;
NotificationUtils.notifyUserVia("Failed to Lock", type, getNotificationStack().getFailId(), new Object[]
{ object });
}
protected void sendConfiguredOutput(final Object newInstance)
{
this.sendOutput(SOCKET_OUTPUT, newInstance);
}
@Override
public void initializeDefaultEventListeners()
{
this.addSocketInputEventListener(SOCKET_OUTPUT, event -> this.sendOutput(SOCKET_OUTPUT, event.getData()));
}
@Override
public boolean canPerform(final ActionContext ctx)
{
return getLockUnlockService().canLock(ctx.getData());
}
@Override
public boolean needsConfirmation(final ActionContext ctx)
{
return false;
}
@Override
public String getConfirmationMessage(final ActionContext ctx)
{
return "Are you sure?";
}
}
|
package com.tencent.mm.plugin.appbrand.jsapi.a;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
class c$7 implements OnClickListener {
final /* synthetic */ c fKg;
c$7(c cVar) {
this.fKg = cVar;
}
public final void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
this.fKg.fJQ.E(this.fKg.fFd, this.fKg.f("fail", null));
}
}
|
package app.home;
import com.hqb.patshop.PatshopApplication;
import com.hqb.patshop.app.home.service.ActivityService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {PatshopApplication.class})
public class ActivityTest {
@Autowired
ActivityService activityService;
@Test
public void testActivityContent(){
System.out.println(activityService.getSignInModel("18378583473"));
}
@Test
public void testSignIn(){
System.out.println(activityService.getSignInModel("18378583473"));
}
}
|
package com.yuan.graduate;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMap.InfoWindowAdapter;
import com.amap.api.maps.AMap.OnCameraChangeListener;
import com.amap.api.maps.AMap.OnInfoWindowClickListener;
import com.amap.api.maps.AMap.OnMapLoadedListener;
import com.amap.api.maps.AMap.OnMarkerClickListener;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.MapsInitializer;
import com.amap.api.maps.Projection;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.Circle;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.offlinemap.OfflineMapCity;
import com.amap.api.maps.offlinemap.OfflineMapManager;
import com.amap.api.maps.offlinemap.OfflineMapManager.OfflineMapDownloadListener;
import com.amap.api.maps.offlinemap.OfflineMapStatus;
import com.yuan.adapt.AdaptListUtils;
import com.yuan.adapt.CommAdapt;
import com.yuan.application.BaseActivity;
import com.yuan.control.CheckControl;
import com.yuan.control.SettingControl;
import com.yuan.dialog.CustomDialog;
import com.yuan.dialog.CustomProgressDialog;
import com.yuan.dialog.DialogUtil;
import com.yuan.localServer.LocalManage;
import com.yuan.model.M员工信息表;
import com.yuan.model.M请假申请;
import com.yuan.prefence.FileConstants;
import com.yuan.unit.FileUtils;
import com.yuan.unit.ImageUtils;
import com.yuan.unit.NetUtils;
import com.yuan.unit.PreferenceUtil;
import com.yuan.unit.TimeUtils;
import com.yuan.unit.ToastHelper;
import com.yuan.view.Commhead;
import com.yuan.view.NetImageView;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Point;
import android.location.Location;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.text.SpannableString;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.view.animation.BounceInterpolator;
import android.view.animation.Interpolator;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 主界面 MAP MENU
*
* @author YUAN
*/
@SuppressLint("HandlerLeak")
public class MainActivity extends BaseActivity implements OnMarkerClickListener,
OnInfoWindowClickListener, OnCameraChangeListener, OnMapLoadedListener, OnClickListener,
InfoWindowAdapter, OnCheckedChangeListener, OfflineMapDownloadListener,
LocationSource, AMapLocationListener {
private MapView mapView = null;
private AMap aMap = null;
private Context mContext = null;
private TextView t_realname = null, t_team = null;
private Commhead main_head;
private ListView menu_list = null;
private ImageButton mapcheck_checkin_btn = null, mapcheck_checkout_btn = null;
private LinearLayout menu_layout = null;
private RelativeLayout main_view = null;
private UiSettings mUiSettings = null;
private LocationManagerProxy mLocationManagerProxy = null;
private TextView menu_space = null;
private CustomProgressDialog progessdialog = null, loadMapprogessdialog = null;
private OfflineMapManager mOfflineMapManager = null;// 离线地图下载控制器
private MarkerOptions markerOption = null;
private Marker marker;// 有跳动效果的marker对象
private OnLocationChangedListener mOnLocationChangedListener;
private Adapter listItemAdapter = null;
private List<?> listItemAdapterList = null;
private NetImageView menu_photo = null;
private static boolean ISCHECKIN = true;// 上班为true 下班为false
private static boolean ISCHECKINING = false;
private boolean isShowMenu = false, isFirstLocation = true;
private LatLng latlngpoint = null;
private static final int IMAGE_REQUEST_CODE = 0;
private static final int CAMERA_REQUEST_CODE = 1;
private static final int RESULT_REQUEST_CODE = 2;
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {// 此方法在ui线程运行
switch (msg.what) {
case NOCHECKINADRESS:
progessdialog = new CustomProgressDialog(mContext);
progessdialog.setUpdateMsg(R.string.locationing);
progessdialog.show();
break;
case NOCHECKOUTADRESS:
progessdialog = new CustomProgressDialog(mContext);
progessdialog.setUpdateMsg(R.string.locationing);
progessdialog.show();
break;
case LOCATIONSUCCEEDIN:
DialogUtil.createCheckInDialog(mContext, mHandler).show();
ISCHECKINING = false;
break;
case LOCATIONSUCCEEDOUT:
DialogUtil.createCheckOutDialog(mContext, mHandler).show();
ISCHECKINING = false;
break;
case CHECKINSUCCEED:
if (progessdialog != null && progessdialog.isShowing()) {
progessdialog.dismiss();
progessdialog = null;
}
ToastHelper.getInstance().shortToast(mContext, "上班打卡成功");
RefreshButton();
break;
case CHECKINFILED:
if (progessdialog != null && progessdialog.isShowing()) {
progessdialog.dismiss();
progessdialog = null;
}
ToastHelper.getInstance().shortToast(mContext, "上班打卡失败");
break;
case LOADMAP:
LoadOfflineMap();
break;
case CHECKOUTSUCCEED:
if (progessdialog != null && progessdialog.isShowing()) {
progessdialog.dismiss();
progessdialog = null;
}
ToastHelper.getInstance().shortToast(mContext, "下班打卡成功");
RefreshButton();
break;
case CHECKOUTFILED:
if (progessdialog != null && progessdialog.isShowing()) {
progessdialog.dismiss();
progessdialog = null;
}
ToastHelper.getInstance().shortToast(mContext, "下班打卡失败");
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapView = (MapView) findViewById(R.id.map_view);
mapView.onCreate(savedInstanceState);// 必须要写
mContext = this;
init();
initSlidingMenu();
initOfflineMap();
startService(new Intent(SERVER_NAME.LOCAL_SERVER));
}
private void LoadOfflineMap() {
String city = PreferenceUtil.getInstance().getString(USER_CITY, null);
city = city.replace("市", "");
boolean flagSuccedToLoadMap = false;
try {
flagSuccedToLoadMap = mOfflineMapManager.downloadByCityName(city);
} catch (com.amap.api.maps.AMapException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (flagSuccedToLoadMap)
{
loadMapprogessdialog = new CustomProgressDialog(mContext);
loadMapprogessdialog.setUpdateMsg(R.string.start_load_offline_map);
loadMapprogessdialog.show();
}
}
/**
* 离线地图具体实现
*/
private void initOfflineMap() {
// TODO Auto-generated method stub
// 设置应用单独的地图存储目录,在下载离线地图或初始化地图时设置
MapsInitializer.sdcardDir = FileUtils.getSdCacheMapDir(this);
mOfflineMapManager = new OfflineMapManager(this, this);
if (!NetUtils.isWifiConnected(mContext))
return;
try
{
boolean agreeToLoadMap = PreferenceUtil.getInstance().getBoolean(AGREEN_TO_LOAD_MAP,
true);
if (!agreeToLoadMap)
return;
} catch (Exception e)
{
e.printStackTrace();
}
String city = PreferenceUtil.getInstance().getString(USER_CITY, null);
if (city == null || city.length() < 1 || city.equals("null"))
return;
boolean isHadOfflineMap = PreferenceUtil.getInstance().getBoolean(HAD_OFFLINE_MAP, false);
if (isHadOfflineMap)
return;
List<OfflineMapCity> list = mOfflineMapManager.getDownloadOfflineMapCityList();
for (OfflineMapCity mapcity : list)
{
if (city.startsWith(mapcity.getCity()) || mapcity.getCity().equals(city))
{
PreferenceUtil.getInstance().putString(USER_CITY, city);
PreferenceUtil.getInstance().putBoolean(HAD_OFFLINE_MAP, true);
return;
}
}
DialogUtil.createOffLineMapDialog(mContext, mHandler, city).show();
}
/**
* 对侧边的选项栏进行初始化隐藏
*/
private void initSlidingMenu() {
menu_layout = (LinearLayout) findViewById(R.id.menu_layout);
t_realname = (TextView) findViewById(R.id.t_realname);
t_team = (TextView) findViewById(R.id.t_team);
menu_space = (TextView) findViewById(R.id.menu_space);
menu_photo = (NetImageView) findViewById(R.id.menu_photo);
menu_space.setOnClickListener(this);
String realname = M员工信息表.getInstance().get姓名();
String team = M员工信息表.getInstance().get所属队室();
M请假申请.getInstance().set申请人(M员工信息表.getInstance().get序号() + "");
if (!TextUtils.isEmpty(realname))
{
t_realname.setText(realname);
}
if (!TextUtils.isEmpty(team))
{
t_team.setText(team);
}
menu_photo.setImageUrl(M员工信息表.getInstance().get照片());
initPhotodialog();
}
private void initPhotodialog() {
// TODO Auto-generated method stub
final CustomDialog dialog = new CustomDialog(mContext);
final ListView mPhotolistview = new ListView(mContext);
Adapter listItemAdapter = new CommAdapt(mContext, createPhotoChoiceList(), "type");
mPhotolistview.setAdapter((ListAdapter) listItemAdapter);
mPhotolistview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
switch (position) {
case 0:
Intent intentFromCapture = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
intentFromCapture.putExtra(
MediaStore.EXTRA_OUTPUT,
Uri.fromFile(new File(FileConstants.USER_IMAGE)));
startActivityForResult(intentFromCapture,
CAMERA_REQUEST_CODE);
break;
case 1:
Intent intentFromGallery = new Intent();
intentFromGallery.setType("image/*"); // 设置文件类型
intentFromGallery
.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intentFromGallery, IMAGE_REQUEST_CODE);
break;
}
if (dialog != null && dialog.isShowing())
{
dialog.dismiss();
}
}
});
dialog.setTitle(R.string.choice_photo_type);
dialog.addContentView(mPhotolistview);
dialog.setNeutralButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
menu_photo.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.show();
}
});
}
@SuppressWarnings({
"rawtypes", "unchecked"
})
private List createPhotoChoiceList() {
// TODO Auto-generated method stub
List list = new ArrayList();
Map map = null;
map = new HashMap();
map.put("type", "拍照");
list.add(map);
map = new HashMap();
map.put("type", "从文件中选择");
list.add(map);
return list;
}
/**
* 初始化AMap对象
*/
private void init() {
if (aMap == null) {
aMap = mapView.getMap();
}
mUiSettings = aMap.getUiSettings();
aMap.setOnCameraChangeListener(this);// 对amap添加移动地图事件监听器
mUiSettings.setZoomGesturesEnabled(true);
mUiSettings.setScrollGesturesEnabled(true);
mUiSettings.setCompassEnabled(true);
mUiSettings.setZoomControlsEnabled(true);
mUiSettings.setScaleControlsEnabled(true);
aMap.setOnMapLoadedListener(this);// 设置amap加载成功事件监听器
aMap.setOnMarkerClickListener(this);// 设置点击marker事件监听器
aMap.setOnInfoWindowClickListener(this);// 设置点击infoWindow事件监听器
aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式
mUiSettings.setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_LEFT);// 设置地图logo显示在底部居中
isFirstLocation = true;
aMap.setLocationSource((LocationSource) this);// 设置定位监听
mUiSettings.setMyLocationButtonEnabled(true); // 是否显示默认的定位按钮
aMap.setMyLocationEnabled(true);// 是否可触发定位并显示定位层
main_view = (RelativeLayout) findViewById(R.id.main_view);
main_head = (Commhead) findViewById(R.id.main_head);
main_head.setLeftIcon(R.drawable.menu);
main_head.setLeftOnClickListener(this);
mapcheck_checkin_btn = (ImageButton) findViewById(R.id.mapcheck_checkin_btn);
mapcheck_checkout_btn = (ImageButton) findViewById(R.id.mapcheck_checkout_btn);
mapcheck_checkin_btn.setOnClickListener(this);
mapcheck_checkout_btn.setOnClickListener(this);
}
public void RefreshButton() {
if (CheckControl.isCheckedInToday()) {
mapcheck_checkin_btn
.setBackgroundResource(R.drawable.mapcheck_checkin_gray_btn_x);
} else {
mapcheck_checkin_btn
.setBackgroundResource(R.drawable.mapcheck_checkin_blue_btn_x);
}
if (CheckControl.isCheckedOutToday()) {
mapcheck_checkout_btn
.setBackgroundResource(R.drawable.mapcheck_checkout_gray_btn_x);
} else {
mapcheck_checkout_btn
.setBackgroundResource(R.drawable.mapcheck_checkout_blue_btn_x);
}
}
/**
* 方法必须重写
*/
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
RefreshButton();
if (listItemAdapter != null)
{
((BaseAdapter) listItemAdapter).notifyDataSetChanged();
}
updateSlidingMenu();
}
private void updateSlidingMenu() {
// TODO Auto-generated method stub
listItemAdapterList = AdaptListUtils.getInstance().getMenuList();
menu_list = (ListView) findViewById(R.id.menu_list);
listItemAdapter = new CommAdapt(mContext, listItemAdapterList, "title");
menu_list.setAdapter((ListAdapter) listItemAdapter);
menu_list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
switch (position) {
case 0:
// 显示地图
closeMenu();
break;
case 1:
startActivity(new Intent(mContext, LeaveActivity.class));
break;
case 2:
startActivity(new Intent(mContext, CheckActivity.class));
break;
case 3:
startActivity(new Intent(mContext, SeeLeaveActivity.class));
break;
case 4:
startActivity(new Intent(mContext, TrailActivity.class));
break;
case 5:
startActivity(new Intent(mContext, NoticeActivity.class).putExtra("type",
"send"));
break;
case 6:
startActivity(new Intent(mContext, NoticeListActivity.class));
break;
case 7:
startActivity(new Intent(mContext, ChangePsdActivity.class));
break;
case 8:
startActivity(new Intent(mContext, MainSettingActivity.class));
break;
case 9:
// 启动分享界面
DialogUtil.createFullAppShareDialog(mContext).show();
break;
case 10:
startActivity(new Intent(mContext, AboutActivity.class));
break;
case 11:
// 退出到登陆界面
startActivity(new Intent(mContext, LoginActivity.class));
break;
}
}
});
}
/**
* 方法必须重写
*/
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
deactivate();
// stopService(new Intent(SERVER_NAME.LOCAL_SERVER));
}
/**
* 方法必须重写
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
outState.putBoolean("isShowMenu", isShowMenu);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
boolean flag = savedInstanceState.getBoolean("isShowMenu", false);
if (flag) {
showMenu();
}
}
/**
* 方法必须重写
*/
@Override
protected void onDestroy() {
mapView.onDestroy();
super.onDestroy();
}
@Override
public void onCameraChange(CameraPosition arg0) {
// TODO Auto-generated method stub
}
@Override
public void onCameraChangeFinish(CameraPosition arg0) {
// TODO Auto-generated method stub
}
@Override
public void onMyDestroy() {
mapView.onDestroy();
super.onMyDestroy();
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.menu_space:
closeMenu();
break;
case R.id.back:
showMenu();
break;
case R.id.mapcheck_checkin_btn:
ISCHECKINING = true;
if (LocalManage.getInstance().adress == null
|| LocalManage.getInstance().adress.length() < 1) {
ISCHECKIN = true;
mHandler.sendEmptyMessage(NOCHECKINADRESS);
} else {
mHandler.sendEmptyMessage(LOCATIONSUCCEEDIN);
}
break;
case R.id.mapcheck_checkout_btn:
if (!CheckControl.isCheckedInToday()) {
ToastHelper.getInstance().shortToast(mContext, "上班还没有签到!");
return;
}
ISCHECKINING = true;
if (LocalManage.getInstance().adress == null
|| LocalManage.getInstance().adress.length() < 1) {
ISCHECKIN = false;
mHandler.sendEmptyMessage(NOCHECKOUTADRESS);
} else {
mHandler.sendEmptyMessage(LOCATIONSUCCEEDOUT);
}
break;
default:
break;
}
}
/**
* 显示侧部Menu 并加载相应的动画
*/
private void showMenu() {
// TODO Auto-generated method stub
menu_layout.startAnimation(AnimationUtils.loadAnimation(this,
R.anim.page_in_left_right));
menu_layout.setBackgroundResource(R.drawable.bg);
menu_layout.setVisibility(View.VISIBLE);
menu_layout.setClickable(true);
menu_space.setClickable(true);
main_view.setClickable(false);
mapView.setClickable(false);
mapcheck_checkin_btn.setClickable(false);
mapcheck_checkout_btn.setClickable(false);
isShowMenu = true;
ToastHelper.getInstance().shortToast(mContext, "按返回键返回值主界面");
}
/**
* 关闭侧部Menu 并加载相应的动画
*/
private void closeMenu() {
// TODO Auto-generated method stub
menu_layout.startAnimation(AnimationUtils.loadAnimation(this,
R.anim.page_out_right_left));
menu_layout.setVisibility(View.GONE);
menu_layout.setClickable(false);
menu_space.setClickable(false);
main_view.setClickable(true);
mapcheck_checkin_btn.setClickable(true);
mapcheck_checkout_btn.setClickable(true);
mapView.setClickable(true);
isShowMenu = false;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (isShowMenu && keyCode == KeyEvent.KEYCODE_BACK) {
closeMenu();
return true;
}
if (!isShowMenu && keyCode == KeyEvent.KEYCODE_BACK) {
startActivity(new Intent(mContext, LoginActivity.class));
finish();
return true;
}
if (keyCode == KeyEvent.KEYCODE_MENU && !isShowMenu) {
showMenu();
return true;
}
if (keyCode == KeyEvent.KEYCODE_MENU && isShowMenu) {
closeMenu();
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
}
public void onDownload(int status, int completeCode, String downName) {
switch (status) {
case OfflineMapStatus.SUCCESS:
loadMapprogessdialog.setUpdateMsg(R.string.load_offline_map_succeed);
if (loadMapprogessdialog != null)
{
loadMapprogessdialog.dismiss();
}
break;
case OfflineMapStatus.LOADING:
if (completeCode == 100)
{
loadMapprogessdialog.setUpdateMsg(R.string.load_offline_map_unzip);
} else {
String tempstr = String.format(
mContext.getResources().getString(R.string.load_offline_map_progress),
(completeCode + "%"));
loadMapprogessdialog.setUpdateMsg(tempstr);
}
break;
case OfflineMapStatus.UNZIP:
loadMapprogessdialog.setUpdateMsg(R.string.load_offline_map_unzip);
break;
case OfflineMapStatus.WAITING:
break;
case OfflineMapStatus.PAUSE:
break;
case OfflineMapStatus.STOP:
break;
case OfflineMapStatus.ERROR:
loadMapprogessdialog.setUpdateMsg(R.string.load_offline_map_failed);
if (loadMapprogessdialog != null)
{
loadMapprogessdialog.dismiss();
}
break;
default:
break;
}
}
private void updateMap() {
// TODO Auto-generated method stub
aMap.clear();
double lat = Double.parseDouble(SettingControl.getWorkLat());
double lng = Double.parseDouble(SettingControl.getWorkLng());
if (Math.abs(lng) > 0.0 && Math.abs(lat) > 0.0)
{
LatLng point = new LatLng(lat, lng);
Circle circle = aMap.addCircle(new CircleOptions().center(point)
.radius(400).strokeColor(Color.BLUE).fillColor(Color.TRANSPARENT)
.strokeWidth(3));
int prevColor = circle.getFillColor();
circle.setFillColor(Color.argb(30, Color.red(prevColor),
Color.green(prevColor), Color.blue(prevColor)));
}
markerOption = new MarkerOptions();
markerOption.position(latlngpoint);
markerOption.title("当前时间:" + TimeUtils.getNowTime()).snippet(
"当前地点:" + LocalManage.getInstance().adress);
markerOption.perspective(true);
markerOption.draggable(true);
markerOption.icon(BitmapDescriptorFactory
.fromResource(R.drawable.arrow));
marker = aMap.addMarker(markerOption);
}
@Override
public boolean onMarkerClick(final Marker marker) {
if (marker.equals(marker)) {
if (aMap != null) {
jumpPoint(marker);
}
}
return false;
}
/**
* marker点击时跳动一下
*/
public void jumpPoint(final Marker marker) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
Projection proj = aMap.getProjection();
Point startPoint = proj.toScreenLocation(latlngpoint);
startPoint.offset(0, -100);
final LatLng startLatLng = proj.fromScreenLocation(startPoint);
final long duration = 1500;
final Interpolator interpolator = new BounceInterpolator();
handler.post(new Runnable() {
@Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float) elapsed
/ duration);
double lng = t * latlngpoint.longitude + (1 - t)
* startLatLng.longitude;
double lat = t * latlngpoint.latitude + (1 - t)
* startLatLng.latitude;
marker.setPosition(new LatLng(lat, lng));
if (t < 1.0) {
handler.postDelayed(this, 16);
}
}
});
}
@Override
public View getInfoContents(Marker arg0) {
View infoContent = getLayoutInflater().inflate(
R.layout.custom_dialog_contents, null);
render(marker, infoContent);
return infoContent;
}
/**
* 自定义infowinfow窗口
*/
public void render(Marker marker, View view) {
String title = marker.getTitle();
TextView titleUi = ((TextView) view.findViewById(R.id.title));
if (title != null) {
SpannableString titleText = new SpannableString(title);
titleUi.setText(titleText);
} else {
titleUi.setText("");
}
String snippet = marker.getSnippet();
TextView snippetUi = ((TextView) view.findViewById(R.id.snippet));
if (snippet != null) {
SpannableString snippetText = new SpannableString(snippet);
snippetUi.setText(snippetText);
} else {
snippetUi.setText("");
}
}
@Override
public View getInfoWindow(Marker arg0) {
View infoContent = getLayoutInflater().inflate(
R.layout.custom_dialog_contents, null);
render(marker, infoContent);
return infoContent;
}
@Override
public void onMapLoaded() {
}
@Override
public void onInfoWindowClick(Marker arg0) {
// TODO Auto-generated method stub
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onLocationChanged(AMapLocation aLocation) {
// TODO Auto-generated method stub
if (mOnLocationChangedListener != null) {
mOnLocationChangedListener.onLocationChanged(aLocation);// 显示系统小蓝点
Bundle locBundle = aLocation.getExtras();
LocalManage.getInstance().adress = locBundle.getString("desc");
if (ISCHECKINING) {
if (ISCHECKIN) {
mHandler.sendEmptyMessage(LOCATIONSUCCEEDIN);
}
else {
mHandler.sendEmptyMessage(LOCATIONSUCCEEDOUT);
}
}
double lng = aLocation.getLongitude();
double lat = aLocation.getLatitude();
LocalManage.getInstance().lat = lat;
LocalManage.getInstance().lng = lng;
latlngpoint = new LatLng(lat, lng);
if (isFirstLocation) {
CameraUpdate cameraupdate = CameraUpdateFactory.newLatLngZoom(
latlngpoint, ZOOM);// 使用工厂模式射程位移动画
aMap.animateCamera(cameraupdate);
isFirstLocation = false;
}
updateMap();
}
}
@Override
public void activate(OnLocationChangedListener listener) {
mOnLocationChangedListener = listener;
if (mLocationManagerProxy == null) {
mLocationManagerProxy = LocationManagerProxy.getInstance(this);
mLocationManagerProxy.requestLocationUpdates(
LocationProviderProxy.AMapNetwork, 5000, 10, this);
}
}
/**
* 停止定位
*/
@Override
public void deactivate() {
mOnLocationChangedListener = null;
if (mLocationManagerProxy != null) {
mLocationManagerProxy.removeUpdates(this);
mLocationManagerProxy.destory();
}
mLocationManagerProxy = null;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case IMAGE_REQUEST_CODE:
try
{
startPhotoZoom(data.getData());
} catch (NullPointerException e)
{// 没有选择照片
e.printStackTrace();
}
break;
case CAMERA_REQUEST_CODE:
File tempFile = new File(FileConstants.USER_IMAGE);
startPhotoZoom(Uri.fromFile(tempFile));
break;
case RESULT_REQUEST_CODE:
if (data != null) {
getImageToView(data);
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
}
public void startPhotoZoom(Uri uri) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
// 设置裁剪
intent.putExtra("crop", "true");
// aspectX aspectY 是宽高的比例
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
// outputX outputY 是裁剪图片宽高
intent.putExtra("outputX", 320);
intent.putExtra("outputY", 320);
intent.putExtra("return-data", true);
startActivityForResult(intent, 2);
}
/**
* 保存裁剪之后的图片数据
*
* @param picdata
*/
private void getImageToView(Intent data) {
Bundle extras = data.getExtras();
if (extras != null) {
final Bitmap photo = extras.getParcelable("data");
menu_photo.setImageBitmap(photo);
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
if (FileUtils.isFileExist(FileConstants.USER_IMAGE))
{
FileUtils.deleteFile(FileConstants.USER_IMAGE);
}
ImageUtils.saveBitmapToFileSystem(mContext, LOCAL_PATH_IMAGES, "user.png",
photo);
M员工信息表.getInstance().uploadPhoto(mContext);
return null;
}
}.execute();
}
}
}
|
package com.graduation.yearbook.Compoment.view.service;
import android.app.IntentService;
import android.content.Intent;
/**
* Created by hanwe on 15/10/20.
*/
public class FunctionIntentService extends IntentService
{
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
public FunctionIntentService(String name)
{
super(name);
}
@Override
protected void onHandleIntent(Intent intent)
{
}
}
|
package com.vilio.fms.fileLoad.controller;
import com.vilio.fms.fileLoad.service.FileDownloadService;
import com.vilio.fms.util.CommonUtil;
import com.vilio.fms.util.Fields;
import com.vilio.fms.util.ZipUtil;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by dell on 2017/5/17.
*/
@Controller("fileDownloadController")
public class FileDownloadController {
private static Logger logger = Logger.getLogger(FileDownloadController.class);
@Resource
FileDownloadService fileDownloadService;
@RequestMapping(value = "/api/fileLoad/getFile",method = RequestMethod.GET)
public void getFile(HttpServletResponse rsp, HttpServletRequest rqs) throws Exception{
logger.info("获取文件(FileDownloadController.getFile)被调用开始,入参:" + "" );
String serialNo = rqs.getParameter("serialNo");
Map result = null;
Map param = new HashMap();
param.put("serialNo",serialNo);
try {
CommonUtil.dealEmpty2Null(param);
result = fileDownloadService.getFile(param);
}catch (Exception e){
logger.error("系统异常:",e);
}
Map body = (Map) result.get("body");
String fileName = (String) body.get("fileName");
rsp.setContentType("application/x-msdownload");
String iso_filename = new String(fileName.getBytes("GBK"), "ISO-8859-1");
rsp.setHeader("Content-Disposition",
"attachment;filename=" + iso_filename);
OutputStream outputStream = rsp.getOutputStream();
InputStream in = (InputStream)result.get("is");
int len=0;
byte[]buf=new byte[1024];
while((len=in.read(buf,0,1024))!=-1){
outputStream.write(buf, 0, len);
}
outputStream.close();
logger.info("获取文件(FileDownloadController.getFile)被调用结束,输出结果:" );
}
@RequestMapping(value = "/api/fileLoad/getFileZip",method = RequestMethod.POST)
public void getFileZip(HttpServletResponse rsp, HttpServletRequest rqs) throws Exception{
// 读取请求内容
BufferedReader br = new BufferedReader(new InputStreamReader(rqs.getInputStream(),"utf-8"));
logger.info("获取文件(FileDownloadController.getFile)被调用开始,入:" + br);
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null){
sb.append(line);
}
logger.info("获取文件(FileDownloadController.getFile)被调用开始,入参:" + sb );
//将json字符串转换为json对象
JSONObject json = JSONObject.fromObject(sb.toString());
Object serialNoList = json.get("serialNoList");
Map result = null;
Map param = new HashMap();
param.put("serialNoList",serialNoList);
try {
CommonUtil.dealEmpty2Null(param);
result = fileDownloadService.getFileZip(param);
}catch (Exception e){
logger.error("系统异常:",e);
}
Map body = (Map) result.get("body");
String fileName = (String) body.get("fileName");
rsp.setContentType("application/x-msdownload");
String iso_filename = new String(fileName.getBytes("GBK"), "ISO-8859-1");
rsp.setHeader("Content-Disposition",
"attachment;filename=" + iso_filename + ".zip");
OutputStream outputStream = rsp.getOutputStream();
InputStream in = (InputStream)result.get("is");
int len=0;
byte[]buf=new byte[1024];
while((len=in.read(buf,0,1024))!=-1){
outputStream.write(buf, 0, len);
}
outputStream.close();
//上传后删除本地生成文件
boolean flag = ZipUtil.deleteZipFile(iso_filename ,in);
logger.info("获取文件(FileDownloadController.getFile)被调用结束,输出结果:" + flag);
}
@RequestMapping(value = "/api/fileLoad/getUrlList",method = RequestMethod.POST)
@ResponseBody
public Map getUrlList(@RequestBody Map paramMap) throws Exception{
logger.info("获取文件地址(FileDownloadController.getUrlList)被调用开始,入参:" + "" );
Map result = new HashMap();
Map<String, Object> headMap = new HashMap<String, Object>();
Map<String, Object> bodyMap = new HashMap<String, Object>();
Map param = new HashMap();
try {
headMap = (Map<String, Object>) paramMap.get(Fields.PARAM_MESSAGE_HEAD);
bodyMap = (Map<String, Object>) paramMap.get(Fields.PARAM_MESSAGE_BODY);
CommonUtil.dealEmpty2Null(bodyMap);
bodyMap = fileDownloadService.getUrlList(bodyMap);
}catch (Exception e){
logger.error("系统异常:",e);
}
result.put(Fields.PARAM_MESSAGE_HEAD, headMap);
result.put(Fields.PARAM_MESSAGE_BODY, bodyMap.get(Fields.PARAM_MESSAGE_BODY));
logger.info("获取文件地址(FileDownloadController.getUrlList)被调用结束,输出结果:" );
return result;
}
}
|
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
/**
*
* @author Yuwono Bangun Nagoro
*/
class AnagramCounting {
static BigInteger factorial(BigInteger n)
{
if(n.compareTo(BigInteger.valueOf(1))==0){return BigInteger.valueOf(1);}
else{return n.multiply(factorial(n.subtract(BigInteger.valueOf(1))));}
}
static String solve(String sin)
{
HashMap hm=new HashMap();
for(int x=0;x<sin.length();++x)
{
if(hm.containsKey(sin.substring(x,x+1)))
{
int ctr=(int) hm.get(sin.substring(x,x+1));
hm.put(sin.substring(x,x+1), new Integer(ctr+1));
}
else{hm.put(sin.substring(x, x+1), new Integer(1));}
}
BigInteger lengthin=factorial(BigInteger.valueOf(sin.length()));
BigInteger siji=BigInteger.valueOf(1);
Set set = hm.entrySet();
Iterator i = set.iterator();
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
siji=siji.multiply(factorial(BigInteger.valueOf((int) me.getValue())));
}
lengthin=lengthin.divide(siji);
return lengthin.toString();
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner scan = new Scanner(System.in);
try
{
while (scan.hasNextLine())
{
String line = scan.nextLine();
System.out.println(solve(line));
}
}
finally
{
if (scan != null)
{scan.close();}
}
}
}
|
package com.freejavaman;
import java.util.ArrayList;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds;
import android.provider.ContactsContract.CommonDataKinds.GroupMembership;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Data;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class ContactMgr extends Activity {
EditText nameEdit, telEdit;
Button insertBtn, delBtn, updateBtn, queryBtn;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//連絡人的姓名與電話欄位
nameEdit = (EditText)this.findViewById(R.id.nameEdit);
telEdit = (EditText)this.findViewById(R.id.telEdit);
//取得新增、刪除、修改、查詢按鈕之物件實體
insertBtn = (Button)this.findViewById(R.id.btn1);
delBtn = (Button)this.findViewById(R.id.btn2);
updateBtn = (Button)this.findViewById(R.id.btn3);
queryBtn = (Button)this.findViewById(R.id.btn4);
//委任點選按鈕的事件
insertBtn.setOnClickListener(new OnClickListener(){
public void onClick(View view) {
doInsert();
}
});
delBtn.setOnClickListener(new OnClickListener(){
public void onClick(View view) {
doDelete();
}
});
updateBtn.setOnClickListener(new OnClickListener(){
public void onClick(View view) {
doUpdate();
}
});
queryBtn.setOnClickListener(new OnClickListener(){
public void onClick(View view) {
doQuery();
}
});
}
//新增聯絡人資料
private void doInsert() {
//取得提供聯絡人資料的ContentProvider
ContentResolver cResolver = this.getContentResolver();
Uri rawURI = ContactsContract.RawContacts.CONTENT_URI;
Uri dataURI = ContactsContract.Data.CONTENT_URI;
Log.v("content", "insert Root Raw URI:" + rawURI.toString());
Log.v("content", "insert Root Data URI:" + dataURI.toString());
ContentValues values = new ContentValues();
values.put(ContactsContract.RawContacts.ACCOUNT_TYPE, "tester@test.com");
values.put(ContactsContract.RawContacts.ACCOUNT_NAME, "com.test");
Uri dataUri = cResolver.insert(rawURI, values);
Log.v("content", "insert Raw URI:" + dataUri.toString());
long id = ContentUris.parseId(dataUri);
Log.v("content", "insert id:" + id);
//設定群組
values.clear();
values.put(ContactsContract.Data.RAW_CONTACT_ID, id);
values.put(ContactsContract.Data.MIMETYPE, GroupMembership.CONTENT_ITEM_TYPE);
values.put(GroupMembership.GROUP_ROW_ID, 11);
dataUri = cResolver.insert(dataURI, values);
Log.v("content", "insert Data(0) URI:" + dataUri.toString());
//設定聯絡資料顯示名稱
values.clear();
values.put(ContactsContract.Data.RAW_CONTACT_ID, id);
values.put(ContactsContract.Data.MIMETYPE, CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
values.put(CommonDataKinds.StructuredName.DISPLAY_NAME, nameEdit.getText().toString());
dataUri = cResolver.insert(dataURI, values);
Log.v("content", "insert Data(1) URI:" + dataUri.toString());
//設定聯絡人電話
values.clear();
values.put(ContactsContract.Data.RAW_CONTACT_ID, id);
values.put(ContactsContract.Data.MIMETYPE, CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
values.put(CommonDataKinds.Phone.NUMBER, telEdit.getText().toString());
values.put(CommonDataKinds.Phone.TYPE, CommonDataKinds.Phone.TYPE_MOBILE);
dataUri = cResolver.insert(dataURI, values);
Log.v("content", "insert Data(2) URI:" + dataUri.toString());
//清除輸入框
nameEdit.setText("");
telEdit.setText("");
Log.v("content", "insert done");
}
//刪除聯絡人資料
private void doDelete() {
//取得提供聯絡人資料的ContentProvider
ContentResolver cResolver = this.getContentResolver();
//Uri contactURI = ContactsContract.Contacts.CONTENT_URI;
Uri rawURI = ContactsContract.RawContacts.CONTENT_URI;
String name = nameEdit.getText().toString();
if (name != null && !name.equals("")) {
//根據指定的名字執行刪除
String whereClause = ContactsContract.Data.DISPLAY_NAME + "=?";
String[] whereArgs = {nameEdit.getText().toString()};
int rows = cResolver.delete(rawURI, whereClause, whereArgs);
//清除輸入框
nameEdit.setText("");
telEdit.setText("");
Log.v("content", "delete done(by name):" + rows);
} else {
//刪除全部的資料
int rows = cResolver.delete(rawURI, null, null);
Log.v("content", "delete done(rawURI):" + rows);
//刪除所有群組
Uri groupURI = android.provider.ContactsContract.Groups.CONTENT_URI;
rows = cResolver.delete(groupURI, null, null);
Log.v("content", "delete done(groupURI):" + rows);
}
}
//更新聯絡人資料
private void doUpdate(){
ContentResolver cResolver = this.getContentResolver();
Uri dataURI = ContactsContract.Data.CONTENT_URI;
Log.v("content", "query contactURI:" + dataURI.toString());
//取得輸入的姓名
String name = nameEdit.getText().toString();
//設定查詢條件
String where = ContactsContract.Data.DISPLAY_NAME + " = ? AND " +
ContactsContract.Data.MIMETYPE + " = ? AND " +
CommonDataKinds.Phone.TYPE + " = ? ";
//設定查詢條件之資料值
String[] selectionArgs = new String[] {name,
CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
"" + CommonDataKinds.Phone.TYPE_MOBILE};
//進行資料查詢
Cursor phoneCur = managedQuery(dataURI, null, where, selectionArgs, null);
//判斷是否有符合條件的資料存在
if (phoneCur != null) {
Log.v("content", "update data exist");
//如果存在,就更新電話
ContentValues values = new ContentValues();
values.put(ContactsContract.CommonDataKinds.Phone.DATA, telEdit.getText().toString());
cResolver.update(dataURI, values, where, selectionArgs);
//清除輸入框
nameEdit.setText("");
telEdit.setText("");
Log.v("content", "update done.");
} else {
Log.v("content", "update no data match");
}
}
//查詢聯絡人資料Zfer
private void doQuery(){
//查詢所有的Account
/*Account[] accounts = AccountManager.get(this).getAccounts();
for (Account acc : accounts){
Log.d("content", "account name = " + acc.name + ", type = " + acc.type);
}*/
//查詢所有的群組
/*Uri groupURI = android.provider.ContactsContract.Groups.CONTENT_URI;
String[] groupFields = new String[] {android.provider.ContactsContract.Groups._ID, android.provider.ContactsContract.Groups.TITLE};
Cursor groupCur = this.managedQuery(groupURI, groupFields, null, null, null);
if (groupCur.moveToFirst()) {
do {
int idInx = groupCur.getColumnIndex(android.provider.ContactsContract.Groups._ID);
int titleInx = groupCur.getColumnIndex(android.provider.ContactsContract.Groups.TITLE);
String id = groupCur.getString(idInx);
String title = groupCur.getString(titleInx);
Log.v("content", "group, id:" + id + ", title:" + title);
} while (groupCur.moveToNext());
} else {
Log.v("content", "no group data");
}*/
//取得提供聯絡人資料的ContentProvider
ContentResolver cResolver = this.getContentResolver();
Uri contactURI = ContactsContract.Contacts.CONTENT_URI;
Log.v("content", "query contactURI:" + contactURI.toString());
//執行查詢的工作
Cursor cursor = null;
String name = nameEdit.getText().toString();
if (name != null && !name.equals("")) {
String[] fields = {ContactsContract.Data._ID, ContactsContract.Data.DISPLAY_NAME, ContactsContract.Contacts.HAS_PHONE_NUMBER};
String whereClause = ContactsContract.Data.DISPLAY_NAME + "=?";
String[] whereArgs = {name};
cursor = cResolver.query(contactURI, fields, whereClause, whereArgs, ContactsContract.Data.DISPLAY_NAME);
} else {
//查詢所有的聯絡資料
cursor = cResolver.query(contactURI, null, null, null, null);
}
//輪詢所有查詢結果
if (cursor.moveToFirst()) {
do {
int idInx = cursor.getColumnIndex(ContactsContract.Contacts._ID);
int nameInx = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
String id = cursor.getString(idInx);
String displayName = cursor.getString(nameInx);
Log.v("content", "query result: id:" + id + ",name:" + displayName);
//取得欄位索引
int hasNumInx = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
//根據欄位索引,取得號碼筆數
String hasNumStr = cursor.getString(hasNumInx);
//轉換成數值型態
int hasNum = Integer.parseInt(hasNumStr);
if (hasNum > 0) {
//查詢所有欄位
String[] fields = null;
//設定查詢條件
String whereClause = ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?";
//設定查詢條件的資料內容, 即聯絡資料的ID
String[] whereArgs = {id};
//進行號碼查詢
Cursor pCur = cResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, fields, whereClause, whereArgs, null);
//輪詢所有結果集合
while (pCur.moveToNext()) {
//號碼欄位的索引值
int phoneNoInx = pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
//取得資料內容
String phoneNo = pCur.getString(phoneNoInx);
Log.v("content", "query result: phoneNo:" + phoneNo);
telEdit.setText(phoneNo);
}
//關閉索引
pCur.close();
} else {
Log.v("content", "query result: no phoneNo");
}
} while (cursor.moveToNext());
} else {
Log.v("content", "no data for query");
}
}
}
|
package com.varad.twitter_mvp_architecture;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.varad.twitter_mvp_architecture.data.Tweet;
import com.varad.twitter_mvp_architecture.ui.TweetAdapter;
import com.varad.twitter_mvp_architecture.ui.TweetPresenter;
import com.varad.twitter_mvp_architecture.ui.TweetPresenterImpl;
import com.varad.twitter_mvp_architecture.ui.TweetView;
import com.varad.twitter_mvp_architecture.util.GlideApp;
import com.varad.twitter_mvp_architecture.util.SimpleDividerItemDecoration;
import java.lang.reflect.Type;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity implements TweetView {
private static final String TAG = MainActivity.class.getSimpleName();
private TweetPresenter<TweetView> mTweetPresenter;
private ArrayList<Tweet> tweetArrayList = new ArrayList<>();
private TweetAdapter tweetAdapter;
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.navigationIconImageView)
ImageView navigationIconImageView;
@BindView(R.id.toolbarTitleTextView)
TextView toolbarTitleTextView;
@BindView(R.id.recyclerView)
RecyclerView recyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
initView();
mTweetPresenter = new TweetPresenterImpl<>();
mTweetPresenter.onAttach(this);
String tweetTextContent = getString(R.string.dummy_tweet_text_content);
tweetArrayList = mTweetPresenter.generateTweetsData(tweetTextContent);
tweetAdapter = new TweetAdapter(this, tweetArrayList);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.addItemDecoration(new SimpleDividerItemDecoration(recyclerView.getContext()));
recyclerView.setAdapter(tweetAdapter);
}
public void initView() {
GlideApp.with(this)
.load(R.mipmap.ic_launcher_round)
.fitCenter()
.circleCrop()
.into(navigationIconImageView);
}
private void setData() {
for (int i = 0; i < 20; i++) {
Tweet tweet = new Tweet();
int itemPosition = i + 1;
tweet.setId(itemPosition);
if (itemPosition % 3 == 0) {
tweet.setIsTextContent(0);
} else {
tweet.setIsTextContent(1);
}
tweet.setTextContent(getString(R.string.dummy_tweet_text_content));
int mod = itemPosition % 5;
ArrayList<String> photos = new ArrayList<>();
ArrayList<String> videos = new ArrayList<>();
switch (mod) {
case 1:
tweet.setUserName("Varad Mondkar");
tweet.setUserHandle("@varadmondkar");
tweet.setUserDpUrl("https://pbs.twimg.com/profile_images/874269731187965952/fg5yxzXP_400x400.jpg");
tweet.setMediaType(1);
photos.add("https://pbs.twimg.com/media/DpWsF6HUYAAo9us.jpg");
photos.add("https://pbs.twimg.com/media/DpWsGxyUcAEjxA2.jpg");
photos.add("https://pbs.twimg.com/media/DpWsHgpU4AARQK_.jpg");
break;
case 2:
tweet.setUserName("Viraj Khatavkar");
tweet.setUserHandle("@virajkhatavkar");
tweet.setUserDpUrl("https://pbs.twimg.com/profile_images/924896616011546624/uRFuVmw-_400x400.jpg");
tweet.setMediaType(1);
photos.add("https://pbs.twimg.com/media/DpcgO95U8AAvl4d.jpg");
photos.add("https://pbs.twimg.com/media/DpcgRR_UcAE9kh3.jpg");
photos.add("https://pbs.twimg.com/media/DpcgTS-UcAIUuNo.jpg");
photos.add("https://pbs.twimg.com/media/DpcgVksUYAErtPL.jpg");
break;
case 3:
tweet.setUserName("Mike Penz");
tweet.setUserHandle("@mikepenz");
tweet.setUserDpUrl("https://pbs.twimg.com/profile_images/560193481688104960/_ycSgnFs_400x400.jpeg");
tweet.setMediaType(1);
photos.add("https://pbs.twimg.com/media/DpYiz82VAAA_Tx7.jpg");
photos.add("https://pbs.twimg.com/media/DpYi1WgUUAAnyHS.jpg");
break;
case 0:
tweet.setUserName("Yatin Deokar");
tweet.setUserHandle("@yatindeokar");
tweet.setUserDpUrl("https://pbs.twimg.com/profile_images/1035125494960680962/0QapHQK7_400x400.jpg");
tweet.setMediaType(2);
videos.add("https://video.twimg.com/ext_tw_video/1037980876598964225/pu/vid/952x720/FYRyGdVWRnHytFuF.mp4?tag=5");
break;
default:
tweet.setUserName("Gaurav Dhaimodkar");
tweet.setUserHandle("@gauravdhaimodkar123456");
tweet.setUserDpUrl("https://pbs.twimg.com/profile_images/1051130590760787968/cHnuyGwK_400x400.jpg");
tweet.setMediaType(1);
photos.add("https://pbs.twimg.com/media/DpYhmNqVAAEqKV1.jpg");
break;
}
if (tweet.getMediaType() == 1) {
tweet.setMedia(photos);
}
if (tweet.getMediaType() == 2) {
tweet.setMedia(videos);
}
tweetArrayList.add(i, tweet);
}
Type tweetType = new TypeToken<ArrayList<Tweet>>() {
}.getType();
Gson gson = new Gson();
String jsonData = gson.toJson(tweetArrayList, tweetType);
// Log.d(TAG, "setData: " + jsonData);
}
@Override
public void showLoader() {
}
@Override
public void hideLoader() {
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onDestroy() {
mTweetPresenter.onDetach();
super.onDestroy();
}
}
|
package ui;
import java.util.InputMismatchException;
import util.Entrada;
import votacao.Votos;
public class VotosUi {
Entrada entrada = new Entrada();
Votos listaDeVotos = new Votos();
public void cadastraCandidato() {
String nome = entrada.inString("Digite o nome do candidato: ");
if (listaDeVotos.verificaExistenciaDeCandidato(nome)) {
System.out.println("Candidato já existe");
}
else {
boolean chave = true;
while (chave) {
try {
int idade = entrada.inInt("Digite a idade de " + nome + " : ");
String partido = entrada.inString("Digite o partido " + nome + " : ");
listaDeVotos.adicionaCandidato(nome, idade, partido);
chave = false;
} catch (InputMismatchException e) {
System.out.println("Digite somente números para idade!");
}
}
}
}
public void votoNoCandidato() {
boolean chave = true;
while (chave) {
String partido = entrada.inString("Digite o número do partido: ");
if (listaDeVotos.votaNoCandidato(partido) == 1) {
System.out.println("Voto computado!");
chave = false;
}
else {
System.out.println("Candidato não encontrado.");
}
}
}
public void imprimeCandidatosMaisVelho() {
if (listaDeVotos.tamanhoDalistaDeVotos() > 0) {
System.out.println("O candidato mais velho é: " + listaDeVotos.retornaCandidatoMaisVelho().getNome()
+ "\nPartido: " + listaDeVotos.retornaCandidatoMaisVelho().getPartido());
}
else {
System.out.println("Não há candidatos!");
}
}
public void imprimeCandidatoMaisNovo() {
if (listaDeVotos.tamanhoDalistaDeVotos() > 0) {
System.out.println("O candidato mais novo é: " + listaDeVotos.retornaCandidatoMaisNovo().getNome()
+ "\nPartido: " + listaDeVotos.retornaCandidatoMaisNovo().getPartido());
}
else {
System.out.println("Não há candidatos!");
}
}
public void imprimeApuração() {
if (listaDeVotos.retornaTotalDeVotos() > 0) {
listaDeVotos.ordenaListaPorVotos();
for (int i = 0; i < listaDeVotos.tamanhoDalistaDeVotos(); i++) {
System.out.println(
listaDeVotos.getCandidato(i).getNome() + "(" + listaDeVotos.getCandidato(i).getPartido() + ")"
+ "\t" + listaDeVotos.calculaPorCentoDeVotos(listaDeVotos.getCandidato(i).getVotos())
+ "%\t" + listaDeVotos.getCandidato(i).getVotos() + " votos");
}
}
else {
System.out.println("Não teve nenhum voto computado.");
}
}
public void imprimeCandidatoMaisVotado() {
if (listaDeVotos.candidatoMaisVotado() != null) {
System.out.println("Candidato mais votado: " + listaDeVotos.candidatoMaisVotado().getNome() + "\nPartido: "
+ listaDeVotos.candidatoMaisVotado().getPartido());
}
else if (listaDeVotos.candidatoMaisVotado() != null && listaDeVotos.retornaTotalDeVotos() == 0) {
System.out.println("Não houve votação.");
}
else {
System.out.println("Não há candidatos!");
}
}
public void imprimeCandidatoMenosVotado() {
if (listaDeVotos.candidatoMenosVotado() != null) {
System.out.println("Candidato menos votado: " + listaDeVotos.candidatoMenosVotado().getNome()
+ "\nPartido: " + listaDeVotos.candidatoMenosVotado().getPartido());
}
else if (listaDeVotos.candidatoMenosVotado() != null && listaDeVotos.retornaTotalDeVotos() == 0) {
System.out.println("Não houve votação.");
}
else {
System.out.println("Não há candidatos!");
}
}
public void imprimeTotalDeVotos() {
System.out.println("Total de votos: " + listaDeVotos.retornaTotalDeVotos());
}
}
|
package com.uwetrottmann.trakt5.entities;
public class SearchResult {
public String type;
public Double score;
public Movie movie;
public Show show;
public Episode episode;
public Person person;
public TraktList list;
}
|
package io.bega.kduino.services;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.widget.ArrayAdapter;
import com.afollestad.materialdialogs.MaterialDialog;
import com.squareup.otto.Bus;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import io.bega.kduino.R;
import io.bega.kduino.api.KdUINOMessages;
import io.bega.kduino.datamodel.KDUINOBuoy;
import io.bega.kduino.datamodel.events.KdUinoMessageBusEvent;
import io.bega.kduino.kdUINOApplication;
import io.bega.kduino.utils.DisplayUtilities;
/**
* Created by usuario on 18/07/15.
*/
public class BluetoothService implements IBluetoothServiceManager {
public static int REQUEST_ENABLE_BT = 0x001;
// SPP UUID service
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private IDisconnectCallback disconnectCallback;
private BluetoothAdapter currentBluetoothAdapter;
private ArrayList<BluetoothDevice> devices = new ArrayList();
private ArrayAdapter<String> BTArrayAdapter;
protected static BluetoothSocket btSocket = null;
protected static OutputStream outputStream = null;
protected static InputStream inputStream= null;
private boolean recieving = false;
private MaterialDialog dialog;
private Context context;
private View view;
private Bus bus;
private IDeviceDiscoveryNameService discoveryNameService;
public ArrayAdapter<String> getBTArrayAdapter()
{
return this.BTArrayAdapter;
}
public ArrayList<BluetoothDevice> getBTDevices()
{
return this.devices;
}
public BluetoothService(Context ctx,
Bus bus,
ArrayAdapter<String> btArrayAdapter,
IDeviceDiscoveryNameService service,
View viewContext)
{
this.view = viewContext;
this.bus = bus;
this.BTArrayAdapter = btArrayAdapter;
this.context = ctx;
this.discoveryNameService = service;
}
private void displayDiscoveryDialog()
{
dialog = new MaterialDialog.Builder(this.context)
.title(R.string.dialog_search_blueetooth_title)
.content(R.string.dialog_search_blueetooth_message)
.progress(true, 0)
.cancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
currentBluetoothAdapter.cancelDiscovery();
}
})
.build();
dialog.show();
}
public Boolean isReceiving()
{
return this.recieving;
}
public static Boolean isEnabledBluetooth()
{
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
return false;
// Device does not support Bluetooth
} else {
return mBluetoothAdapter.isEnabled();
}
}
public boolean isEnabled()
{
currentBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
return currentBluetoothAdapter.isEnabled();
}
public void enableBluetooth(Activity activity)
{
currentBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!currentBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//activity.startActivity(enableBtIntent);
activity.startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
final BroadcastReceiver bReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
if (dialog != null)
{
dialog.dismiss();
}
}
else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
devices.add(device);
String discoveryName = device.getName();
/* if (discoveryNameService != null)
{
discoveryName = discoveryNameService.foundDevice(device.getAddress(), device.getName());
}*/
BTArrayAdapter.add(discoveryName + "\n" + device.getAddress());
BTArrayAdapter.notifyDataSetChanged();
}
}
};
public void searchDevices()
{
currentBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (currentBluetoothAdapter.isDiscovering())
{
currentBluetoothAdapter.cancelDiscovery();
}
else {
//limpiamos el adaptador y empezamos a buscar dispositivos
BTArrayAdapter.clear();
this.devices.clear();
/*for(BluetoothDevice device : currentBluetoothAdapter.getBondedDevices()) {
this.devices.add(device);
String discoveryName = device.getName();
if (discoveryNameService != null)
{
discoveryName = discoveryNameService.foundDevice(device.getAddress(), device.getName());
}
BTArrayAdapter.add(discoveryName + "\n" + device.getAddress() );
} */
this.displayDiscoveryDialog();
currentBluetoothAdapter.startDiscovery();
}
}
@Override
public void connect(String address)
{
if (dialog != null && dialog.isShowing())
{
dialog.dismiss();
}
currentBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(currentBluetoothAdapter==null) {
DisplayUtilities.ShowLargeMessage(this.context.getString(R.string.bluetooth_not_supported),
"",
view,
true,
null);
return;
}
if (currentBluetoothAdapter.isEnabled())
{
createConnection(address);
}
else
{
DisplayUtilities.ShowLargeMessage(this.context.getString(R.string.bluetooth_cant_connect),
"",
view,
false,
null);
}
}
public void createConnection(String address) {
BluetoothDevice device = currentBluetoothAdapter.getRemoteDevice(address);
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e1) {
Log.e(kdUINOApplication.TAG, "Fatal Error,In onResume() and socket create failed,TRY TO CONNECT AGAIN!", e1);
DisplayUtilities.ShowLargeMessage(this.context.getString(R.string.bluetooth_cant_connect),
"",
view,
false,
null);
}
//cancelamos la búsqueda
if (currentBluetoothAdapter.isDiscovering()) {
currentBluetoothAdapter.cancelDiscovery();
}
//establecemos la conexión
try {
btSocket.connect();
}
catch (IOException exception) {
try {
Log.e(kdUINOApplication.TAG, "Fatal Error,In onResume() and socket create failed, TRY AGAIN!", exception);
DisplayUtilities.ShowLargeMessage(this.context.getString(R.string.bluetooth_cant_connect),
"",
view,
false,
null);
btSocket.close();
return;
} catch (IOException e3) {
Log.e(kdUINOApplication.TAG, "Fatal Error,In onResume() and unable to close socket during connection failure", e3);
DisplayUtilities.ShowLargeMessage(this.context.getString(R.string.bluetooth_cant_connect),
"",
view,
false,
null);
return;
}
}
catch (Exception ex)
{
DisplayUtilities.ShowLargeMessage(this.context.getString(R.string.bluetooth_cant_connect),
"",
view,
false,
null);
return;
//btSocket.close();
}
//una vez creada la conexión creamos un outputStrem i inputStream para operar con el posteriormente
try {
outputStream = btSocket.getOutputStream();
inputStream = btSocket.getInputStream();
} catch (IOException exception) {
Log.e(kdUINOApplication.TAG, "Fatal Error,In onResume() and output/input stream creation failed", exception);
DisplayUtilities.ShowLargeMessage(this.context.getString(R.string.bluetooth_cant_connect),
"",
view,
false,
null);
}
catch (Exception ex)
{
DisplayUtilities.ShowLargeMessage(this.context.getString(R.string.bluetooth_cant_connect),
"",
view,
false,
null);
return;
//btSocket.close();
}
// bus.post(new KdUinoMessageBusEvent(KdUINOMessages.BLUETOOTH_CONNECT_TO_KDUINO, address));
//una vez conectados vamos al menu control
}
//creamos el socket para conectarnos
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
if(Build.VERSION.SDK_INT >= 10){
try {
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
return (BluetoothSocket) m.invoke(device, MY_UUID);
} catch (Exception e5) {
Log.e(kdUINOApplication.TAG, "Could not create Insecure RFComm connection", e5);
DisplayUtilities.ShowLargeMessage(this.context.getString(R.string.bluetooth_cant_connect),
"",
view,
false,
null);
}
}
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
public void setDisconnectCallback(IDisconnectCallback callback)
{
this.disconnectCallback = callback;
}
@Override
public void disconnect() {
if (!this.isConnected())
{
return;
}
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception e) {
}
inputStream = null;
}
if (outputStream != null) {
try {
outputStream.close();
} catch (Exception e) {
}
outputStream = null;
}
if (btSocket != null) {
try {
btSocket.close();
} catch (Exception e) {
}
btSocket = null;
}
if (disconnectCallback != null)
{
disconnectCallback.disconnect();
}
}
@Override
public void registerReciever() {
context.registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
context.registerReceiver(bReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED));
}
@Override
public void unregisterReciever() {
context.unregisterReceiver(bReceiver);
}
@Override
public void sendMessage(String message) throws IOException {
if (outputStream != null) {
outputStream.write(message.getBytes());
outputStream.flush();
}
}
@Override
public String recieveMessage(ICounter callback, boolean useCounter) throws IOException
{
this.recieving = false;
final char endata = '+';
char[] buffer = new char[1024];
int byteread = 0; // bytes devueltos del read()
int pos = 0;
// update last firmware, the last firware send the message recieved
if (BluetoothService.inputStream != null) {
//if (BluetoothService.btSocket.isConnected()) {
int comandRead = BluetoothService.inputStream.read();
Log.i(kdUINOApplication.TAG, "Command received from kduino: "+ (char)comandRead);
callback.receivedCommand((char) comandRead);
}
StringBuilder sb = new StringBuilder();
int counter = 0;
int total = 0;
boolean firstRead = true;
do {
try {
if (BluetoothService.inputStream != null) {
//if (BluetoothService.btSocket.isConnected()) {
byteread = BluetoothService.inputStream.read();
}
else
{
return "";
}
//}
/*else
{
new Handler(Looper.getMainLooper())
.post(new Runnable() {
@Override
public void run() {
bus.post(new KdUinoMessageBusEvent(KdUINOMessages.BLUETOOTH_ERROR, null));
}
});
}*/
}
catch (IOException io)
{
this.view.post(new Runnable() {
@Override
public void run() {
try {
((kdUINOApplication) context.getApplicationContext()).getBus()
.post(new KdUinoMessageBusEvent(KdUINOMessages.BLUETOOTH_ERROR, null));
}catch (Exception ex)
{
Log.e(kdUINOApplication.TAG, "Error sending message", ex);
}
}
});
/*new Handler(Looper.getMainLooper())
.post(new Runnable() {
@Override
public void run() {
bus.post(new KdUinoMessageBusEvent(KdUINOMessages.BLUETOOTH_ERROR, null));
}
}); */
Log.e(kdUINOApplication.TAG, "Error inputstrem bluetooth", io);
return "";
}
recieving = true;
if (pos < 1024) {
buffer[pos++] = (char) byteread;
if (useCounter) {
if (byteread == 0x0D) {
if (callback != null) {
callback.updateData(counter);
}
counter++;
}
else if (byteread == 32) {
if (firstRead) {
String value = new String(buffer).trim();
if (value.matches("\\d+")) {
total = Integer.parseInt(value);
if (total == 0)
{
recieving = false;
return "0+";
}
callback.totalCounter(total);
}
firstRead = false;
}
}
}
}
else
{
String message = new String(buffer);
sb.append(message);
buffer = new char[1024];
pos = 0;
buffer[pos] = (char)byteread;
}
} while ((char) byteread != endata);
recieving = false;
String message = new String(buffer);
sb.append(message);
return sb.toString().trim();
}
/* @Override
public String recieveMessage(ICounter callback) throws IOException {
final char endata = '+';
char[] buffer = new char[128];
int byteread; // bytes devueltos del read()
int counter = 0;
int pos = 0;
StringBuilder sb = new StringBuilder();
do {
byteread = BluetoothService.inputStream.read();
if (byteread == 0x0A)
{
counter++;
continue;
}
if (pos < 128 && byteread != 0x0D) {
buffer[pos++] = (char) byteread;
}
else
{
String message = new String(buffer).trim();
if (callback != null)
{
callback.updateData(message, counter);
}
sb.append(message).append("|");
buffer = new char[128];
pos = 0;
}
} while ((char) byteread != endata);
String message = new String(buffer).trim();
sb.append(message);
return sb.toString();
} */
@Override
public Boolean isConnected() {
if (btSocket == null)
{
return false;
}
return btSocket.isConnected();
}
}
|
import java.util.*;
import java.util.function.*;
import java.io.*;
import java.math.*;
import java.awt.geom.*;
public class Solution {
public static final PrintWriter outWriter = new PrintWriter(System.out);
public static final int _BUFFER_SIZE = 1 << 16;
public static final DataInputStream _din = new DataInputStream(System.in);
public static final byte[] _buffer = new byte[_BUFFER_SIZE];
public static int _bufferPointer = 0, _bytesRead = 0;
public static void main() {
int t = nextInt();
while (t-- > 0) {
solve();
}
}
public static void solve() {
int n = nextInt();
int[] counts = new int[n];
for (int _i = 0; _i < n; _i++) {
int d = nextInt();
int[] prefs = new int[d];
for (int i = 0; i < prefs.length; i++) {
prefs[i] = nextInt();
}
int out = -1, min = Integer.MAX_VALUE;
for (int p : prefs) {
if (counts[p] < min) {
out = p;
min = counts[p];
}
if (counts[p] != Integer.MAX_VALUE) {
counts[p]++;
}
}
if (out >= 0) {
counts[out] = Integer.MAX_VALUE;
}
outWriter.println(out);
outWriter.flush();
}
}
public static void main(String[] args) { main(); outWriter.flush(); }
public static void _fillBuffer() {
try {
_bytesRead = _din.read(_buffer, _bufferPointer = 0, _buffer.length);
if (_bytesRead == -1)
_buffer[0] = -1;
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public static byte _read() {
if (_bufferPointer == _bytesRead)
_fillBuffer();
return _buffer[_bufferPointer++];
}
public static String next() {
byte[] strBuf = new byte[64];
int cnt = 0, c;
while ((c = _read()) != -1) {
if (Character.isWhitespace(c)) {
if (cnt == 0) {
continue;
} else {
break;
}
}
if (strBuf.length == cnt) {
strBuf = Arrays.copyOf(strBuf, strBuf.length*2);
}
strBuf[cnt++] = (byte) c;
}
return new String(strBuf, 0, cnt);
}
public static String nextLine() {
byte[] strBuf = new byte[64];
int cnt = 0, c;
while ((c = _read()) != -1) {
if (c == '\n') {
if (cnt == 0) {
continue;
} else {
break;
}
}
if (strBuf.length == cnt) {
strBuf = Arrays.copyOf(strBuf, strBuf.length*2);
}
strBuf[cnt++] = (byte) c;
}
return new String(strBuf, 0, cnt);
}
public static int nextInt() {
int ret = 0;
byte c = _read();
while (c <= ' ')
c = _read();
boolean neg = (c == '-');
if (neg)
c = _read();
do {
ret = ret * 10 + c - '0';
} while ((c = _read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public static long nextLong() {
long ret = 0;
byte c = _read();
while (c <= ' ')
c = _read();
boolean neg = (c == '-');
if (neg)
c = _read();
do {
ret = ret * 10 + c - '0';
} while ((c = _read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public static double nextDouble() {
double ret = 0, div = 1;
byte c = _read();
while (c <= ' ')
c = _read();
boolean neg = (c == '-');
if (neg)
c = _read();
do {
ret = ret * 10 + c - '0';
}
while ((c = _read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = _read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
}
|
package geh.sort.heap;
import java.util.Arrays;
import java.util.Comparator;
public class Heap<T> {
private T[] arr;
private int heapSize;
public static int DESC = 0, ASC = 1;
public Comparator<T> comp;
public Heap(T[] arr, int sort) {
this.arr = arr;
heapSize = arr.length;
if (sort == DESC) {
comp = less;
} else {
comp = greater;
}
makeHeap();
}
public Heap(T[] arr) {
this.arr = arr;
heapSize = arr.length;
comp = less;
makeHeap();
}
public T popHeap(int i) {
T t = arr[0];
arr[0] = arr[i];
arr[i] = t;
adjustHeap(0, i);
return t;
}
// 调整堆
public void adjustHeap(int first, int last) {
int curr, child;
T target;
curr = first;
child = curr * 2 + 1;
target = arr[first];
while (child < last) {
System.out.println("adjustHeap : last=" + last + " child = " + child + " arr : " + Arrays.toString(arr));
// 选出子节点较大者
if ((child + 1) < last
&& (comp.compare(arr[child + 1], arr[child]) > 0)) {
child++;
}
if (comp.compare(arr[child], target) > 0) {
// 如果子节点大于父节点,交换
arr[curr] = arr[child];
curr = child;
child = child * 2 + 1;
} else {
break;
}
}
arr[curr] = target;
}
/**
* 构造堆
*/
public void makeHeap() {
int last, curr;
last = heapSize;
curr = (heapSize - 2) / 2;
// 最后一个节点
while (curr >= 0) {
System.out.println("makeHeap : curr = " + curr + " arr : " + Arrays.toString(arr));
adjustHeap(curr, last);
curr--;
}
}
/**
* 堆排序
*/
public void heapSort() {
int len = heapSize;
for (int i = len - 1; i >= 0; i--) {
popHeap(i);
}
}
@Override
public String toString() {
return Arrays.toString(arr);
}
private Comparator<T> greater = new Comparator<T>() {
@Override
public int compare(T o1, T o2) {
return ((Comparable<T>) o1).compareTo(o2);
}
};
private Comparator<T> less = new Comparator<T>() {
@Override
public int compare(T o1, T o2) {
return ((Comparable<T>) o2).compareTo(o1);
}
};
}
|
package club.eridani.cursa.module.modules.combat;
import club.eridani.cursa.common.annotations.Module;
import club.eridani.cursa.common.annotations.Parallel;
import club.eridani.cursa.module.Category;
import club.eridani.cursa.module.ModuleBase;
import club.eridani.cursa.setting.Setting;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.init.Items;
import net.minecraft.inventory.ClickType;
/**
* Created by B_312 on 06/24/19
*/
@Parallel(runnable = true)
@Module(name = "Anti32KTotem", category = Category.COMBAT)
public class Anti32kTotem extends ModuleBase {
Setting<Boolean> pauseInInventory = setting("PauseInInventory", false);
@Override
public void onRenderTick() {
if (mc.currentScreen != null) {
return;
}
if (pauseInInventory.getValue() && mc.currentScreen instanceof GuiContainer) {
return;
}
if (mc.player.inventory.getStackInSlot(0).getItem() == Items.TOTEM_OF_UNDYING) {
return;
}
for (int i = 9; i < 35; ++i) {
if (mc.player.inventory.getStackInSlot(i).getItem() == Items.TOTEM_OF_UNDYING) {
mc.playerController.windowClick(mc.player.inventoryContainer.windowId, i, 0, ClickType.SWAP, mc.player);
break;
}
}
}
}
|
package io.zipcoder.microlabs.mastering_loops;
import java.util.Scanner;
public class CarRide {
private final String MESSAGE1 = "Are we there yet?\n";
private final String MESSAGE2 = "Good!";
private Scanner user;
private String userInput ="";
public CarRide(){
user = new Scanner(System.in);
}
public void areWeThereYet(){
do{
System.out.println(MESSAGE1);
userInput = user.nextLine();
}
while(!(userInput.equalsIgnoreCase("yes")));
System.out.println(MESSAGE2);
}
public static void main(String[] args) {
//cannot test method since it's void
CarRide c = new CarRide();
c.areWeThereYet();
}
}
|
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Assert;
import org.junit.Test;
public class MathTest {
private Math math;
@BeforeClass
public static void setUpClass() throws Exception {
System.out.println("----------------------");
System.out.println("MathTest - BeforeClass");
}
@AfterClass
public static void tearDownClass() throws Exception {
System.out.println("MathTest - AfterClass");
System.out.println("---------------------");
}
@Before
public void setUp() throws Exception {
System.out.print("Before - ");
math = new Math(22, 33);
}
@After
public void tearDown() throws Exception {
System.out.println(" - After");
math = null;
}
@Test
public void div() throws Exception {
System.out.print("Test div");
Assert.assertEquals(0.6666666666666666, math.div(), 0.001);
}
@Test(expected = ArithmeticException.class)
public void divByZero() {
System.out.print("Test div by zero");
Math math = new Math(10, 0);
math.div();
}
@Test
public void sub() throws Exception {
System.out.print("Test sub");
Assert.assertEquals(-11, math.sub(),0.001);
}
@Test
public void mul() throws Exception {
System.out.print("Test mul");
Assert.assertEquals(726, math.mul(),0.001);
}
@Test
public void sum() throws Exception {
System.out.print("Test sum");
Assert.assertEquals(55, math.sum(), 0.001);
}
}
|
package com.smxknife.java2.io;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* @author smxknife
* 2018/11/20
*/
public class RandomAccessFileDemo2 {
public static void main(String[] args) throws IOException {
File rootPath = new File("");
String filePath = rootPath.getAbsolutePath() + "/src/main/java/com/smxknife/java2/io/FileTest2.txt";
File file = new File(filePath);
System.out.println(file.getAbsolutePath());
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
for (int i = 0; i < 5; i++) {
randomAccessFile.seek(randomAccessFile.length());
randomAccessFile.writeUTF("世界");
randomAccessFile.seek(0);
randomAccessFile.writeUTF("你好" + i);
}
}
}
|
package com.alone.common.mybatis;
import com.alone.common.dto.Page;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
* @author zhouxianjun(Gary)
* @ClassName:
* @Description:
* @date 17-6-27 上午11:51
*/
public interface PageMapper<T> {
List<?> listByPage(@Param("page") Page page, @Param("sortName") String sortName, @Param("sortDir") String sortDir);
}
|
package edu.kit.pse.osip.simulation.view.main;
import edu.kit.pse.osip.core.model.base.Pipe;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
/**
* This class visualizes the valve that is part of every pipe.
*
* @version 1.1
* @author Niko Wilhelm
*/
public class ValveDrawer extends RotatingControlDrawer {
private Pipe pipe;
private double radius;
private double relValveWidth;
private double relValveHeight;
/**
* Generates a new drawer object for valves.
*
* @param pos The center of the drawer.
* @param pipe The pipe to which the valve is attached.
* @param rows The number of rows in which the Tanks are ordered.
*/
public ValveDrawer(Point2D pos, Pipe pipe, int rows) {
super(pos, pipe.getValveThreshold());
this.pipe = pipe;
radius = ViewConstants.VALVE_WIDTH / rows / 2;
relValveWidth = ViewConstants.VALVE_WIDTH / rows;
relValveHeight = ViewConstants.VALVE_HEIGHT / rows;
}
@Override
public final void draw(GraphicsContext context, double timeDiff) {
setSpeed(pipe.getValveThreshold());
if (pipe.isLiquidEntering()) {
updateDegrees(timeDiff, 0.5);
}
Canvas canvas = context.getCanvas();
double totalWidth = canvas.getWidth();
double totalHeight = canvas.getHeight();
double valveHeight = relValveHeight * totalHeight;
double valveWidth = relValveWidth * totalHeight;
double valveTopLeftX = (getPosition().getX() - radius) * totalWidth
- (totalHeight - totalWidth) * radius;
double valveTopLeftY = getPosition().getY() * totalHeight;
double point1xPos = (getPosition().getX() - radius) * totalWidth
- (totalHeight - totalWidth) * radius + ViewConstants.VALVE_CIRCLE_DIST * valveWidth;
double point1yPos = (getPosition().getY() + radius) * totalHeight;
double point3xPos = point1xPos + valveWidth - 2 * ViewConstants.VALVE_CIRCLE_DIST * valveWidth;
double point3yPos = point1yPos;
double point2xPos = getPosition().getX() * totalWidth;
double point2yPos = getPosition().getY() * totalHeight + ViewConstants.VALVE_CIRCLE_DIST * valveWidth;
double point4xPos = point2xPos;
//Width, not height, as we only want to increase by the circle diameter
double point4yPos = point2yPos + valveWidth - 2 * ViewConstants.VALVE_CIRCLE_DIST * valveWidth;
double centerX = getPosition().getX() * totalWidth;
double centerY = (getPosition().getY() + radius) * totalHeight;
context.setStroke(Color.BLACK);
context.setLineWidth(ViewConstants.VALVE_LINE_WIDTH);
context.setFill(Color.WHITE);
context.fillRect(valveTopLeftX, valveTopLeftY, valveWidth, valveHeight);
context.strokeRect(valveTopLeftX, valveTopLeftY, valveWidth, valveHeight);
context.strokeLine(rotateX(point1xPos, centerX, point1yPos, centerY, getDegrees()),
rotateY(point1xPos, centerX, point1yPos, centerY, getDegrees()),
rotateX(point3xPos, centerX, point3yPos, centerY, getDegrees()),
rotateY(point3xPos, centerX, point3yPos, centerY, getDegrees()));
context.strokeLine(rotateX(point2xPos, centerX, point2yPos, centerY, getDegrees()),
rotateY(point2xPos, centerX, point2yPos, centerY, getDegrees()),
rotateX(point4xPos, centerX, point4yPos, centerY, getDegrees()),
rotateY(point4xPos, centerX, point4yPos, centerY, getDegrees()));
context.strokeOval(point1xPos, point2yPos,
radius * 2 * totalHeight - 2 * ViewConstants.VALVE_CIRCLE_DIST * valveWidth,
radius * 2 * totalHeight - 2 * ViewConstants.VALVE_CIRCLE_DIST * valveWidth);
context.setFont(Font.font("Arial", (relValveHeight - relValveWidth) * totalHeight * 0.95));
context.setFill(Color.BLUE);
//Offset of 1 to avoid writing over the valve outline
context.fillText(String.valueOf(pipe.getValveThreshold()), valveTopLeftX + 1,
valveTopLeftY + valveHeight - 2);
}
}
|
package cz.kojotak.udemy.vertx.stockBroker.api.watchlist;
import java.util.Collections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cz.kojotak.udemy.vertx.stockBroker.db.DbHandler;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.vertx.core.Handler;
import io.vertx.core.http.HttpHeaders;
import io.vertx.core.json.JsonArray;
import io.vertx.ext.web.RoutingContext;
import io.vertx.jdbcclient.JDBCPool;
import io.vertx.sqlclient.Row;
import io.vertx.sqlclient.templates.SqlTemplate;
public class GetWatchListFromDatabaseHandler implements Handler<RoutingContext> {
private static final Logger LOG = LoggerFactory.getLogger(GetWatchListFromDatabaseHandler.class);
private final JDBCPool dbPool;
public GetWatchListFromDatabaseHandler(JDBCPool dbPool) {
super();
this.dbPool = dbPool;
}
@Override
public void handle(RoutingContext ctx) {
String accountId = ctx.pathParam("accountId");
LOG.debug("{} for account {}", ctx.normalisedPath(), accountId);
SqlTemplate
.forQuery(dbPool, "select w.asset from watchlist w where w.account_id=#{account_id}")
.mapTo(Row::toJson)
.execute(Collections.singletonMap("account_id", accountId))
.onFailure(DbHandler.error(ctx, "failed to fetch watchlist for account_id="+accountId))
.onSuccess( a$$et->{
if(!a$$et.iterator().hasNext()) {
DbHandler.notFound(ctx, "not available");
return;
}
var resp = new JsonArray();
a$$et.forEach(resp::add);
LOG.info("path {} responds with {}", ctx.pathParams(), resp.encode());
ctx.response()
.putHeader(HttpHeaders.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON)
.end(resp.toBuffer());
});
}
}
|
package com.example.marcelo.tkl_game_lister_app;
import retrofit2.Call;
import retrofit2.http.GET;
public interface RequestInterface {
@GET("s/1b7jlwii7jfvuh0/games")
Call<Response> getJSON();
}
|
package org.opentosca.containerapi.instancedata.model;
import java.util.LinkedList;
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author Florian Haupt <florian.haupt@iaas.uni-stuttgart.de>
*
*/
@XmlRootElement(name = "InstanceDataAPI")
public class InstanceDataEntry {
private String version = "0.1";
private List<SimpleXLink> links = new LinkedList<SimpleXLink>();
protected InstanceDataEntry() {
super();
}
public InstanceDataEntry(List<SimpleXLink> links) {
super();
this.links = links;
}
@XmlAttribute(name = "version", required = true)
public String getVersion() {
return version;
}
@XmlElement(name = "Link")
public List<SimpleXLink> getLinks() {
return links;
}
}
|
package com.bdb.tag;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import org.apache.log4j.Logger;
import com.slort.model.Usuario;
public class CheckSimpleLogonTag extends TagSupport {
private static final Logger log;
private String userKey;
private String pageLogon;
static {
log = Logger.getLogger(com.bdb.tag.CheckSimpleLogonTag.class);
}
public CheckSimpleLogonTag() {
userKey = "bdbUser";
pageLogon = "/logon.jsp";
log.debug("CheckSimpleLogonTag");
}
public final int doEndTag() throws JspException {
log.debug("Comienzo de validacion de logueo");
boolean valid = false;
HttpSession session = pageContext.getSession();
if(session != null && session.getAttribute(userKey) != null)
valid = true;
Usuario user=(Usuario)session.getAttribute(userKey);
if(valid && (user.getPwd()!=null)) {
if (user.esPasswordDefecto()){
try {
pageContext.forward("/usuario.do?reqCode=editCambiarPassword");
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
log.debug("Fin de validacion. Resultado: OK");
return 6;
}
try {
pageContext.forward(pageLogon);
}
catch(Exception e) {
log.error("Error al hacer forward:" + e.toString());
throw new JspException(e.toString());
}
log.debug("Fin de validacion. Resultado: ERROR -> Redireccionado a la pantalla de logon.");
return 5;
}
public final int doStartTag() throws JspException {
return 0;
}
public final String getPageLogon() {
return pageLogon;
}
public final void setPageLogon(String pageLogon) {
this.pageLogon = pageLogon;
}
public void release() {
super.release();
userKey = "bdbUser";
pageLogon = "/logon.jsp";
}
}
|
package com.cmpickle.volumize.data.receivers;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.preference.PreferenceManager;
import android.util.Log;
import com.cmpickle.volumize.Inject.Injector;
import com.cmpickle.volumize.data.repositories.ScheduleEventRepository;
import com.cmpickle.volumize.domain.RestoreHelper;
import com.cmpickle.volumize.domain.ScheduleEventService;
import com.cmpickle.volumize.domain.VolumeService;
import com.cmpickle.volumize.util.preferences.Preferences;
import javax.inject.Inject;
/**
* @author Cameron Pickle
* Copyright (C) Cameron Pickle (cmpickle) on 4/22/2017.
*/
public class AlarmManagerBroadcastReceiver extends BroadcastReceiver {
public static final String ACTION_CHANGE_VOLUME = "change_volume";
public static final String ACTION_CHANGE_VOLUME_TEMP = "change_volume_temp";
VolumeService volumeService;
@Inject
RestoreHelper helper;
public AlarmManagerBroadcastReceiver() {
Injector.get().inject(this);
}
@Override
public void onReceive(Context context, Intent intent) {
Preferences preferences = new Preferences(PreferenceManager.getDefaultSharedPreferences(context));
if(intent.getBooleanExtra(VolumeService.ACTIVE, true) && !preferences.getPauseScheduledEvents()) {
volumeService = new VolumeService(context);
int amount = intent.getIntExtra(VolumeService.AMOUNT, 12);
Log.d("AlarmReceiver", "The volume is now " + amount);
switch (intent.getIntExtra(VolumeService.OPTION, 0)) {
case VolumeService.ALL:
volumeService.setRingToneVolume(amount, intent.getBooleanExtra(VolumeService.VIBRATE, true));
volumeService.setNotificationVolume(amount);
volumeService.setMediaVolume(amount);
volumeService.setSystemVolume(amount);
break;
case VolumeService.RING_TONE:
volumeService.setRingToneVolume(amount, intent.getBooleanExtra(VolumeService.VIBRATE, true));
break;
case VolumeService.MEDIA:
volumeService.setMediaVolume(amount);
break;
case VolumeService.NOTIFICATIONS:
volumeService.setNotificationVolume(amount);
break;
case VolumeService.SYSTEM:
volumeService.setSystemVolume(amount);
break;
}
}
if(intent.getAction().equals(ACTION_CHANGE_VOLUME_TEMP)) {
helper.getEventService().deleteEvent(intent.getStringExtra("eventId"));
}
}
}
|
package several_synchronized;
public class SameObjectReference {
public static synchronized void testMethod1() {
try {
Thread.sleep(5000);
} catch (InterruptedException ie) {
}
}
public static synchronized void testMethod2() {
try {
Thread.sleep(5000);
} catch (InterruptedException ie) {
}
}
public static void main(String[] args) throws InterruptedException {
//final o = new SameObjectReference();
Thread t1 = new Thread() {
public void run() {
SameObjectReference.testMethod1();
}
};
//final SameObjectReference o1 = new SameObjectReference();
Thread t2 = new Thread() {
public void run() {
SameObjectReference.testMethod2();
}
};
t1.start();
t2.start();
Thread.sleep(500);
System.out.println(t2.getState());
}
}
|
package com.tencent.mm.plugin.appbrand.ui;
import android.view.View;
import android.view.ViewGroup;
import com.tencent.mm.plugin.appbrand.ui.e.1;
class e$1$2 implements Runnable {
final /* synthetic */ 1 gvw;
final /* synthetic */ View gvx;
final /* synthetic */ ViewGroup gvy;
e$1$2(1 1, View view, ViewGroup viewGroup) {
this.gvw = 1;
this.gvx = view;
this.gvy = viewGroup;
}
public final void run() {
this.gvx.setVisibility(8);
this.gvy.removeView(this.gvx);
}
}
|
package com.samara.mentoring.ducks;
import java.util.List;
import com.samara.mentoring.console.ConsoleCommand;
public abstract class MovementCommand implements ConsoleCommand {
@Override
public void perform(List<String> params) {
if(params.isEmpty()) {
badParamsMessage();
return;
}
try {
Direction direction = Direction.valueOf(params.get(0).toUpperCase());
doMove(direction);
} catch(IllegalArgumentException e) {
badParamsMessage();
}
}
protected abstract void doMove(Direction direction);
protected abstract void badParamsMessage();
}
|
package kodlamaio.hrms.business.concretes;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import kodlamaio.hrms.business.abstracts.CvSchoolService;
import kodlamaio.hrms.business.abstracts.CvService;
import kodlamaio.hrms.core.utilities.results.DataResult;
import kodlamaio.hrms.core.utilities.results.Result;
import kodlamaio.hrms.core.utilities.results.SuccessDataResult;
import kodlamaio.hrms.core.utilities.results.SuccessResult;
import kodlamaio.hrms.dataAccess.abstracts.CvSchoolDao;
import kodlamaio.hrms.entities.concretes.CvSchool;
import kodlamaio.hrms.entities.concretes.dto.CvSchoolDto;
@Service
public class CvSchoolManager implements CvSchoolService {
private CvSchoolDao cvSchoolDao;
private CvService cvService;
@Autowired
public CvSchoolManager(CvSchoolDao cvSchoolDao,CvService cvService) {
super();
this.cvSchoolDao = cvSchoolDao;
this.cvService= cvService;
}
@Override
public DataResult<List<CvSchool>> getAllByCv_CvId(int cvId) {
return new SuccessDataResult<List<CvSchool>>(this.cvSchoolDao.getAllByCv_CvId(cvId));
}
@Override
public DataResult<List<CvSchool>> getAllByCv_CvIdOrderBySchoolGraduationDateDesc(int cvId) {
return new SuccessDataResult<List<CvSchool>>(this.cvSchoolDao.getAllByCv_CvIdOrderBySchoolGraduationDateDesc(cvId));
}
@Override
public Result add(CvSchoolDto cvSchoolDto) {
CvSchool cvSchoolAdd = new CvSchool();
cvSchoolAdd.setSchoolBeginDate(cvSchoolDto.getSchoolBeginDate());
cvSchoolAdd.setSchoolDepartment(cvSchoolDto.getSchoolDepartment());
cvSchoolAdd.setSchoolGraduationDate(cvSchoolDto.getSchoolGraduationDate());
cvSchoolAdd.setSchoolName(cvSchoolDto.getSchoolName());
cvSchoolAdd.setSchoolType(cvSchoolDto.getSchoolType());
cvSchoolAdd.setCv(cvService.getById(cvSchoolDto.getCvId()).getData());
cvSchoolDao.save(cvSchoolAdd);
return new SuccessResult();
}
@Override
public Result addAll(List<CvSchool> cvSchools) {
return null;
}
@Override
public Result update(CvSchoolDto cvSchoolDto, int id) {
CvSchool cvSchoolUpdate = cvSchoolDao.getOne(id);
cvSchoolUpdate.setSchoolBeginDate(cvSchoolDto.getSchoolBeginDate());
cvSchoolUpdate.setSchoolDepartment(cvSchoolDto.getSchoolDepartment());
cvSchoolUpdate.setSchoolGraduationDate(cvSchoolDto.getSchoolGraduationDate());
cvSchoolUpdate.setSchoolName(cvSchoolDto.getSchoolName());
cvSchoolUpdate.setSchoolType(cvSchoolDto.getSchoolType());
cvSchoolDao.save(cvSchoolUpdate);
return new SuccessResult();
}
@Override
public Result delete(int id) {
this.cvSchoolDao.deleteById(id);
return new SuccessResult();
}
@Override
public DataResult<CvSchool> getById(int id) {
CvSchool cvSchool = cvSchoolDao.findById(id);
return new SuccessDataResult<CvSchool>(cvSchool);
}
// @Override
// public DataResult<List<CvSchool>> getAllByCandidateId(int id) {
// return new SuccessDataResult<List<CvSchool>>(this.cvSchoolDao.getAllByCandidateId(id), "Success");
// }
//
// @Override
// public DataResult<List<CvSchool>> getAllByCandidateIdOrderBySchoolGraduationDateDesc(int id) {
// return new SuccessDataResult<List<CvSchool>>(
// this.cvSchoolDao.getAllByCandidateIdOrderBySchoolGraduationDateDesc(id), "Success");
// }
//
// @Override
// public Result add(CvSchool cvSchool) {
// this.cvSchoolDao.save(cvSchool);
// return new SuccessResult("Success");
// }
//
// @Override
// public Result update(CvSchool cvSchool) {
// return null;
// }
//
// @Override
// public Result delete(CvSchool cvSchool) {
// return null;
// }
//
// @Override
// public Result addAll(List<CvSchool> cvSchools) {
// this.cvSchoolDao.saveAll(cvSchools);
// return new SuccessResult("Success");
// }
}
|
/*
This program will create an endless loop of starting with a dark square
in the center and getting darker as it reaches the border, eventually
becoming the whole thing dark.
*/
public class RandomMosaicWalk4 {
/*
The main method will call the strobe method and repeat the cycle.
*/
public static void main (String [] args) {
Mosaic.open (41, 41, 6, 6);
while (true) {
Mosaic.delay (1000);
strobe ();
Mosaic.fill (0, 0, 0);
}
}
private static void outlineRectangle (int topRow, int leftColumn, int widthOfOutline, int heightOfOutline, int redLevel, int greenLevel, int blueLevel) {
int row;
int col;
for (col = leftColumn; col <= leftColumn + widthOfOutline - 1; col ++) {
Mosaic.setColor (topRow, col, redLevel, greenLevel, blueLevel);
Mosaic.setColor (topRow + heightOfOutline - 1, col, redLevel, greenLevel, blueLevel);
}
for (row = topRow; row <= topRow + heightOfOutline - 1; row ++) {
Mosaic.setColor (row, leftColumn, redLevel, greenLevel, blueLevel);
Mosaic.setColor (row, leftColumn + widthOfOutline - 1, redLevel, greenLevel, blueLevel);
}
}
private static void strobe () {
int left;
int top;
int size;
int brightness;
left = 20;
top = 20;
size = 1;
brightness = 50;
while (left >= 0) {
outlineRectangle (top, left, size, size, brightness, brightness, brightness);
Mosaic.delay (200);
left --;
top --;
size += 2;
brightness += 10;
}
}
}
|
package uz.kassa.test.service.security;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import uz.kassa.test.domain.entity.Employee;
import uz.kassa.test.domain.repository.EmployeeRepository;
@Service
@RequiredArgsConstructor
public class CustomUserDetailsService implements UserDetailsService {
private final EmployeeRepository employeeRepository;
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
Employee employee =
employeeRepository
.findByUsername(email)
.orElseThrow(() -> new UsernameNotFoundException("Username: " + email + " is wrong"));
return LoggedUser.create(employee);
}
public UserDetails loadUserById(Long id) {
Employee employee =
employeeRepository
.findById(id)
.orElseThrow(() -> new UsernameNotFoundException("User with id: " + id + " not found"));
return LoggedUser.create(employee);
}
}
|
package jp.personal.server.utils;
import java.util.List;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.springframework.util.CollectionUtils;
import jp.personal.server.data.admin.AdminDto;
import jp.personal.server.data.message.MessageDto;
import jp.personal.server.data.room.RoomDto;
import jp.personal.server.data.room.RoomWithUsersDto;
import jp.personal.server.data.room.RoomWithUsersMsgDto;
import jp.personal.server.data.user.UserDto;
import jp.personal.server.domain.entity.Administrator;
import jp.personal.server.domain.entity.Message;
import jp.personal.server.domain.entity.Room;
import jp.personal.server.domain.entity.SesUser;
import jp.personal.server.domain.entity.User;
import jp.personal.server.enums.AdminRole;
import jp.personal.server.enums.LoginIdType;
/**
* dtoへの変換を集約します。
*
* @author noguchi_kohei
*/
public enum DtoFuncs {
SINGLETON;
public static Function<Administrator, AdminDto> TO_ADMIN = admin -> {
AdminDto dto = new AdminDto();
dto.setId(admin.getId());
dto.setAdminId(admin.getAdminId());
dto.setAdminRole(AdminRole.get(admin.getRole()));
dto.setName(admin.getUserName());
dto.seteMail(dto.geteMail());
dto.setNote(admin.getNote());
return dto;
};
public static Function<User, UserDto> TO_USER = user -> {
UserDto dto = new UserDto();
dto.setUserId(user.getId());
dto.setLoginId(user.getLoginId());
dto.setName(user.getName());
dto.setLoginIdType(LoginIdType.get(user.getLoginIdType()));
dto.setDiscription(user.getDiscription());
dto.setEMail(Strings.isEmpty(user.getEMail()) ? null : user.getEMail());
dto.setTel(Strings.isEmpty(user.getTel()) ? null : user.getTel());
return dto;
};
public static Function<List<User>, List<UserDto>> TO_USER_LIST = userList -> {
if (CollectionUtils.isEmpty(userList)) {
return null;
}
return userList.stream() //
.map(input -> TO_USER.apply(input)) //
.collect(Collectors.toList());
};
public static Function<SesUser, UserDto> SES_TO_USER = input -> {
UserDto dto = new UserDto();
dto.setUserId(input.getUserId());
dto.setLoginId(input.getLoginId());
dto.setName(input.getName());
dto.setLoginIdType(input.getLoginIdType());
dto.setDiscription(input.getDiscription());
dto.setEMail(Strings.isEmpty(input.getEMail()) ? null : input.getEMail());
dto.setTel(Strings.isEmpty(input.getTel()) ? null : input.getTel());
dto.setLoginUser(true);
return dto;
};
/**
* {@link RoomDto}のlastMessage以外のデータを作成します。
*/
public static BiFunction<Room, User, RoomDto> TO_ROOM = (room, user) -> {
return new RoomDto(room.getId(),//
room.getName(),//
user.getId(), //
user.getLoginId(),//
user.getName(),//
room.getCount(), //
Dates.toString(room.getLastMessageDate(), Dates.VIEW_DATE_FORMAT),//
room.getLastMessageId(), //
null);
};
/**
* {@link RoomWithUsersMsgDto}へメッセージリストなしで変換します。
*/
public static BiFunction<RoomDto, List<User>, RoomWithUsersDto> TO_ROOM_WITH_USERS = (roomDto, userList) -> {
return new RoomWithUsersDto(roomDto.getRoomId(), //
roomDto.getName(), //
roomDto.getCreaeteUserId(), //
roomDto.getCreateUserName(), //
roomDto.getCreateLoginId(), //
TO_USER_LIST.apply(userList), //
roomDto.getCount(),//
roomDto.getLastMessageDate(), //
roomDto.getLastMessageId(), //
roomDto.getLastMessage());
};
/**
* {@link RoomWithUsersMsgDto}へメッセージリストなしで変換します。
*/
public static BiFunction<RoomWithUsersDto, Stream<MessageDto>, RoomWithUsersMsgDto> TO_ROOM_WITH_USERS_MSG = (ruDto,
mDtoStm) -> {
return new RoomWithUsersMsgDto(//
ruDto.getRoomId(), //
ruDto.getName(), //
ruDto.getCreaeteUserId(), //
ruDto.getCreateUserName(), //
ruDto.getCreateLoginId(), //
ruDto.getUserList(), //
mDtoStm.collect(Collectors.toList()), //
ruDto.getCount(), //
ruDto.getLastMessageDate(), //
ruDto.getLastMessageId());
};
public static BiFunction<Message, Optional<UserDto>, MessageDto> USER_DTO_TO_MESSAGE = (message, uDtoOpt) -> {
MessageDto dto = new MessageDto();
dto.setRoomId(message.getRoomId());
dto.setMessageId(message.getId());
dto.setMessageUserId(message.getUserId());
if (uDtoOpt.isPresent()) {//ユーザーが退会済みの場合セットしない。
dto.setMessageUserName(uDtoOpt.get().getName());
dto.setMessageLoginId(uDtoOpt.get().getLoginId());
}
dto.setContent(message.getContent());
return dto;
};
}
|
/* 1: */ package com.kaldin.reports.action;
/* 2: */
/* 3: */ import com.kaldin.user.register.dao.impl.ActivationImplementor;
/* 4: */ import java.util.List;
/* 5: */ import javax.servlet.http.HttpServletRequest;
/* 6: */ import javax.servlet.http.HttpServletResponse;
/* 7: */ import javax.servlet.http.HttpSession;
/* 8: */ import org.apache.struts.action.Action;
/* 9: */ import org.apache.struts.action.ActionForm;
/* 10: */ import org.apache.struts.action.ActionForward;
/* 11: */ import org.apache.struts.action.ActionMapping;
/* 12: */
/* 13: */ public class callCompanyWiseUser
/* 14: */ extends Action
/* 15: */ {
/* 16: */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
/* 17: */ throws Exception
/* 18: */ {
/* 19:28 */ int[] companyid = null;
/* 20: */
/* 21:30 */ List listObj = null;
/* 22:31 */ List list = null;
/* 23:32 */ List compRec = null;
/* 24:33 */ int cidIterator = 0;
/* 25:34 */ ActivationImplementor actImpl = new ActivationImplementor();
/* 26:35 */ compRec = actImpl.getCompanyRec();
/* 27: */
/* 28: */
/* 29: */
/* 30: */
/* 31: */
/* 32: */
/* 33: */
/* 34: */
/* 35: */
/* 36: */
/* 37: */
/* 38: */
/* 39: */
/* 40: */
/* 41: */
/* 42: */
/* 43: */
/* 44: */
/* 45: */
/* 46: */
/* 47:56 */ request.getSession().setAttribute("companylist", compRec);
/* 48:57 */ return mapping.findForward("success");
/* 49: */ }
/* 50: */ }
/* Location: C:\Java Work\Workspace\Kaldin\WebContent\WEB-INF\classes\com\kaldin\kaldin_java.zip
* Qualified Name: kaldin.reports.action.callCompanyWiseUser
* JD-Core Version: 0.7.0.1
*/
|
package com.beiyelin.commonsql.bean;
import com.beiyelin.commonsql.jpa.BaseTreeEntity;
import lombok.Data;
/**
* @Author: Newmann HU
* @Description: Tree模型中,添加sibling node,需要根据sibling的一些信息进行判断,
* 这些信息都保存在这个类中
* 添加子节点总是添加到sibling的后面
* @Date: Created in 22:35 2018-07-09
*/
@Data
public class TreeSiblingNodeAdd<T extends BaseTreeEntity> {
private T sibling;//如果为空,则添加的是第一个节点
private T node;
int pos;//采用nz-zorro的定义,放置位置(-1:目标节点前面, 1: 目标节点后面)
}
|
package by.dt.boaopromtorg.service;
import by.dt.boaopromtorg.entity.CustomerCard;
public interface CustomerCardService {
void addCustomerCard(CustomerCard customerCard);
CustomerCard getCustomerCardByCardId(String cardId);
}
|
package com.qd.mystudy.helloworld;
import java.util.Scanner;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
/**
* Created by liqingdong911 on 2014/11/27.
*/
public class ExecutorTest {
static private ScheduledExecutorService executor = Executors.newScheduledThreadPool(1,
new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setName("test");
t.setDaemon(true);
return t;
}
});
static public void main(String[] args)
{
executor.scheduleWithFixedDelay(new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getId());
}
}, 1L, 1L, TimeUnit.SECONDS);
Scanner scanner = new Scanner(System.in);
scanner.nextLine();
}
}
|
package com.slort.struts.action.ajax;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.hibernate.Session;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.expression.Expression;
import net.sf.hibernate.expression.MatchMode;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.bdb.conexion.Conexion;
import com.bdb.util.DateUtils;
import com.slort.admin.AdmAdapterXML_PIPE;
import com.slort.admin.AdmFlota;
import com.slort.admin.AdmSpringBD;
import com.slort.model.Calculoubicacion;
import com.slort.model.CalculoubicacionDAO;
import com.slort.model.Cliente;
import com.slort.model.ClienteDAO;
import com.slort.model.Flota;
import com.slort.model.FlotaDAO;
import com.slort.model.Historicoubicaciondetalle;
import com.slort.model.HistoricoubicaciondetalleDAO;
import com.slort.model.Hotel;
import com.slort.model.HotelDAO;
import com.slort.model.Reserva;
import com.slort.model.ReservaDAO;
import com.slort.struts.action.SlortDispatchAction;
import com.slort.struts.action.security.ReservaAction;
import com.slort.struts.form.security.ReservaForm;
import com.slort.util.Numbers;
public class GuardarAjaxAction extends SlortDispatchAction {
private static final Logger log = Logger.getLogger(GuardarAjaxAction.class);
public ActionForward getGuardarRankingyUnidad(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){
AjaxPopulate ajax = new AjaxPopulate();
ReservaForm currentForm = (ReservaForm) request.getSession().getAttribute("reservaForm_session");
String paquetededatos_http[]=request.getParameterValues("paquetededatos");
String[] registros=null;
String[] unidad=null;
String[] unidadAsignada=null;
String[] motivo=null;
String[] ranking=null;
String[] tiempo=null;
String[] distancia=null;
for (String string : paquetededatos_http) {
log.info(string);
registros = string.split(";");
unidad = string.split(";");
unidadAsignada = string.split(";");
motivo = string.split(";");
ranking = string.split(";");
tiempo = string.split(";");
distancia = string.split(";");
for (int i=0;i<registros.length;i++) {
String[] registros2 = registros[i].split("-");
ranking[i]=registros2[0];
unidad[i]=registros2[1];
unidadAsignada[i]=registros2[2];
if (registros2.length==6) motivo[i]=registros2[3]; else motivo[i]="";
tiempo[i]=registros2[4];
distancia[i]=registros2[5];
}
}
currentForm.setUnidad(unidad);
currentForm.setUnidadAsignada(unidadAsignada);
currentForm.setRanking(ranking);
currentForm.setMotivo(motivo);
currentForm.setTiempo(tiempo);
currentForm.setDistancia(distancia);
this.beginTransactionSpring(request);
Reserva una_Reserva = null;
ReservaDAO ReservaDAO = (ReservaDAO) this.getBean(request,"ReservaDAO");
una_Reserva = ReservaDAO.findById( currentForm.getIdReserva());
//un_calculoubicacion
Calculoubicacion un_calculoubicacion = currentForm.getCalculoubicacion();
un_calculoubicacion.setCodUnidad( obtenerCodUnidadAsignada(currentForm));
un_calculoubicacion.setReserva(una_Reserva);
CalculoubicacionDAO un_calculoubicacionDAO = (CalculoubicacionDAO) this.getBean(request,"CalculoubicacionDAO");
un_calculoubicacionDAO.save(un_calculoubicacion);
Flota flota=null;
FlotaDAO flotaDAO = (FlotaDAO) this.getBean(request,"FlotaDAO");
flota = flotaDAO.findById(un_calculoubicacion.getCodUnidad());
// grabamos el objeto reversa con la unidad ganadora
una_Reserva.setFlota(flota);
una_Reserva.setCalculoubicacion(un_calculoubicacion);
una_Reserva.setEstado("A realizar");
ReservaDAO.save(una_Reserva);
// grabar el historico historicoubicaciondetalle
HistoricoubicaciondetalleDAO un_HistoricoubicaciondetalleDAO = (HistoricoubicaciondetalleDAO) this.getBean(request,"HistoricoubicaciondetalleDAO");
for (int i = 0; i < currentForm.getUnidad().length; i++) {
Historicoubicaciondetalle un_Historicoubicaciondetalle= new Historicoubicaciondetalle();
flota=null;
flota = flotaDAO.findById( new Integer(currentForm.getUnidad()[i]));
un_Historicoubicaciondetalle.setFlota(flota);
un_Historicoubicaciondetalle.setCalculoubicacion(un_calculoubicacion);
un_Historicoubicaciondetalle.setMotivoNoAsignado(currentForm.getMotivo()[i]);
un_Historicoubicaciondetalle.setHora(DateUtils.getFechaFormateada(DateUtils.getFechaActual("H:mm"),"H:mm"));
un_Historicoubicaciondetalle.setFecha(DateUtils.getFechaActualasDate());
un_Historicoubicaciondetalle.setGpsactivo("1");
un_Historicoubicaciondetalle.setRanking(i);
un_Historicoubicaciondetalle.setTiempoObjetivo(currentForm.getTiempo()[i]);
un_Historicoubicaciondetalle.setDistanciaObjetivo(new Float(currentForm.getDistancia()[i].replace(",", ".")));
un_HistoricoubicaciondetalleDAO.save(un_Historicoubicaciondetalle);
}
// Finalizamos la transaccion
this.commitTransactionSpring(request);
ajax.escribirAjax(response,"OK");
return null;
}
public Integer obtenerCodUnidadAsignada(ReservaForm currentForm){
for (int i = 0; i < currentForm.getUnidad().length; i++) {
if (currentForm.getUnidadAsignada()[i].toString().compareTo( "true")==0){
return new Integer(currentForm.getUnidad()[i]);
}
}
return null;
}
public ActionForward getGuardarSinAsignar(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){
AjaxPopulate ajax = new AjaxPopulate();
ReservaForm currentForm = (ReservaForm) request.getSession().getAttribute("reservaForm_session");
String paquetededatos_http[]=request.getParameterValues("paquetededatos");
String[] registros=null;
String[] unidad=null;
String[] unidadAsignada=null;
String[] motivo=null;
String[] ranking=null;
String[] tiempo=null;
String[] distancia=null;
for (String string : paquetededatos_http) {
log.info(string);
registros = string.split(";");
unidad = string.split(";");
unidadAsignada = string.split(";");
motivo = string.split(";");
ranking = string.split(";");
tiempo = string.split(";");
distancia = string.split(";");
for (int i=0;i<registros.length;i++) {
String[] registros2 = registros[i].split("-");
ranking[i]=registros2[0];
unidad[i]=registros2[1];
unidadAsignada[i]=registros2[2];
if (registros2.length==6) motivo[i]=registros2[3]; else motivo[i]="";
tiempo[i]=registros2[4];
distancia[i]=registros2[5];
}
}
currentForm.setUnidad(unidad);
currentForm.setUnidadAsignada(unidadAsignada);
currentForm.setRanking(ranking);
currentForm.setMotivo(motivo);
currentForm.setTiempo(tiempo);
currentForm.setDistancia(distancia);
this.beginTransactionSpring(request);
Reserva una_Reserva = null;
ReservaDAO ReservaDAO = (ReservaDAO) this.getBean(request,"ReservaDAO");
una_Reserva = ReservaDAO.findById( currentForm.getIdReserva());
//un_calculoubicacion
Calculoubicacion un_calculoubicacion = currentForm.getCalculoubicacion();
un_calculoubicacion.setCodUnidad( obtenerCodUnidadAsignada(currentForm));
un_calculoubicacion.setReserva(una_Reserva);
CalculoubicacionDAO un_calculoubicacionDAO = (CalculoubicacionDAO) this.getBean(request,"CalculoubicacionDAO");
un_calculoubicacionDAO.save(un_calculoubicacion);
Flota flota=null;
FlotaDAO flotaDAO = (FlotaDAO) this.getBean(request,"FlotaDAO");
// grabar el historico historicoubicaciondetalle
HistoricoubicaciondetalleDAO un_HistoricoubicaciondetalleDAO = (HistoricoubicaciondetalleDAO) this.getBean(request,"HistoricoubicaciondetalleDAO");
for (int i = 0; i < currentForm.getUnidad().length; i++) {
Historicoubicaciondetalle un_Historicoubicaciondetalle= new Historicoubicaciondetalle();
flota=null;
flota = flotaDAO.findById( new Integer(currentForm.getUnidad()[i]));
un_Historicoubicaciondetalle.setFlota(flota);
un_Historicoubicaciondetalle.setCalculoubicacion(un_calculoubicacion);
un_Historicoubicaciondetalle.setMotivoNoAsignado(currentForm.getMotivo()[i]);
un_Historicoubicaciondetalle.setHora(DateUtils.getFechaFormateada(DateUtils.getFechaActual("H:mm"),"H:mm"));
un_Historicoubicaciondetalle.setFecha(DateUtils.getFechaActualasDate());
un_Historicoubicaciondetalle.setGpsactivo("1");
un_Historicoubicaciondetalle.setRanking(i);
un_Historicoubicaciondetalle.setTiempoObjetivo(currentForm.getTiempo()[i]);
un_Historicoubicaciondetalle.setDistanciaObjetivo(new Float(currentForm.getDistancia()[i].replace(",", ".")));
un_HistoricoubicaciondetalleDAO.save(un_Historicoubicaciondetalle);
}
// Finalizamos la transaccion
this.commitTransactionSpring(request);
ajax.escribirAjax(response,"OK");
return null;
}
}
|
package HortonWorksPracticeExamTest;
import org.apache.hadoop.io.GenericWritable;
import org.apache.hadoop.io.Writable;
public class GenericRecordWritable extends GenericWritable {
static Class<? extends Writable> classes[];
static{
classes = (Class<? extends Writable>[]) new Class []{
DataRecord.class
};
}
public GenericRecordWritable(){
}
public GenericRecordWritable(Writable instance){
set(instance);
}
@Override
protected Class<? extends Writable>[] getTypes() {
return classes;
}
}
|
package Model;
import io.javalin.Javalin;
import io.javalin.plugin.rendering.vue.VueComponent;
import org.jetbrains.annotations.NotNull;
import javax.naming.Context;
import java.util.logging.Handler;
public class Application {
public static void main(String[] args) {
Javalin app = Javalin.create().start();
app.config.enableWebjars();
app.get("/planet-systems/:planet-system-id", new VueComponent("Planet-detail"));
UniverseRepository PlanetSystemRepository = new UniverseRepository();
PlanetSystemController planetController = new PlanetSystemController(PlanetSystemRepository);
// API
app.get("api/planet-systems/:planet-system-id", planetController::getAllPlanets);
app.get("/", ctx -> ctx.result("Hello, world"));
}
}
|
/**
*
*/
/**
* @author Jinwei Zhang
*
*/
public class MinimumSizeSubarraySum {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MinimumSizeSubarraySumSolution bb =new MinimumSizeSubarraySumSolution();
bb.minSubArrayLen(11, new int[] {1,2,3,4,5});
}
}
class MinimumSizeSubarraySumSolution {
public int minSubArrayLen(int s, int[] nums) {
int min = 0;
int result = Integer.MAX_VALUE;
int sum = 0;
if(nums.length==0) return 0;
for (int i = 0;i<nums.length-1;i++){
if(nums[i]<s){
min = 1;
}else{
min = 0;
}
sum = nums[i];
int j=i+1;
while(j<nums.length){
sum += nums[j];
min ++;
if (sum >= s){
if(min < result){
result = min;
}
break;
}
j++;
}
}
return result = (result == Integer.MAX_VALUE )? 0:result;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.cice.fundamentos;
/**
*
* @author TrendingPC
*/
public class BucleFor {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
//Entre otras cosas sirven para recorrer arrays
int [] arrayEnteros = {1, 2, 3, 4, 5};
//con un solo sout puedo pintar todas las posiciones
for ( int i = 0; i < 5; i ++) {
//System.out.println("El valor de i es:" +i);
//o mejor:
System.out.println("El valor del array en su posicion actual es:" + arrayEnteros[i]);
}
// Escribir un bucle y pintarlo para los numero pares del 1 al 100
for (int i = 0; i <= 100; i ++){
if (i % 2 == 0){
System.out.println (i);
}
}
for (int i = 0; i < arrayEnteros.length; i ++) {
System.out.println(arrayEnteros [i]);
}
}
}
|
package bean;
import com.sleepycat.persist.model.Persistent;
@Persistent
public class Link {
private String source;
private String type;
private String dest;
private double weight;
public Link() {
}
public Link(String source, String type, String dest, double weight) {
super();
this.source = source;
this.type = type;
this.dest = dest;
this.weight = weight;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDest() {
return dest;
}
public void setDest(String dest) {
this.dest = dest;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
@Override
public String toString() {
return "Link [source=" + source + ", type=" + type + ", dest=" + dest + ", weight=" + weight + "]";
}
public boolean equals(Link obj) {
return this.source.equals(obj.getSource()) && this.dest.equals(obj.getDest()) && this.type.equals(obj.getType())
&& this.getWeight() == obj.getWeight() ? true : false;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((dest == null) ? 0 : dest.hashCode());
result = prime * result + ((source == null) ? 0 : source.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
long temp;
temp = Double.doubleToLongBits(weight);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object object) {
Link obj = (Link) object;
return this.source.equalsIgnoreCase(obj.getSource()) && this.dest.equalsIgnoreCase(obj.getDest())
&& this.type.equalsIgnoreCase(obj.getType()) && this.getWeight() == obj.getWeight() ? true : false;
}
}
|
package com.alibaba.excel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import java.util.List;
/**
* Created by 64274 on 2019/5/30.
*
* @ Description: new AnalysisEventListener()
* @ author 山羊来了
* @ date 2019/5/30---13:03
*/
public class MyAnalysisEventListener extends AnalysisEventListener {
private List<Object> rows;
public MyAnalysisEventListener(List<Object> rows) {
this.rows = rows;
}
@Override
public void invoke(Object object, AnalysisContext context) {
System.out.println("invoke..........");
rows.add(object);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
System.out.println("doAfterAllAnalysed..........");
}
}
|
package AnnotationDemo;
import java.lang.annotation.*;
import java.lang.reflect.Method;
/**
* There are three types of 'Retention' annotation SOURCE/CLASS/RUNTIME. They
* change the life-cycle of annotations when the system is run. Class Annotation
* is super-interface for all annotations of interface
*
* @author Bohdan Skrypnyk
*/
@Retention(RetentionPolicy.RUNTIME)
@interface SingleAnno {
int value(); // single annotation must have name 'value'
int num() default 15; // single annotation can be used with 'default' annotations
int num1() default 20;
}
public class Single {
//assign to single annotation
@SingleAnno(100)
//to re-assign any annotation, need to do it for all single/default
//@SingleAnno(value = 100,num = 15, num1 = 5)
public static void myMeth() {
Single single = new Single();
try {
// get object Class, then get object Method
Method meth = single.getClass().getMethod("myMeth");
// get annotations from the method
SingleAnno singleAnno = meth.getAnnotation(SingleAnno.class);
// display annotation value
System.out.println("Single annotation value : " + singleAnno.value()
+ "\nDefault val 1: " + singleAnno.num() + "\nDefault val 2: " + singleAnno.num1());
} catch (NoSuchMethodException ex) {
System.out.println("No Such Method");
}
}
public static void main(String args[]) {
myMeth();
}
}
|
/*
* 文 件 名: ReportRegionService.java
* 版 权: Shanghai zhiduan Mdt InfoTech Ltd
* 描 述: <描述>
* 修 改 人: tongfei
* 修改时间: 2016年10月12日
* 跟踪单号: <跟踪单号>
* 修改单号: <修改单号>
* 修改内容: <修改内容>
*/
package com.rofour.baseball.service.report;
import java.util.List;
import com.rofour.baseball.dao.report.bean.ReportRegionBean;
/**
* <一句话功能简述>
* <功能详细描述>
*
* @author tongfei
* @version [版本号, 2016年10月12日]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
public interface ReportRegionService
{
public List<ReportRegionBean> getRegionList();
public void insert(ReportRegionBean reportRegionBean);
public void delete(int id);
public ReportRegionBean getRegionFromName(String regionName);
public ReportRegionBean getRegionFromId(String regionId);
}
|
package com.tencent.mm.plugin.sns.j;
import com.tencent.mm.plugin.sns.j.c.b;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.vending.app.a$a;
class a$1 extends a$a<b> {
final /* synthetic */ a onj;
a$1(a aVar) {
this.onj = aVar;
super(aVar);
}
protected final /* synthetic */ Object Wd() {
x.i("MicroMsg.SnsTimelineInteractor", "SnsTimelineInteractor index %s", new Object[]{b.class});
return a.bFa();
}
}
|
/**
*
*/
package com.ssh.dao;
import com.ssh.vo.User;
/**
*
* <p>
*
*
* @author 刘晨伟
*
* 创建日期:2015年10月24日
*/
public interface IUserDAO {
public String getUserName();
public String addUser(User user);
}
|
package com.java.twentynine;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatDelegate;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
public class NewsActivity extends AppCompatActivity {
BackendInter bi;
mWbshare wbshareInstance;
mTts ttsInstance;
String id;
NewsText news;
LinearLayout start,pause,share,collect;
LinearLayout head,bottom;
mScrollView middle;
ExpandableListView keyword;
FloatingActionButton fab,baike;
long timer = 0;
boolean collected = false;
boolean recommend = true;
boolean fullscreen = false;
TextView title,tag,author,time,text;
ImageView img;
String sharemsg = "", shareImgUrl;
Handler handler,shareHandler,pictureHandler;
private static final int loadFailed = 0, loadSuccess = 1;
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
int action = event.getAction();
int keycode = event.getKeyCode();
if ((action == KeyEvent.ACTION_DOWN || action == KeyEvent.ACTION_UP) &&
(keycode == KeyEvent.KEYCODE_VOLUME_DOWN || keycode == KeyEvent.KEYCODE_VOLUME_UP))
return onKeyDown(keycode, event);
return super.dispatchKeyEvent(event);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_DOWN:
float size = text.getTextSize();
text.setTextSize(TypedValue.COMPLEX_UNIT_PX, size - 1);
return true;
case KeyEvent.KEYCODE_VOLUME_UP:
float size2 = text.getTextSize();
text.setTextSize(TypedValue.COMPLEX_UNIT_PX, size2 + 1);
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//先做一个加载界面
setContentView(R.layout.loading);
id = getIntent().getStringExtra("NewsText");
showTip("正在加载");
getSupportActionBar().hide();
handler = new Handler() {
@Override
public void handleMessage(Message msg)
{
super.handleMessage(msg);
if (msg.what == loadFailed)
{
showTip((String)msg.obj);
}
else
{
setContentView(R.layout.activity_news);
showTip("加载成功");
bi.viewed(news, NewsActivity.this);
Log.d("viewd?", "result" + bi.isviewed(news.news_ID, NewsActivity.this));
init();
if (bi.isCollectionNews(news.news_ID,NewsActivity.this))
{
collected = true;
((ImageView)findViewById(R.id.s31)).setImageResource(R.drawable.collected);
}
setListeners();
final mAdapter adapter = new mAdapter();
adapter.init(news);
keyword.setAdapter(adapter);
keyword.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView expandableListView, View view, int i, int i1, long l) {
String search = (String)adapter.getChild(i,i1);
Intent intent = new Intent(NewsActivity.this, BaikeWebActivity.class);
intent.putExtra("keyword", search);
showTip("跳转到百度百科...");
startActivity(intent);
return true;
}
});
text.setText(news.news_Content);
tag.setText(news.newsClassTag);
time.setText(news.news_Time.substring(0,8));
author.setText(news.news_Author);
title.setText(news.news_Title);
if (bi.getPicturesDisplay(NewsActivity.this) == 0)
new Thread(getPicture).start();
}
setResult(msg.what);
}
};
shareHandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
showTip("handler share " + sharemsg);
Bitmap map = msg.getData().getParcelable("bitmap");
wbshareInstance.setThumbImg(map);
wbshareInstance.shareMessage();
}
};
pictureHandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
Glide.with(getApplicationContext())
.load(shareImgUrl)
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.skipMemoryCache(true)
.dontAnimate()
.placeholder(R.drawable.pig)
.into(img);
showTip("图片Url:" + shareImgUrl + " from:" + (recommend ? "推荐算法" : "详情图片"));
}
};
bi = new BackendInter();
new Thread(new Runnable() {
@Override
public void run() {
try {
news = bi.getNewsText(id, NewsActivity.this);
Message msg = new Message();
msg.what = loadSuccess;
handler.sendMessage(msg);
} catch (Exception ex) {
Message msg = new Message();
msg.obj = ex.toString();
msg.what = loadFailed;
handler.sendMessage(msg);
}
}
}).start();
AppCompatDelegate.setDefaultNightMode(bi.getNight(NewsActivity.this));
}
Runnable getPicture = new Runnable() {
@Override
public void run() {
String pic = news.news_Pictures;
if (pic.contains(".jpg") || pic.contains(".png") || pic.contains(".bmp") || pic.contains(".jpeg"))
{
String[] pictures = pic.split(";");
String[] picture = pictures[0].split(" ");
if (picture[0].contains(".jpg") || picture[0].contains(".png") || picture[0].contains(".bmp")
|| picture[0].contains(".jpeg"))
{
shareImgUrl = picture[0];
recommend = false;
}
//新闻列表图片加载
}
if (recommend)
{
shareImgUrl = bi.getRandPictures(news.Keywords);
}
pictureHandler.sendMessage(new Message());
}
};
void init()
{
wbshareInstance = new mWbshare();
ttsInstance = new mTts();
keyword = (ExpandableListView) findViewById(R.id.keyword);
title = (TextView) findViewById(R.id.newsTitle2);
tag = (TextView) findViewById(R.id.newsTag2);
author = (TextView) findViewById(R.id.newsAuthor2);
time = (TextView) findViewById(R.id.newsTime2);
text = (TextView) findViewById(R.id.newsText);
img = (ImageView) findViewById(R.id.imgres2);
start = (LinearLayout) findViewById(R.id.s1);
pause = (LinearLayout) findViewById(R.id.s2);
collect = (LinearLayout) findViewById(R.id.s3);
share = (LinearLayout) findViewById(R.id.s4);
head = (LinearLayout) findViewById(R.id.news_header);
middle = (mScrollView) findViewById(R.id.middle);
bottom = (LinearLayout) findViewById(R.id.news_menu);
fab = (FloatingActionButton) findViewById(R.id.floatingActionButton);
baike = (FloatingActionButton) findViewById(R.id.baike);
ImageButton ib = (ImageButton) findViewById(R.id.imageButton);
ib.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
}
private static final int NOTINIT = 0,SPEAKING = 1,PAUSING = 2,STOP = 3;
private int ttsState = NOTINIT;
private void fullScreen(boolean full)
{
if (full)
{
head.setVisibility(View.GONE);
bottom.setVisibility(View.GONE);
fullscreen = true;
}
else
{
head.setVisibility(View.VISIBLE);
bottom.setVisibility(View.VISIBLE);
fullscreen = false;
}
}
void setListeners()
{
middle.setOnScrollListener(new mScrollView.OnScrollChangedListener() {
@Override
public void onScrollChanged(int x, int y, int oldX, int oldY) {
int diff = y - oldY;
//忽略扰动
if (diff < 10 && diff > -10)
{
return;
}
long thistime = System.currentTimeMillis();
if (thistime - timer < 1000)
{
timer = thistime;
return;
}
if (fullscreen)
{
timer = thistime;
return;
}
timer = thistime;
if (diff > 10)
{
//fullScreen(true);
}
}
});
baike.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int Vis = keyword.getVisibility();
if (Vis == View.GONE)
{
keyword.setVisibility(View.VISIBLE);
}
else if (Vis == View.VISIBLE)
{
keyword.setVisibility(View.GONE);
}
}
});
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (fullscreen)
{
fullScreen(false);
}
else
{
fullScreen(true);
}
}
});
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (ttsState == NOTINIT || ttsState == STOP)
{
ttsInstance.initEngine(NewsActivity.this, news.news_Content);
ttsInstance.startSpeaking();
//动画效果
((ImageView)findViewById(R.id.s11)).setImageResource(R.drawable.pause);
((TextView)findViewById(R.id.s12)).setText(R.string.暂停);
showTip("播放");
ttsState = SPEAKING;
}
else if (ttsState == SPEAKING)
{
ttsInstance.pauseSpeaking();
((ImageView)findViewById(R.id.s11)).setImageResource(R.drawable.play);
((TextView)findViewById(R.id.s12)).setText(R.string.resume);
showTip("暂停");
ttsState = PAUSING;
}
else if (ttsState == PAUSING)
{
ttsInstance.resumeSpeaking();
((ImageView)findViewById(R.id.s11)).setImageResource(R.drawable.pause);
((TextView)findViewById(R.id.s12)).setText(R.string.暂停);
showTip("继续");
ttsState = SPEAKING;
}
}
});
pause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (ttsInstance.isSpeaking())
{
ttsInstance.stopSpeaking();
}
ttsInstance.destroy();
ttsState = STOP;
showTip("结束TTS语音");
((ImageView)findViewById(R.id.s11)).setImageResource(R.drawable.play);
((TextView)findViewById(R.id.s12)).setText(R.string.播放);
}
});
collect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (collected)
{
bi.delCollectionNews(news,NewsActivity.this);
collected = false;
((ImageView)findViewById(R.id.s31)).setImageResource(R.drawable.favorites);
}
else if (!collected)
{
bi.addCollectionNews(news, NewsActivity.this);
collected = true;
((ImageView)findViewById(R.id.s31)).setImageResource(R.drawable.collected);
}
}
});
share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
wbshareInstance.init(NewsActivity.this);
wbshareInstance.setShareInfo(news);
showTip("正在生成分享,请等待...");
new Thread(shareDownload).start();
}
});
}
Runnable shareDownload = new Runnable() {
@Override
public void run() {
Message msg = new Message();
try{
Bitmap bitmap = BitmapFactory.decodeStream(getImageStream(shareImgUrl));
Bundle bundle = new Bundle();
bundle.putParcelable("bitmap",bitmap);
msg.setData(bundle);
sharemsg = "success";
shareHandler.sendMessage(msg);
}catch (Exception e)
{
sharemsg = "fail";
shareHandler.sendMessage(msg);
}
}
};
public InputStream getImageStream(String path) throws Exception
{
showTip("getImageStream +" + path);
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod("GET");
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
return conn.getInputStream();
}
return null;
}
private void showTip(String s)
{
Log.d("NewsActivity.class","Tip = " + s);
}
private class mAdapter extends BaseExpandableListAdapter {
List<NewsText.Keyword> keywordList;
List<NewsText.Person> persons,locations;
private static final int KEYWORD = 0, PERSON = 1, LOCATION = 2;
public void init(NewsText news)
{
keywordList = news.Keywords;
persons = news.persons;
locations = news.locations;
}
String getParentText(int i)
{
switch (i)
{
case KEYWORD:
return "Keywords";
case PERSON:
return "Persons";
case LOCATION:
return "Locations";
default:
return "default";
}
}
@Override
public int getGroupCount() {
return 3;
}
@Override
public int getChildrenCount(int i) {
switch (i)
{
case KEYWORD:
return keywordList.size();
case PERSON:
return persons.size();
case LOCATION:
return locations.size();
default:
return 0;
}
}
@Override
public Object getGroup(int i) {
switch (i)
{
case KEYWORD:
return keywordList;
case PERSON:
return persons;
case LOCATION:
return locations;
default:
return null;
}
}
@Override
public Object getChild(int i, int i1) {
switch (i)
{
case KEYWORD:
return keywordList.get(i1).word;
case PERSON:
return persons.get(i1).word;
case LOCATION:
return locations.get(i1).word;
default:
return null;
}
}
@Override
public long getGroupId(int i) {
return i;
}
@Override
public long getChildId(int i, int i1) {
return i * i1;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) {
View res = LayoutInflater.from(NewsActivity.this).inflate(R.layout.expand_item, viewGroup,false);
TextView text = res.findViewById(R.id.keys);
if (text!=null)
text.setText(getParentText(i));
else
showTip("cant find textview");
return res;
}
@Override
public View getChildView(int i, int i1, boolean b, View view, ViewGroup viewGroup) {
View res = LayoutInflater.from(NewsActivity.this).inflate(R.layout.expand_item, viewGroup,false);
TextView text = res.findViewById(R.id.keys);
if (text!=null)
{
if (i == KEYWORD)
{
text.setText(keywordList.get(i1).word);
}
else if (i == PERSON)
{
text.setText(persons.get(i1).word);
}
else
text.setText(locations.get(i1).word);
}
else
showTip("cant find textview");
return res;
}
@Override
public boolean isChildSelectable(int i, int i1) {
return true;
}
}
}
|
package com.bw.movie.mvp.view.apdater.tabapdaters;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bumptech.glide.Glide;
import com.bw.movie.R;
import com.bw.movie.mvp.model.bean.Movieinfo;
import java.util.List;
public class MovieHotApdater extends RecyclerView.Adapter<MovieHotViewHoder> {
Context context;
List<Movieinfo.ResultBean> list;
boolean guanzhu = false;
public MovieHotApdater(Context context, List<Movieinfo.ResultBean> list) {
this.context = context;
this.list = list;
}
@NonNull
@Override
public MovieHotViewHoder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
MovieHotViewHoder hoder = new MovieHotViewHoder(LayoutInflater.from(context).inflate(R.layout.movie_hot_item,parent,false));
return hoder;
}
@Override
public void onBindViewHolder(@NonNull final MovieHotViewHoder holder, int position) {
Glide.with(context).load(list.get(position).getImageUrl()).into(holder.ivMovieImage);
//holder.ivMovieImage.setImageURI(Uri.parse(list.get(position).getImageUrl()));
holder.tvTitle.setText(list.get(position).getSummary());
holder.tvname.setText(list.get(position).getName()+"");
holder.hot_btn_heart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(v==holder.hot_btn_heart){
if(guanzhu){
holder.hot_btn_heart.setImageResource(R.drawable.guanzhu);
}else {
holder.hot_btn_heart.setImageResource(R.drawable.guanzhu1);
}
guanzhu=!guanzhu;
}
}
});
}
@Override
public int getItemCount() {
return list.size();
}
}
|
package com.techlab.basicsofjava;
public class ArrayOfObject {
public static void main(String args[]) {
Object[] thisIsAObjectArray = { "Java Code", new Integer(4) };
System.out.println(thisIsAObjectArray[0]);
System.out.println(thisIsAObjectArray[1]);
// step1 : first create array of 10 elements that holds object addresses.
Emp[] employees = new Emp[10];
// step2 : now create objects in a loop.
for (int i = 0; i < employees.length; i++) {
employees[i] = new Emp(i + 1);// this will call constructor.
}
}
}
class Emp {
int eno;
public Emp(int no) {
eno = no;
System.out.println("emp constructor called..eno is.." + eno);
}
}
|
package com.gerray.fmsystem.ContractorModule;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.gerray.fmsystem.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
public class ContractorProfile extends Fragment {
private ImageView consImage;
private TextView consName, consEmail, consPhone, consSpec, consLoc, consType;
FirebaseAuth auth;
FirebaseDatabase firebaseDatabase;
DatabaseReference firebaseDatabaseReference, reference;
FirebaseUser firebaseUser;
public ContractorProfile() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_consultant_profile, container, false);
consImage = view.findViewById(R.id.consultant_image);
consName = view.findViewById(R.id.cons_name);
consEmail = view.findViewById(R.id.cons_email);
consPhone = view.findViewById(R.id.cons_phone);
consSpec = view.findViewById(R.id.cons_specs);
consType = view.findViewById(R.id.cons_employ);
consLoc = view.findViewById(R.id.cons_loc);
auth = FirebaseAuth.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
firebaseDatabaseReference = firebaseDatabase.getReference();
reference = firebaseDatabase.getReference();
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (firebaseUser != null) {
firebaseDatabaseReference.child("Contractor").child(firebaseUser.getUid())
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (snapshot.child("consultantName").exists()) {
String name = snapshot.child("consultantName").getValue().toString().trim();
consName.setText(name);
}
if (snapshot.child("emailAddress").exists()) {
String emailAddress = snapshot.child("emailAddress").getValue().toString().trim();
consEmail.setText(emailAddress);
}
if (snapshot.child("specialization").exists()) {
String specs = snapshot.child("specialization").getValue().toString().trim();
consSpec.setText(specs);
}
if (snapshot.child("phoneNumber").exists()) {
String phone = snapshot.child("phoneNumber").getValue().toString().trim();
consPhone.setText(phone);
}
if (snapshot.child("consultantLocation").exists()) {
String location = snapshot.child("consultantLocation").getValue().toString().trim();
consLoc.setText(location);
}
if (snapshot.child("category").exists()) {
String category = snapshot.child("category").getValue().toString().trim();
consType.setText(category);
}
if (snapshot.child("consultantImageUrl").exists()) {
String imageUrl = snapshot.child("consultantImageUrl").getValue().toString().trim();
Picasso.with(getContext()).load(imageUrl).into(consImage);
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
return view;
}
}
|
package it.usi.xframe.xas.bfintf;
/**
* Home interface for Enterprise Bean: XasAnnounce
*/
public interface XasAnnounceHome extends javax.ejb.EJBHome {
/**
* Creates a default instance of Session Bean: XasAnnounce
*/
public it.usi.xframe.xas.bfintf.XasAnnounce create()
throws javax.ejb.CreateException, java.rmi.RemoteException;
}
|
/* *****************************************************************************
* Name: Ada Lovelace
* Coursera User ID: 123456
* Last modified: October 16, 1842
**************************************************************************** */
import edu.princeton.cs.algs4.LinkedQueue;
import edu.princeton.cs.algs4.StdRandom;
public class Board {
private int boardSize;
private int blankX, blankY;
private int[][] boardTiles;
private Board twinBoard;
private boolean twinReady;
// create a board from an n-by-n array of tiles,
// where tiles[row][col] = tile at (row, col)
public Board(int[][] tiles)
{
this.boardSize = tiles.length;
this.boardTiles = new int[this.boardSize][this.boardSize];
this.twinReady = false;
for (int i = 0; i < tiles.length; i++)
{
for (int j = 0; j < tiles[i].length; j++)
{
this.boardTiles[i][j] = tiles[i][j];
if (tiles[i][j] == 0)
{
this.blankX = j;
this.blankY = i;
}
}
}
}
// string representation of this board
public String toString()
{
StringBuilder result = new StringBuilder(Integer.toString(this.boardSize));
result.append(System.lineSeparator());
for (int i = 0; i < this.boardSize; i++)
{
for (int j = 0; j < this.boardSize; j++)
{
result.append(Integer.toString(this.boardTiles[i][j]));
if (j != this.boardSize - 1) result.append(" ");
}
if (i != this.boardSize - 1) result.append(System.lineSeparator());
}
return result.toString();
}
// board dimension n
public int dimension()
{
return this.boardSize;
}
// number of tiles out of place
public int hamming()
{
int hammingDistance = 0;
for (int i = 0; i < this.boardSize; i++)
{
for (int j = 0; j < this.boardSize; j++)
{
if (this.boardTiles[i][j] == 0) continue;
if (this.boardTiles[i][j] != this.boardSize * i + j + 1)
{
hammingDistance += 1;
}
}
}
return hammingDistance;
}
// sum of Manhattan distances between tiles and goal
public int manhattan()
{
int manhattanDistance = 0;
for (int i = 0; i < this.boardSize; i++)
{
for (int j = 0; j < this.boardSize; j++)
{
if (this.boardTiles[i][j] == 0) continue;
if (this.boardTiles[i][j] != this.boardSize * i + j + 1)
{
manhattanDistance += Math.abs((this.boardTiles[i][j] - 1) / this.boardSize - i);
manhattanDistance += Math.abs((this.boardTiles[i][j] - 1) % this.boardSize - j);
}
}
}
return manhattanDistance;
}
// is this board the goal board?
public boolean isGoal()
{
return (this.manhattan() == 0);
}
// does this board equal y?
public boolean equals(Object y)
{
if (y == null) return false;
if (y == this) return true;
if (!(y.getClass().equals(this.getClass()))) return false;
Board b = (Board) y;
if (this.boardSize != b.boardSize) return false;
for (int i = 0; i < this.boardSize; i++)
{
for (int j = 0; j < this.boardSize; j++)
{
if (this.boardTiles[i][j] != b.boardTiles[i][j]) return false;
}
}
return true;
}
// all neighboring boards
public Iterable<Board> neighbors()
{
LinkedQueue<Board> neighbors = new LinkedQueue<Board>();
if (this.blankX == 0 && this.blankY == 0)
{
Board n1, n2;
n1 = new Board(this.boardTiles);
n2 = new Board(this.boardTiles);
n1.boardTiles[0][0] = n1.boardTiles[0][1];
n1.boardTiles[0][1] = 0;
n1.blankY = 0;
n1.blankX = 1;
n2.boardTiles[0][0] = n2.boardTiles[1][0];
n2.boardTiles[1][0] = 0;
n2.blankY = 1;
n2.blankX = 0;
neighbors.enqueue(n1);
neighbors.enqueue(n2);
}
else if (this.blankX == 0 && this.blankY == this.boardSize - 1)
{
Board n1, n2;
n1 = new Board(this.boardTiles);
n2 = new Board(this.boardTiles);
n1.boardTiles[this.boardSize - 1][0] = n1.boardTiles[this.boardSize - 1][1];
n1.boardTiles[this.boardSize - 1][1] = 0;
n1.blankY = this.boardSize - 1;
n1.blankX = 1;
n2.boardTiles[this.boardSize - 1][0] = n2.boardTiles[this.boardSize - 2][0];
n2.boardTiles[this.boardSize - 2][0] = 0;
n2.blankY = this.boardSize - 2;
n2.blankX = 0;
neighbors.enqueue(n1);
neighbors.enqueue(n2);
}
else if (this.blankX == this.boardSize - 1 && this.blankY == 0)
{
Board n1, n2;
n1 = new Board(this.boardTiles);
n2 = new Board(this.boardTiles);
n1.boardTiles[0][this.boardSize - 1] = n1.boardTiles[0][this.boardSize - 2];
n1.boardTiles[0][this.boardSize - 2] = 0;
n1.blankY = 0;
n1.blankX = this.boardSize - 2;
n2.boardTiles[0][this.boardSize - 1] = n2.boardTiles[1][this.boardSize - 1];
n2.boardTiles[1][this.boardSize - 1] = 0;
n2.blankY = 1;
n2.blankX = this.boardSize - 1;
neighbors.enqueue(n1);
neighbors.enqueue(n2);
}
else if (this.blankX == this.boardSize - 1 && this.blankY == this.boardSize - 1)
{
Board n1, n2;
n1 = new Board(this.boardTiles);
n2 = new Board(this.boardTiles);
n1.boardTiles[this.boardSize - 1][this.boardSize - 1] = n1.boardTiles[this.boardSize - 1][this.boardSize - 2];
n1.boardTiles[this.boardSize - 1][this.boardSize - 2] = 0;
n1.blankY = this.boardSize - 1;
n1.blankX = this.boardSize - 2;
n2.boardTiles[this.boardSize - 1][this.boardSize - 1] = n2.boardTiles[this.boardSize - 2][this.boardSize - 1];
n2.boardTiles[this.boardSize - 2][this.boardSize - 1] = 0;
n2.blankY = this.boardSize - 2;
n2.blankX = this.boardSize - 1;
neighbors.enqueue(n1);
neighbors.enqueue(n2);
}
else if (this.blankX == 0)
{
Board n1, n2, n3;
n1 = new Board(this.boardTiles);
n2 = new Board(this.boardTiles);
n3 = new Board(this.boardTiles);
n1.boardTiles[this.blankY][0] = n1.boardTiles[this.blankY - 1][0];
n1.boardTiles[this.blankY - 1][0] = 0;
n1.blankY = this.blankY - 1;
n1.blankX = 0;
n2.boardTiles[this.blankY][0] = n2.boardTiles[this.blankY + 1][0];
n2.boardTiles[this.blankY + 1][0] = 0;
n2.blankY = this.blankY + 1;
n2.blankX = 0;
n3.boardTiles[this.blankY][0] = n3.boardTiles[this.blankY][1];
n3.boardTiles[this.blankY][1] = 0;
n3.blankY = this.blankY;
n3.blankX = 1;
neighbors.enqueue(n1);
neighbors.enqueue(n2);
neighbors.enqueue(n3);
}
else if (this.blankY == 0)
{
Board n1, n2, n3;
n1 = new Board(this.boardTiles);
n2 = new Board(this.boardTiles);
n3 = new Board(this.boardTiles);
n1.boardTiles[0][this.blankX] = n1.boardTiles[0][this.blankX - 1];
n1.boardTiles[0][this.blankX - 1] = 0;
n1.blankY = 0;
n1.blankX = this.blankX - 1;
n2.boardTiles[0][this.blankX] = n2.boardTiles[0][this.blankX + 1];
n2.boardTiles[0][this.blankX + 1] = 0;
n2.blankY = 0;
n2.blankX = this.blankX + 1;
n3.boardTiles[0][this.blankX] = n3.boardTiles[1][this.blankX];
n3.boardTiles[1][this.blankX] = 0;
n3.blankY = 1;
n3.blankX = this.blankX;
neighbors.enqueue(n1);
neighbors.enqueue(n2);
neighbors.enqueue(n3);
}
else if (this.blankX == this.boardSize - 1)
{
Board n1, n2, n3;
n1 = new Board(this.boardTiles);
n2 = new Board(this.boardTiles);
n3 = new Board(this.boardTiles);
n1.boardTiles[this.blankY][this.boardSize - 1] = n1.boardTiles[this.blankY - 1][this.boardSize - 1];
n1.boardTiles[this.blankY - 1][this.boardSize - 1] = 0;
n1.blankY = this.blankY - 1;
n1.blankX = this.boardSize - 1;
n2.boardTiles[this.blankY][this.boardSize - 1] = n2.boardTiles[this.blankY + 1][this.boardSize - 1];
n2.boardTiles[this.blankY + 1][this.boardSize - 1] = 0;
n2.blankY = this.blankY + 1;
n2.blankX = this.boardSize - 1;
n3.boardTiles[this.blankY][this.boardSize - 1] = n3.boardTiles[this.blankY][this.boardSize - 2];
n3.boardTiles[this.blankY][this.boardSize - 2] = 0;
n3.blankY = this.blankY;
n3.blankX = this.boardSize - 2;
neighbors.enqueue(n1);
neighbors.enqueue(n2);
neighbors.enqueue(n3);
}
else if (this.blankY == this.boardSize - 1)
{
Board n1, n2, n3;
n1 = new Board(this.boardTiles);
n2 = new Board(this.boardTiles);
n3 = new Board(this.boardTiles);
n1.boardTiles[this.boardSize - 1][this.blankX] = n1.boardTiles[this.boardSize - 1][this.blankX - 1];
n1.boardTiles[this.boardSize - 1][this.blankX - 1] = 0;
n1.blankY = this.boardSize - 1;
n1.blankX = this.blankX - 1;
n2.boardTiles[this.boardSize - 1][this.blankX] = n2.boardTiles[this.boardSize - 1][this.blankX + 1];
n2.boardTiles[this.boardSize - 1][this.blankX + 1] = 0;
n2.blankY = this.boardSize - 1;
n2.blankX = this.blankX + 1;
n3.boardTiles[this.boardSize - 1][this.blankX] = n3.boardTiles[this.boardSize - 2][this.blankX];
n3.boardTiles[this.boardSize - 2][this.blankX] = 0;
n3.blankY = this.boardSize - 2;
n3.blankX = this.blankX;
neighbors.enqueue(n1);
neighbors.enqueue(n2);
neighbors.enqueue(n3);
}
else
{
Board n1, n2, n3, n4;
n1 = new Board(this.boardTiles);
n2 = new Board(this.boardTiles);
n3 = new Board(this.boardTiles);
n4 = new Board(this.boardTiles);
n1.boardTiles[this.blankY][this.blankX] = n1.boardTiles[this.blankY - 1][this.blankX];
n1.boardTiles[this.blankY - 1][this.blankX] = 0;
n1.blankY = this.blankY - 1;
n1.blankX = this.blankX;
n2.boardTiles[this.blankY][this.blankX] = n2.boardTiles[this.blankY + 1][this.blankX];
n2.boardTiles[this.blankY + 1][this.blankX] = 0;
n2.blankY = this.blankY + 1;
n2.blankX = this.blankX;
n3.boardTiles[this.blankY][this.blankX] = n3.boardTiles[this.blankY][this.blankX - 1];
n3.boardTiles[this.blankY][this.blankX - 1] = 0;
n3.blankY = this.blankY;
n3.blankX = this.blankX - 1;
n4.boardTiles[this.blankY][this.blankX] = n4.boardTiles[this.blankY][this.blankX + 1];
n4.boardTiles[this.blankY][this.blankX + 1] = 0;
n4.blankY = this.blankY;
n4.blankX = this.blankX + 1;
neighbors.enqueue(n1);
neighbors.enqueue(n2);
neighbors.enqueue(n3);
neighbors.enqueue(n4);
}
return neighbors;
}
// a board that is obtained by exchanging any pair of tiles
public Board twin()
{
if (this.twinReady) return this.twinBoard;
else
{
this.twinBoard = new Board(this.boardTiles);
int tempY, tempX, tempY2, tempX2;
do {
tempX = StdRandom.uniform(0, this.boardSize);
tempY = StdRandom.uniform(0, this.boardSize);
tempX2 = StdRandom.uniform(0, this.boardSize);
tempY2 = StdRandom.uniform(0, this.boardSize);
} while (this.twinBoard.boardTiles[tempY][tempX] == 0 || this.twinBoard.boardTiles[tempY2][tempX2] == 0 || (tempX == tempX2 && tempY == tempY2));
int temp = this.twinBoard.boardTiles[tempY][tempX];
this.twinBoard.boardTiles[tempY][tempX] = this.twinBoard.boardTiles[tempY2][tempX2];
this.twinBoard.boardTiles[tempY2][tempX2] = temp;
this.twinReady = true;
return this.twinBoard;
}
}
// unit testing (not graded)
public static void main(String[] args)
{
}
}
|
package ru.shipov.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Service;
import ru.shipov.spring.beans.Client;
import ru.shipov.spring.beans.Event;
import ru.shipov.spring.beans.EventType;
import ru.shipov.spring.configs.AppConfig;
import ru.shipov.spring.configs.LoggerConfig;
import ru.shipov.spring.loggers.EventLogger;
import javax.annotation.Resource;
import java.util.Map;
@Service
public class App {
@Autowired
private Client client;
@Resource(name = "#{T(ru.shipov.spring.beans.Event).isDay() ? 'fileEventLogger' : 'consoleEventLogger'}")
private EventLogger logger;
@Resource(name = "loggerMap")
private Map<EventType, EventLogger> loggers;
// private static ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
private static AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
public App() {
}
App(Client client, EventLogger logger, Map<EventType, EventLogger> loggers) {
this.client = client;
this.logger = logger;
this.loggers = loggers;
}
public void logEvent(String message, EventType eventType) {
EventLogger logger = loggers.get(eventType);
if (logger == null)
logger = this.logger;
Event event = context.getBean("event", Event.class);
event.setMessage(message.replace(client.getId(), client.getFullName()));
logger.logEvent(event);
}
public static void main(String[] args) {
context.register(AppConfig.class, LoggerConfig.class);
context.scan("ru.shipov.spring");
context.refresh();
App app = context.getBean("app", App.class);
Client client = context.getBean(Client.class);
Event event = context.getBean(Event.class);
app.logEvent("Hi 1!", EventType.INFO);
app.logEvent("1, wake up!", EventType.ERROR);
context.close();
}
}
|
package mnm.mods.tabbychat.test;
import static org.junit.Assert.*;
import org.junit.Test;
import mnm.mods.tabbychat.util.ChatTextUtils;
import net.minecraft.event.ClickEvent;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.IChatComponent;
public class ChatTextUtilsTest {
@Test
public void testSubChat() {
assertEquals(makeChat(false), ChatTextUtils.subChat(makeChat(true), 7));
}
private static IChatComponent makeChat(boolean tag) {
IChatComponent chat = new ChatComponentText(tag ? "[test] " : "");
chat.getChatStyle().setBold(true);
{
IChatComponent colored = new ChatComponentText("This should be green. ");
colored.getChatStyle().setColor(EnumChatFormatting.GREEN);
chat.appendSibling(colored);
}
chat.appendText(" ");
{
IChatComponent link = new ChatComponentText("This is a link.");
link.getChatStyle().setChatClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, "http://google.com/"));
chat.appendSibling(link);
}
return chat;
}
}
|
package com.tencent.mm.plugin.webview.ui.tools.jsapi;
import com.tencent.mm.sdk.platformtools.x;
class g$102 implements Runnable {
final /* synthetic */ g qiK;
g$102(g gVar) {
this.qiK = gVar;
}
public final void run() {
try {
g.h(this.qiK, new i());
} catch (Exception e) {
x.i("MicroMsg.MsgHandler", "openCunstomWebview, close window exception : %s", new Object[]{e.getMessage()});
}
}
}
|
package chart;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
class Artist extends JFrame {
Container cp = getContentPane();
JTextField textField = new JTextField("");
public Artist(chart_db db){
setTitle("singer °Ë»ö");
cp.setLayout(null);
textField.setBounds(20, 20, 120, 40);
cp.add(textField);
JButton btn = new JButton("È®ÀÎ");
btn.setBounds(150, 20, 100, 40);
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (textField.getText().equals("")) {
return;
}
ArrayList<chartVO> list = db.selectData_artist(textField.getText());
if( list.size() == 0 ) {
return;
}
new inner_TextAreaEx(list);
textField.setText("");
}
});
cp.add(btn);
setSize(300,300);
setVisible(false);
}
}
|
package com.tencent.mm.plugin.appbrand.jsapi.camera;
import com.tencent.mm.plugin.appbrand.jsapi.h;
public final class f extends h {
private static final int CTRL_INDEX = 334;
public static final String NAME = "onCameraStop";
}
|
package com.prog.test.oops;
public class InitAndStaticBlock {
static{
System.out.println("static block test");
}
{
System.out.println("init outer block test");
}
public InitAndStaticBlock() {
System.out.println("constructor loading");
}
/**
* @param args
*/
public static void main(String[] args) {
InitAndStaticBlock test =new InitAndStaticBlock();
InitAndStaticBlock test1=new InitAndStaticBlock();
/***
* if init block is defined inside the main method/other method so this block will
* treat as normal statement and will print the statement
*/
{
System.out.println("init block inside main method test");
}
}
}
|
package application;
public class Liste1
{
private String departement;
private String nom;
private Double quantite;
private Double prix;
private Double total;
//constructeur vide
public Liste1()
{
this(null);
}
//Constructeur avec 1 paramètre
public Liste1(String nom)
{
this.nom=nom;
this.departement="";
this.quantite=0.0;
this.prix=0.0;
}
//Getters et Setters
public String getDepartement() {
return departement;
}
public void setDepartement(String departement) {
this.departement = departement;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public Double getQuantite() {
return quantite;
}
public void setQuantite(Double quantite) {
this.quantite = quantite;
}
public Double getPrix() {
return prix;
}
public void setPrix(Double prix) {
this.prix = prix;
}
public Double getTotal() {
return total;
}
public void setTotal(Double total) {
this.total = total;
}
}
|
package com.tencent.mm.plugin.appbrand.ui;
import android.view.View;
import android.view.View.OnClickListener;
import com.tencent.mm.kernel.g;
import com.tencent.mm.plugin.appbrand.compat.a.a;
import com.tencent.mm.plugin.appbrand.s.j;
import com.tencent.mm.plugin.sport.b.d;
import com.tencent.mm.pluginsdk.model.m;
import com.tencent.mm.ui.base.h;
import java.util.LinkedList;
import java.util.List;
class AppBrandOpenWeRunSettingUI$1 implements OnClickListener {
final /* synthetic */ AppBrandOpenWeRunSettingUI guU;
AppBrandOpenWeRunSettingUI$1(AppBrandOpenWeRunSettingUI appBrandOpenWeRunSettingUI) {
this.guU = appBrandOpenWeRunSettingUI;
}
public final void onClick(View view) {
d.kB(13);
AppBrandOpenWeRunSettingUI appBrandOpenWeRunSettingUI = this.guU;
appBrandOpenWeRunSettingUI.getString(j.app_tip);
appBrandOpenWeRunSettingUI.guT = h.a(appBrandOpenWeRunSettingUI, ((a) g.l(a.class)).cq(appBrandOpenWeRunSettingUI), true, null);
appBrandOpenWeRunSettingUI.guT.show();
g.Eh().dpP.a(30, appBrandOpenWeRunSettingUI);
List linkedList = new LinkedList();
linkedList.add("gh_43f2581f6fd6");
List linkedList2 = new LinkedList();
linkedList2.add(Integer.valueOf(1));
g.Eh().dpP.a(new m(1, linkedList, linkedList2, "", ""), 0);
}
}
|
package com.optimus.model;
import java.io.Serializable;
/**
* Created by Dongchuang on 2017/11/14.
*/
public class ResultInfo implements Serializable {
private static final long serialVersionUID = -1L;
private String resultInfo;
public ResultInfo(String resultInfo) {
super();
this.resultInfo = resultInfo;
}
public ResultInfo() {
super();
}
public String getResultInfo() {
return resultInfo;
}
public void setResultInfo(String resultInfo) {
this.resultInfo = resultInfo;
};
}
|
package GUI.App;
import Controller.UserController;
import Controller.UserControllerImpl;
import com.google.zxing.NotFoundException;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.FileChooser;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
public class AppController {
private UserController userController;
private boolean visitingFacility;
@FXML
Button registerToFacilityButton;
@FXML
AnchorPane activeTokenPane;
public void setUserController(UserControllerImpl userController) {
this.userController = userController;
}
@FXML
public void handleCheckInfectionStatusButton(javafx.event.ActionEvent actionEvent) {
try {
boolean possibleInfection = userController.checkInfectionStatus();
//Show an alert
String headerText = "";
if (possibleInfection) headerText = "High risk: an infected token has been found in your logs";
else headerText = "No Risk: no infected tokens have been found in your logs";
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("STATUS");
alert.setHeaderText(null);
alert.setContentText(headerText);
alert.show();
return;
} catch (Exception e) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("ERROR");
alert.setHeaderText(null);
alert.setContentText(e.getMessage());
alert.show();
return;
}
}
@FXML
public void handleRegisterToFacilityButton(javafx.event.ActionEvent actionEvent) {
if (visitingFacility) {
try {
userController.leaveFacility();
} catch (Exception e) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("ERROR");
alert.setHeaderText(null);
alert.setContentText(e.getMessage());
alert.show();
return;
}
} else {
try {
userController.registerToFacility();
} catch (Exception e) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("ERROR");
alert.setHeaderText(null);
alert.setContentText(e.getMessage());
alert.show();
return;
}
}
}
public void tokenUp(LocalDateTime startTime, LocalDateTime stopTime, ImageView symbol) {
//format the dates to a string notation
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String startTimeString = startTime.format(formatter);
String stopTimeString = stopTime.format(formatter);
//Create the layout for the remaining times
Label activeTokenHeader = new Label("Current active token");
activeTokenHeader.setFont(new Font("Arial", 24));
Label startTimeLabel = new Label("Valid from: " + startTimeString);
Label stopTimeLabel = new Label("Valid until: " + stopTimeString);
Label ExpireInformationLabel = new Label("A new token will be fetched when the current token expires");
//Place the elements in a vbox
VBox container = new VBox(activeTokenHeader, startTimeLabel, stopTimeLabel, ExpireInformationLabel, symbol);
container.setAlignment(Pos.CENTER);
container.setSpacing(5);
//Clear the active token pane and place the vbox in it
activeTokenPane.getChildren().clear();
activeTokenPane.getChildren().add(container);
AnchorPane.setTopAnchor(container, 0.0);
AnchorPane.setLeftAnchor(container, 0.0);
AnchorPane.setRightAnchor(container, 0.0);
//change the register to facility button text
registerToFacilityButton.setText("Leave registered facility");
//Tell the app controller that a token is active
visitingFacility = true;
}
public void tokenDown() {
//Clear the active token pane and add label
activeTokenPane.getChildren().clear();
activeTokenPane.getChildren().add(new Label("No active token at the moment"));
registerToFacilityButton.setText("Register to facility");
//Tell the app controller that no token is active
visitingFacility = false;
}
}
|
/**
*/
package ca.uwaterloo.gp.fmp.impl;
import ca.uwaterloo.gp.fmp.Clonable;
import ca.uwaterloo.gp.fmp.ConfigState;
import ca.uwaterloo.gp.fmp.FmpPackage;
import java.util.Collection;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.util.EObjectWithInverseResolvingEList;
import org.eclipse.emf.ecore.util.InternalEList;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Clonable</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link ca.uwaterloo.gp.fmp.impl.ClonableImpl#getState <em>State</em>}</li>
* <li>{@link ca.uwaterloo.gp.fmp.impl.ClonableImpl#getClones <em>Clones</em>}</li>
* <li>{@link ca.uwaterloo.gp.fmp.impl.ClonableImpl#getPrototype <em>Prototype</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public abstract class ClonableImpl extends NodeImpl implements Clonable {
/**
* The default value of the '{@link #getState() <em>State</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getState()
* @generated
* @ordered
*/
protected static final ConfigState STATE_EDEFAULT = ConfigState.UNDECIDED_LITERAL;
/**
* The cached value of the '{@link #getState() <em>State</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getState()
* @generated
* @ordered
*/
protected ConfigState state = STATE_EDEFAULT;
/**
* The cached value of the '{@link #getClones() <em>Clones</em>}' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getClones()
* @generated
* @ordered
*/
protected EList clones;
/**
* The cached value of the '{@link #getPrototype() <em>Prototype</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getPrototype()
* @generated
* @ordered
*/
protected Clonable prototype;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ClonableImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected EClass eStaticClass() {
return FmpPackage.Literals.CLONABLE;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ConfigState getState() {
return state;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setState(ConfigState newState) {
ConfigState oldState = state;
state = newState == null ? STATE_EDEFAULT : newState;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, FmpPackage.CLONABLE__STATE, oldState, state));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList getClones() {
if (clones == null) {
clones = new EObjectWithInverseResolvingEList(Clonable.class, this, FmpPackage.CLONABLE__CLONES, FmpPackage.CLONABLE__PROTOTYPE);
}
return clones;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Clonable getPrototype() {
if (prototype != null && prototype.eIsProxy()) {
InternalEObject oldPrototype = (InternalEObject)prototype;
prototype = (Clonable)eResolveProxy(oldPrototype);
if (prototype != oldPrototype) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, FmpPackage.CLONABLE__PROTOTYPE, oldPrototype, prototype));
}
}
return prototype;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Clonable basicGetPrototype() {
return prototype;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetPrototype(Clonable newPrototype, NotificationChain msgs) {
Clonable oldPrototype = prototype;
prototype = newPrototype;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, FmpPackage.CLONABLE__PROTOTYPE, oldPrototype, newPrototype);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setPrototype(Clonable newPrototype) {
if (newPrototype != prototype) {
NotificationChain msgs = null;
if (prototype != null)
msgs = ((InternalEObject)prototype).eInverseRemove(this, FmpPackage.CLONABLE__CLONES, Clonable.class, msgs);
if (newPrototype != null)
msgs = ((InternalEObject)newPrototype).eInverseAdd(this, FmpPackage.CLONABLE__CLONES, Clonable.class, msgs);
msgs = basicSetPrototype(newPrototype, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, FmpPackage.CLONABLE__PROTOTYPE, newPrototype, newPrototype));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case FmpPackage.CLONABLE__CLONES:
return ((InternalEList)getClones()).basicAdd(otherEnd, msgs);
case FmpPackage.CLONABLE__PROTOTYPE:
if (prototype != null)
msgs = ((InternalEObject)prototype).eInverseRemove(this, FmpPackage.CLONABLE__CLONES, Clonable.class, msgs);
return basicSetPrototype((Clonable)otherEnd, msgs);
}
return super.eInverseAdd(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case FmpPackage.CLONABLE__CLONES:
return ((InternalEList)getClones()).basicRemove(otherEnd, msgs);
case FmpPackage.CLONABLE__PROTOTYPE:
return basicSetPrototype(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case FmpPackage.CLONABLE__STATE:
return getState();
case FmpPackage.CLONABLE__CLONES:
return getClones();
case FmpPackage.CLONABLE__PROTOTYPE:
if (resolve) return getPrototype();
return basicGetPrototype();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case FmpPackage.CLONABLE__STATE:
setState((ConfigState)newValue);
return;
case FmpPackage.CLONABLE__CLONES:
getClones().clear();
getClones().addAll((Collection)newValue);
return;
case FmpPackage.CLONABLE__PROTOTYPE:
setPrototype((Clonable)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void eUnset(int featureID) {
switch (featureID) {
case FmpPackage.CLONABLE__STATE:
setState(STATE_EDEFAULT);
return;
case FmpPackage.CLONABLE__CLONES:
getClones().clear();
return;
case FmpPackage.CLONABLE__PROTOTYPE:
setPrototype((Clonable)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean eIsSet(int featureID) {
switch (featureID) {
case FmpPackage.CLONABLE__STATE:
return state != STATE_EDEFAULT;
case FmpPackage.CLONABLE__CLONES:
return clones != null && !clones.isEmpty();
case FmpPackage.CLONABLE__PROTOTYPE:
return prototype != null;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (state: ");
result.append(state);
result.append(')');
return result.toString();
}
} //ClonableImpl
|
/**
*
*/
package com.bridgelabz.jdbc;
/**
* Created By:Medini P.D
* Date:- 12/06/2018
* Purpose:
*/
public class StringPoolTest {
public static void main(String[] args) { // Integer.valueOf(), String.equals()
String eol = System.getProperty("line.separator"); //java7 System.lineSeparator();
String s1 = "Yash".intern();
System.out.format("Val:%s Hash:%s SYS:%s "+eol, s1, s1.hashCode(), System.identityHashCode(s1));
String s2 = "Yas"+"h".intern();
System.out.format("Val:%s Hash:%s SYS:%s "+eol, s2, s2.hashCode(), System.identityHashCode(s2));
String s3 = "Yas".intern()+"h".intern();
System.out.format("Val:%s Hash:%s SYS:%s "+eol, s3, s3.hashCode(), System.identityHashCode(s3));
String s4 = "Yas"+"h";
System.out.format("Val:%s Hash:%s SYS:%s "+eol, s4, s4.hashCode(), System.identityHashCode(s4));
}
}
|
package com.tencent.mm.plugin.webview.modeltools;
import com.tencent.mm.aa.q;
import com.tencent.mm.bt.h.d;
import com.tencent.mm.g.a.bc;
import com.tencent.mm.g.a.kx;
import com.tencent.mm.g.a.ty;
import com.tencent.mm.kernel.g;
import com.tencent.mm.model.ar;
import com.tencent.mm.model.au;
import com.tencent.mm.model.bs;
import com.tencent.mm.model.bv.a;
import com.tencent.mm.network.n;
import com.tencent.mm.plugin.webview.fts.h;
import com.tencent.mm.plugin.webview.fts.i;
import com.tencent.mm.plugin.webview.model.ac;
import com.tencent.mm.plugin.webview.model.ad;
import com.tencent.mm.plugin.webview.model.ae;
import com.tencent.mm.plugin.webview.model.ag;
import com.tencent.mm.plugin.webview.model.am;
import com.tencent.mm.plugin.webview.modelcache.k;
import com.tencent.mm.protocal.c.cfk;
import com.tencent.mm.protocal.c.iv;
import com.tencent.mm.sdk.b.b;
import com.tencent.mm.sdk.b.c;
import com.tencent.mm.sdk.platformtools.x;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import org.xwalk.core.XWalkEnvironment;
public final class e implements ar {
private static final HashMap<Integer, d> cVM;
private a hdi = new 15(this);
private n jkm = new 9(this);
private c<bc> jul = new 7(this);
private ad pTR;
private ae pTS;
private ac pTT;
private h pTU;
private com.tencent.mm.plugin.webview.model.e pTV;
private ag pTW;
private com.tencent.mm.plugin.webview.b.e pTX;
private i pTY;
private com.tencent.mm.plugin.webview.fts.c pTZ;
private com.tencent.mm.plugin.webview.fts.d pUa;
private com.tencent.mm.plugin.webview.c.a pUb;
private final com.tencent.mm.plugin.webview.modelcache.n pUc = new com.tencent.mm.plugin.webview.modelcache.n();
c pUd = new 16(this);
final c<ty> pUe = new c<ty>() {
{
this.sFo = ty.class.getName().hashCode();
}
public final /* synthetic */ boolean a(b bVar) {
am.pSK = ((ty) bVar).cfE.cfF.substring(11);
return true;
}
};
c pUf = new 2(this);
c pUg = new 3(this);
c pUh = new 4(this);
c pUi = new 5(this);
c pUj = new 6(this);
private c pUk = new c<kx>() {
{
this.sFo = kx.class.getName().hashCode();
}
public final /* synthetic */ boolean a(b bVar) {
kx kxVar = (kx) bVar;
if (kxVar.bVh.scene == 0) {
e.bUV().pPq = 0;
e.bUV().pLd = null;
} else {
e.bUV().pPq = 1;
e.bUV().pLd = new cfk();
e.bUV().pLd.szS = 1;
e.bUV().pLd.szT = new iv();
e.bUV().pLd.szT.bPS = kxVar.bVh.appId;
e.bUV().pLd.szT.rka = kxVar.bVh.type;
e.bUV().pLd.szT.rkb = kxVar.bVh.version;
e.bUV().pLd.szT.rkc = kxVar.bVh.bVj;
}
return false;
}
};
public static e bUR() {
au.HN();
e eVar = (e) bs.iK("plugin.webview");
if (eVar != null) {
return eVar;
}
eVar = new e();
x.e("MicroMsg.SubCoreTools", "new SubCoreTools add to subCore:%d", new Object[]{Integer.valueOf(eVar.hashCode())});
au.HN().a("plugin.webview", eVar);
return eVar;
}
public static com.tencent.mm.plugin.webview.c.a bUS() {
if (bUR().pUb == null) {
bUR().pUb = new com.tencent.mm.plugin.webview.c.a();
}
return bUR().pUb;
}
public static com.tencent.mm.plugin.webview.fts.c bUT() {
if (bUR().pTZ == null) {
bUR().pTZ = new com.tencent.mm.plugin.webview.fts.c();
}
return bUR().pTZ;
}
public static com.tencent.mm.plugin.webview.fts.d bUU() {
if (bUR().pUa == null) {
bUR().pUa = new com.tencent.mm.plugin.webview.fts.d();
}
return bUR().pUa;
}
public static i bUV() {
if (bUR().pTY == null) {
bUR().pTY = new i();
}
return bUR().pTY;
}
public static ad bUW() {
if (bUR().pTR == null) {
bUR().pTR = new ad();
}
return bUR().pTR;
}
public static ae bUX() {
if (bUR().pTS == null) {
bUR().pTS = ae.bUk();
}
return bUR().pTS;
}
public static h bUY() {
if (bUR().pTU == null) {
e bUR = bUR();
au.HU();
bUR.pTU = new h(com.tencent.mm.model.c.FO());
}
return bUR().pTU;
}
public static com.tencent.mm.plugin.webview.model.e bUZ() {
if (bUR().pTV == null) {
e bUR = bUR();
au.HU();
bUR.pTV = new com.tencent.mm.plugin.webview.model.e(com.tencent.mm.model.c.FO());
}
return bUR().pTV;
}
public static ag bVa() {
if (bUR().pTW == null) {
e bUR = bUR();
au.HU();
bUR.pTW = new ag(com.tencent.mm.model.c.FO());
}
return bUR().pTW;
}
public static com.tencent.mm.plugin.webview.b.e bVb() {
if (bUR().pTX == null) {
e bUR = bUR();
g.Ek();
bUR.pTX = new com.tencent.mm.plugin.webview.b.e(g.Ei().dqq);
}
return bUR().pTX;
}
public final void onAccountRelease() {
x.i("MicroMsg.SubCoreTools", "onAccountRelease hc:%d", new Object[]{Integer.valueOf(hashCode())});
com.tencent.mm.sdk.b.a.sFg.c(this.pUf);
com.tencent.mm.sdk.b.a.sFg.c(this.pUh);
com.tencent.mm.sdk.b.a.sFg.c(this.pUi);
com.tencent.mm.sdk.b.a.sFg.c(this.pUj);
com.tencent.mm.sdk.b.a.sFg.c(this.pUd);
com.tencent.mm.sdk.b.a.sFg.c(this.pUk);
com.tencent.mm.sdk.b.a.sFg.c(this.jul);
com.tencent.mm.sdk.b.a.sFg.c(this.pUg);
au.b(this.jkm);
if (this.pTT != null) {
ac acVar = this.pTT;
if (acVar.pRI != null) {
com.tencent.mm.plugin.downloader.model.d.aCU();
com.tencent.mm.plugin.downloader.model.b.b(acVar.pRI);
}
if (acVar.pRJ != null && acVar.pRJ.size() > 0) {
for (Long l : acVar.pRJ) {
x.i("MicroMsg.WebViewAutoDownloader", "remove download task : %d", new Object[]{l});
com.tencent.mm.plugin.downloader.model.d.aCU().cl(l.longValue());
}
}
}
if (this.pUa != null) {
com.tencent.mm.plugin.webview.fts.d dVar = this.pUa;
com.tencent.mm.sdk.b.a.sFg.c(dVar.fIu);
if (dVar.pOz != null) {
au.DF().b(1048, dVar);
au.DF().c(dVar.pOz);
dVar.pOz = null;
}
this.pUa = null;
}
if (this.pTY != null) {
i iVar = this.pTY;
iVar.pPi.dead();
iVar.pPt.dead();
i.a aVar = iVar.pPv;
if (aVar.pPn != null) {
au.DF().c(aVar.pPn);
}
if (aVar.pPB != null) {
aVar.pPB.gYf = true;
}
i.b bVar = iVar.pPw;
if (bVar.pPD != null) {
au.DF().b(bVar.pPD.getType(), bVar.pPx);
}
if (iVar.jsw != null) {
((com.tencent.mm.plugin.fts.a.n) g.n(com.tencent.mm.plugin.fts.a.n.class)).cancelSearchTask(iVar.jsw);
iVar.jsw = null;
}
this.pTY = null;
}
if (this.pTZ != null) {
com.tencent.mm.plugin.webview.fts.c cVar = this.pTZ;
cVar.nll.dead();
cVar.pOt.dead();
q.KH().d(cVar);
this.pTZ = null;
}
au.getSysCmdMsgExtension().b("hijackconfig", this.hdi, true);
if (this.pTV != null) {
this.pTV.bTV();
}
com.tencent.mm.plugin.webview.modelcache.n nVar = this.pUc;
au.getSysCmdMsgExtension().b("webcache", nVar.pTc, true);
com.tencent.mm.sdk.b.a.sFg.c(nVar.pTd);
com.tencent.mm.sdk.b.a.sFg.c(nVar.pTe);
com.tencent.mm.plugin.webview.modelcache.q bUL = com.tencent.mm.plugin.webview.modelcache.q.a.bUL();
com.tencent.mm.sdk.b.a.sFg.c(bUL.pTk);
com.tencent.mm.sdk.b.a.sFg.c(bUL.pTl);
bUL.release(true);
this.pUe.dead();
h bTK = h.bTK();
h.a aVar2 = bTK.pPb;
if (aVar2.pPn != null) {
au.DF().c(aVar2.pPn);
}
if (aVar2.pPo != null) {
aVar2.pPo.gYf = true;
}
bTK.pPi.dead();
g.m(com.tencent.mm.plugin.webview.d.a.class);
}
static {
HashMap hashMap = new HashMap();
cVM = hashMap;
hashMap.put(Integer.valueOf("WebViewHostsFilterTable".hashCode()), new 1());
List<com.tencent.mm.plugin.webview.modelcache.d.a> linkedList = new LinkedList();
linkedList.add(com.tencent.mm.plugin.webview.modelcache.a.bUD());
linkedList.addAll(k.bUH());
linkedList.add(com.tencent.mm.plugin.webview.modelcache.h.bUD());
for (com.tencent.mm.plugin.webview.modelcache.d.a aVar : linkedList) {
cVM.put(Integer.valueOf(aVar.id), aVar);
}
cVM.put(Integer.valueOf("WEBVIEW_JSLOG_BLOCK_LIST_TABLE".hashCode()), new 10());
cVM.put(Integer.valueOf("WEBVIEW_LOCAL_DATA".hashCode()), new 11());
cVM.put(Integer.valueOf("WEBVIEW_DATA".hashCode()), new 12());
cVM.put(Integer.valueOf("WEBVIEW_HISTORY_DATA".hashCode()), new 13());
}
public final HashMap<Integer, d> Ci() {
return cVM;
}
public final void gi(int i) {
}
public final void bn(boolean z) {
x.i("MicroMsg.SubCoreTools", "onAccountPostReset hc:%d", new Object[]{Integer.valueOf(hashCode())});
au.HN();
if (((e) bs.iK("plugin.webview")) == null) {
au.HN().a("plugin.webview", new e());
x.e("MicroMsg.SubCoreTools", "getCore, should not be here:%d", new Object[]{Integer.valueOf(r0.hashCode())});
}
com.tencent.mm.sdk.b.a.sFg.b(this.pUf);
com.tencent.mm.sdk.b.a.sFg.b(this.pUh);
com.tencent.mm.sdk.b.a.sFg.b(this.pUi);
com.tencent.mm.sdk.b.a.sFg.b(this.pUj);
com.tencent.mm.sdk.b.a.sFg.b(this.pUd);
com.tencent.mm.sdk.b.a.sFg.b(this.pUk);
com.tencent.mm.sdk.b.a.sFg.b(this.jul);
com.tencent.mm.sdk.b.a.sFg.b(this.pUg);
au.getSysCmdMsgExtension().a("hijackconfig", this.hdi, true);
au.a(this.jkm);
com.tencent.mm.plugin.webview.modelcache.n nVar = this.pUc;
com.tencent.mm.plugin.webview.modelcache.n.bUJ();
com.tencent.mm.plugin.webview.modelcache.q bUL = com.tencent.mm.plugin.webview.modelcache.q.a.bUL();
com.tencent.mm.sdk.b.a.sFg.b(bUL.pTk);
com.tencent.mm.sdk.b.a.sFg.b(bUL.pTl);
au.getSysCmdMsgExtension().a("webcache", nVar.pTc, true);
com.tencent.mm.sdk.b.a.sFg.b(nVar.pTd);
com.tencent.mm.sdk.b.a.sFg.b(nVar.pTe);
com.tencent.mm.plugin.ah.c.nbP.a(new am());
this.pUe.cht();
com.tencent.mm.y.g.b.a(new 14(this));
XWalkEnvironment.init(com.tencent.mm.sdk.platformtools.ad.getContext());
g.Eg();
XWalkEnvironment.setGrayValueByUserId(com.tencent.mm.kernel.a.Df());
h.bTK();
h.start();
g.a(com.tencent.mm.plugin.webview.d.a.class, new com.tencent.mm.plugin.webview.ui.tools.bag.k());
}
public final void bo(boolean z) {
com.tencent.mm.plugin.webview.modelcache.n.bUJ();
}
}
|
package littleservantmod.client.gui;
import littleservantmod.api.IServant;
import littleservantmod.api.profession.IProfession;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.inventory.GuiContainer;
public class ElementChangeProfessionCurrent extends ElementChangeProfession {
protected IProfession now;
protected GuiButton buttonOk;
public ElementChangeProfessionCurrent(GuiContainer gui, int posX, int posY, IProfession profession, IServant servant, GuiButton buttonOk) {
super(gui, posX, posY, profession, servant);
this.now = profession;
this.buttonOk = buttonOk;
}
public void setProfession(IProfession profession) {
this.profession = profession;
this.buttonOk.enabled = !this.now.equals(this.profession);
}
public IProfession getProfession() {
return this.profession;
}
}
|
package com.etar.purifier.modules.websokect.entity;
/**
* @author hzh
* @date 2018/10/25
*/
public class WSResponeVo {
private String devCode;
private int state;
public String getDevCode() {
return devCode;
}
public void setDevCode(String devCode) {
this.devCode = devCode;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
}
|
package org.firstinspires.ftc.teamcode;
import com.qualcomm.hardware.bosch.BNO055IMU;
import com.qualcomm.hardware.bosch.JustLoggingAccelerationIntegrator;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.HardwareMap;
import com.qualcomm.robotcore.hardware.Servo;
import org.firstinspires.ftc.robotcore.external.Telemetry;
import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit;
import org.firstinspires.ftc.robotcore.external.navigation.AxesOrder;
import org.firstinspires.ftc.robotcore.external.navigation.AxesReference;
import org.firstinspires.ftc.robotcore.external.navigation.Orientation;
/**
* Created by Abhishek Vangipuram on 8/28/2017.
*/
public class RobotHardware {
public DcMotor frontLeftMotor;
public DcMotor frontRightMotor;
public DcMotor backLeftMotor;
public DcMotor backRightMotor;
public DcMotor andyMarkMotor;
public Servo servo1;
public Servo servo2;
public Servo servo3;
BNO055IMU imu;
Telemetry localtelemetry;
public final int ANDYMARK_REVOLUTION = 1120;
public final int TETRIX_REVOLUTION = 1440;
public final double WHEEL_DIAMETER = 4.0;
public final double COUNTS_PER_INCH = ANDYMARK_REVOLUTION/(WHEEL_DIAMETER*Math.PI);
public DcMotor getFrontLeft()
{
return frontLeftMotor;
}
public DcMotor getFrontRight()
{
return frontRightMotor;
}
public DcMotor getBackLeft()
{
return backLeftMotor;
}
public DcMotor getBackRight()
{
return backRightMotor;
}
public DcMotor getAndyMarkMotor(){return andyMarkMotor;}
public HardwareMap hwMap = null;
public void init(HardwareMap hwMap) {
// Save reference to Hardware map
frontLeftMotor = hwMap.dcMotor.get("frontLeft");
frontRightMotor = hwMap.dcMotor.get("frontRight");
backLeftMotor = hwMap.dcMotor.get("backLeft");
backRightMotor = hwMap.dcMotor.get("backRight");
//servo for the balancing stone
servo1=hwMap.servo.get("servo1");
//servo for displacing the jewels
servo2=hwMap.servo.get("servo2");
//adding servo for clamp
servo3=hwMap.servo.get("servo3");
//adding rev imu (gyro,accelerometer,etc.)
// Set up the parameters with which we will use our IMU. Note that integration
// algorithm here just reports accelerations to the logcat log; it doesn't actually
// provide positional information.
BNO055IMU.Parameters parameters = new BNO055IMU.Parameters();
parameters.angleUnit = BNO055IMU.AngleUnit.DEGREES;
parameters.accelUnit = BNO055IMU.AccelUnit.METERS_PERSEC_PERSEC;
parameters.calibrationDataFile = "BNO055IMUCalibration.json"; // see the calibration sample opmode
parameters.loggingEnabled = true;
parameters.loggingTag = "IMU";
parameters.accelerationIntegrationAlgorithm = new JustLoggingAccelerationIntegrator();
// Retrieve and initialize the IMU. We expect the IMU to be attached to an I2C port
// on a Core Device Interface Module, configured to be a sensor of type "AdaFruit IMU",
// and named "imu".
imu = hwMap.get(BNO055IMU.class, "imu");
imu.initialize(parameters);
// Set all motors to zero power
servo1.setPosition(0);
servo2.setPosition(0);
resetMotors();
resetEncoderValues();
}
public void resetMotors(){
frontLeftMotor.setPower(0);
frontRightMotor.setPower(0);
backLeftMotor.setPower(0);
backRightMotor.setPower(0);
}
public void reset(){
resetMotors();
resetEncoderValues();
servo1.setPosition(0);
servo2.setPosition(0);
servo3.setPosition(0);
}
public void setDrivePower(double left, double right) {
frontLeftMotor.setPower(left);
backLeftMotor.setPower(left);
frontRightMotor.setPower(right);
backRightMotor.setPower(right);
}
/*
final double FORWARD_SPEED = 0.3;
final double TURN_SPEED = 0.2;
protected void driveForward(){setDrivePower( FORWARD_SPEED,FORWARD_SPEED);}
protected void driveBackward(){setDrivePower( -FORWARD_SPEED,-FORWARD_SPEED);}
protected void turnRight() {setDrivePower(TURN_SPEED,-TURN_SPEED);}
protected void turnLeft() {setDrivePower(-TURN_SPEED,TURN_SPEED);}
*/
protected void driveForwardInches(double inches, double power){
//make inches/counts negative to go backwards
resetEncoderValues();
int counts = (int)Math.round(COUNTS_PER_INCH*inches);
frontRightMotor.setTargetPosition(-counts);
backRightMotor.setTargetPosition(-counts);
frontLeftMotor.setTargetPosition(counts);
backLeftMotor.setTargetPosition(counts);
setEncoderMode(DcMotor.RunMode.RUN_TO_POSITION);
setDrivePower(power,power);
while (Math.abs(frontLeftMotor.getTargetPosition()-frontLeftMotor.getCurrentPosition())>10){
}
resetMotors();
resetEncoderValues();
}
protected void resetEncoderValues(){
setEncoderMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
}
protected void setEncoderMode(DcMotor.RunMode mode){
frontRightMotor.setMode(mode);
backLeftMotor.setMode(mode);
backRightMotor.setMode(mode);
frontLeftMotor.setMode(mode);
}
public void driveStraight(double power){
double tolerance=5;
Orientation angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES);
if(imu.isGyroCalibrated()){
setEncoderMode(DcMotor.RunMode.RUN_USING_ENCODER); //keep this mode if encoders work
//if(Math.abs(angles.firstAngle)<=tolerance){
while(Math.abs(angles.firstAngle)<=tolerance){
setDrivePower(0.1,0.3);
//}
}
//if (Math.abs(angles.firstAngle)>=tolerance){
while(Math.abs(angles.firstAngle)>=tolerance){
setDrivePower(0.3,0.1);
//}
}
//else{setDrivePower(power,power);}
}
//else{
setDrivePower(power,power);
//}
}
public void turnDegrees(float degrees){
double tolerance;
Orientation angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES);
if(imu.isGyroCalibrated()){
setEncoderMode(DcMotor.RunMode.RUN_USING_ENCODER); //keep this mode if encoders work
telemetry.addData("Heading:",angles.firstAngle);
//if(degrees>0){
while(angles.firstAngle<degrees){
setDrivePower(-0.2,0.2);
}
//}
//if(degrees<0){
while(angles.firstAngle>degrees){
setDrivePower(0.2,-0.2);
}
resetMotors();
//}
//set angles.firstAngle to 0 by calibrating the sensor to have a new zero
//as otherwise, you will have to turn based off the first 0, or where we start our robot
//place this recalibration code HERE
}
else{
//turnDegreesEncoder --> make a method that turns based on encoders
//turn at a certain power for 1 second, for left and right, find how many degrees it turns
//and using math, find the time to turn per degree with encoders
}
}
}
|
package fiscal;
public enum FiscalSituacaoPesagemEnum {
LIVRE(1L), FISCALIZAR(2L), AGUARDANDO_PESAGEM(3L), LIBERADO(4L), RETIDO(5L), FUGA(6L), AUTUADO(7L), PESAGEM_REALIZADA(8L), ATENDIMENTO(9L);
FiscalSituacaoPesagemEnum(Long value) {
this.value = value;
}
private Long value;
public void setValue(Long value) {
this.value = value;
}
public Long getValue() {
return value;
}
public boolean compareTo(FiscalSituacaoPesagem situacaoPesagem) {
return situacaoPesagem.getId().equals(this.getValue()) ? true : false;
}
}
|
package recursive;
public class DemoRecursions {
public static void main(String[] args) {
// TODO Auto-generated method stub
int result = RecursiveMaths.sum(3);
System.out.println(result);
int fib = RecursiveMaths.fibonacci(8);
System.out.println(fib);
}
}
|
// Sun Certified Java Programmer
// Chapter 7, P620_2
// Generics and Collections
import java.util.*;
class Dog extends Animal {
}
|
package com.sporsimdi.action.util;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class UtilDate {
private Calendar cal;
public UtilDate() {
cal = Calendar.getInstance(new Locale("tr"));
}
public UtilDate(Date date) {
cal = Calendar.getInstance(new Locale("tr"));
if (date != null) {
cal.setTime(date);
} else {
cal = null;
}
}
public UtilDate(int year, int month, int date) {
cal = Calendar.getInstance(new Locale("tr"));
cal.set(year, month, date);
}
public void setTime(Date date) {
cal.setTime(date);
}
public Date getTime() {
return cal.getTime();
}
public int getMonthCount(UtilDate utilDate) {
return getMonthCount(utilDate.getTime());
}
public int getMonthCount(Date date) {
Calendar calDate = Calendar.getInstance(new Locale("tr"));
calDate.setTime(date);
int count = (calDate.get(Calendar.YEAR) - cal.get(Calendar.YEAR)) * 12;
count = count + calDate.get(Calendar.MONTH) - cal.get(Calendar.MONTH);
// if (calDate.get(Calendar.DATE) > cal.get(Calendar.DATE)) {
// count = count + 1;
// }
return count;
}
public int get(int field) {
return cal.get(field);
}
public Date add(int field, int amount) {
cal.add(field, amount);
return cal.getTime();
}
public Date addMonth(int amount) {
int gun = cal.get(Calendar.DATE);
cal.add(Calendar.MONTH, amount);
cal.add(Calendar.DATE, -1);
if (gun - cal.get(Calendar.DATE) > 1) {
cal.add(Calendar.DATE, 1);
}
return cal.getTime();
}
public Date set(int field, int amount) {
int month = cal.get(Calendar.MONTH);
cal.set(field, amount);
if (field == Calendar.DATE) { // ayın son günlerindeki sıkıntıyı
// gidermek için
if (month < cal.get(Calendar.MONTH)) {
cal.set(Calendar.DATE, 1);
cal.add(Calendar.MONTH, -1);
}
}
return cal.getTime();
}
public Date set(int year, int month, int date) {
cal.set(year, month, date);
return cal.getTime();
}
public Date setTimeOnly(int hourOfDay, int minute, int second) {
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE), hourOfDay, minute, second);
return cal.getTime();
}
@Override
public String toString() {
if (cal == null) {
return "~";
} else {
Format dateFormat = new SimpleDateFormat("dd.MMM.yyyy", new Locale("tr"));
return dateFormat.format(cal.getTime());
}
}
public String toString(String pattern) {
if (cal == null) {
return "~";
} else {
Format dateFormat = new SimpleDateFormat(pattern, new Locale("tr"));
return dateFormat.format(cal.getTime());
}
}
public boolean before(UtilDate utildate) {
return cal.before(utildate);
}
public boolean after(UtilDate utildate) {
return cal.after(utildate);
}
public int compareTo(UtilDate utildate) {
return cal.compareTo(utildate.cal);
}
public int compareTo(String str, String pattern) {
Format dateFormat = new SimpleDateFormat(pattern, new Locale("tr"));
Integer intCal = new Integer(dateFormat.format(cal.getTime()));
Integer intStr = new Integer(str);
return intCal.compareTo(intStr);
}
public String getDisplayName(int field) {
return cal.getDisplayName(field, Calendar.LONG, new Locale("tr", "TR"));
}
}
|
package com.ibm.jikesbt;
/*
* Licensed Material - Property of IBM
* (C) Copyright IBM Corp. 1998, 2003
* All rights reserved
*/
import java.io.Serializable;
import java.util.Enumeration;
import java.util.NoSuchElementException;
/**
BT_ConstantPoolItemVector is a variable size contiguous indexable array of {@link BT_ConstantPoolItem}s.
The size of the BT_ConstantPoolItemVector is the number of BT_ConstantPoolItems it contains.
The capacity of the BT_ConstantPoolItemVector is the number of BT_ConstantPoolItems it can hold.
<p> BT_ConstantPoolItems may be inserted at any position up to the size of the
BT_ConstantPoolItemVector, increasing the size of the BT_ConstantPoolItemVector. BT_ConstantPoolItems at any
position in the BT_ConstantPoolItemVector may be removed, shrinking the size of
the BT_ConstantPoolItemVector. BT_ConstantPoolItems at any position in the BT_ConstantPoolItemVector may be replaced,
which does not affect the BT_ConstantPoolItemVector size.
<p> The capacity of a BT_ConstantPoolItemVector may be specified when the BT_ConstantPoolItemVector is
created. If the capacity of the BT_ConstantPoolItemVector is exceeded, the capacity
is increased, doubling by default.
* @author IBM
**/
public final class BT_ConstantPoolItemVector
implements Cloneable, Serializable {
/**
* The number of elements or the size of the vector.
*/
protected int elementCount;
/**
* The elements of the vector.
*/
protected BT_ConstantPoolItem[] elementData;
/**
* The amount by which the capacity of the vector is increased.
*/
protected int capacityIncrement;
/**
* Initial empty value for elementData.
*/
private final static BT_ConstantPoolItem[] emptyData =
new BT_ConstantPoolItem[0];
private static final int DEFAULT_SIZE = 0;
/**
* Constructs a new BT_ConstantPoolItemVector using the default capacity.
*
*/
public BT_ConstantPoolItemVector() {
this(DEFAULT_SIZE, 0);
}
/**
* Constructs a new BT_ConstantPoolItemVector using the specified capacity.
*
*
* @param capacity the initial capacity of the new vector
*/
public BT_ConstantPoolItemVector(int capacity) {
this(capacity, 0);
}
/**
* Constructs a new BT_ConstantPoolItemVector using the specified capacity and
* capacity increment.
*
*
* @param capacity the initial capacity of the new BT_ConstantPoolItemVector
* @param capacityIncrement the amount to increase the capacity
when this BT_ConstantPoolItemVector is full
*/
public BT_ConstantPoolItemVector(int capacity, int capacityIncrement) {
elementCount = 0;
elementData =
(capacity == 0) ? emptyData : new BT_ConstantPoolItem[capacity];
this.capacityIncrement = capacityIncrement;
}
/**
* Adds the specified object at the end of this BT_ConstantPoolItemVector.
*
*
* @param object the object to add to the BT_ConstantPoolItemVector
*/
public void addElement(BT_ConstantPoolItem object) {
insertElementAt(object, elementCount);
}
/**
* Answers the number of elements this BT_ConstantPoolItemVector can hold without
* growing.
*
*
* @return the capacity of this BT_ConstantPoolItemVector
*
* @see #ensureCapacity
* @see #size
*/
public int capacity() {
return elementData.length;
}
/**
* Answers a new BT_ConstantPoolItemVector with the same elements, size, capacity
* and capacityIncrement as this BT_ConstantPoolItemVector.
*
*
* @return a shallow copy of this BT_ConstantPoolItemVector
*
* @see java.lang.Cloneable
*/
public Object clone() {
try {
BT_ConstantPoolItemVector vector =
(BT_ConstantPoolItemVector) super.clone();
int length = elementData.length;
vector.elementData = new BT_ConstantPoolItem[length];
System.arraycopy(elementData, 0, vector.elementData, 0, length);
return vector;
} catch (CloneNotSupportedException e) {
return null;
}
}
/**
* Searches this BT_ConstantPoolItemVector for the specified object.
*
*
* @param object the object to look for in this BT_ConstantPoolItemVector
* @return true if object is an element of this BT_ConstantPoolItemVector, false otherwise
*
* @see #indexOf
* @see java.lang.Object#equals
*/
public boolean contains(BT_ConstantPoolItem object) {
return indexOf(object, 0) != -1;
}
/**
* Copies the elements of this BT_ConstantPoolItemVector into the specified BT_ConstantPoolItem array.
*
*
* @param elements the BT_ConstantPoolItem array into which the elements
* of this BT_ConstantPoolItemVector are copied
*
* @see #clone
*/
public void copyInto(BT_ConstantPoolItem[] elements) {
System.arraycopy(elementData, 0, elements, 0, elementCount);
}
/**
* Answers the element at the specified location in this BT_ConstantPoolItemVector.
*
*
* @param location the index of the element to return in this BT_ConstantPoolItemVector
* @return the element at the specified location
*
* @exception ArrayIndexOutOfBoundsException when location < 0 || >= size()
*
* @see #size
*/
public BT_ConstantPoolItem elementAt(int location) {
//BB fast range check, no need to check for < 0 as the array access will throw the exception
if (location < elementCount) {
return elementData[location];
}
throw new ArrayIndexOutOfBoundsException();
}
/**
* Answers an Enumeration on the elements of this BT_ConstantPoolItemVector. The
* results of the Enumeration may be affected if the contents
* of this BT_ConstantPoolItemVector are modified.
*
*
* @return an Enumeration of the elements of this BT_ConstantPoolItemVector
*
* @see #elementAt
* @see Enumeration
*/
public Enumeration elements() {
return new BT_ArrayEnumerator(elementData, elementCount);
}
/**
* Ensures that this BT_ConstantPoolItemVector can hold the specified number of elements
* without growing.
*
*
* @param minimumCapacity the minimum number of elements that this
* vector will hold before growing
*
* @see #capacity
*/
public void ensureCapacity(int minimumCapacity) {
if (elementData.length < minimumCapacity)
grow(minimumCapacity);
}
/**
* Answers the first element in this BT_ConstantPoolItemVector.
*
*
* @return the element at the first position
*
* @exception NoSuchElementException when this vector is empty
*
* @see #elementAt
* @see #lastElement
* @see #size
*/
public BT_ConstantPoolItem firstElement() {
if (elementCount == 0)
throw new NoSuchElementException();
return elementData[0];
}
private void grow(int newCapacity) {
BT_ConstantPoolItem newData[] = new BT_ConstantPoolItem[newCapacity];
System.arraycopy(elementData, 0, newData, 0, elementCount);
elementData = newData;
}
/**
* Searches in this BT_ConstantPoolItemVector for the index of the specified object. The
* search for the object starts at the beginning and moves towards the
* end of this BT_ConstantPoolItemVector.
*
*
* @param object the object to find in this BT_ConstantPoolItemVector
* @return the index in this BT_ConstantPoolItemVector of the specified element, -1 if the
* element isn't found
*
* @see #contains
* @see #lastIndexOf
*/
public int indexOf(BT_ConstantPoolItem object) {
return indexOf(object, 0);
}
/**
* Searches in this BT_ConstantPoolItemVector for the index of the specified object. The
* search for the object starts at the specified location and moves
* towards the end of this BT_ConstantPoolItemVector.
*
*
* @param object the object to find in this BT_ConstantPoolItemVector
* @param location the index at which to start searching
* @return the index in this BT_ConstantPoolItemVector of the specified element, -1 if the
* element isn't found
*
* @exception ArrayIndexOutOfBoundsException when location < 0
*
* @see #contains
* @see #lastIndexOf
*/
public int indexOf(BT_ConstantPoolItem object, int location) {
BT_ConstantPoolItem element;
for (int i = location; i < elementCount; i++) {
if ((element = elementData[i]) == object)
return i;
if ((element != null) && (element.equals(object)))
return i;
}
return -1;
}
/**
* Inserts the specified object into this BT_ConstantPoolItemVector at the specified
* location. This object is inserted before any previous element at
* the specified location. If the location is equal to the size of
* this BT_ConstantPoolItemVector, the object is added at the end.
*
*
* @param object the object to insert in this BT_ConstantPoolItemVector
* @param location the index at which to insert the element
*
* @exception ArrayIndexOutOfBoundsException when location < 0 || > size()
*
* @see #addElement
* @see #size
*/
public void insertElementAt(
BT_ConstantPoolItem object,
int location) {
int count;
if (location >= 0 && location <= elementCount) {
if (elementCount == elementData.length) {
int newCapacity =
(capacityIncrement == 0 ? elementCount : capacityIncrement)
+ elementCount;
if (newCapacity == 0)
newCapacity++;
grow(newCapacity);
}
if ((count = elementCount - location) > 0) {
System.arraycopy(
elementData,
location,
elementData,
location + 1,
count);
}
elementData[location] = object;
elementCount++;
return;
}
throw new ArrayIndexOutOfBoundsException();
}
/**
* Answers if this BT_ConstantPoolItemVector has no elements, a size of zero.
*
*
* @return true if this BT_ConstantPoolItemVector has no elements, false otherwise
*
* @see #size
*/
public boolean isEmpty() {
return elementCount == 0;
}
/**
* Answers the last element in this BT_ConstantPoolItemVector.
*
*
* @return the element at the last position
*
* @exception NoSuchElementException when this vector is empty
*
* @see #elementAt
* @see #firstElement
* @see #size
*/
public BT_ConstantPoolItem lastElement() {
try {
return elementData[elementCount - 1];
} catch (ArrayIndexOutOfBoundsException e) {
throw new NoSuchElementException();
}
}
/**
* Searches in this BT_ConstantPoolItemVector for the index of the specified object. The
* search for the object starts at the end and moves towards the start
* of this BT_ConstantPoolItemVector.
*
*
* @param object the object to find in this BT_ConstantPoolItemVector
* @return the index in this BT_ConstantPoolItemVector of the specified element, -1 if the
* element isn't found
*
* @see #contains
* @see #indexOf
*/
public int lastIndexOf(BT_ConstantPoolItem object) {
return lastIndexOf(object, elementCount - 1);
}
/**
* Searches in this BT_ConstantPoolItemVector for the index of the specified object. The
* search for the object starts at the specified location and moves
* towards the start of this BT_ConstantPoolItemVector.
*
*
* @param object the object to find in this BT_ConstantPoolItemVector
* @param location the index at which to start searching
* @return the index in this BT_ConstantPoolItemVector of the specified element, -1 if the
* element isn't found
*
* @exception ArrayIndexOutOfBoundsException when location >= size()
*
* @see #contains
* @see #indexOf
*/
public int lastIndexOf(BT_ConstantPoolItem object, int location) {
BT_ConstantPoolItem element;
if (location < elementCount) {
for (int i = location; i >= 0; i--) {
if ((element = elementData[i]) == object)
return i;
if ((element != null) && (element.equals(object)))
return i;
}
return -1;
}
throw new ArrayIndexOutOfBoundsException();
}
/**
* Removes all elements from this BT_ConstantPoolItemVector, leaving the size zero and
* the capacity unchanged.
*
*
* @see #isEmpty
* @see #size
*/
public void removeAllElements() {
for (int i = 0; i < elementCount; i++) {
elementData[i] = null;
}
elementCount = 0;
}
/**
* Removes the first occurrence, starting at the beginning and
* moving towards the end, of the specified object from this
* BT_ConstantPoolItemVector.
*
*
* @param object the object to remove from this BT_ConstantPoolItemVector
* @return true if the specified object was found, false otherwise
*
* @see #removeAllElements
* @see #removeElementAt
* @see #size
*/
public boolean removeElement(BT_ConstantPoolItem object) {
int index;
if ((index = indexOf(object, 0)) == -1)
return false;
removeElementAt(index);
return true;
}
/**
* Removes the element at the specified location from this BT_ConstantPoolItemVector.
*
*
* @param location the index of the element to remove
*
* @exception ArrayIndexOutOfBoundsException when location < 0 || >= size()
*
* @see #removeElement
* @see #removeAllElements
* @see #size
*/
public void removeElementAt(int location) {
if (location < elementCount) {
int size;
elementCount--;
if ((size = elementCount - location) > 0) {
System.arraycopy(
elementData,
location + 1,
elementData,
location,
size);
}
elementData[elementCount] = null;
return;
}
throw new ArrayIndexOutOfBoundsException();
}
/**
* Replaces the element at the specified location in this BT_ConstantPoolItemVector with
* the specified object.
*
*
* @param object the object to add to this BT_ConstantPoolItemVector
* @param location the index at which to put the specified object
*
* @exception ArrayIndexOutOfBoundsException when location < 0 || >= size()
*
* @see #size
*/
public void setElementAt(BT_ConstantPoolItem object, int location) {
if (location < elementCount) {
elementData[location] = object;
return;
}
throw new ArrayIndexOutOfBoundsException();
}
/**
* Sets the size of this BT_ConstantPoolItemVector to the specified size. If there
* are more than length elements in this BT_ConstantPoolItemVector, the elements
* at end are lost. If there are less than length elements in
* the BT_ConstantPoolItemVector, the additional elements contain null.
*
*
* @param length the new size of this BT_ConstantPoolItemVector
*
* @see #size
*/
public void setSize(int length) {
ensureCapacity(length);
if (elementCount > length) {
for (int i = length; i < elementCount; i++)
elementData[i] = null;
}
elementCount = length;
}
/**
* Answers the number of elements in this BT_ConstantPoolItemVector.
*
*
* @return the number of elements in this BT_ConstantPoolItemVector
*
* @see #elementCount
* @see #lastElement
*/
public int size() {
return elementCount;
}
/**
* Answers the string representation of this BT_ConstantPoolItemVector.
*
*
* @return the string representation of this BT_ConstantPoolItemVector
*
* @see #elements
*/
public String toString() {
if (elementCount == 0)
return "[]";
int length = elementCount - 1;
StringBuffer buffer = new StringBuffer();
buffer.append('[');
for (int i = 0; i < length; i++) {
buffer.append(elementData[i]);
buffer.append(',');
}
buffer.append(elementData[length]);
buffer.append(']');
return buffer.toString();
}
/**
* Sets the capacity of this BT_ConstantPoolItemVector to be the same as the size.
*
*
* @see #capacity
* @see #ensureCapacity
* @see #size
*/
public void trimToSize() {
if (elementData.length != elementCount)
grow(elementCount);
}
// ---------- End of code common to all JikesBT Vectors ----------
}
|
package utils;
import java.util.Properties;
import javax.mail.Session;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Message;
import javax.mail.internet.MimeMessage;
import javax.mail.Message.RecipientType;
import javax.mail.Transport;
import javax.mail.MessagingException;
public class EmailSender{
public static void sendEmail(String email, String subject,String msg,String senderEmail,String senderEmailPassword){
Properties properties = new Properties();
properties.put("mail.transport.protocol","smtp");
properties.put("mail.smtp.auth","true");
properties.put("mail.smtp.host","smtp.gmail.com");
properties.put("mail.smtp.port","587");
properties.put("mail.smtp.starttls.enable","true");
Session emailSession = Session.getInstance(properties,new MyPasswordAuthenticator());
MimeMessage message = new MimeMessage(emailSession);
try{
message.setFrom(senderEmail);
message.setRecipients(Message.RecipientType.TO,email);
message.setSubject(subject);
message.setContent(msg,"text/html");
Transport.send(message);
}catch(MessagingException e){
e.printStackTrace();
}
}
}
class MyPasswordAuthenticator extends Authenticator{
public PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication("legecyprezzie@gmail.com","PrezzieLegecy@1");
}
}
|
package com.example.demo.response;
import java.util.List;
import org.springframework.stereotype.Component;
import com.example.demo.model.AirLineDetails;
import lombok.Getter;
import lombok.Setter;
@Component
@Getter
@Setter
public class Response {
private List<AirLineDetails> response;
public List<AirLineDetails> getResponse() {
return response;
}
public void setResponse(List<AirLineDetails> response) {
this.response = response;
}
}
|
package com.example.demojpush.config;
import cn.jpush.api.JPushClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
@Configuration
@ConfigurationProperties
public class JPushConfig {
@Value("${push.appkey}")
private String appkey;
@Value("${push.secret}")
private String secret;
private JPushClient jPushClient;
@PostConstruct
public void initJPUshClient(){
System.out.println("appkey = " + appkey + " secret = " + secret);
jPushClient = new JPushClient(secret, appkey);
}
public JPushClient getjPushClient() {
return jPushClient;
}
}
|
package net.virtuallyabstract.minecraft;
import javax.script.*;
import java.io.*;
import org.bukkit.*;
import org.bukkit.entity.*;
import org.bukkit.plugin.*;
public class ScriptManager
{
private static ScriptEngineManager factory;
static
{
factory = new ScriptEngineManager();
}
public static boolean scriptingEnabled()
{
ScriptEngine engine = factory.getEngineByName("groovy");
if(engine == null)
return false;
else
return true;
}
private static String findDungeonScript(Dungeon d)
{
File test = new File(d.getFileName() + ".groovy");
if(test.exists())
return test.getPath();
test = new File(d.getFileName() + ".js");
if(test.exists())
return test.getPath();
return null;
}
public static void runDungeonStartScript(Dungeon d, Server s, Player p, Plugin plugin)
{
runScript(d, s, p, plugin, "dungeon_start");
}
public static void runDungeonExitScript(Dungeon d, Server s, Player p, Plugin plugin)
{
runScript(d, s, p, plugin, "dungeon_exit");
}
public static void runScript(Dungeon d, Server s, Player p, Plugin plugin, String methodName)
{
String script = findDungeonScript(d);
if(script == null)
return;
ScriptEngine engine = null;
if(script.endsWith("groovy"))
engine = factory.getEngineByName("groovy");
if(script.endsWith("js"))
engine = factory.getEngineByName("js");
if(engine == null)
{
System.out.println("Hmm...found a script: " + script + " but couldn't find an engine for it");
return;
}
engine.put("dungeon", d);
engine.put("server", s);
engine.put("player", p);
engine.put("plugin", plugin);
try
{
engine.eval(new FileReader(script));
if(engine instanceof Invocable)
{
Invocable inv = (Invocable)engine;
inv.invokeFunction(methodName);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.