text
stringlengths
10
2.72M
package jupiterpa; import java.util.*; import lombok.*; import lombok.experimental.*; import jupiterpa.util.*; public interface ISales extends IService { List<MProduct> getProducts(); MProduct getProduct(EID materialId) throws EconomyException; EID postOrder(MOrder order) throws EconomyException; @Data @Accessors(chain = true) public class MProduct { EID materialId; String description; Double price; String currency; } @Data @Accessors(chain = true) public class MOrder { EID orderId; int partner; EID materialId; int quantity; } }
package com.jlgproject.activity; import android.content.Intent; import android.util.Log; import android.view.View; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.handmark.pulltorefresh.library.PullToRefreshBase; import com.handmark.pulltorefresh.library.PullToRefreshListView; import com.jlgproject.R; import com.jlgproject.adapter.BusinessVideoPlayAdapter; import com.jlgproject.base.BaseActivity; import com.jlgproject.http.AddHeaders; import com.jlgproject.http.BaseUrl; import com.jlgproject.http.GetParmars; import com.jlgproject.http.HttpMessageInfo; import com.jlgproject.http.OkHttpUtils; import com.jlgproject.model.Video_Information_Bean; import com.jlgproject.model.Video_List_Bean; import com.jlgproject.util.ConstUtils; import com.jlgproject.util.L; import com.jlgproject.util.SharedUtil; import com.jlgproject.util.ToastUtil; import com.jlgproject.util.UserInfoState; import com.jlgproject.view.CustomView.MyJCVideoPlayerStandard; import java.io.IOException; import java.util.List; import fm.jiecao.jcvideoplayer_lib.JCUserAction; import fm.jiecao.jcvideoplayer_lib.JCUserActionStandard; import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer; import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard; import okhttp3.Call; public class BusinessVideoPlay extends BaseActivity implements View.OnClickListener, HttpMessageInfo.IMessage, AdapterView.OnItemClickListener , PullToRefreshBase.OnRefreshListener2 { MyJCVideoPlayerStandard myJCVideoPlayerStandard; private PullToRefreshListView lv_b_v; private TextView tv_b_v_title, tv_b_v_jianjie, tv_b_v_time;//标题,简介,时间 private String url; // 1.设置几个状态码方便我们进行状态的判断 //正常状态 private static final int NOMORL = 2; //2.是刷新的状态 private static final int REFRESH = 2; //3.上啦刷新加载更多 private static final int LOADMORE = 3; private int status = 1; private int pn = 1; private int ps = 8; private Video_Information_Bean video_list_bean; private BusinessVideoPlayAdapter buness_video; private List<Video_Information_Bean.DataBean.RecommendDetailBean> items; private int id; @Override public int loadWindowLayout() { return R.layout.business_video; } @Override public void initDatas() { Intent intent = getIntent(); url = intent.getStringExtra("url"); id = intent.getIntExtra("id", 0); } @Override public void initViews() { lv_b_v = (PullToRefreshListView) findViewById(R.id.listview); lv_b_v.setOnItemClickListener(this); lv_b_v.setOnRefreshListener(this); lv_b_v.setMode(PullToRefreshBase.Mode.PULL_FROM_END); AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT); View header = getLayoutInflater().inflate(R.layout.video_header, lv_b_v, false); header.setLayoutParams(layoutParams); ListView lv = lv_b_v.getRefreshableView(); lv.addHeaderView(header, null, false); tv_b_v_title = (TextView) header.findViewById(R.id.tv_b_v_title);//标题 tv_b_v_jianjie = (TextView) header.findViewById(R.id.tv_b_v_jianjie);//简介 tv_b_v_time = (TextView) header.findViewById(R.id.tv_b_v_time);//时间 myJCVideoPlayerStandard = (MyJCVideoPlayerStandard) header.findViewById(R.id.jc_video); myJCVideoPlayerStandard.setUp(url, JCVideoPlayerStandard.SCREEN_LAYOUT_NORMAL, ""); myJCVideoPlayerStandard.backButton.setVisibility(View.VISIBLE); myJCVideoPlayerStandard.backButton.setOnClickListener(this);//返回图标点击事件 JCVideoPlayer.setJcUserAction(new MyUserActionStandard()); requestBunessVideo(); } private void requestBunessVideo() { //访问视频详情接口 if (ShowDrawDialog(this)) { HttpMessageInfo<Video_Information_Bean> info = new HttpMessageInfo<>(BaseUrl.BUNESS_VIDEO, new Video_Information_Bean()); info.setiMessage(this); GetParmars parmars = new GetParmars(); parmars.add("pn", pn); parmars.add("ps", ps); L.e("_______",id+""); parmars.add("id", id); OkHttpUtils.getInstance().getServiceMassage(OkHttpUtils.TYPE_GET, info, parmars, null, 1); } } @Override public void onClick(View v) { if (v == myJCVideoPlayerStandard.backButton) { finish(); } } @Override public void getServiceData(Object o) { if (o instanceof Video_Information_Bean && o != null) { video_list_bean = (Video_Information_Bean) o; if (video_list_bean != null) { lv_b_v.onRefreshComplete(); DismissDialog(); SharedUtil.getSharedUtil().putObject(this, ConstUtils.VIDEO_LISTS, video_list_bean); if (video_list_bean.getState().equals("ok")) { Video_Information_Bean.DataBean.CourseDetailBean courseDetail = video_list_bean.getData().getCourseDetail(); if (courseDetail!=null){ tv_b_v_title.setText(courseDetail.getTitle());//视频标题 tv_b_v_jianjie.setText(courseDetail.getBrief());//视频简介 tv_b_v_time.setText(courseDetail.getUpdateTime());//视频时间 Video_Information_Bean.DataBean data = video_list_bean.getData();//获取视频列表 displayData(data); } } else { ToastUtil.showShort(this, video_list_bean.getMessage()); } } } } //抽取的展示数据的方法 private void displayData(final Video_Information_Bean.DataBean manger) { if (items ==null) { items = manger.getRecommendDetail(); buness_video = new BusinessVideoPlayAdapter(BusinessVideoPlay.this, items); lv_b_v.setAdapter(buness_video); buness_video.notifyDataSetChanged(); } if (status == REFRESH) { L.e("--------刷新——————"); items.clear(); buness_video.setItems(items); buness_video.notifyDataSetChanged(); } if (status == LOADMORE) { //上拉加载 List<Video_Information_Bean.DataBean.RecommendDetailBean> items2 = manger.getRecommendDetail(); items.addAll(items2); buness_video.setItems(items); buness_video.notifyDataSetChanged(); } } @Override public void getErrorData(Call call, IOException e) { DismissDialog(); lv_b_v.onRefreshComplete(); ToastUtil.showShort(this, "网络异常,请稍后再试"); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (items != null) { Video_Information_Bean.DataBean.RecommendDetailBean recommendDetailBean = items.get(position - 2); myJCVideoPlayerStandard.setUp(recommendDetailBean.getUrl(), JCVideoPlayerStandard.SCREEN_LAYOUT_NORMAL, ""); myJCVideoPlayerStandard.backButton.setOnClickListener(this);//返回图标点击事件 myJCVideoPlayerStandard.backButton.setVisibility(View.VISIBLE); JCVideoPlayer.setJcUserAction(new MyUserActionStandard()); tv_b_v_title.setText(recommendDetailBean.getTitle()); tv_b_v_jianjie.setText(recommendDetailBean.getBrief()); tv_b_v_time.setText(recommendDetailBean.getUpdateTime()); int id2=recommendDetailBean.getId(); Intent intent =new Intent(); intent.putExtra("id",id2); intent.putExtra("url",recommendDetailBean.getUrl()); intent.setClass(this,BusinessVideoPlay.class); startActivity(intent); finish(); } } @Override public void onPullDownToRefresh(PullToRefreshBase refreshView) { pn = 1; status = REFRESH; requestBunessVideo(); } @Override public void onPullUpToRefresh(PullToRefreshBase refreshView) { pn = pn + 1; status = LOADMORE; requestBunessVideo(); } class MyUserActionStandard implements JCUserActionStandard { @Override public void onEvent(int type, String url, int screen, Object... objects) { switch (type) { case JCUserAction.ON_CLICK_START_ICON: Log.i("USER_EVENT", "ON_CLICK_START_ICON" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen); break; case JCUserAction.ON_CLICK_START_ERROR: Log.i("USER_EVENT", "ON_CLICK_START_ERROR" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen); break; case JCUserAction.ON_CLICK_START_AUTO_COMPLETE: Log.i("USER_EVENT", "ON_CLICK_START_AUTO_COMPLETE" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen); break; case JCUserAction.ON_CLICK_PAUSE: Log.i("USER_EVENT", "ON_CLICK_PAUSE" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen); break; case JCUserAction.ON_CLICK_RESUME: Log.i("USER_EVENT", "ON_CLICK_RESUME" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen); break; case JCUserAction.ON_SEEK_POSITION: Log.i("USER_EVENT", "ON_SEEK_POSITION" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen); break; case JCUserAction.ON_AUTO_COMPLETE: Log.i("USER_EVENT", "ON_AUTO_COMPLETE" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen); break; case JCUserAction.ON_ENTER_FULLSCREEN: Log.i("USER_EVENT", "ON_ENTER_FULLSCREEN" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen); break; case JCUserAction.ON_QUIT_FULLSCREEN: Log.i("USER_EVENT", "ON_QUIT_FULLSCREEN" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen); break; case JCUserAction.ON_ENTER_TINYSCREEN: Log.i("USER_EVENT", "ON_ENTER_TINYSCREEN" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen); break; case JCUserAction.ON_QUIT_TINYSCREEN: Log.i("USER_EVENT", "ON_QUIT_TINYSCREEN" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen); break; case JCUserAction.ON_TOUCH_SCREEN_SEEK_VOLUME: Log.i("USER_EVENT", "ON_TOUCH_SCREEN_SEEK_VOLUME" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen); break; case JCUserAction.ON_TOUCH_SCREEN_SEEK_POSITION: Log.i("USER_EVENT", "ON_TOUCH_SCREEN_SEEK_POSITION" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen); break; case JCUserActionStandard.ON_CLICK_START_THUMB: Log.i("USER_EVENT", "ON_CLICK_START_THUMB" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen); break; case JCUserActionStandard.ON_CLICK_BLANK: Log.i("USER_EVENT", "ON_CLICK_BLANK" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen); break; default: Log.i("USER_EVENT", "unknow"); break; } } } @Override protected void onPause() { super.onPause(); JCVideoPlayer.releaseAllVideos(); } @Override public void onBackPressed() { if (JCVideoPlayer.backPress()) { return; } super.onBackPressed(); } }
package com.tencent.mm.ui.widget.snackbar; import android.app.Activity; import android.content.Context; import android.os.Build.VERSION; import android.os.Handler; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.ViewGroup.MarginLayoutParams; import android.view.WindowManager.LayoutParams; import android.widget.LinearLayout; import android.widget.TextView; import com.tencent.mm.bw.a.f; import com.tencent.mm.bw.a.g; import com.tencent.mm.ui.ao; import com.tencent.mm.ui.aq; public final class a { Handler mHandler = new Handler(); View mParentView; SnackContainer uMA; b uMB; c uMC; private final OnClickListener uMD = new 1(this); public interface b { void aMj(); } public a(Activity activity, int i) { View findViewById = activity.findViewById(16908290); LayoutInflater layoutInflater = (LayoutInflater) activity.getSystemService("layout_inflater"); layoutInflater.inflate(g.snackbar_container, (ViewGroup) findViewById); a((ViewGroup) findViewById, layoutInflater.inflate(g.snackbar_main, (ViewGroup) findViewById, false), i, activity); } public a(Context context, View view, int i) { LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService("layout_inflater"); layoutInflater.inflate(g.snackbar_container, (ViewGroup) view); a((ViewGroup) view, layoutInflater.inflate(g.snackbar_main, (ViewGroup) view, false), i, context); } private void a(ViewGroup viewGroup, View view, int i, Context context) { boolean z; if (viewGroup != null) { this.uMA = (SnackContainer) viewGroup.findViewById(f.snackContainer); } if (this.uMA == null) { this.uMA = new SnackContainer(viewGroup); } this.mParentView = view; if (i == 36) { this.uMA.setOnTouchListener(new OnTouchListener() { public final boolean onTouch(View view, MotionEvent motionEvent) { if (b.aKp() && a.this.uMA.isShowing()) { b.mH(false); a.this.mHandler.postDelayed(new 1(this), 100); } return true; } }); } ((TextView) view.findViewById(f.snackButton)).setOnClickListener(this.uMD); ao.t("snackbar:isNavBarVisibility : %B,navBarHeightd:%d", new Object[]{Boolean.valueOf(aq.gt(context)), Integer.valueOf(aq.gs(context))}); Activity activity = (Activity) context; if (VERSION.SDK_INT >= 19) { LayoutParams attributes = activity.getWindow().getAttributes(); if (attributes.flags == ((attributes.flags & -134217729) | 134217728)) { z = true; ao.t("snackbar:isNavBarTranslucent : %B", new Object[]{Boolean.valueOf(z)}); if (z && r3) { LinearLayout linearLayout = (LinearLayout) view.findViewById(f.snackBar); MarginLayoutParams marginLayoutParams = (MarginLayoutParams) linearLayout.getLayoutParams(); marginLayoutParams.bottomMargin = r4; linearLayout.setLayoutParams(marginLayoutParams); return; } } } z = false; ao.t("snackbar:isNavBarTranslucent : %B", new Object[]{Boolean.valueOf(z)}); if (z) { } } }
package com.hawk.application.web; import java.util.Arrays; import java.util.List; import java.util.Map; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.hawk.application.model.Application; import com.hawk.application.service.ApplicationService; @Controller public class ApplicationCreateController extends BaseController { private final ApplicationService applicationService; @Autowired public ApplicationCreateController(ApplicationService applicationService) { this.applicationService = applicationService; } @InitBinder public void setAllowedFields(WebDataBinder dataBinder) { dataBinder.setDisallowedFields("id"); } @ModelAttribute("platformTypes") public List<String> populatePlatformTypes() { return Arrays.asList("iso"); } @RequestMapping(value = "/applications/new", method = RequestMethod.GET) public String initCreationForm(Map<String, Object> model) { Application application = new Application(); model.put("application", application); return "application/createApplication"; } @RequestMapping(value = "/applications/new", method = RequestMethod.POST) public String processCreationForm(@Valid Application application, BindingResult result) { if (result.hasErrors()) { return "application/createApplication"; } else { this.applicationService.saveApplication(getLoginEmail(), application); return "redirect:/applications"; } } }
package org.tibetjungle.misc.ocr; import java.io.File; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.List; import org.apache.commons.io.FilenameUtils; import com.github.axet.lookup.common.ClassResources; public class OCR extends com.github.axet.lookup.OCR { public OCR(float threshold) { super(threshold); } /** * 原有的方法在处理windows文件中路径分隔符时,字体资源不能正常加载,所以复写它的这个方法以便可以正确的加载字体 */ @Override public void loadFont(Class<?> c, File path) { ClassResources e = new ClassResources(c, path); List<String> str = e.names(); for (String s : str) { File f = new File(path, s); InputStream is = c.getResourceAsStream( translateSeperator( f.getPath() ) ); String symbol = FilenameUtils.getBaseName(s); try { symbol = URLDecoder.decode(symbol, "UTF-8"); } catch (UnsupportedEncodingException ee) { throw new RuntimeException(ee); } String name = path.getName(); loadFontSymbol(name, symbol, is); } } /** * 将路径中的\替换为/,如\foo\bar/com -> /foo/bar/com */ private String translateSeperator( String path ){ if( null == path ) return path; return path.replaceAll( "\\\\", "/"); } }
package com.vapenation.twittermongo; import org.apache.camel.CamelContext; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.Exchange; import org.springframework.stereotype.Component; import org.springframework.beans.factory.annotation.Autowired; @Component public class UserRoute extends RouteBuilder { @Autowired CamelContext context; @Override public void configure() throws Exception { from("timer:aTimer?fixedRate=true&period=10s") .setHeader(Exchange.HTTP_METHOD, constant("GET")) .to("https://randomuser.me/api") .routeId("TEST") .log("${body}"); } }
package com.tencent.mm.plugin.freewifi; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.wifi.WifiManager; import android.os.Looper; import com.tencent.map.geolocation.TencentLocationListener; import com.tencent.mm.plugin.freewifi.model.d; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.x; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public final class a { Activity activity; private WifiManager bnh; Condition bvW; private long dJH; boolean jhA = false; boolean jhB = false; private BroadcastReceiver jhC; Lock jhz; String ssid; public a(String str, Activity activity) { this.activity = activity; this.dJH = 15000; this.ssid = str; this.jhz = new ReentrantLock(); this.bvW = this.jhz.newCondition(); this.bnh = (WifiManager) ad.getContext().getSystemService(TencentLocationListener.WIFI); } public final void a(a aVar) { 1 1 = new 1(this, aVar); if (((ConnectivityManager) ad.getContext().getSystemService("connectivity")).getNetworkInfo(1).isConnected() && this.ssid.equals(d.aOC())) { 1.onSuccess(); } else if (Thread.currentThread() == Looper.getMainLooper().getThread()) { throw new RuntimeException("ConnectNetworkHelper组件不能在主线程中运行。"); } else { this.jhC = new 2(this); try { int aNQ; this.jhz.lock(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("android.net.wifi.STATE_CHANGE"); intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE"); this.activity.registerReceiver(this.jhC, intentFilter); if (!this.bnh.isWifiEnabled()) { aNQ = new e(this.activity).aNQ(); x.i("MicroMsg.FreeWifi.ConnectNetworkHelper", "enable ret = " + aNQ); if (aNQ != 0) { 1.pT(aNQ); aNO(); this.jhz.unlock(); return; } } aNQ = d.BZ(this.ssid); if (aNQ != 0) { aNO(); 1.pT(aNQ); aNO(); this.jhz.unlock(); return; } boolean z = false; while (true) { if (!this.jhA || !this.jhB) { long currentTimeMillis = System.currentTimeMillis(); z = this.bvW.await(this.dJH, TimeUnit.MILLISECONDS); if (!z) { break; } currentTimeMillis = System.currentTimeMillis() - currentTimeMillis; this.dJH -= currentTimeMillis; x.i("MicroMsg.FreeWifi.ConnectNetworkHelper", "costMillis=" + currentTimeMillis + "; left timeout=" + this.dJH); this.dJH = this.dJH > 0 ? this.dJH : 3000; } else { break; } } if (z) { 1.onSuccess(); } else { 1.pT(-16); } aNO(); this.jhz.unlock(); } catch (InterruptedException e) { x.i("MicroMsg.FreeWifi.ConnectNetworkHelper", "sessionKey=%s, step=%d, desc=ConnectNetworkHelper encounter interrupted exception. msg=%s", new Object[]{m.E(this.activity.getIntent()), Integer.valueOf(m.F(this.activity.getIntent())), e.getMessage()}); 1.pT(-17); aNO(); this.jhz.unlock(); } catch (Throwable th) { aNO(); this.jhz.unlock(); throw th; } } } private void aNO() { try { this.activity.unregisterReceiver(this.jhC); } catch (IllegalArgumentException e) { } } }
/** * Javassonne * http://code.google.com/p/javassonne/ * * @author Adam Albright * @date Jan 25, 2009 * * Copyright 2009 Javassonne Team * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package org.javassonne.ui.controls; import java.awt.Graphics; import java.awt.image.BufferedImage; import javax.swing.JPanel; /** * This class forms a container to easily place images onto JPanels * * @author Adam Albright * */ public class JImagePanel extends JPanel { BufferedImage image_; int width_; int height_; // Default constructor // @params: image (BufferedImage) - the image to place into the container // width (int) - target width of the image and container // height (int) - target height of the image and container public JImagePanel(BufferedImage image, int width, int height) { image_ = image; width_ = width; height_ = height; } // Protected method for drawing the image onto the JPanel protected void paintComponent(Graphics g) { super.paintComponent(g); this.setSize(width_, height_); g.drawImage(image_, 0, 0, width_, height_, null); } public void setImage(BufferedImage image) { image_ = image; this.repaint(); } }
package android.support.v4.app; import android.support.v4.app.ac.b.a; class z$f$a$1 implements a { z$f$a$1() { } }
package com.paidaki.Greeklish; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Letter { private String greek; private List<String> english; public Letter(String greek, String... english) { this.greek = greek; this.english = new ArrayList<>(); Collections.addAll(this.english, english); } public String getGreek() { return greek; } public List<String> getEnglish() { return english; } @Override public String toString() { return getGreek(); } }
/** * */ package org.rebioma.server.services; import java.util.List; import java.util.Set; import org.apache.log4j.Logger; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.criterion.Order; import org.hibernate.criterion.Projections; import org.rebioma.client.OccurrenceQuery; import org.rebioma.client.OccurrenceQuery.ResultFilter; import org.rebioma.client.OrderKey; import org.rebioma.client.bean.Occurrence; import org.rebioma.client.bean.User; import org.rebioma.server.services.OccurrenceDbImpl.OccurrenceFilter; import org.rebioma.server.services.QueryFilter.Operator; import org.rebioma.server.util.ManagedSession; /** * @author Mikajy * */ public class OccurrenceSearchDbPg implements IOccurrenceSearchDb{ private static final Logger log = Logger.getLogger(OccurrenceSearchDbPg.class); private RecordReviewDb recordReviewDb = DBFactory.getRecordReviewDb(); @Override public List<Occurrence> find(OccurrenceQuery query, Set<OccurrenceFilter> filters, User user, int tryCount) throws Exception { log.debug("finding Occurrence instances by query."); try { Session session = ManagedSession.createNewSessionAndTransaction(); List<Occurrence> results = null; Criteria criteria = session.createCriteria(Occurrence.class); OccurrenceFilter userReviewFilter = null; OccurrenceFilter myreviewPublicFilter = null; ResultFilter resultFilter = query.getResultFilter(); for (OccurrenceFilter filter : filters) { if (filter.column.equals(filter.getPropertyName("userReviewed"))) { userReviewFilter = filter; if (resultFilter != null) { if (resultFilter == ResultFilter.PUBLIC) { myreviewPublicFilter = new OccurrenceFilter("public = true"); } else if (resultFilter == ResultFilter.PRIVATE) { myreviewPublicFilter = new OccurrenceFilter("public = false"); } resultFilter = null; } } } if (myreviewPublicFilter != null) { filters.add(myreviewPublicFilter); } filters.remove(userReviewFilter); OccurrenceFilter idsFilter = null; if (userReviewFilter != null) { Boolean reviewed = null; if (userReviewFilter.operator == Operator.EQUAL) { reviewed = (Boolean) userReviewFilter.getValue(); } List<Integer> occIds = recordReviewDb.getRecordReviewOccIds(user.getId(), reviewed); System.out.println(occIds.size()); if (occIds.isEmpty()) { occIds.add(0); } idsFilter = new OccurrenceFilter("id", Operator.IN, occIds); filters.add(idsFilter); } //filtre sur les identifiants d'occurrence if(query.getOccurrenceIdsFilter() != null && !query.getOccurrenceIdsFilter().isEmpty()){ OccurrenceFilter occIdsFilter = new OccurrenceFilter("id", Operator.IN, query.getOccurrenceIdsFilter()); filters.add(occIdsFilter); } log.info("find filters: " + OccurrenceDbImpl.addCreterionByFilters(criteria, user, filters, resultFilter, tryCount)); if (userReviewFilter != null) { filters.remove(idsFilter); filters.add(userReviewFilter); } if (myreviewPublicFilter != null) { filters.remove(myreviewPublicFilter); } List<OrderKey> orderingMap = query.getOrderingMap(); log.info("order map = " + orderingMap); if (query.isCountTotalResults()) { criteria.setFirstResult(0); criteria.setProjection(Projections.count("id")); Integer count = (Integer) criteria.uniqueResult(); if (count != null) { query.setCount(count); } } else { query.setCount(-1); } // Sets the start, limit, and order by accepted species: criteria.setFirstResult(query.getStart()); if (query.getLimit() != OccurrenceQuery.UNLIMITED) { criteria.setMaxResults(query.getLimit()); } criteria.setProjection(null); /*for (OrderKey orderKey : orderingMap) { String property = orderKey.getAttributeName(); String occAttribute = getOccurrencePropertyName(property); if (orderKey.isAsc()) { log.info("order by property " + occAttribute + " in ascending order"); criteria.addOrder(Order.asc(occAttribute)); } else { log.info("order by property " + occAttribute + " in descending order"); criteria.addOrder(Order.desc(occAttribute)); } }*/ criteria.addOrder(Order.asc("id")); results = criteria.list(); // filters.addAll(removedFilters); log.debug("find by example successful, result size: " + results.size()); ManagedSession.commitTransaction(session); return results; } catch (RuntimeException re) { log.error("find by example failed", re); re.printStackTrace(); throw re; } catch (Exception e) { log.error("unexpected error: ", e); e.printStackTrace(); throw e; } } }
package de.jmda.app.xstaffr.common.domain; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; /** company or person that supplied {@link Candidate} in {@link SearchResult} */ @Entity @NamedQueries ({ @NamedQuery(name=Supplier__.QUERY_ALL_NAME, query=Supplier__.QUERY_ALL_EXPRESSION), @NamedQuery(name=Supplier__.QUERY_COUNT_NAME, query=Supplier__.QUERY_COUNT_EXPRESSION), @NamedQuery(name=Supplier__.QUERY_UPDATE_DELETE_ALL_NAME, query=Supplier__.QUERY_UPDATE_DELETE_ALL_EXPRESSIOM), @NamedQuery(name=Supplier__.QUERY_BY_NAME_NAME, query=Supplier__.QUERY_BY_NAME_EXPRESSION) }) public class Supplier implements Serializable, Comparable<Supplier>//, RemoveOperationProvider { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @OneToMany(mappedBy="supplier"/*, cascade = {CascadeType.ALL}*/) private Set<SearchResult> results = new HashSet<>(); @Column(unique=true, nullable=false) private String name; @Lob private String text; /** make jpa happy */ protected Supplier() { } public Supplier(String name) { if (name == null) throw new IllegalArgumentException("disallowed null parameter for name"); this.name = name; } public Long getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getText() { return text; } public void setText(String text) { this.text = text; } public Set<SearchResult> getSearchResults() { return results; } public void setResults(Set<SearchResult> results) { this.results = results; } public String asString() { return getClass().getSimpleName() + " [" + asStringSimpleFields() + "]"; } public String asStringDepthOne() { return "Customer [[" + asStringSimpleFields() + "], [" + asStringNonSimpleFields() + "]]"; } @Override public int compareTo(Supplier other) { return getName().compareTo(other.getName()); } private String asStringSimpleFields() { return getClass().getSimpleName() + " [" + "id=" + id + ", name=" + name + "]"; } private String asStringNonSimpleFields() { return "roles [" + String.join(", ", resultsAsStrings()) + "]"; } private Iterable<String> resultsAsStrings() { Collection<String> result = new ArrayList<>(); getSearchResults().forEach(item -> result.add(item.asString())); return result; } }
package com.tencent.mm.plugin.webview.ui.tools.fts; import android.os.Bundle; import com.tencent.mm.plugin.webview.ui.tools.fts.FTSSOSHomeWebViewUI.17; import java.util.Map; class FTSSOSHomeWebViewUI$17$1 implements Runnable { final /* synthetic */ Bundle qah; final /* synthetic */ Map qes; final /* synthetic */ 17 qet; FTSSOSHomeWebViewUI$17$1(17 17, Bundle bundle, Map map) { this.qet = 17; this.qah = bundle; this.qes = map; } public final void run() { boolean a; if (this.qet.qeq.pNV != null) { a = this.qet.qeq.pNV.a(this.qah.getString("type", "0"), this.qah.getString("isMostSearchBiz", "0"), this.qah.getString("isSug", "0"), this.qah.getString("scene", "0"), this.qah.getString("isLocalSug", "0"), this.qet.qeq.getTotalQuery(), this.qet.qeq.getInEditTextQuery(), this.qet.qeq.bXp(), this.qet.qeq.bXi(), this.qet.qeq.qel, this.qes); } else { a = false; } if (a) { this.qet.qeq.bXk().setHint(this.qet.qeq.AV(0)); this.qet.qeq.qdW.Dd(7); } } }
package com.kerbii.undersiege; public abstract class ArrowBase extends GameObject { public static final int FLYING = 0, EMBEDDED = 1, BROKEN = 2, EFFECT = 3, TOCASTLE = 4; public int state; // public static final int GENERIC = 0, FIRE = 1, LIGHTNING = 2, ICE = 3, ARCHER = 4, MOB = 5; public int arrowType; public static float arrowFlightSpeed; float updateX, updateY; float speed; public float effectCenterX; public float effectCenterY; public float effectRange; public float effectDamage; MobBase embeddedMob; public int animationIndex; private static float vertices[] = { -40.0f, -4.0f, 0.0f, 0.0f, -4.0f, 0.0f, -40.0f, 4.0f, 0.0f, 0.0f, 4.0f, 0.0f }; public ArrowBase(float x, float y, float xTarget, float yTarget, float speed, int[] animationArray, float effectRange, float effectDamage) { super(x, y, 0, 0, vertices); this.speed = speed; this.effectDamage = effectDamage; float xChange = -(x - xTarget); float yChange = -(y - yTarget); float totalDistance = (float) Math.sqrt((xChange * xChange) + (yChange * yChange)); updateX = (xChange / totalDistance) / 16.0f; updateY = (yChange / totalDistance) / 16.0f; angle = (float) (Math.atan(yChange / xChange) * (180 / Math.PI)); state = FLYING; } public ArrowBase(float x, float y, float xTarget, float yTarget, float speed, int[] animationArray) { this(x, y, xTarget, yTarget, speed, animationArray, 0, 0); } public void update(long deltaTime) { if (state == FLYING) { x += updateX * speed * deltaTime; y += updateY * speed * deltaTime; } else if (state == EMBEDDED) { if (!embeddedMob.special()) state = BROKEN; if (embeddedMob.state == MobBase.MOVING) { x += embeddedMob.speedX * deltaTime; y += embeddedMob.speedY * deltaTime; } else if (embeddedMob.state == MobBase.DYING || embeddedMob.state == MobBase.DEAD){ state = BROKEN; } } if (state == BROKEN || (state != EFFECT && (x > 850 || y > 530 || y < -50))) { draw = false; } if (state == FLYING) { millisSinceLastFrame += deltaTime; if (millisSinceLastFrame >= millisPerFrame) { int animationSkips = (int) (millisSinceLastFrame / millisPerFrame); animationIndex += animationSkips; if (animationIndex > 2) { animationIndex = animationIndex - 3; } millisSinceLastFrame = 0; } } } public void hit(MobBase mob, float health) { if (state == FLYING) { speed -= health; if (speed < 8 && state != EMBEDDED) { state = BROKEN; } else { } } } public ArrayList<MobBase> hitMobs(ArrayList<MobBase> mobsInRange) { mobsInRange.removeAll(); return mobsInRange; } public void embed(MobBase mob) { state = EMBEDDED; embeddedMob = mob; } public float damage() { if (state == EFFECT) { return effectDamage; } else return speed + effectDamage; } }
package com.tencent.mm.ui; import android.content.Intent; import com.tencent.mm.R; import com.tencent.mm.ab.e; import com.tencent.mm.ab.l; import com.tencent.mm.model.au; import com.tencent.mm.model.c; import com.tencent.mm.modelsimple.ab; import com.tencent.mm.plugin.account.ui.RegByMobileSetPwdUI; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.ui.base.h; import com.tencent.mm.ui.w.a; class j$11 implements e { final /* synthetic */ j tjf; j$11(j jVar) { this.tjf = jVar; } public final void a(int i, int i2, String str, l lVar) { x.i("MicroMsg.LauncherUI.GlobalAlertMgr", "summeralert onSceneEnd " + i + " errCode " + i2 + " errMsg " + str + " " + lVar.getType()); if (this.tjf.eHw != null) { this.tjf.eHw.dismiss(); this.tjf.eHw = null; } if (lVar.getType() == 255) { au.DF().b(255, this.tjf.tjb); if (i == 0 && i2 == 0) { this.tjf.lx(true); } else if (!a.a(this.tjf.tiY, i, i2, str, 4)) { this.tjf.lx(false); } } else if (lVar.getType() != 384) { } else { if (i == 0 && i2 == 0) { au.HU(); c.DT().set(77830, ((ab) lVar).Oj()); Intent intent = new Intent(this.tjf.tiY, RegByMobileSetPwdUI.class); intent.putExtra("kintent_hint", this.tjf.getString(R.l.settings_modify_password_tip)); this.tjf.tiY.startActivity(intent); return; } this.tjf.mRA = true; h.a(this.tjf.tiY, R.l.settings_password_error, R.l.app_tip, new 1(this)); } } }
package javaapplication25; import java.io.*; import java.util.*; public class itemService { item use = new item (); public void add(String namee,int i) { item e=new item(); e.setName(namee,i); } public void remove(item e) { } public void view() { } }
package com.sharjeelhussain.smd_project; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.os.Bundle; import android.view.View; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.ChildEventListener; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.FirebaseDatabase; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; public class login extends AppCompatActivity { Button Signin; EditText Email, Password; TextView mov_to_reg; ArrayList<RegistrationModel> List; //offline mode private boolean isNetworkConnected() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected(); } // public static String encryptPassword(String input) { try { // getInstance() method is called with algorithm SHA-512 MessageDigest md = MessageDigest.getInstance("SHA-512"); // digest() method is called // to calculate message digest of the input string // returned as array of byte byte[] messageDigest = md.digest(input.getBytes()); // Convert byte array into signum representation BigInteger no = new BigInteger(1, messageDigest); // Convert message digest into hex value String hashtext = no.toString(16); // Add preceding 0s to make it 32 bit while (hashtext.length() < 32) { hashtext = "0" + hashtext; } // return the HashText return hashtext; } // For specifying wrong message digest algorithms catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); Signin=findViewById(R.id.signin); Email=findViewById(R.id.email); Password=findViewById(R.id.password); mov_to_reg=findViewById(R.id.mov_to_reg); List = new ArrayList<RegistrationModel>(); Signin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String email=Email.getText().toString(); String password=Password.getText().toString(); boolean Found = false; String passwordoff=""; for (int i=0;i<List.size();i++) { if (List.get(i).getEmail().equals(email)) { Found = true; passwordoff=List.get(i).getPassword(); break; } } if(email.length()==0 || password.length()==0) { Toast.makeText(login.this, "Kindly enter username and password.", Toast.LENGTH_LONG).show(); } else if(!Found) { Toast.makeText(login.this, "Email not registered in "+getIntent().getExtras().getString("Type")+".", Toast.LENGTH_LONG).show(); } else { if (isNetworkConnected()) { FirebaseAuth.getInstance().signInWithEmailAndPassword(email, password) .addOnCompleteListener(login.this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Toast.makeText(login.this, "Login Successful.", Toast.LENGTH_LONG).show(); if(getIntent().getExtras().getString("Type").equals("Patient")) { Intent i =new Intent(login.this,Patient_Dashboard_CheckUp.class); i.putExtra("Email",email); startActivity(i); } else { Intent i =new Intent(login.this,Doctor_Dashboard.class); i.putExtra("Email",email); startActivity(i); } } else { // If sign in fails, display a message to the user. task.addOnFailureListener(login.this, new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { if(e.getMessage().contains("password is invalid")) { Toast.makeText(login.this, "Password does not match with user account.", Toast.LENGTH_LONG).show(); } else if (e.getMessage().contains("There is no user record")) { Toast.makeText(login.this, "User account not registered.", Toast.LENGTH_LONG).show(); } else { Toast.makeText(login.this, e.getMessage(), Toast.LENGTH_LONG).show(); } } }); } } }); } else { if (encryptPassword(password).equals(passwordoff)) { // Sign in success, update UI with the signed-in user's information Toast.makeText(login.this, "Login Successful.", Toast.LENGTH_LONG).show(); if(getIntent().getExtras().getString("Type").equals("Patient")) { Intent i =new Intent(login.this,Patient_Dashboard_CheckUp.class); i.putExtra("Email",email); startActivity(i); } else { Intent i =new Intent(login.this,Doctor_Dashboard.class); i.putExtra("Email",email); startActivity(i); } } else { Toast.makeText(login.this, "Password does not match with user account.", Toast.LENGTH_LONG).show(); } } } } }); mov_to_reg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isNetworkConnected()) { Intent intent=new Intent(getApplicationContext(),Registration.class); intent.putExtra("Type",getIntent().getExtras().getString("Type")); startActivity(intent); } else { Toast.makeText(login.this, "No Internet Access.", Toast.LENGTH_SHORT).show(); } } }); FirebaseDatabase.getInstance().getReference("Registration").child(getIntent().getExtras().getString("Type")).addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(@NonNull final DataSnapshot dataSnapshot, @Nullable String s) { RegistrationModel cts = dataSnapshot.getValue(RegistrationModel.class); List.add(cts); } @Override public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { } @Override public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) { } @Override public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } }
package java1; public class lastoccu { public static void main(String[] args) { String s= new String("CIVIC"); char[] ch =s.toCharArray(); char c='C'; int temp=0; for(int i=0;i<ch.length;i++) { if(ch[i]==c) { temp=i; } } System.out.println(temp); } }
package com.darglk.todolist.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import com.darglk.todolist.entity.Task; import com.darglk.todolist.entity.User; import com.darglk.todolist.service.TaskService; import com.darglk.todolist.service.UserService; @Controller @RequestMapping("/admin/task") public class AdminTaskController { @Autowired private TaskService taskService; @Autowired private UserService userService; @GetMapping("/all") public String listAllTasks(Model model, @RequestParam(name="page", defaultValue="0", required=false) Integer page, @RequestParam(name="searchTerm", defaultValue="", required=false) String searchTerm) { Pageable pageable = new PageRequest(page, 3); Page<Task> tasks = taskService.getTasks(searchTerm, pageable); model.addAttribute("tasks", tasks); model.addAttribute("page", page); model.addAttribute("searchTerm", searchTerm); return "list-tasks"; } @GetMapping("/listByUserId") public String listTasksByUserId(Model model,@RequestParam(name="page", defaultValue="0", required=false) Integer page, @RequestParam(name="searchTerm", defaultValue="", required=false) String searchTerm, @RequestParam(name="userId") Integer userId) { User user = userService.getUser(userId); fetchTasksAndPrepareModelAttributes(model, page, searchTerm, user); return "list-tasks"; } private void fetchTasksAndPrepareModelAttributes(Model model, Integer page, String searchTerm, User user) { Pageable pageable = new PageRequest(page,3); Page<Task> tasks = taskService.getTasksByUserId((long)user.getId(), searchTerm, pageable); model.addAttribute("tasks", tasks); model.addAttribute("page", page); model.addAttribute("searchTerm", searchTerm); } }
package com.smxknife.hbase.demo02; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.*; import org.apache.hadoop.hbase.util.Bytes; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.time.LocalDate; import java.time.ZoneId; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.ThreadLocalRandom; /** * @author smxknife * 2021/5/23 */ public class _Test02_Protobuf { Configuration configuration = null; Connection conn = null; // 表的管理对象 Admin admin = null; // 表名对象 TableName tableName = TableName.valueOf("ent_energy_dws"); // 数据操作对象 Table table = null; @Test public void insert() throws IOException { // 构造里面指定rowkey // 这种方式可以作为冷数据进行处理,可以有效的压缩数据大小 // 因为这种方式无法使用filter进行数据过滤 // final EnergyDws.EnergyData energyData = EnergyDws.EnergyData.newBuilder() // .setEnergyCode("2100") // .setRegionCode("330100") // .setIndustryCode("C31") // .setDataCode("0000") // .setDataValue(40.0) // .setDataTime(LocalDateTime.now().atZone(ZoneId.systemDefault()).toEpochSecond()).build(); // Put put = new Put(Bytes.toBytes("2000")); // // 这种情况下,就没办法分成不同的列族,只能用一个列族 // put.addColumn(Bytes.toBytes("energy_data"), Bytes.toBytes("data"), energyData.toByteArray()); // table.put(put); } @Test public void test() { final String format = String.format("%018d", 1); System.out.println(format); } @Test public void batchInsertNoProtobuf() throws IOException { /** * rowkey = 时间 + energyCode + 企业代码 * 列族:energy * - energyCode * - regionCode * - industryCode * - domainCode * - dataCode * - dataValue * - dataTime */ final byte[] energy = Bytes.toBytes("energy"); final byte[] energyCode = Bytes.toBytes("energyCode"); final byte[] regionCode = Bytes.toBytes("regionCode"); final byte[] industryCode = Bytes.toBytes("industryCode"); final byte[] dataValue = Bytes.toBytes("dataValue"); final byte[] dataTime = Bytes.toBytes("dataTime"); LocalDate end = LocalDate.now(); LocalDate start = end.minusYears(1); List<Put> puts = new ArrayList<>(); for (int i = 0; i < 10; i++) { final String entCode = String.format("%018d", i); final byte[] region = Bytes.toBytes(String.format("31%02d", i)); byte[] industry = null; if (i % 2 == 0) { industry = Bytes.toBytes("C31"); } else { industry = Bytes.toBytes("C33"); } System.out.println("iiiiii"); for (int j = 3300; j < 3305; j++) { System.out.println("jjjjjjj"); for (LocalDate temp = start ;temp.isBefore(end);temp = temp.plusDays(1)) { final long time = start.atStartOfDay().atZone(ZoneId.systemDefault()).toEpochSecond(); final String rowKey = (Long.MAX_VALUE - time) + "_" + j + "_" + entCode; Put put = new Put(Bytes.toBytes(rowKey)); put.addColumn(energy, energyCode, Bytes.toBytes(String.valueOf(j))); put.addColumn(energy, regionCode, region); put.addColumn(energy, industryCode, industry); put.addColumn(energy, dataValue, Bytes.toBytes(ThreadLocalRandom.current().nextInt(10))); put.addColumn(energy, dataTime, Bytes.toBytes(time)); puts.add(put); System.out.println("---- " + i + " _ " + j + " _ " + start); } } } table.put(puts); puts.clear(); } @Test public void createTable() throws IOException { // 定义表描述对象 final TableDescriptorBuilder tableDescriptorBuilder = TableDescriptorBuilder.newBuilder(tableName); // 定义列族描述对象 final ColumnFamilyDescriptorBuilder energyBuilder = ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes("energy")); // final ColumnFamilyDescriptorBuilder regionBuilder = ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes("region")); // final ColumnFamilyDescriptorBuilder industryBuilder = ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes("industry")); // final ColumnFamilyDescriptorBuilder domainBuilder = ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes("domain")); // final ColumnFamilyDescriptorBuilder dataBuilder = ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes("data")); // 添加列族信息给表 tableDescriptorBuilder.setColumnFamilies(Arrays.asList(energyBuilder.build())); if (admin.tableExists(tableName)) { // 这里可以删除表 admin.disableTable(tableName); admin.deleteTable(tableName); } // 创建表 admin.createTable(tableDescriptorBuilder.build()); } @Before public void init() throws IOException { // 创建配置文件对象 configuration = HBaseConfiguration.create(); // 加载zookeeper,从zk中获取hbase的配置 configuration.set("hbase.zookeeper.quorum", "localhost:2181"); // 获取连接 conn = ConnectionFactory.createConnection(configuration); // 获取表管理对象 admin = conn.getAdmin(); // 获取数据操作对象 table = conn.getTable(tableName); } @After public void destroy() { try { admin.close(); } catch (IOException e) { e.printStackTrace(); } try { table.close(); } catch (IOException e) { e.printStackTrace(); } try { conn.close(); } catch (IOException e) { e.printStackTrace(); } } }
package lambdaExpressions; import java.time.LocalDate; import java.time.chrono.IsoChronology; import java.util.ArrayList; import java.util.List; public class Person { public Person(String name, LocalDate birthday, Sex gender, String emailAddress) { this.name = name; this.birthday = birthday; this.gender = gender; this.emailAddress = emailAddress; } public enum Sex {MALE,FEMALE} String name; LocalDate birthday; Sex gender; String emailAddress; public String getName() { return name; } public Sex getGender() { return gender; } public int getAge(){ return birthday.until(IsoChronology.INSTANCE.dateNow()).getYears(); } public LocalDate getBirthday() { return birthday; } public String getEmailAddress() { return emailAddress; } public void printPerson() { System.out.println(name + ", " + this.getAge()); } public static int compareByAge(Person a, Person b){ return a.birthday.compareTo(b.birthday); } public static List<Person> creatListPerson() { List<Person> list = new ArrayList<>(); list.add(new Person("a", IsoChronology.INSTANCE.date(1991, 7, 8), Sex.MALE, "a@s.com")); list.add(new Person("b", IsoChronology.INSTANCE.date(1992, 7, 6), Sex.MALE, "b@s.com")); list.add(new Person("c", IsoChronology.INSTANCE.date(2001, 7, 16), Sex.FEMALE, "c@s.com")); list.add(new Person("d", IsoChronology.INSTANCE.date(1996, 7, 28), Sex.MALE, "d@s.com")); list.add(new Person("e", IsoChronology.INSTANCE.date(2000, 7, 28), Sex.MALE, "d@s.com")); return list; } }
package com.yoeki.kalpnay.hrporatal.Profile.Certification; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.yoeki.kalpnay.hrporatal.R; import com.yoeki.kalpnay.hrporatal.setting.Textclass; import java.util.List; public class CertificationRecyclerViewAdapter extends RecyclerView.Adapter<CertificationRecyclerViewAdapter.ViewHolder> { private List<String> mData; private LayoutInflater mInflater; private static Context context; // private ItemClickListener mClickListener; // data is passed into the constructor CertificationRecyclerViewAdapter(Context context, List<String> data) { this.mInflater = LayoutInflater.from(context); this.mData = data; this.context = context; } // inflates the row layout from xml when needed @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = mInflater.inflate(R.layout.certification_recycler, parent, false); return new ViewHolder(view); } // binds the data to the TextView in each row @Override public void onBindViewHolder(ViewHolder holder, int position) { String unit = mData.get(position); String[] Break = unit.split("~"); try { if (Break[0].equalsIgnoreCase("null") || Break[0].equalsIgnoreCase("") || Break[0].equalsIgnoreCase(" ")) { holder.CEName.setText("N/A"); } else { holder.CEName.setText(Break[0]); } }catch (Exception e){ e.printStackTrace(); } if(Break[1].equalsIgnoreCase("null") || Break[1].equalsIgnoreCase("") || Break[1].equalsIgnoreCase(" ")) { holder.CEType.setText("N/A"); }else { holder.CEType.setText(Break[1]); } if(Break[2].equalsIgnoreCase("null") || Break[2].equalsIgnoreCase("") || Break[2].equalsIgnoreCase(" ")){ holder.CEProvider.setText("N/A"); }else { holder.CEProvider.setText(Break[2]); } if(Break[3].equalsIgnoreCase("null") || Break[3].equalsIgnoreCase("") || Break[3].equalsIgnoreCase(" ")){ holder.expired.setText("N/A"); }else { holder.expired.setText(Break[3]); } } // total number of rows @Override public int getItemCount() { return mData.size(); } // stores and recycles views as they are scrolled off screen public class ViewHolder extends RecyclerView.ViewHolder { Textclass expired,CEProvider,CEType,CEName; ViewHolder(View itemView) { super(itemView); CEName = itemView.findViewById(R.id.CEName); CEType = itemView.findViewById(R.id.CEType); CEProvider = itemView.findViewById(R.id.CEProvider); expired = itemView.findViewById(R.id.expired); } } }
package com.eres.waiter.waiter.adapters; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.util.DiffUtil; import android.support.v7.util.ListUpdateCallback; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.eres.waiter.waiter.R; import com.eres.waiter.waiter.activity.MyMenuActivity; import com.eres.waiter.waiter.adapters.diffUtil.TableCallback; import com.eres.waiter.waiter.model.TablesItem; import com.eres.waiter.waiter.model.singelton.DataSingelton; import com.eres.waiter.waiter.preferance.SettingPreferances; import java.util.ArrayList; import java.util.List; public class AdapterEmpty extends RecyclerView.Adapter<AdapterEmpty.MyViewHolder> { List<TablesItem> strings; private MyInterfaceItem myInterfaceItem; public void setMyInterfaceItem(MyInterfaceItem myInterfaceItem) { this.myInterfaceItem = myInterfaceItem; } public AdapterEmpty(List<TablesItem> string) { strings = new ArrayList<>(); strings.clear(); strings.addAll(string); } public void updateList(List<TablesItem> newList) { DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new TableCallback(strings, newList)); Log.d("TEST_N", "updateList: " + strings.size() + "===" + newList.size()); strings.clear(); strings.addAll(newList); diffResult.dispatchUpdatesTo(this); notifyDataSetChanged(); } @NonNull @Override public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_first_rec, parent, false); return new MyViewHolder(view); } @Override public void onBindViewHolder(@NonNull MyViewHolder holder, int position) { holder.textView.setText(strings.get(position).getName()); holder.view.setOnClickListener(v -> { myInterfaceItem.itemPosition(position); DataSingelton.getMyOrders().clear(); SettingPreferances preferances = SettingPreferances.getSharedPreferance(null); preferances.setOrderId(0); preferances.setTableName(strings.get(position).getName()); preferances.setTableId(strings.get(position).getId()); holder.view.getContext().startActivity(new Intent(holder.textView.getContext(), MyMenuActivity.class)); }); } public interface MyInterfaceItem { void itemPosition(int position); } @Override public int getItemCount() { return strings.size(); } class MyViewHolder extends RecyclerView.ViewHolder { private TextView textView; private LinearLayout view; public MyViewHolder(View itemView) { super(itemView); textView = itemView.findViewById(R.id.table); view = itemView.findViewById(R.id.item_liner); } } }
package pojo; // Generated Mar 14, 2018 12:29:09 PM by Hibernate Tools 4.3.1 import java.util.HashSet; import java.util.Set; /** * ProgramSubtitle generated by hbm2java */ public class ProgramSubtitle implements java.io.Serializable { private Integer idProgramSubTitle; private ProgramTitle programTitle; private String subTitleNo; private String subTitleName; private Integer status; private Integer syn; private Set<Vort> vorts = new HashSet<Vort>(0); public ProgramSubtitle() { } public ProgramSubtitle(ProgramTitle programTitle) { this.programTitle = programTitle; } public ProgramSubtitle(ProgramTitle programTitle, String subTitleNo, String subTitleName, Integer status, Integer syn, Set<Vort> vorts) { this.programTitle = programTitle; this.subTitleNo = subTitleNo; this.subTitleName = subTitleName; this.status = status; this.syn = syn; this.vorts = vorts; } public Integer getIdProgramSubTitle() { return this.idProgramSubTitle; } public void setIdProgramSubTitle(Integer idProgramSubTitle) { this.idProgramSubTitle = idProgramSubTitle; } public ProgramTitle getProgramTitle() { return this.programTitle; } public void setProgramTitle(ProgramTitle programTitle) { this.programTitle = programTitle; } public String getSubTitleNo() { return this.subTitleNo; } public void setSubTitleNo(String subTitleNo) { this.subTitleNo = subTitleNo; } public String getSubTitleName() { return this.subTitleName; } public void setSubTitleName(String subTitleName) { this.subTitleName = subTitleName; } public Integer getStatus() { return this.status; } public void setStatus(Integer status) { this.status = status; } public Integer getSyn() { return this.syn; } public void setSyn(Integer syn) { this.syn = syn; } public Set<Vort> getVorts() { return this.vorts; } public void setVorts(Set<Vort> vorts) { this.vorts = vorts; } }
package negocio.excecao; public class AnoNaoDeclaradoException extends Exception{ public AnoNaoDeclaradoException(){ super("Ano nao foi declarado"); } }
package com.galvanize.carapp.repository; import com.galvanize.carapp.model.RaceCar; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface RaceCarRepository extends JpaRepository<RaceCar, Long> { }
package com.itheima.ssm.service; import com.itheima.ssm.domain.Product; import java.util.List; /** * 商品业务层实现类 */ public interface ProductService { //查询所有商品 public List<Product> findAll() throws Exception; //保存商品 void save(Product product) throws Exception; }
package cn.jk.mybatis.test; import cn.jk.mybatis.config.JkConfiguration; import cn.jk.mybatis.executor.CachingExecutor; import cn.jk.mybatis.executor.Executor; import cn.jk.mybatis.session.JkSqlSession; public class BootStrap { public static void main(String[] args) { start(); } private static void start() { JkConfiguration configuration = new JkConfiguration(); configuration.setPath(""); Executor executor = new CachingExecutor(); JkSqlSession session = new JkSqlSession(configuration ,executor); } }
package com.linkedbook.entity; import java.io.Serializable; import java.util.Objects; public class PopularCategoryPK implements Serializable { private static final long serialVersionUID = 1L; private String bookId; private int categoryId; public PopularCategoryPK(){ } public PopularCategoryPK(String bookId, int categoryId){ this.bookId = bookId; this.categoryId = categoryId; } // Getter, Setter @Override public boolean equals(Object obj) { if(this == obj) { return true; } if(obj == null || this.getClass() != obj.getClass()) { return false; } PopularCategoryPK popularCategoryPK = (PopularCategoryPK)obj; if(this.bookId.equals(popularCategoryPK.bookId) && this.categoryId == popularCategoryPK.categoryId ) { return true; } return false; } @Override public int hashCode() { return Objects.hash(bookId, categoryId); } }
package evm.dmc.api.model.account; import java.time.Instant; import java.util.Set; import javax.persistence.Entity; import evm.dmc.api.model.ProjectModel; import lombok.AllArgsConstructor; import lombok.NoArgsConstructor; @Entity @NoArgsConstructor public class AccountExt extends Account{ /** * */ private static final long serialVersionUID = 7054355736554325207L; // protected AccountExt() {} // public AccountExt(Account acc) { // super(acc); // } // // public AccountExt(Account acc, String role){ // super(acc); // this.setRole(role); // } // // public AccountExt(Account acc, Role role){ // super(acc); // this.setRole(role); // } public AccountExt(String username, String password, String email, String firstName, String lastName) { super(username, password, email, firstName, lastName); this.setRole(role); } // public AccountExt(String username, String password, String email, String firstName, String lastName, Role role) { super(username, password, email, firstName, lastName, role); } // // public AccountExt(String username, String password, String email, // String firstName, String lastName, Role role) { // super(username, password, email, firstName, lastName); // super.setRole(role); // } public void setRole(String role) { super.role = Role.valueOf(role); } // public void setRole(Role role) { // super.role = role; // } // public Account getAccount() { // return this; // } }
package psk.com.mediaplayerdemo.service; import android.app.Notification; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.AudioManager; import android.media.MediaPlayer; import android.os.Handler; import android.os.IBinder; import android.os.PowerManager; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.app.NotificationCompat; import android.widget.RemoteViews; import java.io.IOException; import java.util.ArrayList; import psk.com.mediaplayerdemo.MusicPlayerApplication; import psk.com.mediaplayerdemo.R; import psk.com.mediaplayerdemo.model.MantraModel; import psk.com.mediaplayerdemo.utils.Constants; public class MediaService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener { private MediaPlayer mediaPlayer; private MantraModel model; private MantraModel nextModel; private Handler handlerElapsedTime; private LocalBroadcastManager manager; private Runnable runnableElapsedTime = new Runnable() { @Override public void run() { if (mediaPlayer.isPlaying()) { int currentPosition = mediaPlayer.getCurrentPosition(); Intent intent = new Intent(Constants.UPDATE_SEEK_BAR_RECEIVER); intent.putExtra(Constants.DURATION_EXTRA, currentPosition); manager.sendBroadcast(intent); handlerElapsedTime.postDelayed(runnableElapsedTime, 500); } } }; public MediaService() { } @Override public IBinder onBind(Intent intent) { throw new UnsupportedOperationException("Not yet implemented"); } @Override public void onCreate() { super.onCreate(); manager = LocalBroadcastManager.getInstance(getApplicationContext()); } @Override public int onStartCommand(Intent intent, int flags, int startId) { model = (MantraModel) intent.getSerializableExtra((Constants.SONG_MODEL_EXTRA)); MantraModel currentModel = MusicPlayerApplication.getCurrentModel(); if (intent.getAction().equals(Constants.ACTION_PLAY)) { if (intent.hasExtra(Constants.IS_FROM_UI_EXTRA)) { if (mediaPlayer.isPlaying()) { mediaPlayer.pause(); sendNotification(R.drawable.uamp_ic_play_arrow_white_48dp, currentModel.getMantraName()); sendStatus(Constants.STATUS_PAUSED); } else { handlerElapsedTime.post(runnableElapsedTime); mediaPlayer.start(); sendStatus(Constants.STATUS_PLAYING); sendNotification(R.drawable.uamp_ic_pause_white_48dp, currentModel.getMantraName()); } } else { if (!model.equals(currentModel)) { ArrayList<Integer> changed = new ArrayList<>(); if (currentModel != null) { int currentIndex = MusicPlayerApplication.getMantraModelArrayList().indexOf(currentModel); MusicPlayerApplication.getMantraModelArrayList().get(currentIndex).setPlaying(false); changed.add(currentIndex); } int index = MusicPlayerApplication.getMantraModelArrayList().indexOf(model); MusicPlayerApplication.getMantraModelArrayList().get(index).setPlaying(true); changed.add(index); MusicPlayerApplication.setCurrentModel(model); Intent intent1 = new Intent(Constants.UPDATE_LIST_INTENT_FILTER_RECEIVER); intent1.putExtra(Constants.CHANGED_LIST_EXTRA, changed); manager.sendBroadcast(intent1); nextModel = model; if (mediaPlayer == null) { initMediaPlayer(); setDataSource(model); } else { handlerElapsedTime.removeCallbacks(runnableElapsedTime); stopAndRestart(); } } } } else if (intent.getAction().equals(Constants.ACTION_STOP)) { mediaPlayer.reset(); mediaPlayer.release(); mediaPlayer = null; stopForeground(true); stopSelf(); sendStatus(Constants.STATUS_STOPPED); ArrayList<Integer> changed = new ArrayList<>(); int currentIndex = MusicPlayerApplication.getMantraModelArrayList().indexOf(currentModel); MusicPlayerApplication.getMantraModelArrayList().get(currentIndex).setPlaying(false); changed.add(currentIndex); Intent intent1 = new Intent(Constants.UPDATE_LIST_INTENT_FILTER_RECEIVER); intent1.putExtra(Constants.CHANGED_LIST_EXTRA, changed); manager.sendBroadcast(intent1); MusicPlayerApplication.setCurrentModel(null); handlerElapsedTime.removeCallbacks(runnableElapsedTime); } else if (intent.getAction().equals(Constants.ACTION_SEEK)) { int seekTo = intent.getIntExtra(Constants.SEEK_TO_EXTRA, 0); mediaPlayer.seekTo(seekTo); } else if (intent.getAction().equals(Constants.ACTION_NEXT)) { playNext(); } else if (intent.getAction().equals(Constants.ACTION_PREVIOUS)) { playPrevious(); } return START_NOT_STICKY; } private void playNext() { MantraModel currentModel = MusicPlayerApplication.getCurrentModel(); ArrayList<MantraModel> mantraModelArrayList = MusicPlayerApplication.getMantraModelArrayList(); if (currentModel != null) { if (mantraModelArrayList != null) { int currentIndex = mantraModelArrayList.indexOf(currentModel); int nextIndex = currentIndex + 1; if (nextIndex == mantraModelArrayList.size()) { nextIndex = 0; } nextModel = mantraModelArrayList.get(nextIndex); MusicPlayerApplication.setCurrentModel(nextModel); stop(); initMediaPlayer(); setDataSource(nextModel); nextModel.setPlaying(true); if(!currentModel.equals(nextModel)) { ArrayList<Integer> changed = new ArrayList<>(); MusicPlayerApplication.getMantraModelArrayList().get(currentIndex).setPlaying(false); changed.add(currentIndex); changed.add(nextIndex); Intent intent1 = new Intent(Constants.UPDATE_LIST_INTENT_FILTER_RECEIVER); intent1.putExtra(Constants.CHANGED_LIST_EXTRA, changed); manager.sendBroadcast(intent1); } } } } private void playPrevious() { MantraModel currentModel = MusicPlayerApplication.getCurrentModel(); ArrayList<MantraModel> mantraModelArrayList = MusicPlayerApplication.getMantraModelArrayList(); if (currentModel != null) { if (mantraModelArrayList != null) { int currentIndex = mantraModelArrayList.indexOf(currentModel); int previousIndex = currentIndex - 1; if (previousIndex == -1) { previousIndex = mantraModelArrayList.size() - 1; } nextModel = mantraModelArrayList.get(previousIndex); MusicPlayerApplication.setCurrentModel(nextModel); stop(); initMediaPlayer(); setDataSource(nextModel); nextModel.setPlaying(true); if(!currentModel.equals(nextModel)) { ArrayList<Integer> changed = new ArrayList<>(); MusicPlayerApplication.getMantraModelArrayList().get(currentIndex).setPlaying(false); changed.add(currentIndex); changed.add(previousIndex); Intent intent1 = new Intent(Constants.UPDATE_LIST_INTENT_FILTER_RECEIVER); intent1.putExtra(Constants.CHANGED_LIST_EXTRA, changed); manager.sendBroadcast(intent1); } } } } private void sendStatus(String status) { Intent intent = new Intent(Constants.UPDATE_MEDIA_PLAYER_RECEIVER); intent.putExtra(Constants.MEDIA_PLAYER_STATUS_EXTRA, status); if (status.equals(Constants.STATUS_PLAYING)) { intent.putExtra(Constants.DURATION_EXTRA, mediaPlayer.getDuration()); } manager.sendBroadcast(intent); } private void initMediaPlayer() { if (mediaPlayer == null) { mediaPlayer = new MediaPlayer(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); } } private void setDataSource(MantraModel model) { String path = model.getMantra(); try { mediaPlayer.setDataSource(path); mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK); mediaPlayer.setOnPreparedListener(this); mediaPlayer.setOnCompletionListener(this); mediaPlayer.prepareAsync(); sendNotification(R.drawable.uamp_ic_pause_white_48dp, model.getMantraName()); } catch (IOException e) { e.printStackTrace(); } } private void stop() { mediaPlayer.reset(); mediaPlayer.release(); mediaPlayer = null; } private void sendNotification(int drawable, String songName) { Intent playPauseIntent = new Intent(getApplicationContext(), MediaService.class); playPauseIntent.setAction(Constants.ACTION_PLAY); playPauseIntent.putExtra(Constants.IS_FROM_UI_EXTRA, true); PendingIntent playPausePendingIntent = PendingIntent.getService(getApplicationContext(), 0, playPauseIntent, PendingIntent.FLAG_UPDATE_CURRENT); Intent stopIntent = new Intent(getApplicationContext(), MediaService.class); stopIntent.setAction(Constants.ACTION_STOP); PendingIntent stopPendingIntent = PendingIntent.getService(getApplicationContext(), 0, stopIntent, PendingIntent.FLAG_UPDATE_CURRENT); Intent nextIntent = new Intent(getApplicationContext(), MediaService.class); nextIntent.setAction(Constants.ACTION_NEXT); PendingIntent nextPendingIntent = PendingIntent.getService(getApplicationContext(), 0, nextIntent, PendingIntent.FLAG_UPDATE_CURRENT); Intent previousIntent = new Intent(getApplicationContext(), MediaService.class); previousIntent.setAction(Constants.ACTION_PREVIOUS); PendingIntent previousPendingIntent = PendingIntent.getService(getApplicationContext(), 0, previousIntent, PendingIntent.FLAG_UPDATE_CURRENT); Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher); RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.layout_notification); Notification notification = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_notification) /*.setLargeIcon( Bitmap.createScaledBitmap(icon, 128, 128, false))*/ .setContent(remoteViews) .setOngoing(true) .setStyle(new NotificationCompat.BigTextStyle()) .build(); notification.bigContentView = remoteViews; notification.priority = Notification.PRIORITY_MAX; remoteViews.setTextViewText(R.id.tvName, songName); remoteViews.setOnClickPendingIntent(R.id.ibPlay, playPausePendingIntent); remoteViews.setOnClickPendingIntent(R.id.ibStop, stopPendingIntent); remoteViews.setOnClickPendingIntent(R.id.ibNext, nextPendingIntent); remoteViews.setOnClickPendingIntent(R.id.ibPrevious, previousPendingIntent); remoteViews.setImageViewResource(R.id.ibPlay, drawable); startForeground(100, notification); } @Override public void onPrepared(MediaPlayer mp) { mp.start(); MusicPlayerApplication.getCurrentModel().setDuration(mp.getDuration()); sendStatus(Constants.STATUS_PLAYING); handlerElapsedTime = new Handler(); handlerElapsedTime.post(runnableElapsedTime); } private void stopAndRestart() { stop(); initMediaPlayer(); setDataSource(nextModel); } @Override public void onCompletion(MediaPlayer mediaPlayer) { handlerElapsedTime.removeCallbacks(runnableElapsedTime); Intent intent = new Intent(Constants.UPDATE_SEEK_BAR_RECEIVER); intent.putExtra(Constants.DURATION_EXTRA, mediaPlayer.getDuration()); manager.sendBroadcast(intent); playNext(); } }
package com.accp.service.impl; import com.accp.entity.Stockapply; import com.accp.dao.StockapplyDao; import com.accp.service.IStockapplyService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** * <p> * 服务实现类 * </p> * * @author ljq * @since 2019-08-28 */ @Service public class StockapplyServiceImpl extends ServiceImpl<StockapplyDao, Stockapply> implements IStockapplyService { }
package com.mx.profuturo.bolsa.model.reports.templates; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import com.mx.profuturo.bolsa.model.reports.vo.data.MotivosRechazoVO; public class MotivosRechazoTemplate extends BaseTemplate { //fecha candidato motivo etapa analista observador/gerente gerencia regional division //X:motivo Y: cantidad public MotivosRechazoTemplate() { } public MotivosRechazoTemplate(String branch) { this.mode= branch; } @Override public String getFileName() { return "motivos-rechazo.xlsx"; } @Override public Row getXLSCORPHeaders(Row row,Sheet s, Integer p) { row.createCell(p++).setCellValue("Fecha"); // s.autoSizeColumn(p);; row.createCell(p++).setCellValue("Candidato"); // s.autoSizeColumn(p); row.createCell(p++).setCellValue("Motivo"); // s.autoSizeColumn(p); row.createCell(p++).setCellValue("Etapa"); // s.autoSizeColumn(p); row.createCell(p++).setCellValue("Analista"); // s.autoSizeColumn(p); row.createCell(p++).setCellValue("Observador"); // s.autoSizeColumn(p); return row; } @Override protected Row getXLSCORPRowMapping(Row row, Sheet s, Object o, Integer p) { MotivosRechazoVO vo = (MotivosRechazoVO)o; row.createCell(p++).setCellValue(vo.getFecha()); // s.autoSizeColumn(p); row.createCell(p++).setCellValue(vo.getCandidato()); // s.autoSizeColumn(p); row.createCell(p++).setCellValue(vo.getMotivo()); // s.autoSizeColumn(p); row.createCell(p++).setCellValue(vo.getEtapa()); // s.autoSizeColumn(p); row.createCell(p++).setCellValue(vo.getAnalista()); // s.autoSizeColumn(p); row.createCell(p++).setCellValue(vo.getObservador()); return row; } @Override protected Row getXLSCOMHeaders(Row row, Sheet s, Integer p) { row.createCell(p++).setCellValue("Fecha"); // s.autoSizeColumn(p);; row.createCell(p++).setCellValue("Candidato"); // s.autoSizeColumn(p); row.createCell(p++).setCellValue("Motivo"); // s.autoSizeColumn(p); row.createCell(p++).setCellValue("getEtapa"); // s.autoSizeColumn(p); row.createCell(p++).setCellValue("getAnalista"); // s.autoSizeColumn(p); row.createCell(p++).setCellValue("Observador"); // s.autoSizeColumn(p); return row; } @Override protected Row getXLSCOMRowMapping(Row row, Sheet s, Object o, Integer p) { MotivosRechazoVO vo = (MotivosRechazoVO)o; // s.autoSizeColumn(p);; row.createCell(p++).setCellValue(vo.getFecha()); // s.autoSizeColumn(p); row.createCell(p++).setCellValue(vo.getCandidato()); // s.autoSizeColumn(p); row.createCell(p++).setCellValue(vo.getMotivo()); // s.autoSizeColumn(p); row.createCell(p++).setCellValue(vo.getEtapa()); // s.autoSizeColumn(p); row.createCell(p++).setCellValue(vo.getAnalista()); // s.autoSizeColumn(p); row.createCell(p++).setCellValue(vo.getObservador()); // s.autoSizeColumn(p); return row; } }
package Pages; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; public class CustomiseStatementPage { @FindBy(linkText = "Customised Statement") public WebElement CustomizedStatementPageField; @FindBy(name = "accountno") public WebElement AccountNumberField; @FindBy(name = "fdate") public WebElement FromDateField; @FindBy(name = "tdate") public WebElement TodateField; @FindBy(name = "amountlowerlimit") public WebElement MinTransactionField; @FindBy(name = "numtransaction") public WebElement NumberTransactionField; @FindBy (name= "AccSubmit") public WebElement SubmitbuttField; }
package tij.concurrents.part2; import java.util.ArrayList; import java.util.concurrent.*; public class TaskWithResult implements Callable<String> { private int id ; public TaskWithResult(int id){ this.id = id; } @Override public String call() throws Exception { String str = "starting..."; Thread.sleep(5); str+="loading..."; Thread.sleep(5); return "ID:"+id+" "+str+"finished"; } public static void main(String[] args) { callResult(); } static void callResult(){ ExecutorService exec = Executors.newCachedThreadPool(); final ArrayList<Future<String>> results = new ArrayList<Future<String>>(); for (int i=0;i<10;i++) { Future<String> future = exec.submit(new TaskWithResult(i)); results.add(future); } exec.execute(new Runnable(){ @Override public void run() { for (int i =0;i<1000;i++) { // try {//测试何谓在Future未准备就绪时get()会阻塞。根据结果来看可能意味着阻塞当前线程 // results.get(0).get(); // } catch (InterruptedException e) { // e.printStackTrace(); // } catch (ExecutionException e) { // e.printStackTrace(); // } System.out.print(i+","); Thread.yield(); } } }); for (Future<String> future : results) { try { String result = future.get(); System.out.println(result); }catch (InterruptedException e) { e.printStackTrace(); return; } catch (ExecutionException e) { e.printStackTrace(); } finally { exec.shutdown(); } } } }
package com.xiaoxiao.tiny.frontline.service.impl; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.sun.org.apache.bcel.internal.generic.LADD; import com.xiaoxiao.pojo.XiaoxiaoLabels; import com.xiaoxiao.pojo.vo.XiaoxiaoLabelVo; import com.xiaoxiao.tiny.frontline.feign.RedisCacheFeignClient; import com.xiaoxiao.tiny.frontline.mapper.FrontlineTinyLabelMapper; import com.xiaoxiao.tiny.frontline.service.FrontlineTinyLabelService; import com.xiaoxiao.tiny.frontline.utils.PageUtils; import com.xiaoxiao.utils.PageResult; import com.xiaoxiao.utils.Result; import com.xiaoxiao.utils.StatusCode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.util.List; /** * _ooOoo_ * o8888888o * 88" . "88 * (| -_- |) * O\ = /O * ____/`---'\____ * .' \\| |// `. * / \\||| : |||// \ * / _||||| -:- |||||- \ * | | \\\ - /// | | * | \_| ''\---/'' | | * \ .-\__ `-` ___/-. / * ___`. .' /--.--\ `. . __ * ."" '< `.___\_<|>_/___.' >'"". * | | : `- \`.;`\ _ /`;.`/ - ` : | | * \ \ `-. \_ __\ /__ _/ .-` / / * ======`-.____`-.___\_____/___.-`____.-'====== * `=---=' * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ * 佛祖保佑 永无BUG * 佛曰: * 写字楼里写字间,写字间里程序员; * 程序人员写程序,又拿程序换酒钱。 * 酒醒只在网上坐,酒醉还来网下眠; * 酒醉酒醒日复日,网上网下年复年。 * 但愿老死电脑间,不愿鞠躬老板前; * 奔驰宝马贵者趣,公交自行程序员。 * 别人笑我忒疯癫,我笑自己命太贱; * 不见满街漂亮妹,哪个归得程序员? * * @project_name:xiaoxiao_final_blogs * @date:2019/12/2:20:53 * @author:shinelon * @Describe: */ @Service public class FrontlineTinyLabelServiceImpl implements FrontlineTinyLabelService { @Value("${MARKED_WORDS_SUCCESS}") private String MARKED_WORDS_SUCCESS; @Value("${MARKED_WORDS_FAULT}") private String MARKED_WORDS_FAULT; @Autowired private RedisCacheFeignClient client; @Autowired private FrontlineTinyLabelMapper frontlineTinyLabelMapper; /** * 查询首页标签文章数据 * @return * @param page * @param rows */ @Override public Result findIndexLabelArticle(Integer page, Integer rows) { PageResult result = null; try { result = this.client.getIndexArticleLabel(); if(result.getResult() != null && result.getResult().size() > 0){ return Result.ok(StatusCode.OK, this.MARKED_WORDS_SUCCESS,result); } } catch (Exception e) { e.printStackTrace(); } PageHelper.startPage(page, rows); List<XiaoxiaoLabelVo> labelVos = this.frontlineTinyLabelMapper.findIndexLabelArticle(); PageResult result1 = PageUtils.getResult(new PageInfo<XiaoxiaoLabelVo>(labelVos), page); if(labelVos != null && labelVos.size() > 0){ try { this.client.insertIndexArticleLabel(result1); } catch (Exception e) { e.printStackTrace(); } return Result.ok(StatusCode.OK, true, this.MARKED_WORDS_SUCCESS,result1); } return Result.error(StatusCode.ERROR, this.MARKED_WORDS_FAULT); } /** * 获取全部的标签 * @param page * @param rows * @return */ @Override public Result findAllLabel(Integer page, Integer rows) { try { List<XiaoxiaoLabels> labelToRedis = this.client.getLabelToRedis(); if(labelToRedis != null && labelToRedis.size() > 0){ return Result.ok(StatusCode.OK, true, this.MARKED_WORDS_SUCCESS, labelToRedis); } } catch (Exception e) { e.printStackTrace(); } List<XiaoxiaoLabels> allLabel = this.frontlineTinyLabelMapper.findAllLabel(); if(allLabel != null && allLabel.size() > 0){ try { this.client.insertLabelToRedis(allLabel); } catch (Exception e) { e.printStackTrace(); } return Result.ok(StatusCode.OK, true,this.MARKED_WORDS_SUCCESS,allLabel); } return Result.error(StatusCode.ERROR, this.MARKED_WORDS_FAULT); } /** * 获取标签个数 * @return */ @Override public Result count() { try { XiaoxiaoLabelVo labelCount = this.client.getLabelCount(); if(labelCount != null){ return Result.ok(StatusCode.OK, true,this.MARKED_WORDS_SUCCESS,labelCount); } } catch (Exception e) { e.printStackTrace(); } XiaoxiaoLabelVo count = this.frontlineTinyLabelMapper.count(); if (count != null){ try { this.client.insertLabelCount(count); } catch (Exception e) { e.printStackTrace(); } return Result.ok(StatusCode.OK, true,this.MARKED_WORDS_SUCCESS,count); } return Result.error(StatusCode.ERROR, this.MARKED_WORDS_FAULT); } /** * 获取文章的全部的标签名字 * @param articleId * @return */ @Override public Result findArticleLabelName(Long articleId) { List<XiaoxiaoLabels> articleLabelName = this.frontlineTinyLabelMapper.findArticleLabelName(articleId); if(articleLabelName != null && articleLabelName.size() > 0){ return Result.ok(StatusCode.OK,true,this.MARKED_WORDS_SUCCESS,articleLabelName); } return Result.error(StatusCode.OK, this.MARKED_WORDS_FAULT); } }
package com.deltastuido.nexus.application; import java.sql.Timestamp; import java.time.Instant; import com.deltastuido.nexus.domain.Message; import com.google.common.base.Preconditions; public class MessageBuilder { private Message message; private MessageBuilder() { this.message = new Message(); } public static MessageBuilder create() { return new MessageBuilder(); } public static MessageBuilder create(Message message) { MessageBuilder builder = new MessageBuilder(); Message msg = builder.getMessage(); msg.setBody(message.getBody()); msg.setDest(message.getDest()); msg.setId(message.getId()); msg.setMsgType(message.getMsgType()); msg.setSrc(message.getSrc()); msg.setSubject(message.getSubject()); msg.setUrl(message.getUrl()); return builder; } public MessageBuilder from(String sender) { this.getMessage().setSrc(sender); return this; } public MessageBuilder to(String receiver) { this.getMessage().setDest(receiver); return this; } public MessageBuilder title(String title) { this.getMessage().setSubject(title); return this; } public MessageBuilder body(String body) { this.getMessage().setBody(body); return this; } public MessageBuilder withUrl(String url) { this.getMessage().setUrl(url); return this; } public MessageBuilder msgType(int t) { this.getMessage().setMsgType(t); return this; } public MessageBuilder id(String id) { this.getMessage().setId(id); return this; } public Message build() { Preconditions.checkNotNull(this.getMessage().getBody()); Preconditions.checkNotNull(this.getMessage().getSrc()); Preconditions.checkNotNull(this.getMessage().getDest()); Preconditions.checkNotNull(this.getMessage().getSubject()); this.getMessage().setDeleted(false); this.getMessage().setReaded(false); this.getMessage().setTimeCreated(Timestamp.from(Instant.now())); return this.getMessage(); } private Message getMessage() { return message; } }
package com.tencent.mm.plugin.appbrand.appcache; import java.io.InputStream; interface WxaCommLibRuntimeReader$c { WxaPkgWrappingInfo abQ(); InputStream openRead(String str); }
package uk.co.mobsoc.beacons.transientdata; import java.util.ArrayList; import org.bukkit.block.Block; import uk.co.mobsoc.beacons.storage.TeamData; public abstract class Event { private int warmuptimer = 0; private int maintimer = 0; private int cooldowntimer = 0; /** * Sets the time - in ticks (i * 20) (should be seconds - not guaranteed) that the game will count down from before the event starts in earnest * @param i */ protected void setWarmUpTimer(int i){ warmuptimer = i; } /** * Sets the time - in ticks (i * 20) (should be seconds - not guaranteed) that the game will count down from while the event takes place * @param i */ protected void setMainTimer(int i){ maintimer = i; } /** * * @param i */ protected void setCoolDownTimer(int i){ cooldowntimer = i; } /** * Returns true if the event is still ongoing * @return */ public boolean isActive(){ return warmuptimer > 0 || maintimer > 0 || cooldowntimer > 0; } /** * Gets the first team involved in this event. Null is not allowed - one team must always be returned * @return */ public abstract TeamData getTeam1(); /** * Gets the second team involved in this event. Null is allowed if the event is against Mobs. * @return */ public abstract TeamData getTeam2(); private ArrayList<BlockData> blockEdits = new ArrayList<BlockData>(); public void rememberBlock(Block b){ BlockData bd = new BlockData(b); blockEdits.add(bd); bd.removeBlock(); } /** * Fail-safe replacement of blocks. Done instantly and is kept in case of errors or sudden server shut down */ public void bailAllBlocks(){ // Do all non-attached blocks - solid whole blocks. for(BlockData bd : blockEdits){ if(!bd.attached){ bd.setBlock(); } } // Do all attached blocks - signs, lights. Things that will fall off without support for(BlockData bd : blockEdits){ if(bd.attached){ bd.setBlock(); } } } }
package baekjoon.numbertheory_combinatorics; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Test_11050 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int N = Integer.parseInt(st.nextToken()); int K = Integer.parseInt(st.nextToken()); int answer = factorial(N) / (factorial(K) * factorial(N - K)); System.out.println(answer); } static int factorial(int number) { if (number == 0) { return 1; } if (number == 1) { return number; } return number * factorial(number - 1); } }
package entities.components; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import utils.CommonFunctions; import static org.testng.Assert.assertTrue; public class SignInFormComponent extends BaseComponent { private By forgotPassword = By.cssSelector("a.forgot-password-link"); private By whereMyPassword = By.xpath("//div[@class='message-button']"); private By whereMyPasswordContent = By.xpath("//div[@class='message-content']"); //private By emailField = By.id("shipping-email"); private By passwordField = By.xpath("//input[@id='password' or @id='current-password']"); private By toGuestCheckoutLink = By.xpath("//a[text()='Proceed to Guest Checkout']"); private EmailComponent emailComponent = new EmailComponent(); public void signIn(String email, String password) { fillEmail(email); fillPassword(password); CommonFunctions.attachScreenshot("Login page with filled fields"); } public void proceedToGuestCheckout() { assertTrue(isElementClickable(toGuestCheckoutLink), "Proceed to guest checkout not clickable. Or doesn't isExist"); getDriver().findElement(toGuestCheckoutLink).click(); } public void pressForgotPasswordLink() { assertTrue(isElementClickable(forgotPassword), "Forgot password link not clickable. Or doesn't isExist"); CommonFunctions.attachScreenshot("Login page: Forgot Password"); getDriver().findElement(forgotPassword).click(); } public void fillEmail(String value) { emailComponent.fillEmailField(value); } public void fillPassword(String value) { WebElement passEl = findElement(passwordField); passEl.clear(); CommonFunctions.sleep(1000); passEl.sendKeys(value); //focusOut(passEl); } public void pressWhereDoIEnterMyPassword() { assertTrue(isElementClickable(whereMyPassword), "'Where do I enter my password' link not clickable. Or doesn't isExist"); getDriver().findElement(whereMyPassword).click(); } public String getContentAboutPasswordFill() { assertTrue(isElementVisible(whereMyPasswordContent, 5), "Content doesn't isExist."); return getDriver().findElement(whereMyPasswordContent).getText(); } @Override public boolean isExist(int timeout) { return isElementVisible(forgotPassword, timeout) || emailComponent.isExist(timeout); } @Override public boolean isExist() { return isElementVisible(forgotPassword) || emailComponent.isExist(5); } public boolean isPasswordFieldVisible() { return isElementVisible(passwordField, 5); } }
package org.switchyard.quickstarts.webservice.consumer2.ws; import java.io.Serializable; @SuppressWarnings("serial") public class ProcessOrderRequest implements Serializable { private Order order; public Order getOrder() { return order; } public void setOrder(Order order) { this.order = order; } }
import static java.util.Arrays.asList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class SomeJavaCode { { } public SomeJavaCode() { super(); } { } public static final List defaults = java.util.Arrays.asList(new Integer[]{Integer.valueOf(3), Integer.valueOf(2), Integer.valueOf(1)}); static { Collections.sort(defaults, new SomeJavaCode$1()); } private SomeJavaCode$Valid status = SomeJavaCode$Valid.MAYBE; public void run() { for (/*synthetic*/ java.util.Iterator i$ = defaults.iterator(); i$.hasNext(); ) { Integer i = (Integer)i$.next(); System.out.println("entry: " + i); } switch (SomeJavaCode$2.$SwitchMap$SomeJavaCode$Valid[(this.status).ordinal()]) { case 1: System.out.println(this.status.name()); break; default: break; } } } enum SomeJavaCode$Valid extends Enum<SomeJavaCode$Valid> { /*public static final*/ TRUE /* = new SomeJavaCode$Valid("TRUE", 0) */, /*public static final*/ FALSE /* = new SomeJavaCode$Valid("FALSE", 1) */, /*public static final*/ MAYBE /* = new SomeJavaCode$Valid("MAYBE", 2) */; /*synthetic*/ private static final SomeJavaCode$Valid[] $VALUES = new SomeJavaCode$Valid[]{SomeJavaCode$Valid.TRUE, SomeJavaCode$Valid.FALSE, SomeJavaCode$Valid.MAYBE}; public static SomeJavaCode$Valid[] values() { return (SomeJavaCode$Valid[])$VALUES.clone(); } public static SomeJavaCode$Valid valueOf(String name) { return (SomeJavaCode$Valid)Enum.valueOf(SomeJavaCode.Valid.class, name); } private SomeJavaCode$Valid(/*synthetic*/ String $enum$name, /*synthetic*/ int $enum$ordinal) { super($enum$name, $enum$ordinal); } } class SomeJavaCode$1 implements Comparator { SomeJavaCode$1() { super(); } @Override() public int compare(final Integer first, final Integer second) { return first.intValue() % 2 - second.intValue() % 2; } @Override() /*synthetic*/ public int compare(/*synthetic*/ final Object first, /*synthetic*/ final Object second) { return this.compare((Integer)first, (Integer)second); } } /*synthetic*/ class SomeJavaCode$2 { /*synthetic*/ static final int[] $SwitchMap$SomeJavaCode$Valid = new int[SomeJavaCode.Valid.values().length]; static { try { SomeJavaCode$2.$SwitchMap$SomeJavaCode$Valid[SomeJavaCode.Valid.FALSE.ordinal()] = 1; } catch (NoSuchFieldError ex) { } } }
package com.example.vjobanputra.simpletodo; import android.provider.BaseColumns; /** * Created by vjobanputra on 8/12/15. */ public final class TodoDbContract { public TodoDbContract() {} public static abstract class Items implements BaseColumns { public static final String TABLE_NAME = "items"; public static final String COLUMN_NAME_ITEM_ID = "itemId"; public static final String COLUMN_NAME_ITEM_TEXT = "itemText"; public static final String COLUMN_NAME_ITEM_DUE_DATE = "itemDueDate"; public static final String COLUMN_NAME_ITEM_PRIORITY = "itemPriority"; public static final String COLUMN_NAME_ITEM_DONE = "itemDone"; } }
package com.zadu.nightout; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.Notification; import android.app.NotificationManager; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.SharedPreferences; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.NotificationCompat; import android.util.Log; import android.view.WindowManager.LayoutParams; import android.widget.Toast; public class CheckinAlert extends DialogFragment{ private AlertsFragment.OnAlertsFragmentInteractionListener mListener; private MyOpenHelper mSqlHelper; final String TAG = "CheckinAlert"; @Override public void onAttach(Activity activity) { super.onAttach(activity); mSqlHelper = MyOpenHelper.getInstance(getActivity()); } @Override public void onDetach() { super.onDetach(); mListener = null; } /** The application should be exit, if the user presses the back button */ @Override public void onDestroy() { super.onDestroy(); getActivity().finish(); } @Override public void show(FragmentManager manager, String tag) { if (manager.findFragmentByTag(tag) == null) { super.show(manager, tag); } } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { super.onCreate(savedInstanceState); boolean isLast = getArguments().getBoolean("isLast"); int misses = getArguments().getInt("numMisses"); int notifId = getArguments().getInt("notifId"); /** Turn Screen On and Unlock the keypad when this alert dialog is displayed */ getActivity().getWindow().addFlags(LayoutParams.FLAG_TURN_SCREEN_ON | LayoutParams.FLAG_DISMISS_KEYGUARD); /** Creating a alert dialog builder */ AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); setUpDialog(builder, isLast, misses, notifId); /** Creating the alert dialog window */ return builder.create(); } private void setUpDialog(AlertDialog.Builder builder, boolean isFinal, int missed, final int notificationId) { final NotificationManager mNotificationManager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE); try { Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); Ringtone r = RingtoneManager.getRingtone(getActivity(), notification); r.play(); } catch (Exception e) { e.printStackTrace(); } if(!isFinal) { /** Setting title for the alert dialog */ builder.setTitle("Check-in Alert"); /** Setting the content for the alert dialog */ builder.setMessage("It's time to check in for your " + ((CheckinActivity) getActivity()).getPlanName() + " plan. You have missed " + missed + " times."); /** Defining button event listeners */ builder.setPositiveButton("Check In", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mNotificationManager.cancel(notificationId); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); preferences.edit().putString("checkin_change", "true").apply(); } }); builder.setNegativeButton("Turn Off", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mNotificationManager.cancel(notificationId); String planName = ((CheckinActivity) getActivity()).getPlanName(); mSqlHelper.updatePingsOnOff(planName, false); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); preferences.edit().putString("pings_onoff_change", "true").apply(); } }); } else { /** Setting title for the alert dialog */ builder.setTitle("Check-in Alert"); builder.setMessage("You've exceeded the number of misses for " + ((CheckinActivity) getActivity()).getPlanName() + " plan. A message has been sent to your emergency contacts."); builder.setPositiveButton("OK", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mNotificationManager.cancel(notificationId); String planName = ((CheckinActivity) getActivity()).getPlanName(); mSqlHelper.updatePingsOnOff(planName, false); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); preferences.edit().putString("pings_onoff_change", "true").apply(); } }); } } }
package zomeapp.com.zomechat.adapters; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.drawable.Animatable; import android.net.Uri; import android.support.design.widget.Snackbar; import android.support.v7.widget.RecyclerView; import android.util.DisplayMetrics; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import android.widget.TextView; import com.facebook.cache.common.CacheKey; import com.facebook.common.references.CloseableReference; import com.facebook.common.util.UriUtil; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.drawee.controller.BaseControllerListener; import com.facebook.drawee.interfaces.DraweeController; import com.facebook.drawee.view.SimpleDraweeView; import com.facebook.imagepipeline.bitmaps.PlatformBitmapFactory; import com.facebook.imagepipeline.image.ImageInfo; import com.facebook.imagepipeline.request.ImageRequest; import com.facebook.imagepipeline.request.ImageRequestBuilder; import com.facebook.imagepipeline.request.Postprocessor; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import zomeapp.com.zomechat.R; import zomeapp.com.zomechat.activities.FeedDetailActivity; import zomeapp.com.zomechat.application.ZomeApplication; import zomeapp.com.zomechat.dialogs.ReportDialog; import zomeapp.com.zomechat.models.Feed; /** * Created by tkiet082187 on 07.10.15. */ public class FeedsAdapter extends RecyclerView.Adapter<FeedsAdapter.ViewHolder> { private final ArrayList<Feed> feedArrayList; private Context context; private ZomeApplication application; private Snackbar snackbar; private DisplayMetrics metrics; public FeedsAdapter(Context context, ArrayList<Feed> feeds) { this.context = context; feedArrayList = feeds; application = (ZomeApplication) this.context.getApplicationContext(); metrics = Resources.getSystem().getDisplayMetrics(); } @Override public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.feeds_optimized_row, viewGroup, false); snackbar = Snackbar.make(viewGroup, "", Snackbar.LENGTH_SHORT); return new FeedsAdapter.ViewHolder(v); } @Override public void onViewRecycled(ViewHolder holder) { application.mZomeUtils.imagePipeline.clearCaches(); Log.e("view", "recycling"); super.onViewRecycled(holder); } @Override public void onBindViewHolder(final ViewHolder viewHolder, int i) { final Feed feed = feedArrayList.get(i); RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewHolder.mIvProfileImage.getLayoutParams(); if (!feed.getImageUrl().equals("")) { viewHolder.ivAttachedPhoto.setVisibility(View.VISIBLE); Log.e("device dim", metrics.widthPixels + "x" + metrics.heightPixels); Log.e("wLP, wIV", viewHolder.ivAttachedPhoto.getLayoutParams().width + ", " + viewHolder.ivAttachedPhoto.getWidth()); Postprocessor postProcessor = new Postprocessor() { @Override public CloseableReference<Bitmap> process(Bitmap sourceBitmap, PlatformBitmapFactory bitmapFactory) { Log.e("pp bmp dim", sourceBitmap.getWidth() + "x" + sourceBitmap.getHeight()); return null; } @Override public String getName() { return null; } @Override public CacheKey getPostprocessorCacheKey() { return null; } }; ImageRequest request = ImageRequestBuilder.newBuilderWithSource(Uri.parse(feed.getImageUrl())).setPostprocessor(postProcessor).build(); DraweeController controller = Fresco.newDraweeControllerBuilder() .setUri(Uri.parse(feed.getImageUrl())) // .setImageRequest(request) .setOldController(viewHolder.ivAttachedPhoto.getController()) .setControllerListener(new BaseControllerListener<ImageInfo>() { @Override public void onFinalImageSet(String id, ImageInfo imageInfo, Animatable animatable) { super.onFinalImageSet(id, imageInfo, animatable); // Log.e("imageInfo", imageInfo.getWidth() + "x" + imageInfo.getHeight()); // Log.e("vh info", viewHolder.ivAttachedPhoto.getWidth() + "x" + viewHolder.ivAttachedPhoto.getHeight()); // Log.e("vh drawable info", viewHolder.ivAttachedPhoto.getDrawable().getBounds().width() + "x" + viewHolder.ivAttachedPhoto.getDrawable().getBounds().height()); // Log.e("vh drawable dim", viewHolder.ivAttachedPhoto.getDrawable().getBounds().top + "x" + viewHolder.ivAttachedPhoto.getDrawable().getBounds().bottom + "x" + viewHolder.ivAttachedPhoto.getDrawable().getBounds().left + "x" + viewHolder.ivAttachedPhoto.getDrawable().getBounds().right); viewHolder.ivAttachedPhoto.setAspectRatio((float) imageInfo.getWidth() / imageInfo.getHeight()); Log.e("vh drawable info", viewHolder.ivAttachedPhoto.getDrawable().getBounds().width() + "x" + viewHolder.ivAttachedPhoto.getDrawable().getBounds().height()); /*if (viewHolder.ivAttachedPhoto.getHeight() > viewHolder.ivAttachedPhoto.getWidth() && imageInfo.getWidth() > imageInfo.getHeight()) { viewHolder.ivAttachedPhoto.setAspectRatio((float) imageInfo.getHeight() / imageInfo.getWidth()); } else { viewHolder.ivAttachedPhoto.setAspectRatio((float) imageInfo.getWidth() / imageInfo.getHeight()); }*/ } @Override public void onIntermediateImageSet(String id, ImageInfo imageInfo) { super.onIntermediateImageSet(id, imageInfo); // Log.e("imageInfo", imageInfo.getWidth() + "x" + imageInfo.getHeight()); // Log.e("vh info", viewHolder.ivAttachedPhoto.getWidth() + "x" + viewHolder.ivAttachedPhoto.getHeight()); // Log.e("vh drawable info", viewHolder.ivAttachedPhoto.getDrawable().getBounds().width() + "x" + viewHolder.ivAttachedPhoto.getDrawable().getBounds().height()); // Log.e("vh drawable dim", viewHolder.ivAttachedPhoto.getDrawable().getBounds().top + "x" + viewHolder.ivAttachedPhoto.getDrawable().getBounds().bottom + "x" + viewHolder.ivAttachedPhoto.getDrawable().getBounds().left + "x" + viewHolder.ivAttachedPhoto.getDrawable().getBounds().right); viewHolder.ivAttachedPhoto.setAspectRatio((float) imageInfo.getWidth() / imageInfo.getHeight()); Log.e("vh drawable info", viewHolder.ivAttachedPhoto.getDrawable().getBounds().width() + "x" + viewHolder.ivAttachedPhoto.getDrawable().getBounds().height()); /*if (viewHolder.ivAttachedPhoto.getHeight() > viewHolder.ivAttachedPhoto.getWidth() && imageInfo.getWidth() > imageInfo.getHeight()) { viewHolder.ivAttachedPhoto.setAspectRatio((float) imageInfo.getHeight() / imageInfo.getWidth()); } else { viewHolder.ivAttachedPhoto.setAspectRatio((float) imageInfo.getWidth() / imageInfo.getHeight()); }*/ } }) .build(); viewHolder.ivAttachedPhoto.setController(controller); params.addRule(RelativeLayout.CENTER_VERTICAL, 0); params.addRule(RelativeLayout.ALIGN_PARENT_TOP); } else { viewHolder.ivAttachedPhoto.setVisibility(View.GONE); params.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0); params.addRule(RelativeLayout.CENTER_VERTICAL); } SimpleDateFormat sdf = new SimpleDateFormat("h:mm a zzz M/d/y", Locale.getDefault()); try { Date parseDate = sdf.parse(feed.getTime()); application.mZomeUtils.returnApproxTime(parseDate, viewHolder.mTvTime); } catch (ParseException e) { e.printStackTrace(); } application.mZomeUtils.setTags(viewHolder.mTvContent, feed.getContent()); viewHolder.mTvProfileName.setText(feed.getOwnerName()); Uri uri = new Uri.Builder() .scheme(UriUtil.LOCAL_RESOURCE_SCHEME) // "res" .path(String.valueOf(R.drawable.anonymous_large)) .build(); if (!feed.getOwnerImageUrl().equals("")) { uri = Uri.parse(feed.getOwnerImageUrl()); } viewHolder.mIvProfileImage.setImageURI(uri); viewHolder.rlContent.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.e("feedId", feed.getPostId()); Intent intent = new Intent(context.getApplicationContext(), FeedDetailActivity.class); intent.putExtra("feedId", feed.getPostId()); intent.putExtra("time", feed.getTime()); intent.putExtra("profileName", feed.getOwnerName()); intent.putExtra("content", feed.getContent()); intent.putExtra("extraImage", feed.getImageUrl()); if (!feed.getImageUrl().equals("")) { intent.putExtra("image", feed.getImageUrl()); } if (!feed.getOwnerImageUrl().equals("")) { intent.putExtra("ownerImage", feed.getOwnerImageUrl()); } context.startActivity(intent); } }); viewHolder.rlContent.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { snackbar = application.mZomeUtils.getSnackbar( v, "Report post '" + feed.getContent() + "'?", "Click here to Report", new View.OnClickListener() { @Override public void onClick(View v) { if (application.mZomeUtils.isUserAnonymous) { application.mZomeUtils.showToastAnonymousUserMessage("make a report."); } else { ReportDialog dialog = new ReportDialog( context, 0, "POST", feed.getContent(), feed.getPostId() ); dialog.show(); } } } ); snackbar.show(); return true; } }); viewHolder.mTvHearts.setText(String.valueOf(feed.getHeartsCount())); viewHolder.mTvReplies.setText(String.valueOf(feed.getCommentsCount())); } @Override public int getItemCount() { return feedArrayList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { private final SimpleDraweeView mIvProfileImage; private final TextView mTvProfileName, mTvContent, mTvTime, mTvHearts, mTvReplies; private final SimpleDraweeView ivAttachedPhoto; private final RelativeLayout rlContent; ViewHolder(View v) { super(v); rlContent = (RelativeLayout) v.findViewById(R.id.rlContent); mIvProfileImage = (SimpleDraweeView) v.findViewById(R.id.ivProfilePicture); mTvProfileName = (TextView) v.findViewById(R.id.tvProfileName); mTvContent = (TextView) v.findViewById(R.id.tvContent); mTvTime = (TextView) v.findViewById(R.id.tvTime); ivAttachedPhoto = (SimpleDraweeView) v.findViewById(R.id.ivAttachedPhoto); mTvHearts = (TextView) v.findViewById(R.id.tvHearts); mTvReplies = (TextView) v.findViewById(R.id.tvReplies); } } public void animateTo(List<Feed> models) { applyAndAnimateRemovals(models); applyAndAnimateAdditions(models); applyAndAnimateMovedItems(models); } private void applyAndAnimateRemovals(List<Feed> newFeeds) { for (int i = feedArrayList.size() - 1; i >= 0; i--) { final Feed feed = feedArrayList.get(i); if (!newFeeds.contains(feed)) { removeItem(i); } } } private void applyAndAnimateAdditions(List<Feed> newFeeds) { for (int i = 0, count = newFeeds.size(); i < count; i++) { final Feed feed = newFeeds.get(i); if (!feedArrayList.contains(feed)) { addItem(i, feed); } } } private void applyAndAnimateMovedItems(List<Feed> newFeeds) { for (int toPosition = newFeeds.size() - 1; toPosition >= 0; toPosition--) { final Feed feed = newFeeds.get(toPosition); final int fromPosition = feedArrayList.indexOf(feed); if (fromPosition >= 0 && fromPosition != toPosition) { moveItem(fromPosition, toPosition); } } } public Feed removeItem(int position) { final Feed model = feedArrayList.remove(position); notifyItemRemoved(position); return model; } public void addItem(int position, Feed feed) { feedArrayList.add(position, feed); notifyItemInserted(position); } public void moveItem(int fromPosition, int toPosition) { final Feed feed = feedArrayList.remove(fromPosition); feedArrayList.add(toPosition, feed); notifyItemMoved(fromPosition, toPosition); } }
package app.integro.sjbhs; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; import java.util.ArrayList; import app.integro.sjbhs.adapters.NewsAdapter; import app.integro.sjbhs.apis.ApiClients; import app.integro.sjbhs.apis.ApiServices; import app.integro.sjbhs.models.News; import app.integro.sjbhs.models.NewsList; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class NewsActivity extends AppCompatActivity { private ArrayList<News> newsArrayList; private RecyclerView rvNews; private NewsAdapter newsAdapter; private TextView tvNoItems; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_news); rvNews = (RecyclerView) findViewById(R.id.rvNews); tvNoItems=findViewById(R.id.tvNoItems); rvNews.setLayoutManager(new LinearLayoutManager(getApplicationContext())); newsArrayList = new ArrayList<>(); getNews(); } public void getNews() { Call<NewsList> newsListCall = ApiClients.getClient().create(ApiServices.class).getNewsList(); newsListCall.enqueue(new Callback<NewsList>() { @Override public void onResponse(Call<NewsList> call, Response<NewsList> response) { if (response.isSuccessful()) { if (response.body().getNewsList() != null) { int size = response.body().getNewsList().size(); Log.d("RESPONSE", "NewsList " + size); for (int i = 0; i < size; i++) { newsArrayList.add(response.body().getNewsList().get(i)); } newsAdapter=new NewsAdapter(getApplicationContext(),newsArrayList); rvNews.setAdapter(newsAdapter); } else { tvNoItems.setVisibility(View.VISIBLE); tvNoItems.setText("No Items Found..!"); } } else { Log.d("RESPONSE", "RESPONSE FAIL"); } } @Override public void onFailure(Call<NewsList> call, Throwable t) { Log.d("RESPONSE", "SERVER FAIL"); } }); } }
package com.tencent.mm.plugin.downloader.a; public final class b { public static int ibs = 0; public static int ibt = 1; public static int ibu = 2; }
package sort_algorithm; public class CountingSort { public static void main(String[] args){ int[] intArray = {2, 5, 9, 8, 2, 8, 7, 10, 4, 3}; countingSort(intArray, 1, 10); for(int i=0; i < intArray.length; i++){ if(i == intArray.length-1){ System.out.println(intArray[i]); } else { System.out.print(intArray[i] + ", "); } } } public static void countingSort(int[] input, int min, int max){ // Element의 범위에 알맞는 배열 생성 int[] countArray = new int[(max-min)+1]; for(int i=0; i < input.length; i++){ // 해당 element의 index를 알기 위해선 min을 빼줘야 함 // 해당 Element가 나왔다면 ++해줌 countArray[input[i] - min]++; } // input 배열에 써나가기 위한 index int j = 0; // min에서 max 값, 즉 각 element 마다 계속 반복 for(int i = min; i <= max; i++){ // countArray의 i-min의 위치이면 해당 element의 count가 저장된 곳 // 즉, 그 value가 0 초과라면 element가 1번 이상 나왔다는 의미 while(countArray[i - min] > 0){ // 해당 반복 동안 원래의 input 배열에 해당 element를 채워 넣음 input[j++] = i; // 그리고 채워 넣은 만큼 count value를 낮춤춤 countArray[i -min]--; } } } }
package com.paytechnologies.cloudacar.AsynTask; import java.io.IOException; import java.net.UnknownHostException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.HttpHostConnectException; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.paytechnologies.cloudacar.CompleteProfile; import com.paytechnologies.cloudacar.TravelPrefences; import com.paytechnologies.cloudacar.TripDTO; import android.app.Activity; import android.content.Context; import android.os.AsyncTask; import android.util.Log; public class DirectionPathTask extends AsyncTask<String, String, String>{ Activity _complete_profile; String start_add_compo = ""; String start_add_component; Context c; int responseCode; public DirectionPathTask() { // TODO Auto-generated constructor stub //_complete_profile = completeProfile; } @Override protected String doInBackground(String... arg0) { // TODO Auto-generated method stub System.out.println(arg0[0]); HttpResponse response; //String Url="http://maps.googleapis.com/maps/api/directions/json?"; //String Url1="origin="+arg0[0]+"&destination="+arg0[1]+"&"; //String Url2 ="mode=driving&language=us-ENG&sensor=false"; StringBuilder urlString = new StringBuilder(); urlString.append("http://maps.googleapis.com/maps/api/geocode/json"); urlString.append("?address="+arg0[0]+"&sensor=false&mode=driving&alternatives=true"); //String Url = "http://maps.googleapis.com/maps/api/geocode/json?"; //String Url1 = "address="+arg0[0]+"&sensor=false" ; String mainUrl = urlString.toString(); mainUrl=mainUrl.replaceAll(" ", "+"); Log.d("MainUrl", ""+mainUrl); HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = null; httpGet = new HttpGet(mainUrl); try { System.out.println("Executing New URL..."); response = httpClient.execute(httpGet); System.out.println("check response "+response.toString()); HttpEntity entity = response.getEntity(); String jsonResponseString = EntityUtils.toString(entity); Log.d("Http Response:",jsonResponseString); try { JSONObject response_server = new JSONObject(jsonResponseString); JSONArray jsonResults = response_server.getJSONArray("results"); Log.d("JsonRoute is", ""+jsonResults); JSONObject address = jsonResults.getJSONObject(0); Log.d("Address is", ""+address); JSONArray address_compo = address.getJSONArray("address_components"); Log.d("Addres_compo", ""+address_compo); TripDTO trip =new TripDTO(); for(int i=0;i<address_compo.length();i++){ String long_name= address_compo.getJSONObject(i).getString("long_name"); Log.d("Long name", ""+long_name); JSONArray types= address_compo.getJSONObject(i).getJSONArray("types"); Log.d("Types", ""+types); // StringBuilder start_add_compo = new StringBuilder(); for(int j = 0 ;j<types.length();j++){ String types1= types.getString(j); start_add_compo = start_add_compo + types1 + '=' +'\'' + long_name +'\''+ ','; trip.setStartAddCompo(start_add_compo); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } responseCode = response.getStatusLine().getStatusCode(); } catch (HttpHostConnectException e){ // TODO Auto-generated catch block //e.printStackTrace(); responseCode = 1101;//LCH: Our custom error code... } catch (UnknownHostException e){ // TODO Auto-generated catch block //e.printStackTrace(); responseCode = 1101;//LCH: Our custom error code... }catch (ClientProtocolException e) { // writing exception to log e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }
public abstract class Veiculo{ //Atributos: private String placa = ""; private String marca = ""; private String modelo = ""; private float velocMax = 0; //Declaração e Instanciação TstPlaca tst = new TstPlaca(); Motor mot = new Motor(); //Métodos Setters: public void setPlaca(String placa){ if(tst.certificPlaca(placa)){ this.placa = placa; } else { this.placa = "AAA-AAAA"; } } public void setMot(Motor mot){ this.mot = mot; } public void setMarca(String marca){ this.marca = marca; } public void setModelo(String modelo){ this.modelo = modelo; } public void setVelocMax(String velocMax){ this.velocMax = Float.parseFloat(velocMax); } // Métodos Getters: public String getPlaca(){ return placa; } public String getMarca(){ return marca; } public String getModelo(){ return modelo; } public float getVelocMax(){ return velocMax; } public Motor getMot(){ return mot; } }
package com.example.myapplication.support_kt; import kotlin.Function; /** * ****************************** * * @author YOULU-wwb * date: 2020/4/21 14:29 * description: * ****************************** */ public class SupportUtil { }
package com.handsomedong.dynamic.datasource.spring.boot.autoconfigure; import com.handsomedong.dynamic.datasource.aop.DynamicDataSourceAnnotationBeanPostProcessor; import com.handsomedong.dynamic.datasource.aop.DynamicDataSourceAnnotationInterceptor; import com.handsomedong.dynamic.datasource.helper.DynamicDataSourceContextHolder; import com.handsomedong.dynamic.datasource.helper.DynamicRoutingDataSource; import com.handsomedong.dynamic.datasource.provider.DefaultDynamicDataSourceProvider; import com.handsomedong.dynamic.datasource.provider.DynamicDataSourceProvider; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import javax.sql.DataSource; import java.sql.SQLException; import java.util.Map; /** * Created by HandsomeDong on 2021/9/29 0:50 * 自动配置类 */ @Slf4j @Configuration @EnableConfigurationProperties(DynamicDataSourceProperties.class) @AutoConfigureBefore(value = DataSourceAutoConfiguration.class, name = "com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure") @Import(DruidDynamicDataSourceConfiguration.class) public class DynamicDataSourceAutoConfiguration { private final DynamicDataSourceProperties properties; @Autowired @Qualifier("shardingDataSourceMap") private Map<String, DataSource> shardingDataSourceMap; public DynamicDataSourceAutoConfiguration(DynamicDataSourceProperties properties) { this.properties = properties; } @Bean @ConditionalOnMissingBean public DynamicDataSourceProvider dynamicDataSourceProvider() { return new DefaultDynamicDataSourceProvider(properties); } @Bean @ConditionalOnMissingBean public DataSource dataSource(DynamicDataSourceProvider provider) throws SQLException { DynamicRoutingDataSource dynamicRoutingDataSource = new DynamicRoutingDataSource(); // 设置多数据源 Map<String, DataSource> dataSourceMap = provider.loadDataSources(); // 设置sharding-jdbc数据源 dataSourceMap.putAll(shardingDataSourceMap); // 加载数据源 dataSourceMap.forEach(dynamicRoutingDataSource::addDataSource); //设置默认数据源 dynamicRoutingDataSource.setDefaultTargetDataSource(dataSourceMap.get(properties.getDefaultDatasourceKey())); DynamicDataSourceContextHolder.DEFAULT_KEY = properties.getDefaultDatasourceKey(); return dynamicRoutingDataSource; } @Bean @ConditionalOnMissingBean public DynamicDataSourceAnnotationInterceptor dynamicDataSourceAnnotationInterceptor() { return new DynamicDataSourceAnnotationInterceptor(); } @Bean @ConditionalOnMissingBean public DynamicDataSourceAnnotationBeanPostProcessor dynamicDataSourceAnnotationBeanPostProcessor(DynamicDataSourceAnnotationInterceptor interceptor) { return new DynamicDataSourceAnnotationBeanPostProcessor(interceptor); } }
package hirondelle.web4j.security; import hirondelle.web4j.request.RequestParser; /** Determine if text is likely spam. <P>See {@link hirondelle.web4j.BuildImpl} for important information on how this item is configured. {@link hirondelle.web4j.BuildImpl#forSpamDetector()} returns the configured implementation of this interface. <P><a href="http://en.wikipedia.org/wiki/Forum_spam">Spam</a> refers to unwanted input from undesirable parties (usually advertising of some sort) that is often POSTed to servers using automated means. <P>Most spam contains <em>links</em>. Implementations are encouraged to detect unwanted links. <P>The <tt>SpamDetectionInFirewall</tt> setting in <tt>web.xml</tt> can instruct the {@link hirondelle.web4j.security.ApplicationFirewall} to use the configured <tt>SpamDetector</tt> to reject <em>all</em> requests containing at least one parameter that appears to be spam. Such filtering is applied as a <a href="ApplicationFirewall.html#HardValidation">hard validation</a>, and will <em>not</em> result in a polished response to the end user. <P>If that policy is felt to be too aggressive, then the only alternative is to check <em>all items input as text</em> using {@link hirondelle.web4j.model.Check#forSpam()} (usually in a Model Object constructor). Such checks do <em>not</em> need to be applied to numeric or date data, since the regular conversion validations done by {@link RequestParser} for numbers and dates will already detect and reject any spam. */ public interface SpamDetector { /** Determine if the given text is very likely spam. @param aText value of a request parameter. */ boolean isSpam(String aText); }
package uk.gov.ons.ctp.response.action.export.config; import lombok.Data; import net.sourceforge.cobertura.CoverageIgnore; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import uk.gov.ons.ctp.common.message.rabbit.Rabbitmq; /** The apps main holder for centralized config read from application.yml or env vars */ @CoverageIgnore @Configuration @ConfigurationProperties @Data public class AppConfig { private Rabbitmq rabbitmq; private ExportSchedule exportSchedule; private DataGrid dataGrid; private Logging logging; private Sftp sftp; }
import java.util.Scanner; public class P9 { public static void main(String[] args) { final int UNIT_LITER = 9; Scanner sc = new Scanner(System.in); System.out.println("Input the length"); while (!sc.hasNextLong()) { sc.next(); System.out.println("Confirm your input"); } long length = sc.nextLong(); System.out.println("Input the width"); while (!sc.hasNextLong()) { sc.next(); System.out.println("Confirm your input"); } long width = sc.nextLong(); long ceilingWidth = Math.multiplyExact(length, width); long div = Math.floorDiv(ceilingWidth, UNIT_LITER); double ceil = Math.ceil(div); System.out.println("You will need to purchase" + ceil + "liters of paint to cover" + ceilingWidth + "square meters."); } }
/** * */ package com.chengzhang.picturematching; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; /** * @author Jackie * */ public class Launcher extends Activity { private Button _startButton, _exitButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.launcher); initComponent(); } private void initComponent() { _startButton = (Button)findViewById(R.id.Start); _exitButton = (Button)findViewById(R.id.Exit); _startButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Launcher.this, PictureMatching.class); startActivity(intent); } }); _exitButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); System.exit(RESULT_OK); } }); } }
/* * (C) Copyright 2012 Nuxeo SA (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Contributors: * matic */ package org.nuxeo.osgi.util.jar; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.HashMap; import java.util.jar.JarFile; /** * @author matic * */ public class URLClassLoaderCloser { protected URLClassLoader loader; protected ArrayList<?> loaders; protected Field jarField; protected Method getJarFileMethod; protected HashMap<?, ?> lmap; public URLClassLoaderCloser(URLClassLoader loader) { try { introspectClassLoader(loader); } catch (NoSuchFieldException e) { throw new RuntimeException("Cannot introspect url class loader " + loader, e); } catch (SecurityException e) { throw new RuntimeException("Cannot introspect url class loader " + loader, e); } catch (IllegalAccessException e) { throw new RuntimeException("Cannot introspect url class loader " + loader, e); } catch (ClassNotFoundException e) { throw new RuntimeException("Cannot introspect url class loader " + loader, e); } catch (NoSuchMethodException e) { throw new RuntimeException("Cannot introspect url class loader " + loader, e); } } protected void introspectClassLoader(URLClassLoader loader) throws NoSuchFieldException, SecurityException, IllegalAccessException, ClassNotFoundException, NoSuchMethodException { this.loader = loader; Field ucpField = URLClassLoader.class.getDeclaredField("ucp"); ucpField.setAccessible(true); Object ucp = ucpField.get(loader); Class<?> ucpClass = ucp.getClass(); Field lmapField = ucpClass.getDeclaredField("lmap"); lmapField.setAccessible(true); lmap = (HashMap<?, ?>) lmapField.get(ucp); Field loadersField = ucpClass.getDeclaredField("loaders"); loadersField.setAccessible(true); loaders = (ArrayList<?>) loadersField.get(ucp); Class<?> jarLoaderClass = getJarLoaderClass(); jarField = jarLoaderClass.getDeclaredField("jar"); jarField.setAccessible(true); getJarFileMethod = jarLoaderClass.getDeclaredMethod("getJarFile", new Class<?>[] { URL.class }); getJarFileMethod.setAccessible(true); } protected static Class<?> getJarLoaderClass() throws ClassNotFoundException { return URLClassLoaderCloser.class.getClassLoader().loadClass("sun.misc.URLClassPath$JarLoader"); } protected static String serializeURL(URL location) { StringBuilder localStringBuilder = new StringBuilder(128); String str1 = location.getProtocol(); if (str1 != null) { str1 = str1.toLowerCase(); localStringBuilder.append(str1); localStringBuilder.append("://"); } String str2 = location.getHost(); if (str2 != null) { str2 = str2.toLowerCase(); localStringBuilder.append(str2); int i = location.getPort(); if (i == -1) i = location.getDefaultPort(); if (i != -1) localStringBuilder.append(":").append(i); } String str3 = location.getFile(); if (str3 != null) localStringBuilder.append(str3); return localStringBuilder.toString(); } public boolean close(URL location) throws IOException { if (lmap.isEmpty()) { return false; } Object firstKey = lmap.keySet().iterator().next(); Object loader = firstKey instanceof URL ? lmap.remove(location) : lmap.remove(serializeURL(location)); if (loader == null) { return false; } loaders.remove(loader); JarFile jar = null; try { jar = (JarFile) jarField.get(loader); jarField.set(loader, null); } catch (IllegalArgumentException e) { throw new RuntimeException( "Cannot use reflection on url class path", e); } catch (IllegalAccessException e) { throw new RuntimeException( "Cannot use reflection on url class path", e); } jar.close(); return true; } }
/* * ********************************************************* * Copyright (c) 2019 @alxgcrz All rights reserved. * This code is licensed under the MIT license. * Images, graphics, audio and the rest of the assets be * outside this license and are copyrighted. * ********************************************************* */ package com.codessus.ecnaris.ambar.fragments; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import com.codessus.ecnaris.ambar.R; import com.codessus.ecnaris.ambar.activities.MainActivity; import com.codessus.ecnaris.ambar.helpers.AmbarManager; import com.codessus.ecnaris.ambar.models.personaje.Personaje; import java.util.List; import butterknife.BindView; import butterknife.BindViews; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.Unbinder; import static com.codessus.ecnaris.ambar.helpers.AmbarManager.MODE_READ; /** * HOJA de personaje */ public class HojaFragment extends Fragment { @BindView(R.id.fragment_hoja_img_card) ImageView imageViewCard; @BindView(R.id.fragment_hoja_textView_name) TextView nameTextView; @BindView(R.id.fragment_hoja_textView_class) TextView classTextView; @BindView(R.id.fragment_hoja_textView_level) TextView levelTextView; @BindView(R.id.fragment_hoja_textView_experiencia) TextView experienciaTextView; @BindView(R.id.fragment_hoja_textView_vida) TextView vidaTextView; @BindView(R.id.fragment_hoja_textView_estado) TextView estadoTextView; @BindView(R.id.fragment_hoja_value_money) TextView monedasTextView; @BindViews({R.id.fragment_hoja_textView_attribute_fuerza, R.id.fragment_hoja_textView_attribute_aguante, R.id.fragment_hoja_textView_attribute_agilidad, R.id.fragment_hoja_textView_attribute_percepcion, R.id.fragment_hoja_textView_attribute_carisma, R.id.fragment_hoja_textView_attribute_ataque, R.id.fragment_hoja_textView_attribute_daño, R.id.fragment_hoja_textView_attribute_defensa, R.id.fragment_hoja_textView_attribute_absorcion}) List<TextView> atributos; // Navigation (Oculta por defecto) @BindView(R.id.include_navigation_next) ImageButton nextImageButton; @BindView(R.id.include_navigation_cancel) ImageButton cancelImageButton; private Unbinder unbinder; // --- CONSTRUCTOR --- // public HojaFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View rootView = inflater.inflate(R.layout.fragment_hoja, container, false); // Inyectar las Views unbinder = ButterKnife.bind(this, rootView); // Mostrar los botones de navegación cancelImageButton.setVisibility(View.VISIBLE); nextImageButton.setVisibility(View.VISIBLE); // Recuperar el personaje Personaje personaje = AmbarManager.instance().getPersonaje(); // Cargar los datos imageViewCard.setImageDrawable(personaje.getCard()); nameTextView.setText(personaje.getName()); classTextView.setText(personaje.getClase().getLocalizedClassName(getActivity().getBaseContext())); levelTextView.setText(String.valueOf(personaje.getCurrentLevel())); experienciaTextView.setText(String.format(getString(R.string.fragment_hoja_textView_experiencia), personaje.getExperiencia(), personaje.getExperienciaForNextLevel())); vidaTextView.setText(String.format(getString(R.string.fragment_hoja_textView_vida), personaje.getVidaReal(), personaje.getVida())); estadoTextView.setText(personaje.getEstado().getName()); monedasTextView.setText(String.valueOf(personaje.getMonedasTotales())); for (int i = 0; i < atributos.size(); i++) { String value = "0"; switch (i) { case 0: value = String.valueOf(personaje.getFuerzaTotal()); break; case 1: value = String.valueOf(personaje.getAguanteTotal()); break; case 2: value = String.valueOf(personaje.getAgilidadTotal()); break; case 3: value = String.valueOf(personaje.getPercepcionTotal()); break; case 4: value = String.valueOf(personaje.getCarismaTotal()); break; case 5: value = String.valueOf(personaje.getAtaque()); break; case 6: if (personaje.getDañoMinimo() == personaje.getDañoMaximo()) { value = String.valueOf(personaje.getDaño()); } else { value = personaje.getDañoMinimo() + "-" + personaje.getDañoMaximo(); } break; case 7: value = String.valueOf(personaje.getDefensa()); break; case 8: value = String.valueOf(personaje.getAbsorcion()); break; } atributos.get(i).setText(value); } return rootView; } /** * Método que se ejecuta al pulsar en el botón 'NEXT' * * @param button pulsado */ @OnClick({R.id.include_navigation_next, R.id.include_navigation_cancel}) public void navigation(View button) { // Cargar el fragment correspondiente if (button.getId() == R.id.include_navigation_cancel) { // Cargar el fragment de lectura ((MainActivity) getActivity()).loadNextFragment(button, new LecturaFragment()); } else if (button.getId() == R.id.include_navigation_next) { // Cargar el fragment de aptitudes indicando que estamos en modo READ ((MainActivity) getActivity()).loadNextFragment(button, AptitudesFragment.newInstance(MODE_READ)); } } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); } }
/* TODO: Understand concept of annonymous class. */ interface It { void at(); } public class Annonymous { public static void main(String args[]) { It e=new It() { public void at() { System.out.println("Annonymous define"); } }; e.at(); } }
public class Wrapper { int hops; String url; Wrapper(String url1, int d1) { hops=d1; url= new String(url1); } public String getUrl() { return url; } public int getHops() { return hops; } }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.09.03 at 09:19:50 PM EDT // package org.oasisopen.xliff; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.datatype.XMLGregorianCalendar; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence maxOccurs="unbounded" minOccurs="0"> * &lt;element ref="{urn:oasis:names:tc:xliff:document:1.2}note"/> * &lt;/sequence> * &lt;attribute name="phase-name" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="process-name" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="company-name" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="tool-id" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="tool" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="date" type="{http://www.w3.org/2001/XMLSchema}dateTime" /> * &lt;attribute name="job-id" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="contact-name" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="contact-email" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="contact-phone" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "note" }) @XmlRootElement(name = "phase") public class Phase { protected List<Note> note; @XmlAttribute(name = "phase-name", required = true) protected String phaseName; @XmlAttribute(name = "process-name", required = true) protected String processName; @XmlAttribute(name = "company-name") protected String companyName; @XmlAttribute(name = "tool-id") protected String toolId; @XmlAttribute(name = "tool") protected String tool; @XmlAttribute(name = "date") @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar date; @XmlAttribute(name = "job-id") protected String jobId; @XmlAttribute(name = "contact-name") protected String contactName; @XmlAttribute(name = "contact-email") protected String contactEmail; @XmlAttribute(name = "contact-phone") protected String contactPhone; /** * Gets the value of the note property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the note property. * * <p> * For example, to add a new item, do as follows: * <pre> * getNote().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Note } * * */ public List<Note> getNote() { if (note == null) { note = new ArrayList<Note>(); } return this.note; } /** * Gets the value of the phaseName property. * * @return * possible object is * {@link String } * */ public String getPhaseName() { return phaseName; } /** * Sets the value of the phaseName property. * * @param value * allowed object is * {@link String } * */ public void setPhaseName(String value) { this.phaseName = value; } /** * Gets the value of the processName property. * * @return * possible object is * {@link String } * */ public String getProcessName() { return processName; } /** * Sets the value of the processName property. * * @param value * allowed object is * {@link String } * */ public void setProcessName(String value) { this.processName = value; } /** * Gets the value of the companyName property. * * @return * possible object is * {@link String } * */ public String getCompanyName() { return companyName; } /** * Sets the value of the companyName property. * * @param value * allowed object is * {@link String } * */ public void setCompanyName(String value) { this.companyName = value; } /** * Gets the value of the toolId property. * * @return * possible object is * {@link String } * */ public String getToolId() { return toolId; } /** * Sets the value of the toolId property. * * @param value * allowed object is * {@link String } * */ public void setToolId(String value) { this.toolId = value; } /** * Gets the value of the tool property. * * @return * possible object is * {@link String } * */ public String getTool() { return tool; } /** * Sets the value of the tool property. * * @param value * allowed object is * {@link String } * */ public void setTool(String value) { this.tool = value; } /** * Gets the value of the date property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getDate() { return date; } /** * Sets the value of the date property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setDate(XMLGregorianCalendar value) { this.date = value; } /** * Gets the value of the jobId property. * * @return * possible object is * {@link String } * */ public String getJobId() { return jobId; } /** * Sets the value of the jobId property. * * @param value * allowed object is * {@link String } * */ public void setJobId(String value) { this.jobId = value; } /** * Gets the value of the contactName property. * * @return * possible object is * {@link String } * */ public String getContactName() { return contactName; } /** * Sets the value of the contactName property. * * @param value * allowed object is * {@link String } * */ public void setContactName(String value) { this.contactName = value; } /** * Gets the value of the contactEmail property. * * @return * possible object is * {@link String } * */ public String getContactEmail() { return contactEmail; } /** * Sets the value of the contactEmail property. * * @param value * allowed object is * {@link String } * */ public void setContactEmail(String value) { this.contactEmail = value; } /** * Gets the value of the contactPhone property. * * @return * possible object is * {@link String } * */ public String getContactPhone() { return contactPhone; } /** * Sets the value of the contactPhone property. * * @param value * allowed object is * {@link String } * */ public void setContactPhone(String value) { this.contactPhone = value; } }
package xframe.example.pattern.observer; public final class ContreteObserver implements Observer {//具体观察者 public void update(Observable observable, Object arg) { System.out.println(this.toString() + " received notify."); } }
package cn.wzvtcsoft.validator.exceptions; /** * DomainRule 中的 rule 不符合规范,则抛出此异常 */ public class DomainRuleCheckException extends RuntimeException { public DomainRuleCheckException(String message) { super(message); } }
/** * This package contains the model for the management of CSARInstances. * * Copyright 2013 Christian Endres * * @author endrescn@fachschaft.informatik.uni-stuttgart.de * */ package org.opentosca.model.csarinstancemanagement;
package com.zpjr.cunguan.action.impl.investment; import com.google.gson.JsonObject; import com.zpjr.cunguan.action.action.investment.IInvestmentAction; import com.zpjr.cunguan.common.base.BaseAction; import com.zpjr.cunguan.common.retrofit.MyCallBack; import com.zpjr.cunguan.common.retrofit.PresenterCallBack; import com.zpjr.cunguan.entity.module.LoanModule; import java.util.List; import java.util.Map; import retrofit2.Call; import retrofit2.Response; /** * Description: 描述 * Autour: LF * Date: 2017/7/11 14:44 */ public class InvestmentActionImpl extends BaseAction implements IInvestmentAction { @Override public void getProductList(Map<String, String> patameter,final PresenterCallBack callBack) { Call<JsonObject> call=mService.getProductList(patameter); call.enqueue(new MyCallBack<JsonObject>() { @Override public void onSuccess(Response<JsonObject> response) { callBack.onSuccess(response.body()); } @Override public void onFail(String message) { callBack.onFail(message); } }); } }
package com.service.impl; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.dao.RoomMapper; import com.model.Room; import com.service.RoomService; @Service public class RoomServiceImpl implements RoomService { @Autowired private RoomMapper roomMapper; @Override public Room selectScreenByRoom(Room room) { // TODO Auto-generated method stub return roomMapper.selectScreenByRoom(room); } @Override public int insertSelective(Room room) { // TODO Auto-generated method stub return roomMapper.insertSelective(room); } @Override public Room selectByPrimaryKey(Room room) { // TODO Auto-generated method stub return roomMapper.selectByPrimaryKey(room.getId()); } @Override public int updateByPrimaryKeySelective(Room room) { // TODO Auto-generated method stub return roomMapper.updateByPrimaryKeySelective(room); } @Override public List<String> selectAllId() { // TODO Auto-generated method stub return roomMapper.selectAllId(); } @Override public List<Room> selectAllRoom(Room room) { // TODO Auto-generated method stub return roomMapper.selectAllRoom(room); } @Override public List<Room> selectVirtualRoom(Map<String, Object> map) { // TODO Auto-generated method stub return roomMapper.selectVirtualRoom(map); } @Override public int deleteByPrimaryKey(Room room) { // TODO Auto-generated method stub return roomMapper.deleteByPrimaryKey(room.getId()); } }
package com.kdp.wanandroidclient.ui.core.model; import com.kdp.wanandroidclient.bean.Article; import com.kdp.wanandroidclient.bean.Banner; import com.kdp.wanandroidclient.bean.BaseBean; import com.kdp.wanandroidclient.bean.HomeData; import com.kdp.wanandroidclient.bean.PageListData; import com.kdp.wanandroidclient.net.callback.RxPageListObserver; import java.util.List; import io.reactivex.Observable; import io.reactivex.functions.Function3; import io.reactivex.observers.DisposableObserver; /** * 首页业务接口 * author: 康栋普 * date: 2018/2/22 */ public interface IHomeModel { /** * 获取首页banner、置顶文章、列表文章 * @param page 页码 * @param function3 * @param rxObserver */ void getHomeData(int page, Function3<BaseBean<List<Banner>>, BaseBean<List<Article>>, BaseBean<PageListData<Article>>, HomeData> function3, DisposableObserver<HomeData> rxObserver); /** * 获取更多文章 * @param page 页码 * @param rxPageListObserver */ void getMoreArticleList(int page,RxPageListObserver<Article> rxPageListObserver); Observable<BaseBean<List<Banner>>> getBannerObservable(); Observable<BaseBean<List<Article>>> getHomeTopObservable(); Observable<BaseBean<PageListData<Article>>> getHomeListObservable(int page); }
package JavaSE.OO.IO; import java.io.*; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; /* * java.io.ObjectOutputStream;序列化java对象到硬盘(Serial) * java.io.ObjectInputStream;将硬盘中的数据反序列化到jvm内存(DeSerial) */ public class ObjectOutputStreamTest { public static void main(String[] args) throws Exception, Exception { //创建java对象 User u1=new User("冯洛伊曼"); //创建输出流(序列化流) ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("E:\\test06.txt")); //写 oos.writeObject(u1); //刷新 oos.flush(); //关闭 oos.close(); } } /* * 标识接口的作用:起到标识的作用 * jvm如果看到该对象实现了某个标识接口,会对他特殊待遇,会给该类添加一个属性 * static final long serialVersionUID=序列化版本号 * 可以手动写定序列化版本号 */ class User implements Serializable{//该接口是可序列化的,该接口没有任何方法,是一个标识接口 //如果不想该属性参加序列化,需要使用transient关键字修饰 //transient String name; String name; User(String name){ this.name=name; } public String toString() { return "User[name]="+name+"]"; } }
package gov.smart.health.activity.self.adapter; import android.content.Context; import android.content.Intent; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.util.List; import gov.smart.health.R; import gov.smart.health.activity.find.DetailActivity; import gov.smart.health.activity.find.model.FindAttentionListDataModel; import gov.smart.health.activity.message.FriendInfoActivity; import gov.smart.health.activity.self.MyAttentionDetailActivity; import gov.smart.health.activity.self.model.LikeAttentionInfoListModel; import gov.smart.health.model.FriendModel; import gov.smart.health.utils.SHConstants; /** * Created by laoniu on 2017/07/23. */ public class MyAttentionRefreshRecyclerAdapter extends RecyclerView.Adapter<MyAttentionRefreshRecyclerAdapter.ViewHolder>{ private LayoutInflater mInflater; private List<LikeAttentionInfoListModel> mLists; private Context mContext; public MyAttentionRefreshRecyclerAdapter(Context context , List<LikeAttentionInfoListModel> lists){ mContext = context; this.mInflater=LayoutInflater.from(context); this.mLists = lists; } public void addDataLists(List<LikeAttentionInfoListModel> lists) { if (this.mLists == null){ this.mLists = lists; } else { this.mLists.addAll(lists); } notifyDataSetChanged(); } public void addNewDataLists(List<LikeAttentionInfoListModel> lists) { if (this.mLists == null){ this.mLists = lists; } else { this.mLists.addAll(0,lists); } notifyDataSetChanged(); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { final View view = mInflater.inflate(R.layout.list_myattention_item,parent,false); ViewHolder viewHolder = new ViewHolder(view); return viewHolder; } /** * 数据的绑定显示 * @param holder * @param position */ @Override public void onBindViewHolder(ViewHolder holder, int position) { final LikeAttentionInfoListModel model = mLists.get(position); holder.image.setImageResource(R.mipmap.healthicon); holder.title.setText(model.follow_pk_person); holder.content.setText(model.follow_person_name); holder.itemView.setTag(position); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.putExtra(SHConstants.PersonAttentionModelKey,model); intent.setClass(mContext, MyAttentionDetailActivity.class); //mContext.startActivity(intent); } }); } @Override public int getItemCount() { return this.mLists == null? 0 : this.mLists.size(); } //自定义的ViewHolder,持有每个Item的的所有界面元素 class ViewHolder extends RecyclerView.ViewHolder { public ImageView image; public TextView title; public TextView content; public ViewHolder(View view){ super(view); image = (ImageView)view.findViewById(R.id.myattention_item_img); title = (TextView)view.findViewById(R.id.myattention_item_title); content = (TextView)view.findViewById(R.id.myattention_item_content); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setClass(mContext, MyAttentionDetailActivity.class); mContext.startActivity(intent); } }); } } }
package AddressManage; import Login.LoginPage; import cucumber.api.java.en.And; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import org.junit.Assert; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class DeleteAddress { // create attributes with classes, that will be used private static WebDriver driver; private LoginPage loginPage; private DeleteAddressPage deleteAddressPage; private String shopWebsite = "https://prod-kurs.coderslab.pl/index.php?controller=authentication"; private String loginEmail = "wojciechkawu@gmail.com"; private String loginPassword = "CodersLab"; // Login to the PrestaShop with given credentials @Given("User is looged In") public void userIsLoogedIn() { // Set driver System.setProperty("webdriver.chrome.driver", "src/main/resources/chromedriver"); driver = new ChromeDriver(); // Get full screen of browser and set max wait time driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.manage().window().maximize(); driver.get(shopWebsite); // login to the page and initialize global variables of classes used in test loginPage = new LoginPage(driver); loginPage.loginAs(loginEmail, loginPassword); deleteAddressPage = new DeleteAddressPage(driver); } // Go to addresses page @When("Go to addresses page to delete one") public void goToAddressesPageToDeleteOne() { deleteAddressPage.clickUserAccount(); deleteAddressPage.clickAddress(); } // Find address and delete chosen one @And("Find address keyword (.*) and click delete button") public void findAddressKeywordAddressAliasAndClickDeleteButton(String addressAlias) { deleteAddressPage.deleteAddressButton(addressAlias); } // Confirm address deletion (Assertion) @Then("User will see \"([^\"]*)\"") public void userWillSee(String deleteMessage) { // Write code here that turns the phrase above into concrete actions Assert.assertEquals(deleteMessage, deleteAddressPage.getDeleteInformation()); } // End test - quit browser @And("Browser is closed after deletion") public void browserIsClosedAfterDeletion() { driver.quit(); } }
package com.github.netudima.jmeter.junit.report; import java.io.File; public class TestUtils { public static String getTestFilePath(String file) { return TestUtils.class.getResource(file).getFile(); } public static File getTestFile(String file) { return new File(getTestFilePath(file)); } }
package net.minecraft.network; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToMessageDecoder; import java.util.List; import javax.crypto.Cipher; import javax.crypto.ShortBufferException; public class NettyEncryptingDecoder extends MessageToMessageDecoder<ByteBuf> { private final NettyEncryptionTranslator decryptionCodec; public NettyEncryptingDecoder(Cipher cipher) { this.decryptionCodec = new NettyEncryptionTranslator(cipher); } protected void decode(ChannelHandlerContext p_decode_1_, ByteBuf p_decode_2_, List<Object> p_decode_3_) throws ShortBufferException, Exception { p_decode_3_.add(this.decryptionCodec.decipher(p_decode_1_, p_decode_2_)); } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\network\NettyEncryptingDecoder.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package org.sodeja.event; import java.util.ArrayList; import java.util.List; public abstract class AbstractEventDispatcherEmitter implements EventDispatcher, EventEmitter { private List<EventListener<?>> listeners; public AbstractEventDispatcherEmitter() { listeners = new ArrayList<EventListener<?>>(); } @Override public void addListener(EventListener<?> listener) { listeners.add(listener); } @Override public void removeListener(EventListener<?> listener) { listeners.remove(listener); } protected void dispatch(Event event) { List<EventListener<?>> listenersCopy = new ArrayList<EventListener<?>>(listeners); for(EventListener<?> listener : listenersCopy) { dispatch(event, listener); } } @SuppressWarnings("unchecked") protected void dispatch(Event event, EventListener<?> listener) { if(listener.getClass().equals(EventListener.class)) { ((EventListener) listener).onEvent(event); } if(event.getClass().equals(listener.getClassT())) { ((EventListener) listener).onEvent(event); return; } // // ParameterizedType parameterizedType = ((ParameterizedType) listener.getClass().getGenericInterfaces()[0]); // Type type = parameterizedType.getActualTypeArguments()[0]; // if(! (type instanceof Class)) { // return; //// throw new IllegalArgumentException(); // } // // Class listenerParamerClass = (Class) type; // if(listenerParamerClass.equals(event.getClass())) { // ((EventListener) listener).onEvent(event); // return; // } // // throw new UnsupportedOperationException(); } }
package org.arthur.review.model; public class SampleSolution { int SID; String Solution_Number; String Problem_Name; String Problem_Number; String Problem_Solution_Pair; String Upload_Location; String Good_Apects; String Bad_Aspects; public int getSID() { return SID; } public void setSID(int sID) { SID = sID; } public String getSolution_Number() { return Solution_Number; } public void setSolution_Number(String solution_Number) { Solution_Number = solution_Number; } public String getProblem_Name() { return Problem_Name; } public void setProblem_Name(String problem_Name) { Problem_Name = problem_Name; } public String getProblem_Number() { return Problem_Number; } public void setProblem_Number(String problem_Number) { Problem_Number = problem_Number; } public String getProblem_Solution_Pair() { return Problem_Solution_Pair; } public void setProblem_Solution_Pair(String problem_Solution_Pair) { Problem_Solution_Pair = problem_Solution_Pair; } public String getUpload_Location() { return Upload_Location; } public void setUpload_Location(String upload_Location) { Upload_Location = upload_Location; } public String getGood_Apects() { return Good_Apects; } public void setGood_Apects(String good_Apects) { Good_Apects = good_Apects; } public String getBad_Aspects() { return Bad_Aspects; } public void setBad_Aspects(String bad_Aspects) { Bad_Aspects = bad_Aspects; } }
package com.one.sugarcane.entity; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; @Entity @Table(name="USERINFO") public class UserInfo { private Integer userID; private String userName; private String userEmail; private int userGender; private String userWork; private String userPicture; private String userEducation; private String userPhoneNumber; private String birthday; private String address_province; private String address_city; private String address_area; private Set<GradeLevel>gradeLevel = new HashSet<GradeLevel>(); private UserLogin userLogin; private Set<UserHobby> userHobby = new HashSet<UserHobby>(); //冯海晴 @Id @GeneratedValue(generator="a") @GenericGenerator(name="a",strategy="identity") public Integer getUserID() { return userID; } public void setUserID(Integer userID) { this.userID = userID; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserEmail() { return userEmail; } public void setUserEmail(String userEmail) { this.userEmail = userEmail; } public int getUserGender() { return userGender; } public void setUserGender(int userGender) { this.userGender = userGender; } public String getUserEducation() { return userEducation; } public void setUserEducation(String userEducation) { this.userEducation = userEducation; } public String getUserPhoneNumber() { return userPhoneNumber; } public void setUserPhoneNumber(String userPhoneNumber) { this.userPhoneNumber = userPhoneNumber; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public String getAddress_province() { return address_province; } public void setAddress_province(String address_province) { this.address_province = address_province; } public String getAddress_city() { return address_city; } public void setAddress_city(String address_city) { this.address_city = address_city; } public String getAddress_area() { return address_area; } public void setAddress_area(String address_area) { this.address_area = address_area; } @OneToMany(mappedBy="userInfo",targetEntity=GradeLevel.class,cascade=CascadeType.MERGE) public Set<GradeLevel> getGradeLevel() { return gradeLevel; } public void setGradeLevel(Set<GradeLevel> gradeLevel) { this.gradeLevel = gradeLevel; } @OneToOne(mappedBy="userInfo") public UserLogin getUserLogin() { return userLogin; } public void setUserLogin(UserLogin userLogin) { this.userLogin = userLogin; } public UserInfo() {} public UserInfo(String userName, String userEmail, int userGender, String userEducation, String userPhoneNumber, String birthday, String address_province, String address_city, String address_area, Set<GradeLevel> gradeLevel, UserLogin userLogin) { super(); this.userName = userName; this.userEmail = userEmail; this.userGender = userGender; this.userEducation = userEducation; this.userPhoneNumber = userPhoneNumber; this.birthday = birthday; this.address_province = address_province; this.address_city = address_city; this.address_area = address_area; this.gradeLevel = gradeLevel; this.userLogin = userLogin; } /** * 添加属性职业 * @author 冯海晴 * @return */ public String getUserWork() { return userWork; } public void setUserWork(String userWork) { this.userWork = userWork; } /** * 添加用户信息与用户爱好的一对多关联 * @author 冯海晴 * @date 2018.5.24 * @return */ @OneToMany(mappedBy="userInfo",targetEntity=UserHobby.class,cascade=CascadeType.MERGE) public Set<UserHobby> getUserHobby() { return userHobby; } public void setUserHobby(Set<UserHobby> userHobby) { this.userHobby = userHobby; } public String getUserPicture() { return userPicture; } public void setUserPicture(String userPicture) { this.userPicture = userPicture; } }
package org.training.issuetracker.pages; /** * Class that contains necessary info about Status Page: * -page name; * -all parameters that are available from this page; * -all attributes that are provided for this page; * * @author Dzmitry_Salnikau * @since 17.04.2014 */ public class StatusPage extends AbstractPage{ public static final String NAME = "status"; // Parameters public static final String PARAM_NAME = "name"; // Attributes public static final String ATTR_EDIT_STATUS = "editStatus"; // Messages // titles public static final String MSG_TTL_EDIT_STATUS = "label.status.title.edit_status"; // success public static final String MSG_SCS_STATUS_UPDATED = "label.status.success.status_updated"; // errors public static final String MSG_ERR_NO_STATUS = "label.status.error.no_status"; public static final String MSG_ERR_NO_ACCESS = "label.status.error.no_access"; public static final String MSG_ERR_FAILED_TO_UPDATE = "label.status.error.failed_to_update"; public static final String MSG_ERR_INVALID_VALUES = "label.status.error.invalid_values"; }
package com.spintech.testtask.controller; import java.util.Collections; import java.util.List; import java.util.StringTokenizer; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.spintech.testtask.converter.UserConverter; import com.spintech.testtask.dto.ActorDto; import com.spintech.testtask.dto.ShowDto; import com.spintech.testtask.dto.UserDto; import com.spintech.testtask.service.ShowService; import com.spintech.testtask.service.UserService; import com.spintech.testtask.service.tmdb.impl.SpinTechTmdbApiImpl; import static org.springframework.web.bind.annotation.RequestMethod.GET; import static org.springframework.web.bind.annotation.RequestMethod.POST; @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @Autowired private ShowService showService; @Autowired private UserConverter userConverter; @Autowired private SpinTechTmdbApiImpl spinTechTmdbApi; @RequestMapping(value = "/register", method = POST) public ResponseEntity registerUser( @RequestParam String email, @RequestParam String password) { if (userService.registerUser(email, password) != null) { return ResponseEntity.status(HttpStatus.OK).body(null); } else { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); } } @RequestMapping(value = "/add_fav_actors", method = POST) public ResponseEntity addFavActorsToUser( @RequestParam String email, @RequestParam String password, @RequestParam String favActors) { List<String> favs = getTokensWithCollection(favActors); List<ActorDto> favActorsDtosList = favs.stream().map(actor -> ActorDto.builder().tmdb_id(Integer.valueOf(actor)).build()).collect(Collectors.toList()); UserDto user = userService.addFavActorsToUser(email, password, favActorsDtosList); if (user != null) { return ResponseEntity.status(HttpStatus.OK).body(null); } else { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); } } @RequestMapping(value = "/del_fav_actors", method = POST) public ResponseEntity del_FavActorsToUser( @RequestParam String email, @RequestParam String password) { UserDto user = userService.delFavActorsFromUser(email, password); if (user != null) { return ResponseEntity.status(HttpStatus.OK).body(null); } else { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); } } @RequestMapping(value = "/markUnwatched", method = POST) public ResponseEntity markUnwatched( @RequestParam String email, @RequestParam String password, List<ShowDto> unwatched) { UserDto user = userService.findUser(email, password); //user.setUnwatched_shows(unwatched); if (user != null) { return ResponseEntity.status(HttpStatus.OK).body(null); } else { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); } } @RequestMapping(value = "/get_unwatched_shows_with_fav_actor", method = GET) public ResponseEntity getUserUnwatchedShowsWithFavActors( @RequestParam String email, @RequestParam String password) { UserDto user = userService.findUser(email, password); List<ShowDto> shows = showService.getUserUnwatchedShowsWithFavActors(userConverter.convertUserDtoToUser(user)); if (shows != null && !shows.isEmpty()) { return ResponseEntity.status(HttpStatus.OK).contentType(MediaType.APPLICATION_JSON).body(shows); } else { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); } } public List<String> getTokensWithCollection(String str) { return Collections.list(new StringTokenizer(str, ",")).stream() .map(token -> (String) token) .collect(Collectors.toList()); } }
package datastructure.graph; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @Author weimin * @Date 2020/10/20 0020 17:28 */ public class Graph { // 顶点 private List<String> nodes; // 邻接矩阵 private int[][] edges; // 边的数目 private int edgeCount; private boolean[] isVisited; /** * * @param n 顶点的个数 */ public Graph(int n) { edges = new int[n][n]; nodes = new ArrayList<>(n); isVisited = new boolean[n]; } // 添加顶点 public void addNode(String s){ nodes.add(s); } // 添加边 public void addEdge(int v1,int v2,int value){ edges[v1][v2] = value; edges[v2][v1] = value; edgeCount++; } // 节点的个数 public int getNodeCount(){ return nodes.size(); } // 边的数量 public int getEdgeCount(){ return edgeCount; } // 节点对应的数据 0->A public String get(int i){ return nodes.get(i); } // 两个顶点的权值 public int getWeight(int v1,int v2){ return edges[v1][v2]; } public void show(){ for (int[] edge : edges) { System.out.println(Arrays.toString(edge)); } } // 返回第一个相邻节点的下标 public int getFirstNextIndex(int i){ for (int j = 0; j < nodes.size(); j++) { if (edges[i][j]==1){ return j; } } return -1; } public int getNextNextIndex(int v1,int v2){ for (int i = v2+1; i < nodes.size(); i++) { if (edges[v1][i]==1){ return i; } } return -1; } // 深度优先遍历 private void dfs(int first){ System.out.println(get(first)); isVisited[first] = true; int i = getFirstNextIndex(first); while (i!=-1){ if(!isVisited[i]){ System.out.println(get(i)); isVisited[i] = true; } i = getNextNextIndex(first,i); } } public void dfs(){ for (int i = 0; i < getNodeCount(); i++) { if(!isVisited[i]){ dfs(i); } } } public static void main(String[] args) { Graph graph = new Graph(5); graph.addNode("A"); graph.addNode("B"); graph.addNode("C"); graph.addNode("D"); graph.addNode("E"); graph.addEdge(0,1,1); graph.addEdge(0,2,1); graph.addEdge(1,2,1); graph.addEdge(1,3,1); graph.addEdge(1,4,1); graph.show(); graph.dfs(); } }
package statement; import infocontainer.GalaxyRomanInfo; import java.util.regex.Matcher; import java.util.regex.Pattern; public abstract class StatementParser { protected GalaxyRomanInfo galaxyRomanInfo; private StatementParser nextHandler = null; Pattern pattern; Matcher matcher; public StatementParser(GalaxyRomanInfo galaxyRomanInfo) { this.galaxyRomanInfo = galaxyRomanInfo; } public void setNextHandler(StatementParser nextHandler) { this.nextHandler = nextHandler; } public void handleStatement(String statement) { if (isThisStatement(statement)) { parseStatement(statement); return; } if (nextHandler != null) { nextHandler.handleStatement(statement); } } public abstract void parseStatement(String statement); public boolean isThisStatement(String statement) { matcher = pattern.matcher(statement); return matcher.matches(); } }
package com.pg.whatsstatussaver.LocalDatabase; import android.arch.persistence.room.ColumnInfo; import android.arch.persistence.room.Entity; import android.arch.persistence.room.PrimaryKey; import java.io.Serializable; @Entity public class ImagesUrlTable implements Serializable { @PrimaryKey(autoGenerate = true) private int id; @ColumnInfo(name = "url") private String url; public String getVideo() { return video; } public void setVideo(String video) { this.video = video; } @ColumnInfo(name = "video") private String video; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
package com.kzw.leisure.model; import com.kzw.leisure.bean.BookSourceRule; import com.kzw.leisure.bean.Query; import com.kzw.leisure.bean.SearchBookBean; import com.kzw.leisure.contract.SearchBookContract; import com.kzw.leisure.network.RetrofitHelper; import com.kzw.leisure.rxJava.RxHelper; import com.kzw.leisure.rxJava.RxSchedulers; import com.kzw.leisure.utils.analyze.AnalyzeRule; import org.reactivestreams.Publisher; import java.util.ArrayList; import java.util.List; import io.reactivex.BackpressureStrategy; import io.reactivex.Flowable; import io.reactivex.functions.Function; /** * author: kang4 * Date: 2019/12/4 * Description: */ public class SearchBookModel implements SearchBookContract.Model { @Override public Flowable<List<SearchBookBean>> searchBook(Query query, BookSourceRule bean) { return RetrofitHelper .getInstance() .getResponse(query) .flatMap((Function<String, Publisher<List<SearchBookBean>>>) s -> analyze(s, bean)) .compose(RxHelper.handleResult()) .compose(RxSchedulers.io_main()); } private Flowable<List<SearchBookBean>> analyze(String body, BookSourceRule bean) { return Flowable.create(emitter -> { List<SearchBookBean> list = new ArrayList<>(); AnalyzeRule analyzer = new AnalyzeRule(null); analyzer.setContent(body, bean.getRuleSearchUrl()); try { List<Object> collections = analyzer.getElements(bean.getRuleSearchList()); for (Object o : collections) { analyzer.setContent(o); SearchBookBean searchBookBean = new SearchBookBean(); searchBookBean.setSearchAuthor(analyzer.getString(bean.getRuleSearchAuthor())); searchBookBean.setSearchCoverUrl(analyzer.getString(bean.getRuleSearchCoverUrl())); searchBookBean.setSearchIntroduce(analyzer.getString(bean.getRuleSearchIntroduce())); searchBookBean.setSearchKind(analyzer.getString(bean.getRuleSearchKind())); searchBookBean.setSearchLastChapter(analyzer.getString(bean.getRuleSearchLastChapter())); searchBookBean.setSearchName(analyzer.getString(bean.getRuleSearchName())); searchBookBean.setSearchNoteUrl(analyzer.getString(bean.getRuleSearchNoteUrl())); searchBookBean.setCurrentSearchRule(bean); searchBookBean.getSearchNoteUrlList().add(analyzer.getString(bean.getRuleSearchNoteUrl())); searchBookBean.getSearchRuleList().add(bean); list.add(searchBookBean); } } catch (Exception e) { e.printStackTrace(); emitter.onError(e); } emitter.onNext(list); emitter.onComplete(); }, BackpressureStrategy.ERROR); } }
package ru.otus.hw12.jetty.servlet; import com.google.gson.Gson; import ru.otus.hw12.hibernate.dbservice.DbServiceUser; import ru.otus.hw12.model.User; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static javax.servlet.http.HttpServletResponse.SC_OK; public class UsersApiServlet extends HttpServlet { private static final int ID_PATH_PARAM_POSITION = 1; private final DbServiceUser dbServiceUser; private final Gson gson; public UsersApiServlet(DbServiceUser dbServiceUser, Gson gson) { this.dbServiceUser = dbServiceUser; this.gson = gson; } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("application/json;charset=UTF-8"); ServletOutputStream out = response.getOutputStream(); List<User> userList = new ArrayList<>(); dbServiceUser.getUsers().forEach(obj -> { User user = new User(); user.setId(obj.getId()); user.setUsername(obj.getUsername()); user.setLogin(obj.getLogin()); user.setPassword(obj.getPassword()); userList.add(user); } ); out.print(gson.toJson(userList)); response.setStatus(SC_OK); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String jsonObj = request.getReader().readLine(); User newUser = gson.fromJson(jsonObj, User.class); dbServiceUser.saveUser(newUser); response.setStatus(SC_OK); } }
package com.example.demorestrepo.entity; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import javax.persistence.*; import java.util.HashSet; import java.util.Set; @Entity @EqualsAndHashCode(of = "id") @Data @NoArgsConstructor public class CustomerGroup { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String groupName; @OneToMany(fetch=FetchType.LAZY, cascade=CascadeType.ALL) @JoinColumn(name = "groupId") private Set<Customer> customers = new HashSet(); }
package server; /* * 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. */ import java.net.ServerSocket; import java.net.Socket; import java.util.LinkedList; /** * * @author leone */ //Para este juego, vamos a utilizar la libreria socket, que se basa en el protocolo TCP mayormente //adios al UDP public class Servidor { //inicializacion del puerto a manera de una constante private final int puerto = 56076; //Lista de sockets para el almacenamiento de los sockets de los jugadores private LinkedList<Socket> jugadores = new LinkedList<Socket>(); //establecemos variables que definan algunas reglas del juego //conexiones maximas en el server private int connectMax = 2; //turnos private boolean turno = true; //array bidimensional (matriz) para almacenar los movimientos private int M[][] = new int[3][3]; private int turnos = 1; public void recibir(){ try{ //Inicializamos la matriz del juego con -1 for (int i = 0; i < 3; i++){ for (int j = 0; j < 3; j++){ M[i][j] = -1; } } //Creacion del Socket para nuestro servidor ServerSocket servidor = new ServerSocket(puerto, connectMax); //Ciclo infinito para estar escuchando por nuevos jugadores System.out.println("Esperando a los jugadores...."); while(true){ //Cuando un jugador se conecte guardamos el socket en nuestra lista Socket cliente = servidor.accept(); //Se agrega el socket a la lista jugadores.add(cliente); //Se le genera un turno X o O int xo = turnos % 2 == 0 ? 1 : 0; turnos++; //Instanciamos un hilo que estara atendiendo al cliente y lo ponemos a escuchar Runnable run = new ServidorHilo(cliente, jugadores, xo, M); Thread hilo = new Thread(run); hilo.start(); } }catch(Exception e){ e.printStackTrace(); } } //Funcion main para correr el servidor public static void main(String[] args) { Servidor servidor= new Servidor(); servidor.recibir(); } }
package conferenceplanner; import java.text.ParseException; import java.util.Date; /** * Created by Victor on 18/05/14. */ public class Session { private String title; private Date startTime; private Date endTime; public Session(){} public Session(String title, String startTimeInString, String endTimeInString) { try { this.title = title; this.startTime = Constants.DEFAULT_DATE_FORMAT.parse(startTimeInString); this.endTime = Constants.DEFAULT_DATE_FORMAT.parse(endTimeInString); } catch (ParseException e){ System.out.println("Either start or end time is not valid."); } } public void setTitle(String title) { this.title = title; } public void setStartTimeFromString(String startTime) { try { this.startTime = Constants.DEFAULT_DATE_FORMAT.parse(startTime); } catch (ParseException e) { System.out.println("Start time is not valid"); } } public void setEndTimeFromString(String endTime) { try { Date endTimeDate = Constants.DEFAULT_DATE_FORMAT.parse(endTime); if (this.startTime != null) { if (endTimeDate.before(this.startTime)) { throw new IllegalArgumentException("Proposed end time is before start time"); } } this.endTime = endTimeDate; } catch (ParseException e) { e.printStackTrace(); } } public int getDuration() { return (int) ((endTime.getTime() - startTime.getTime()) / 1000 / 60); } public String getStartTimeInString() { return Constants.DEFAULT_DATE_FORMAT.format(startTime); } public String getEndTimeInString() { return Constants.DEFAULT_DATE_FORMAT.format(endTime); } public Date getEndTime() { return endTime; } public Date getStartTime() { return startTime; } }
package com.abhi.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; @Entity @Table(name="USER_DETAILS") @NamedQueries ( { @NamedQuery(name = "UserDetails.findUserByEmailId", query = "SELECT user FROM UserDetails user WHERE user.email = :emailId") } ) public class UserDetails { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="ID") private Integer id; @Column(name="FIRST_NAME") private String firstname; @Column(name="LAST_NAME") private String lastname; @Column(name="EMAIL_ID") private String email; @Column(name="PHONE_NUMBER") private String telephone; public String getEmail() { return email; } public String getTelephone() { return telephone; } public void setEmail(String email) { this.email = email; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getFirstname() { return firstname; } public String getLastname() { return lastname; } public void setFirstname(String firstname) { this.firstname = firstname; } public void setLastname(String lastname) { this.lastname = lastname; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } }
package com.rc.frames; import com.rc.app.Launcher; import com.rc.components.*; import com.rc.db.model.ContactsUser; import com.rc.db.service.ContactsUserService; import com.rc.entity.SelectUserData; import com.rc.panels.SelectUserPanel; import com.rc.res.Colors; import com.rc.utils.FontUtil; import javax.swing.*; import javax.swing.border.LineBorder; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.List; import static com.rc.app.Launcher.roomService; /** * Created by song on 07/06/2017. */ public class CreateGroupDialog extends JDialog { private static CreateGroupDialog context; private JPanel editorPanel; private RCTextField groupNameTextField; private JCheckBox privateCheckBox; private SelectUserPanel selectUserPanel; private JPanel buttonPanel; private JButton cancelButton; private JButton okButton; private List<SelectUserData> userList = new ArrayList<>(); private ContactsUserService contactsUserService = Launcher.contactsUserService; public static final int DIALOG_WIDTH = 580; public static final int DIALOG_HEIGHT = 500; public CreateGroupDialog(Frame owner, boolean modal) { super(owner, modal); context = this; initComponents(); initData(); initView(); setListeners(); } private void initData() { List<ContactsUser> contactsUsers = contactsUserService.findAll(); for (ContactsUser con : contactsUsers) { /*if (con.getUsername().equals("admin") || con.getUsername().equals("appStoreTest")) { continue; }*/ userList.add(new SelectUserData(con.getUsername(), false)); } selectUserPanel = new SelectUserPanel(DIALOG_WIDTH, DIALOG_HEIGHT - 100, userList); } private void initComponents() { int posX = MainFrame.getContext().getX(); int posY = MainFrame.getContext().getY(); posX = posX + (MainFrame.getContext().currentWindowWidth - DIALOG_WIDTH) / 2; posY = posY + (MainFrame.getContext().currentWindowHeight - DIALOG_HEIGHT) / 2; setBounds(posX, posY, DIALOG_WIDTH, DIALOG_HEIGHT); setUndecorated(true); getRootPane().setBorder(new LineBorder(Colors.DIALOG_BORDER)); /*if (OSUtil.getOsType() != OSUtil.MacOS) { // 边框阴影,但是会导致字体失真 AWTUtilities.setWindowOpaque(this, false); //getRootPane().setOpaque(false); getRootPane().setBorder(ShadowBorder.newInstance()); }*/ // 输入面板 editorPanel = new JPanel(); groupNameTextField = new RCTextField(); groupNameTextField.setPlaceholder("群聊名称"); groupNameTextField.setPreferredSize(new Dimension(DIALOG_WIDTH / 2, 35)); groupNameTextField.setFont(FontUtil.getDefaultFont(14)); groupNameTextField.setForeground(Colors.FONT_BLACK); groupNameTextField.setMargin(new Insets(0, 15, 0, 0)); privateCheckBox = new JCheckBox("私有"); privateCheckBox.setFont(FontUtil.getDefaultFont(14)); privateCheckBox.setToolTipText("私有群组对外不可见,聊天内容无法被非群成员浏览,只有创建者才有权限添加成员,建议勾选此项"); privateCheckBox.setSelected(true); // 按钮组 buttonPanel = new JPanel(); buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT, 10, 10)); cancelButton = new RCButton("取消"); cancelButton.setForeground(Colors.FONT_BLACK); okButton = new RCButton("创建", Colors.MAIN_COLOR, Colors.MAIN_COLOR_DARKER, Colors.MAIN_COLOR_DARKER); okButton.setBackground(Colors.PROGRESS_BAR_START); } private void initView() { editorPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10)); editorPanel.add(groupNameTextField); //editorPanel.add(privateCheckBox); buttonPanel.add(cancelButton, new GBC(0, 0).setWeight(1, 1).setInsets(15, 0, 0, 0)); buttonPanel.add(okButton, new GBC(1, 0).setWeight(1, 1)); add(editorPanel, BorderLayout.NORTH); add(selectUserPanel, BorderLayout.CENTER); add(buttonPanel, BorderLayout.SOUTH); } private void setListeners() { cancelButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { setVisible(false); super.mouseClicked(e); } }); okButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (okButton.isEnabled()) { okButton.setEnabled(false); String roomName = groupNameTextField.getText(); if (roomName == null || roomName.isEmpty()) { JOptionPane.showMessageDialog(null, "请输入群聊名称", "请输入群聊名称", JOptionPane.WARNING_MESSAGE); groupNameTextField.requestFocus(); okButton.setEnabled(true); return; } checkRoomExists(roomName); } super.mouseClicked(e); } }); } private void checkRoomExists(String name) { if (roomService.findByName(name) != null) { showRoomExistMessage(name); okButton.setEnabled(true); } else { List<SelectUserData> list = selectUserPanel.getSelectedUser(); String[] usernames = new String[list.size()]; for (int i = 0; i < list.size(); i++) { usernames[i] = list.get(i).getName(); } createChannelOrGroup(name, privateCheckBox.isSelected(), usernames); } } /** * 创建Channel或Group * * @param name * @param privateGroup * @param usernames */ private void createChannelOrGroup(String name, boolean privateGroup, String[] usernames) { // todo 发送创建请求 } public static CreateGroupDialog getContext() { return context; } public void showRoomExistMessage(String roomName) { JOptionPane.showMessageDialog(null, "群组\"" + roomName + "\"已存在", "群组已存在", JOptionPane.WARNING_MESSAGE); groupNameTextField.setText(""); groupNameTextField.requestFocus(); } }
package com.navin.melalwallet.ui.login; public interface ILoginView<T> { public void onUsernameError(); public void onPasswordError(); public void onFailureError(String reason); public void onError(String reason); public void onSuccess(T response); public void showProgressBar(); public void hidesProgressBar(); }
package Manufacturing.ProductLine; import Manufacturing.CanEntity.Can; import Manufacturing.Ingredient.Ingredient; import java.util.List; /** * 生产线总接口 * * @author 孟繁霖 * @date 2021-10-25 15:06 */ public interface ProductLine { /** * 获取具体生产线的名字(如appleLine,peachLine等) * @return : java.lang.String * @author 孟繁霖 * @date 2021-10-25 15:05 */ String getConcreteName(); List<Ingredient> preTreat(List<Ingredient> baseIngredientList); /** * 加工罐头 * * @param count : 加工的罐头数量 * @Param produceManner: 加工方式 * @author 孟繁霖 * @since 2021-10-11 23:42 */ List<Can> produce(int count,String produceManner); static Can produceSample() { return null; } }
package com.diozero.internal.soc.amlogic; /*- * #%L * Organisation: diozero * Project: diozero - Core * Filename: AmlogicS922XMmapGpio.java * * This file is part of the diozero project. More information about this project * can be found at https://www.diozero.com/. * %% * Copyright (C) 2016 - 2023 diozero * %% * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * #L% */ import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.IntBuffer; import java.util.Optional; import java.util.concurrent.ThreadLocalRandom; import org.tinylog.Logger; import com.diozero.api.DeviceMode; import com.diozero.api.GpioPullUpDown; import com.diozero.api.InvalidModeException; import com.diozero.internal.spi.MmapGpioInterface; import com.diozero.util.Hex; import com.diozero.util.MmapIntBuffer; import com.diozero.util.SleepUtil; public class AmlogicS922MmapGpio implements MmapGpioInterface { private static final String MEM_DEVICE = "/dev/mem"; /* * The actual base address of the register is 0xFF634400. However, that is not * aligned with the page boundaries. In order to deal with this, we use the * previous page boundary (0xFF634000). Since we are dealing with 32-bit ints, * we make up the 0x400 byte difference by adding 0x100 to each of the offsets. * Therefore, none of these match the documented addresses or offsets, but they * all actually work. */ private static final long J2_GPIO_BASE_ADDRESS = 0xFF63_4000L; private static final int BLOCK_SIZE = 4096; private static final int J2_GPIO_START = 410; private static final int J2_GPIOA_PIN_START = J2_GPIO_START + 50; private static final int J2_GPIOA_PIN_END = J2_GPIO_START + 65; private static final int J2_GPIOX_PIN_START = J2_GPIO_START + 66; private static final int J2_GPIOX_PIN_END = J2_GPIO_START + 85; // GPIOA offsets private static final int J2_GPIOA_OEN_REG_OFFSET = 0x120; private static final int J2_GPIOA_OUT_REG_OFFSET = 0x121; private static final int J2_GPIOA_INP_REG_OFFSET = 0x122; private static final int J2_GPIOA_PUEN_REG_OFFSET = 0x14D; private static final int J2_GPIOA_PUPD_REG_OFFSET = 0x13F; // GPIOX offsets private static final int J2_GPIOX_OEN_REG_OFFSET = 0x116; private static final int J2_GPIOX_OUT_REG_OFFSET = 0x117; private static final int J2_GPIOX_INP_REG_OFFSET = 0x118; private static final int J2_GPIOX_PUEN_REG_OFFSET = 0x14A; private static final int J2_GPIOX_PUPD_REG_OFFSET = 0x13C; private boolean initialised; private MmapIntBuffer j2MappedByteBuffer; @Override public synchronized void initialise() { if (!initialised) { j2MappedByteBuffer = new MmapIntBuffer(MEM_DEVICE, J2_GPIO_BASE_ADDRESS, BLOCK_SIZE, ByteOrder.LITTLE_ENDIAN); initialised = true; } } @Override public synchronized void close() { if (initialised) { j2MappedByteBuffer.close(); initialised = false; } } /* * Offset to the GPIO Output Enable register */ private static int gpioToOutputEnableRegOffset(int gpio) { if (gpio >= J2_GPIOA_PIN_START && gpio <= J2_GPIOA_PIN_END) { return J2_GPIOA_OEN_REG_OFFSET; } if (gpio >= J2_GPIOX_PIN_START && gpio <= J2_GPIOX_PIN_END) { return J2_GPIOX_OEN_REG_OFFSET; } return -1; } /* * Offset to the GPIO Output register */ private static int gpioToOutputRegOffset(int gpio) { if (gpio >= J2_GPIOA_PIN_START && gpio <= J2_GPIOA_PIN_END) { return J2_GPIOA_OUT_REG_OFFSET; } if (gpio >= J2_GPIOX_PIN_START && gpio <= J2_GPIOX_PIN_END) { return J2_GPIOX_OUT_REG_OFFSET; } return -1; } /* * Offset to the GPIO Input register */ private static int gpioToInputRegOffset(int gpio) { if (gpio >= J2_GPIOA_PIN_START && gpio <= J2_GPIOA_PIN_END) { return J2_GPIOA_INP_REG_OFFSET; } if (gpio >= J2_GPIOX_PIN_START && gpio <= J2_GPIOX_PIN_END) { return J2_GPIOX_INP_REG_OFFSET; } return -1; } /* * Offset to the GPIO Pull up/down enable register */ private static int gpioToPullUpDownEnableRegOffset(int gpio) { if (gpio >= J2_GPIOA_PIN_START && gpio <= J2_GPIOA_PIN_END) { return J2_GPIOA_PUEN_REG_OFFSET; } if (gpio >= J2_GPIOX_PIN_START && gpio <= J2_GPIOX_PIN_END) { return J2_GPIOX_PUEN_REG_OFFSET; } return -1; } /* * Offset to the GPIO Pull up/down register */ private static int gpioToPullUpDownRegOffset(int gpio) { if (gpio >= J2_GPIOA_PIN_START && gpio <= J2_GPIOA_PIN_END) { return J2_GPIOA_PUPD_REG_OFFSET; } if (gpio >= J2_GPIOX_PIN_START && gpio <= J2_GPIOX_PIN_END) { return J2_GPIOX_PUPD_REG_OFFSET; } return -1; } /* * Offset to the GPIO bit */ private static int gpioToRegShiftBit(int gpio) { if (gpio >= J2_GPIOA_PIN_START && gpio <= J2_GPIOA_PIN_END) { return gpio - J2_GPIOA_PIN_START; } if (gpio >= J2_GPIOX_PIN_START && gpio <= J2_GPIOX_PIN_END) { return gpio - J2_GPIOX_PIN_START; } return -1; } private MmapIntBuffer getIntBuffer() { if (!initialised) { throw new IllegalStateException("Memory map is not initialized"); } return j2MappedByteBuffer; } @Override public DeviceMode getMode(int gpio) { int fsel = gpioToOutputEnableRegOffset(gpio); int shift = gpioToRegShiftBit(gpio); if (fsel == -1 || shift == -1) { Logger.error("Invalid GPIO {}", Integer.valueOf(gpio)); return DeviceMode.UNKNOWN; } MmapIntBuffer mmap_int_buffer = getIntBuffer(); if ((mmap_int_buffer.get(fsel) & 1 << shift) == 0) { return DeviceMode.DIGITAL_OUTPUT; } return DeviceMode.DIGITAL_INPUT; } @Override public void setMode(int gpio, DeviceMode mode) { switch (mode) { case DIGITAL_INPUT: // mmap_int_buffer.put(fsel, mmap_int_buffer.get(fsel) | (1 << shift)); setModeUnchecked(gpio, 1); break; case DIGITAL_OUTPUT: // mmap_int_buffer.put(fsel, mmap_int_buffer.get(fsel) & ~(1 << shift)); setModeUnchecked(gpio, 0); break; default: throw new InvalidModeException("Invalid GPIO mode " + mode + " for pin " + gpio); } } @Override public void setModeUnchecked(int gpio, int mode) { int fsel = gpioToOutputEnableRegOffset(gpio); int shift = gpioToRegShiftBit(gpio); if (fsel == -1 || shift == -1) { Logger.error("Invalid GPIO {}", Integer.valueOf(gpio)); return; } MmapIntBuffer mmap_int_buffer = getIntBuffer(); // Mode can only be 0 or 1 if (mode == 0) { mmap_int_buffer.put(fsel, mmap_int_buffer.get(fsel) & ~(1 << shift)); } else { mmap_int_buffer.put(fsel, mmap_int_buffer.get(fsel) | (1 << shift)); } } @Override public Optional<GpioPullUpDown> getPullUpDown(int gpio) { int puen = gpioToPullUpDownEnableRegOffset(gpio); int shift = gpioToRegShiftBit(gpio); if (puen == -1 || shift == -1) { throw new IllegalArgumentException("Invalid GPIO " + gpio); } MmapIntBuffer mmap_int_buffer = getIntBuffer(); if ((mmap_int_buffer.get(puen) & (1 << shift)) != 0) { int pupd = gpioToPullUpDownRegOffset(gpio); return Optional.of((mmap_int_buffer.get(pupd) & (1 << shift)) == 0 ? GpioPullUpDown.PULL_DOWN : GpioPullUpDown.PULL_UP); } return Optional.of(GpioPullUpDown.NONE); } @Override public void setPullUpDown(int gpio, GpioPullUpDown pud) { int shift = gpioToRegShiftBit(gpio); int puen = gpioToPullUpDownEnableRegOffset(gpio); if (puen == -1 || shift == -1) { Logger.error("Invalid GPIO {}", Integer.valueOf(gpio)); return; } MmapIntBuffer mmap_int_buffer = getIntBuffer(); if (pud == GpioPullUpDown.NONE) { mmap_int_buffer.put(puen, mmap_int_buffer.get(puen) & ~(1 << shift)); } else { mmap_int_buffer.put(puen, mmap_int_buffer.get(puen) | (1 << shift)); int pupd = gpioToPullUpDownRegOffset(gpio); if (pud == GpioPullUpDown.PULL_UP) { mmap_int_buffer.put(pupd, mmap_int_buffer.get(pupd) | (1 << shift)); } else { mmap_int_buffer.put(pupd, mmap_int_buffer.get(pupd) & ~(1 << shift)); } } } @Override public boolean gpioRead(int gpio) { int reg = gpioToInputRegOffset(gpio); int shift = gpioToRegShiftBit(gpio); if (reg == -1 || shift == -1) { Logger.error("Invalid GPIO {}", Integer.valueOf(gpio)); return false; } MmapIntBuffer mmap_int_buffer = getIntBuffer(); return (mmap_int_buffer.get(reg) & (1 << shift)) != 0; } @Override public void gpioWrite(int gpio, boolean value) { // Note no boundary checks to maximise performance int reg = gpioToOutputRegOffset(gpio); int shift = gpioToRegShiftBit(gpio); MmapIntBuffer mmap_int_buffer = getIntBuffer(); if (value) { mmap_int_buffer.put(reg, mmap_int_buffer.get(reg) | (1 << shift)); } else { mmap_int_buffer.put(reg, mmap_int_buffer.get(reg) & ~(1 << shift)); } } @SuppressWarnings("boxing") public static void main(String[] args) { System.out.println(ByteOrder.nativeOrder()); if (args.length != 2) { System.out.println("Usage: " + AmlogicS922MmapGpio.class.getName() + " <gpio> <iterations>"); System.exit(1); } int gpio = Integer.parseInt(args[0]); int iterations = Integer.parseInt(args[1]); int gp_set_reg = gpio < J2_GPIOX_PIN_START ? J2_GPIOA_OUT_REG_OFFSET : J2_GPIOX_OUT_REG_OFFSET; int gp_set_reg2 = gpioToOutputRegOffset(gpio); System.out.println("gp_set_reg=" + gp_set_reg + ", gp_set_reg2=" + gp_set_reg2); int gp_lev_reg = gpio < J2_GPIOX_PIN_START ? J2_GPIOA_INP_REG_OFFSET : J2_GPIOX_INP_REG_OFFSET; int gp_lev_reg2 = gpioToInputRegOffset(gpio); System.out.println("gp_lev_reg=" + gp_lev_reg + ", gp_lev_reg2=" + gp_lev_reg2); int gp_fsel_reg = gpio < J2_GPIOX_PIN_START ? J2_GPIOA_OEN_REG_OFFSET : J2_GPIOX_OEN_REG_OFFSET; int gp_fsel_reg2 = gpioToOutputEnableRegOffset(gpio); System.out.println("gp_fsel_reg=" + gp_fsel_reg + ", gp_fsel_reg2=" + gp_fsel_reg2); System.out.format("gpioToGPSETReg(%d)=0x%04x%n", 214, gpioToOutputRegOffset(214)); System.out.format("gpioToGPSETReg(%d)=0x%04x%n", 219, gpioToOutputRegOffset(219)); System.out.format("gpioToGPFSELReg(%d)=0x%04x%n", 214, gpioToOutputEnableRegOffset(214)); System.out.format("gpioToGPFSELReg(%d)=0x%04x%n", 219, gpioToOutputEnableRegOffset(219)); try (AmlogicS905MmapGpio mmap_gpio = new AmlogicS905MmapGpio()) { mmap_gpio.initialise(); System.out.println("getMode(" + gpio + ")=" + mmap_gpio.getMode(gpio)); mmap_gpio.setMode(gpio, DeviceMode.DIGITAL_OUTPUT); System.out.println("getMode(" + gpio + ")=" + mmap_gpio.getMode(gpio)); System.out.println("Current val=" + mmap_gpio.gpioRead(gpio)); for (int i = 0; i < 5; i++) { System.out.println("on"); mmap_gpio.gpioWrite(gpio, true); System.out.println("Current val=" + mmap_gpio.gpioRead(gpio)); SleepUtil.sleepSeconds(1); System.out.println("off"); mmap_gpio.gpioWrite(gpio, false); System.out.println("Current val=" + mmap_gpio.gpioRead(gpio)); SleepUtil.sleepSeconds(1); } boolean exit = false; if (exit) { System.exit(1); } if (true) { long start_ms = System.currentTimeMillis(); for (int i = 0; i < iterations; i++) { mmap_gpio.gpioWrite(gpio, true); mmap_gpio.gpioWrite(gpio, false); } long duration_ms = System.currentTimeMillis() - start_ms; double frequency = iterations / (duration_ms / 1000.0); System.out.format("Duration for %,d iterations: %,.3f s, frequency: %,.0f Hz%n", iterations, ((float) duration_ms) / 1000, frequency); } for (int i = 0; i < 5; i++) { System.out.println("on"); mmap_gpio.gpioWrite(gpio, true); SleepUtil.sleepSeconds(1); System.out.println("off"); mmap_gpio.gpioWrite(gpio, false); SleepUtil.sleepSeconds(1); } } } public static void test() { final ThreadLocalRandom rand = ThreadLocalRandom.current(); IntBuffer buffer = ByteBuffer.allocateDirect(500).asIntBuffer(); for (int i = 0; i < buffer.capacity(); i++) { buffer.put(rand.nextInt()); } buffer.flip(); Hex.dumpIntBuffer(buffer, 0, 2); } }
package algorithms; import structures.HashTable; import java.util.Set; import java.util.List; import java.util.Arrays; public class KnapsackDP { private int max(int a, int b) { return (a > b) ? a : b; } public Integer compute(int capacity, List<Integer> values, List<Integer> weights, Set<Integer> optimalSubset) { int n = values.size() + 1; int cap = capacity + 1; int[][] table = new int[n][cap]; // System.out.println("[DEBUG] capcity = " + capacity + ", cap = " + cap); for (int item = 1; item < n; item++) { for (int weight = 1; weight < cap; weight++) { if (weights.get(item - 1) <= weight) { // System.out.println("[DEBUG11] item = " + item + ", weight = " + weight); // System.out.println("[DEBUG11] weight = " + weight + ", weights.get(item-1) = " + weights.get(item-1)); // System.out.println("[DEBUG11] weightDiff = " + (weight - weights.get(item-1)) + ", table[item-1][weightDiff] = " + table[item - 1][weight - weights.get(item-1)]); // System.out.println("[DEBUG11] tableEntry1 = " + table[item - 1][weight] + ", tableEntry2 = " + table[item - 1][weight - weights.get(item-1)]); // System.out.println("[DEBUG11] values.get(item - 1) = " + values.get(item - 1) + ", max = " + max(table[item - 1][weight], values.get(item - 1) + table[item - 1][weight - weights.get(item-1)])); table[item][weight] = max(table[item - 1][weight], values.get(item - 1) + table[item - 1][weight - weights.get(item-1)]); } else { // System.out.println("[DEBUG12] table[item][weight] = " + table[item][weight] + ", table[item - 1][weight] = " + table[item - 1][weight]); // System.out.println("[DEBUG12] weight = " + weight + ", weights.get(item-1) = " + weights.get(item-1)); // System.out.println("[DEBUG12] item = " + item + ", weight = " + weight + ", tableEntry1 = " + table[item - 1][weight]); table[item][weight] = table[item - 1][weight]; } } } // System.out.println(Arrays.deepToString(table).replace("], ", "]\n")); int currentItem = n - 1; int currentWeight = capacity; while(currentItem > 0) { if(table[currentItem][currentWeight] > table[currentItem - 1][currentWeight]) { optimalSubset.add(currentItem); currentWeight -= weights.get(currentItem - 1); currentItem--; } else { currentItem--; } } return table[n - 1][capacity]; } public Integer MFKnapsack(int i, int j, HashTable table, List<Integer> weights, List<Integer> values) { if (i < 1) return 0; Integer current = table.get(i,j); if (current == 0) { Integer value = 0; if (j < weights.get(i-1)) { value = MFKnapsack(i - 1, j, table, weights, values); } else { value = max(MFKnapsack(i - 1, j, table, weights, values), values.get(i - 1) + MFKnapsack(i - 1, j - weights.get(i - 1), table, weights, values)); } table.add(i, j, value); } return current; } public Integer computeWithHash(int capacity, List<Integer> values, List<Integer> weights, Set<Integer> optimalSubset, Integer k) { int n = values.size() + 1; int cap = capacity + 1; // System.out.println("[DEBUG] capcity = " + capacity + ", cap = " + cap); HashTable table = new HashTable(capacity, k); Integer result = 0; for (int item = 1; item < n; item++) { for (int weight = 1; weight < cap; weight++) { result = MFKnapsack(item, weight, table, weights, values); } } int currentItem = n - 1; int currentWeight = capacity; while(currentItem > 0) { try { Integer entry1 = table.get(currentItem, currentWeight); Integer entry2 = table.get((currentItem - 1), currentWeight); if (entry1 > entry2) { optimalSubset.add(currentItem); currentWeight -= weights.get(currentItem - 1); currentItem--; } else { currentItem--; } } catch(java.lang.NumberFormatException e) { System.out.println("[ERROR] currentItem = " + currentItem + ", currentWeight = " + currentWeight + ", entry1 = " + table.get(currentItem, currentWeight)); break; } } return table.get(n-1, capacity); } }
package sunnyTestng; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class DatabaseConnectivity { public static void main(String[] args) { // TODO Auto-generated method stub try { // This will load the driver Class.forName("oracle.jdbc.driver.OracleDriver"); System.out.println("Driver Loaded"); // This will connect with Database , getConnection taking three argument // first argument Test_Oracle is the dsn which you can change as per your system, // second argument is username and third argument is password Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","password"); System.out.println("Connection created"); // This will create statement Statement smt=con.createStatement(); System.out.println("Statement created"); // Now execute the query, here facebook is the table which I have created in DB ResultSet rs= smt.executeQuery("Select * from sunny"); System.out.println("Query Executed"); // Iterate the resultset now while(rs.next()){ String uname= rs.getString("ID"); String pass= rs.getString("NAME"); String email= rs.getString("CITY"); System.out.println("Uname is "+uname+" password is "+pass+" email id is "+email); } } catch (Exception e) { System.out.println(e.getMessage()); } } }
import java.util.*; class Calculator{ public static void main(String args[]){ double income, spend; Scanner scanner = new Scanner(System.in); System.out.print("Enter the amount of income"); String tmp = scanner.nextLine(); income = Double.parseDouble(tmp); System.out.print("Enter the amount spent"); String tmp2 = scanner.nextLine(); spend = Double.parseDouble(tmp2); gTotal(income, spend, gTotal); System.out.println("The remaining amount is " + remainVal); } } class Calculation { double remainVal; double gTotal(double income, double spend, double gTotal) { double total = income - spend; remainVal = gTotal - total; return remainVal; } }
package com.mideas.rpg.v2.game; public enum ClassType { DEATHKNIGHT, GUERRIER, HUNTER, MAGE, MONK, PALADIN, PRIEST, ROGUE, SHAMAN, WARLOCK }
package com.ljw.service; import com.ljw.vo.ChemClassInfoVO; import java.util.List; /** * @Description: * @Author Created by liangjunwei on 2018/8/2 17:36 */ public interface QueryGoodsService { List<ChemClassInfoVO> queryAllChemClassInfo(); }
package com.booking.hotelapi.entity.assembler; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.*; import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.server.RepresentationModelAssembler; import org.springframework.stereotype.Component; import com.booking.hotelapi.controller.BedTypeController; import com.booking.hotelapi.entity.BedType; @Component public class BedTypeModelAssembler implements RepresentationModelAssembler<BedType, EntityModel<BedType>> { @Override public EntityModel<BedType> toModel(BedType bedType) { return EntityModel.of(bedType, linkTo(methodOn(BedTypeController.class).findById(bedType.getBedTypeId())).withSelfRel(), linkTo(methodOn(BedTypeController.class).getBedTypes()).withRel("bedTypes")); } }
package com.mtsmda.tools.gui.util; /** * Created by c-DMITMINZ on 24.07.2015. */ public class StringUtil { public static boolean stringIsNotNULLOrEmpty(String string) { if (string != null && !string.trim().isEmpty()) { return true; } return false; } }
package com.wangjing.po.qr; public class TempQRTicketApply { private String action_name = "QR_SCENE"; private int expire_seconds; private TempQRScene action_info; public String getAction_name() { return action_name; } public int getExpire_seconds() { return expire_seconds; } public void setExpire_seconds(int expire_seconds) { this.expire_seconds = expire_seconds; } public TempQRScene getAction_info() { return action_info; } public void setAction_info(TempQRScene action_info) { this.action_info = action_info; } }
/** **************************************************************************** * Copyright (c) The Spray Project. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Spray Dev Team - initial API and implementation **************************************************************************** */ package org.eclipselabs.spray.runtime.graphiti.layout; import org.eclipse.graphiti.services.Graphiti; import org.eclipse.graphiti.services.ILayoutService; import org.eclipselabs.spray.runtime.graphiti.layout.SprayLayoutService.SprayAlignment; /** * @author Jos Warmer (jos.warmer@openmodeling.nl) */ public interface ISprayLayoutManager { static final public ILayoutService layoutService = Graphiti.getLayoutService(); /** * layout the shape connected to this layout manager. Will recursively go * into subshapes if needed. */ public void layout(); /** * Change the height of the corresponding shape equal to 'newHeight'. Will * recursively go into subshapes and strethc them as well. * * @param newHeight */ // public void stretchHeightTo(int newHeight); /** * Get the margin for this layout manager. The margin is additional space at * the top. bottom, left and right. */ public int getMargin(); /** * Sets the margin for this layout manager. The margin is additional space * at the top. bottom, left and right. */ public void setMargin(int margin); public int getSpacing(); public void setSpacing(int spacing); /** * Sets the alignment that the children should have TODO As we only need the * CENTER alignment in Logan, this is the only option that is implemented, * other alignment options are ignored. * <p> * For horizontal layout default alignment is BEGINNING * <p> * For vertical layout default alignment is FILL * * @param alignment */ public void setAlignment(SprayAlignment alignment); public SprayAlignment getAlignment(); public boolean isFlexible(); }